From 62d919941bbcf8a40c75729c637857db0b58c162 Mon Sep 17 00:00:00 2001 From: ngqile Date: Wed, 2 Dec 2026 11:13:43 +0800 Subject: [PATCH] feat(portal): WhatsApp inbox page List with Mine (plus Unassigned and All for a WhatsApp Admin), search, unread and owner; the chat with bubbles, delivery state and failures with Retry, media through the portal proxy, the 24-hour window, the text composer and the template picker, and reassignment for admins. The list polls every 30 s and an open chat every 10 s; opening an unread chat marks it read and refreshes the sidebar badge. /whatsapp is gated by BO_WHATSAPP (the route list test now includes it). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs --- .../components/whatsapp/ConversationList.tsx | 126 +++++++ .../components/whatsapp/TemplatePicker.tsx | 151 ++++++++ .../app/components/whatsapp/Thread.tsx | 341 ++++++++++++++++++ .../app/lib/i18n/defaultMessages.ts | 40 ++ .../app/lib/routeModules.test.ts | 2 +- solvway-admin-portal/app/lib/routeModules.ts | 1 + .../app/whatsapp/page.test.tsx | 281 +++++++++++++++ solvway-admin-portal/app/whatsapp/page.tsx | 50 +++ 8 files changed, 991 insertions(+), 1 deletion(-) create mode 100644 solvway-admin-portal/app/components/whatsapp/ConversationList.tsx create mode 100644 solvway-admin-portal/app/components/whatsapp/TemplatePicker.tsx create mode 100644 solvway-admin-portal/app/components/whatsapp/Thread.tsx create mode 100644 solvway-admin-portal/app/whatsapp/page.test.tsx create mode 100644 solvway-admin-portal/app/whatsapp/page.tsx diff --git a/solvway-admin-portal/app/components/whatsapp/ConversationList.tsx b/solvway-admin-portal/app/components/whatsapp/ConversationList.tsx new file mode 100644 index 0000000..a8ee8d0 --- /dev/null +++ b/solvway-admin-portal/app/components/whatsapp/ConversationList.tsx @@ -0,0 +1,126 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import { MessageCircle } from "lucide-react"; +import { Input } from "@/app/components/ui/input"; +import { Tabs, TabsList, TabsTrigger } from "@/app/components/ui/tabs"; +import { EmptyState, ErrorState } from "@/app/components/ui/states"; +import { ApiError } from "@/app/lib/clientApi"; +import { usePolling } from "@/app/lib/hooks/usePolling"; +import { listConversations, type WhatsAppConversation, type WhatsAppTab } from "@/app/lib/services/whatsapp"; +import { useT } from "@/app/lib/i18n/MessagesProvider"; +import { cn } from "@/app/lib/utils"; + +export const contactLabel = (c: Pick) => c.contactName || `+${c.contactWaId}`; + +/** dd/MM HH:mm in local time; the list and the bubbles share it. */ +export function shortTime(iso: string | null) { + if (!iso) return ""; + const d = new Date(iso); + const p = (n: number) => String(n).padStart(2, "0"); + return `${p(d.getDate())}/${p(d.getMonth() + 1)} ${p(d.getHours())}:${p(d.getMinutes())}`; +} + +type Props = { + admin: boolean; + companyId: number | undefined; + selected: string | null; + onSelect: (uuid: string) => void; +}; + +/** Tabs, search and the polled list. Mine for everyone; Unassigned and All for a WhatsApp Admin. */ +export function ConversationList({ admin, companyId, selected, onSelect }: Props) { + const t = useT(); + const [tab, setTab] = useState("mine"); + const [typed, setTyped] = useState(""); + const [query, setQuery] = useState(""); + useEffect(() => { + const id = window.setTimeout(() => setQuery(typed.trim()), 300); + return () => window.clearTimeout(id); + }, [typed]); + + const tabs: WhatsAppTab[] = admin ? ["mine", "unassigned", "all"] : ["mine"]; + const label: Record = { mine: t("WaTabMine"), unassigned: t("WaUnassigned"), all: t("WaTabAll") }; + + return ( +
+
+ setTab(v as WhatsAppTab)}> + + {tabs.map((k) => ( + + {label[k]} + + ))} + + + setTyped(e.target.value)} /> +
+ {/* Remounting on a new tab, search or company restarts the poll with a fresh first read. */} + +
+ ); +} + +function Rows({ tab, query, companyId, admin, selected, onSelect }: Props & { tab: WhatsAppTab; query: string }) { + const t = useT(); + const [items, setItems] = useState(null); + const [error, setError] = useState<"config" | "load" | null>(null); + const alive = useRef(true); + useEffect(() => () => { alive.current = false; }, []); + + const load = () => + listConversations(tab, query, 0, companyId).then( + (p) => { + if (!alive.current) return; + setItems(p.items); + setError(null); + }, + (err: unknown) => { + if (!alive.current) return; + const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined; + setError(code === "WHATSAPP_NOT_CONFIGURED" ? "config" : "load"); + }, + ); + // ponytail: first page only (30 newest); add paging when a queue outgrows it. + usePolling(load, 30_000, "whatsapp-unread-changed"); + + if (error === "config") return } />; + if (error === "load" && !items) return ; + if (!items) return
; + if (items.length === 0) return } />; + + return ( +
    + {items.map((c) => ( +
  • + +
  • + ))} +
+ ); +} diff --git a/solvway-admin-portal/app/components/whatsapp/TemplatePicker.tsx b/solvway-admin-portal/app/components/whatsapp/TemplatePicker.tsx new file mode 100644 index 0000000..ebcad9d --- /dev/null +++ b/solvway-admin-portal/app/components/whatsapp/TemplatePicker.tsx @@ -0,0 +1,151 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { Button } from "@/app/components/ui/button"; +import { Input } from "@/app/components/ui/input"; +import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/app/components/ui/dialog"; +import { listTemplates, sendTemplate, syncTemplates, type WhatsAppMessage, type WhatsAppTemplate } from "@/app/lib/services/whatsapp"; +import { useT } from "@/app/lib/i18n/MessagesProvider"; +import { cn } from "@/app/lib/utils"; + +/** The body with each {{n}} replaced by its typed value; an empty field keeps its placeholder. */ +export const fillTemplate = (body: string, params: string[]) => + body.replace(/\{\{(\d+)\}\}/g, (all, n: string) => params[Number(n) - 1]?.trim() || all); + +type Props = { + open: boolean; + onOpenChange: (open: boolean) => void; + conversationUuid: string; + companyId: number | undefined; + admin: boolean; + onSent: (m: WhatsAppMessage) => void; +}; + +export function TemplatePicker({ open, onOpenChange, conversationUuid, companyId, admin, onSent }: Props) { + const t = useT(); + const [templates, setTemplates] = useState(null); + const [chosen, setChosen] = useState(null); + const [params, setParams] = useState([]); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + useEffect(() => { + if (!open) return; + let cancelled = false; + listTemplates(companyId).then( + (list) => !cancelled && setTemplates(list), + () => !cancelled && setError(t("WaTemplatesFailed")), + ); + return () => { cancelled = true; }; + }, [open, companyId, t]); + + const reset = (next: boolean) => { + if (!next) { + setChosen(null); + setParams([]); + setError(null); + } + onOpenChange(next); + }; + + const pick = (tpl: WhatsAppTemplate) => { + setChosen(tpl); + setParams(Array.from({ length: tpl.paramCount }, () => "")); + }; + + const sync = () => { + setBusy(true); + setError(null); + // A super admin syncing with no company picked gets [] back; re-list so the picker never empties by mistake. + syncTemplates(companyId) + .then((list) => (list.length > 0 ? list : listTemplates(companyId))) + .then(setTemplates, () => setError(t("WaTemplatesFailed"))) + .finally(() => setBusy(false)); + }; + + const send = () => { + if (!chosen) return; + setBusy(true); + setError(null); + sendTemplate(conversationUuid, chosen, params.map((p) => p.trim()), companyId) + .then((m) => { + onSent(m); + reset(false); + }, () => setError(t("WaSendFailed"))) + .finally(() => setBusy(false)); + }; + + const complete = chosen !== null && params.every((p) => p.trim() !== ""); + + return ( + + + + {t("WaChooseTemplate")} + + + {!chosen ? ( +
+ {templates?.length === 0 &&

{t("WaNoTemplates")}

} +
    + {templates?.map((tpl) => ( +
  • + +
  • + ))} +
