wacrm/src/app/(dashboard)/inbox/page.tsx
Arnas Donauskas 5d0944e087
feat(inbox): wire conversation assignment dropdown
Replace the no-op Assign button in the thread header with a dropdown that
reads/writes conversations.assigned_agent_id. Lists profiles visible
under RLS (single-tenant today, ready for shared workspaces) and offers
Unassign when the conversation is already claimed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 15:14:42 +03:00

348 lines
12 KiB
TypeScript

"use client";
import { useState, useCallback, useEffect, useRef } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { createClient } from "@/lib/supabase/client";
import type { Conversation, Message, Contact, ConversationStatus } from "@/types";
import { useRealtime } from "@/hooks/use-realtime";
import { ConversationList } from "@/components/inbox/conversation-list";
import { MessageThread } from "@/components/inbox/message-thread";
import { ContactSidebar } from "@/components/inbox/contact-sidebar";
import { toast } from "sonner";
import { WifiOff } from "lucide-react";
import { cn } from "@/lib/utils";
export default function InboxPage() {
const router = useRouter();
const searchParams = useSearchParams();
/**
* `?c=<id>` deep-link support. Used when landing here from the
* dashboard's recent-conversations list so the right thread opens
* automatically instead of showing the empty center panel.
*/
const deepLinkConvId = searchParams.get("c");
const [conversations, setConversations] = useState<Conversation[]>([]);
const [activeConversation, setActiveConversation] =
useState<Conversation | null>(null);
const [activeContact, setActiveContact] = useState<Contact | null>(null);
const [messages, setMessages] = useState<Message[]>([]);
const [whatsappConnected, setWhatsappConnected] = useState<boolean | null>(
null
);
// Fire the deep-link auto-select exactly once per URL — subsequent
// list refreshes (realtime, manual refetch) must not snap the user
// back to the deep-linked conversation if they've already clicked
// elsewhere.
const autoSelectedForDeepLinkRef = useRef<string | null>(null);
// Check WhatsApp connection status on mount
useEffect(() => {
const checkConnection = async () => {
const supabase = createClient();
const {
data: { session },
} = await supabase.auth.getSession();
const user = session?.user;
if (!user) return;
// Table is `whatsapp_config` (singular) — the previous "whatsapp_configs"
// query always returned no rows, so the banner always showed "not connected".
const { data } = await supabase
.from("whatsapp_config")
.select("status")
.eq("user_id", user.id)
.maybeSingle();
setWhatsappConnected(data?.status === "connected");
};
checkConnection();
}, []);
// Handle realtime message events
const handleMessageEvent = useCallback(
(event: { eventType: string; new: Message; old: Partial<Message> }) => {
const newMsg = event.new;
if (event.eventType === "INSERT") {
// Add to messages if it belongs to active conversation
if (
activeConversation &&
newMsg.conversation_id === activeConversation.id
) {
setMessages((prev) => {
// Avoid duplicates
if (prev.some((m) => m.id === newMsg.id)) return prev;
// Replace optimistic message if it exists
const withoutOptimistic = prev.filter(
(m) => !m.id.startsWith("temp-")
);
return [...withoutOptimistic, newMsg];
});
}
// Update conversation list preview
setConversations((prev) =>
prev.map((c) =>
c.id === newMsg.conversation_id
? {
...c,
last_message_text: newMsg.content_text ?? "",
last_message_at: newMsg.created_at,
unread_count:
activeConversation?.id === newMsg.conversation_id
? 0
: c.unread_count + 1,
}
: c
)
);
}
if (event.eventType === "UPDATE") {
// Update message status
setMessages((prev) =>
prev.map((m) => (m.id === newMsg.id ? { ...m, ...newMsg } : m))
);
}
},
[activeConversation]
);
// Handle realtime conversation events
const handleConversationEvent = useCallback(
(event: {
eventType: string;
new: Conversation;
old: Partial<Conversation>;
}) => {
const conv = event.new;
if (event.eventType === "INSERT") {
setConversations((prev) => [conv, ...prev]);
}
if (event.eventType === "UPDATE") {
setConversations((prev) =>
prev.map((c) => (c.id === conv.id ? { ...c, ...conv } : c))
);
// Update active conversation if it changed
if (activeConversation && conv.id === activeConversation.id) {
setActiveConversation((prev) =>
prev ? { ...prev, ...conv } : prev
);
}
}
},
[activeConversation]
);
// Subscribe to realtime
useRealtime({
channelName: "inbox-realtime",
onMessageEvent: handleMessageEvent,
onConversationEvent: handleConversationEvent,
enabled: true,
});
const handleConversationsLoaded = useCallback(
(loaded: Conversation[]) => {
setConversations(loaded);
// Resolve a pending deep-link here rather than in an effect — this
// is an event handler, so the setState calls below are allowed by
// react-hooks/set-state-in-effect. Runs once per ?c=<id> URL value
// via the ref, so realtime refreshes of the list can't snap the
// user back to the deep-linked thread after they've navigated.
if (
deepLinkConvId &&
autoSelectedForDeepLinkRef.current !== deepLinkConvId &&
loaded.length > 0
) {
autoSelectedForDeepLinkRef.current = deepLinkConvId;
// If the deep-linked conversation is already the active one
// (e.g. because the user clicked it in the list and we
// router.replace()'d the URL, which made the ConversationList
// refetch and land us back here), do NOT re-apply it. Doing so
// would setMessages([]) on a thread whose messages have
// already been loaded by MessageThread — and because
// conversationId didn't change, MessageThread wouldn't
// refetch. The thread would read "No messages yet" until a
// full page reload rehydrated state from scratch.
if (activeConversation?.id === deepLinkConvId) return;
const match = loaded.find((c) => c.id === deepLinkConvId);
if (match) {
setActiveConversation(match);
setActiveContact(match.contact ?? null);
setMessages([]);
}
}
},
[deepLinkConvId, activeConversation?.id]
);
const handleSelectConversation = useCallback(
(conv: Conversation) => {
// Re-clicking the already-active conversation would clear the
// messages array, but the fetch effect in MessageThread only re-runs
// when conversationId changes — so messages would stay empty until
// the user navigated away and back. Bail out early instead.
if (activeConversation?.id === conv.id) return;
setActiveConversation(conv);
setActiveContact(conv.contact ?? null);
setMessages([]);
// Record the selection on the deep-link ref BEFORE we change the
// URL. The router.replace below flips `deepLinkConvId`, which can
// in turn cause ConversationList to refetch and eventually call
// handleConversationsLoaded again. Without this line, the ref
// still points at the previous value, the auto-select block
// sees `ref !== deepLinkConvId`, fires a second time, and
// clobbers the messages MessageThread just fetched.
autoSelectedForDeepLinkRef.current = conv.id;
// Reflect the selection in the URL so a refresh lands the user
// back in the same thread, and so copy-paste links work. Use
// replace() to avoid polluting browser history with every click.
router.replace(`/inbox?c=${conv.id}`, { scroll: false });
},
[activeConversation?.id, router]
);
// Mobile "back" — deselect the conversation so the list pane comes
// back. Also clears the ?c= param so a refresh lands on the list
// instead of re-opening the thread the user just backed out of.
const handleCloseConversation = useCallback(() => {
setActiveConversation(null);
setActiveContact(null);
setMessages([]);
// Clearing the ref lets the deep-link auto-selector fire again if
// the user later visits /inbox?c=<same-id> — desirable UX.
autoSelectedForDeepLinkRef.current = null;
router.replace("/inbox", { scroll: false });
}, [router]);
const handleMessagesLoaded = useCallback((loaded: Message[]) => {
setMessages(loaded);
}, []);
const handleNewMessage = useCallback((msg: Message) => {
setMessages((prev) => {
if (prev.some((m) => m.id === msg.id)) return prev;
return [...prev, msg];
});
}, []);
const handleUpdateMessage = useCallback(
(id: string, updates: Partial<Message>) => {
setMessages((prev) =>
prev.map((m) => (m.id === id ? { ...m, ...updates } : m))
);
},
[]
);
const handleStatusChange = useCallback(
(conversationId: string, status: ConversationStatus) => {
setConversations((prev) =>
prev.map((c) => (c.id === conversationId ? { ...c, status } : c))
);
if (activeConversation?.id === conversationId) {
setActiveConversation((prev) => (prev ? { ...prev, status } : prev));
}
},
[activeConversation]
);
const handleAssignChange = useCallback(
(conversationId: string, assignedAgentId: string | null) => {
setConversations((prev) =>
prev.map((c) =>
c.id === conversationId
? { ...c, assigned_agent_id: assignedAgentId ?? undefined }
: c
)
);
if (activeConversation?.id === conversationId) {
setActiveConversation((prev) =>
prev
? { ...prev, assigned_agent_id: assignedAgentId ?? undefined }
: prev
);
}
},
[activeConversation]
);
// On mobile (<lg) we show a SINGLE pane — either the list or the
// thread — rather than cramming both side-by-side. Selecting a
// conversation slides the thread in; the thread's back button pops
// it back to the list. On lg+ both panes render side-by-side as
// before, unchanged.
const hasActiveConv = !!activeConversation;
return (
<div className="-m-4 flex h-[calc(100vh-3.5rem)] flex-col overflow-hidden sm:-m-6">
{/* WhatsApp connection banner — in the flex column, not absolute,
so it pushes the panels down instead of overlapping them. */}
{whatsappConnected === false && (
<div className="flex shrink-0 items-center justify-center gap-2 border-b border-amber-500/20 bg-amber-500/10 px-4 py-2">
<WifiOff className="h-4 w-4 text-amber-400" />
<p className="text-xs text-amber-400">
WhatsApp® is not connected. Go to Settings to connect your account.
</p>
</div>
)}
<div className="flex flex-1 overflow-hidden">
{/* Left panel: Conversation list.
Hidden on mobile when a conversation is selected so the
thread can occupy the full width. Always visible on lg+. */}
<div
className={cn(
"flex h-full flex-1 lg:flex-none",
hasActiveConv ? "hidden lg:flex" : "flex",
)}
>
<ConversationList
activeConversationId={activeConversation?.id ?? null}
onSelect={handleSelectConversation}
conversations={conversations}
onConversationsLoaded={handleConversationsLoaded}
/>
</div>
{/* Center panel: Message thread.
Hidden on mobile when no conversation is selected so the
list can occupy the full width. Always visible on lg+
(shows its own empty-state if no thread is picked yet). */}
<div
className={cn(
"flex h-full flex-1 lg:flex",
hasActiveConv ? "flex" : "hidden lg:flex",
)}
>
<MessageThread
conversation={activeConversation}
contact={activeContact}
messages={messages}
onMessagesLoaded={handleMessagesLoaded}
onNewMessage={handleNewMessage}
onUpdateMessage={handleUpdateMessage}
onStatusChange={handleStatusChange}
onAssignChange={handleAssignChange}
onBack={handleCloseConversation}
/>
</div>
{/* Right panel: Contact sidebar — desktop only. */}
<div className="hidden lg:block">
<ContactSidebar contact={activeContact} />
</div>
</div>
</div>
);
}