+
+ ) : ( +
+

{fillTemplate(chosen.bodyText, params)}

+ {params.map((value, i) => ( + setParams((ps) => ps.map((p, j) => (j === i ? e.target.value : p)))} + /> + ))} +
+ )} + + {error &&

{error}

} + + + {!chosen && admin && ( + + )} + {chosen && ( + + )} + {chosen && ( + + )} + +
+
+ ); +} diff --git a/solvway-admin-portal/app/components/whatsapp/Thread.tsx b/solvway-admin-portal/app/components/whatsapp/Thread.tsx new file mode 100644 index 0000000..acd5be9 --- /dev/null +++ b/solvway-admin-portal/app/components/whatsapp/Thread.tsx @@ -0,0 +1,341 @@ +"use client"; + +import { useEffect, useRef, useState } from "react"; +import Link from "next/link"; +import { ArrowLeft, Check, CheckCheck, Clock, FileText, MapPin } from "lucide-react"; +import { Button } from "@/app/components/ui/button"; +import { ErrorState } from "@/app/components/ui/states"; +import { ApiError } from "@/app/lib/clientApi"; +import { usePolling } from "@/app/lib/hooks/usePolling"; +import { + assignConversation, + getThread, + listAssignees, + markRead, + mediaUrl, + sendText, + type WhatsAppConversation, + type WhatsAppMessage, +} from "@/app/lib/services/whatsapp"; +import { useT } from "@/app/lib/i18n/MessagesProvider"; +import { cn } from "@/app/lib/utils"; +import { contactLabel, shortTime } from "./ConversationList"; +import { TemplatePicker } from "./TemplatePicker"; + +const HOUR = 3600_000; + +/** Older pages, then the latest page, then messages sent here that the next poll has not returned yet; each uuid once. */ +function merge(...lists: WhatsAppMessage[][]) { + const byUuid = new Map(); + for (const list of lists) for (const m of list) byUuid.set(m.uuid, m); + return [...byUuid.values()]; +} + +type Props = { uuid: string; companyId: number | undefined; admin: boolean; onBack: () => void }; + +/** One chat: header, bubbles and composer. Keyed by uuid in the page, so a new chat starts clean. */ +export function Thread({ uuid, companyId, admin, onBack }: Props) { + const t = useT(); + const [conv, setConv] = useState(null); + const [latest, setLatest] = useState([]); + const [older, setOlder] = useState([]); + const [local, setLocal] = useState([]); + const [hasOlder, setHasOlder] = useState(false); + const [failed, setFailed] = useState(false); + const [notice, setNotice] = useState(null); + const [text, setText] = useState(""); + const [sending, setSending] = useState(false); + const [picker, setPicker] = useState(false); + // When the last poll returned: the window countdown reads it instead of the clock during render. + const [polledAt, setPolledAt] = useState(0); + const loadedOlder = useRef(false); + const bottom = useRef(null); + + const load = () => + getThread(uuid, undefined, companyId).then( + (r) => { + setConv(r.conversation); + setPolledAt(Date.now()); + setLatest(r.messages); + setFailed(false); + if (!loadedOlder.current) setHasOlder(r.hasOlder); + if (r.conversation.unreadCount > 0) { + markRead(uuid, companyId).then(() => window.dispatchEvent(new Event("whatsapp-unread-changed")), () => {}); + } + }, + () => setFailed(true), + ); + // ponytail: polling every 10 s while open; server-sent events if replies must feel instant. + usePolling(load, 10_000); + + const messages = merge(older, latest, local); + const lastUuid = messages[messages.length - 1]?.uuid; + useEffect(() => { + bottom.current?.scrollIntoView?.({ block: "end" }); + }, [lastUuid]); + + const loadOlder = () => { + const first = messages[0]; + if (!first) return; + getThread(uuid, first.uuid, companyId).then((r) => { + loadedOlder.current = true; + setOlder((o) => [...r.messages, ...o]); + setHasOlder(r.hasOlder); + }, () => setNotice(t("WaThreadFailed"))); + }; + + const send = (body: string, clear: boolean) => { + setSending(true); + setNotice(null); + sendText(uuid, body, companyId) + .then((m) => { + setLocal((l) => [...l, m]); + if (clear) setText(""); + }) + .catch((err: unknown) => { + const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined; + if (code === "WINDOW_CLOSED") { + setNotice(t("WaWindowClosedNow")); + load(); + } else setNotice(t("WaSendFailed")); + }) + .finally(() => setSending(false)); + }; + + if (failed && !conv) return ; + if (!conv) return
; + + const hoursLeft = conv.lastInboundAt ? Math.ceil((Date.parse(conv.lastInboundAt) + 24 * HOUR - polledAt) / HOUR) : 0; + + return ( +
+
+ +
+

{contactLabel(conv)}

+

+ {conv.contactName && +{conv.contactWaId}} + {conv.leadUuid && ( + <> + {conv.contactName && " ยท "} + + {conv.leadName || t("WaLead")} + + + )} +

+
+
+ {admin ? ( + + ) : ( + {t("WaOwnerIs", { name: conv.ownerName ?? t("WaUnassigned") })} + )} + + {conv.windowOpen ? t("WaWindowOpen", { h: Math.max(hoursLeft, 1) }) : t("WaWindowClosed")} + +
+
+ +
+ {hasOlder && ( +
+ +
+ )} +
    + {messages.map((m) => ( + send(m.body!, false) : undefined} /> + ))} +
+
+
+ +
+ {notice &&

{notice}

} + {conv.windowOpen ? ( +
{ + e.preventDefault(); + if (text.trim()) send(text.trim(), true); + }} + > +