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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
This commit is contained in:
1 parent
2cbd939567
commit
62d919941b
8 files changed
+991
-1
No files matched your search
@@ -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<WhatsAppConversation, "contactName" | "contactWaId">) => 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<WhatsAppTab>("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<WhatsAppTab, string> = { mine: t("WaTabMine"), unassigned: t("WaUnassigned"), all: t("WaTabAll") };
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-col">
|
||||
<div className="space-y-3 border-b p-3">
|
||||
<Tabs value={tab} onValueChange={(v) => setTab(v as WhatsAppTab)}>
|
||||
<TabsList>
|
||||
{tabs.map((k) => (
|
||||
<TabsTrigger key={k} value={k}>
|
||||
{label[k]}
|
||||
</TabsTrigger>
|
||||
))}
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<Input type="search" aria-label={t("WaSearch")} placeholder={t("WaSearch")} value={typed} onChange={(e) => setTyped(e.target.value)} />
|
||||
</div>
|
||||
{/* Remounting on a new tab, search or company restarts the poll with a fresh first read. */}
|
||||
<Rows key={`${tab}|${query}|${companyId ?? ""}`} tab={tab} query={query} companyId={companyId} admin={admin} selected={selected} onSelect={onSelect} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Rows({ tab, query, companyId, admin, selected, onSelect }: Props & { tab: WhatsAppTab; query: string }) {
|
||||
const t = useT();
|
||||
const [items, setItems] = useState<WhatsAppConversation[] | null>(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 <EmptyState title={t("WaNotConfigured")} icon={<MessageCircle className="size-8" />} />;
|
||||
if (error === "load" && !items) return <ErrorState message={t("WaListFailed")} onRetry={load} className="m-3" />;
|
||||
if (!items) return <div className="m-3 h-16 animate-pulse rounded-lg bg-muted" />;
|
||||
if (items.length === 0) return <EmptyState title={t("WaNoChats")} icon={<MessageCircle className="size-8" />} />;
|
||||
|
||||
return (
|
||||
<ul className="scrollable min-h-0 flex-1 overflow-y-auto">
|
||||
{items.map((c) => (
|
||||
<li key={c.uuid} className="border-b last:border-b-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSelect(c.uuid)}
|
||||
aria-current={c.uuid === selected ? "true" : undefined}
|
||||
className={cn(
|
||||
"flex w-full flex-col gap-0.5 px-3 py-2.5 text-left text-sm transition-colors hover:bg-muted/50",
|
||||
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none focus-visible:ring-inset",
|
||||
c.uuid === selected && "bg-accent text-accent-foreground hover:bg-accent",
|
||||
)}
|
||||
>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="truncate font-medium">{contactLabel(c)}</span>
|
||||
<span className="ml-auto shrink-0 text-xs text-muted-foreground tabular-nums">{shortTime(c.lastMessageAt)}</span>
|
||||
</span>
|
||||
{c.leadName && <span className="truncate text-xs text-muted-foreground">{c.leadName}</span>}
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="truncate text-muted-foreground">{c.lastMessagePreview}</span>
|
||||
{c.unreadCount > 0 && (
|
||||
<span className="ml-auto shrink-0 rounded-full bg-primary px-1.5 text-xs leading-5 font-semibold text-primary-foreground tabular-nums">
|
||||
{t("WaUnread", { n: c.unreadCount })}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
{admin && <span className="truncate text-xs text-muted-foreground">{c.ownerName ?? t("WaUnassigned")}</span>}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -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<WhatsAppTemplate[] | null>(null);
|
||||
const [chosen, setChosen] = useState<WhatsAppTemplate | null>(null);
|
||||
const [params, setParams] = useState<string[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(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 (
|
||||
<Dialog open={open} onOpenChange={reset}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("WaChooseTemplate")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
{!chosen ? (
|
||||
<div className="space-y-2">
|
||||
{templates?.length === 0 && <p className="text-sm text-muted-foreground">{t("WaNoTemplates")}</p>}
|
||||
<ul className="scrollable max-h-80 space-y-2 overflow-y-auto">
|
||||
{templates?.map((tpl) => (
|
||||
<li key={`${tpl.name}:${tpl.language}`}>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!tpl.supported}
|
||||
onClick={() => pick(tpl)}
|
||||
className={cn(
|
||||
"w-full rounded-lg border p-3 text-left text-sm transition-colors",
|
||||
"hover:bg-accent hover:text-accent-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none",
|
||||
"disabled:pointer-events-none disabled:opacity-50",
|
||||
)}
|
||||
>
|
||||
<span className="flex items-center gap-2 font-medium">
|
||||
{tpl.name}
|
||||
<span className="text-xs font-normal text-muted-foreground">{tpl.language}</span>
|
||||
{!tpl.supported && <span className="ml-auto text-xs font-normal text-muted-foreground">{t("WaTemplateUnsupported")}</span>}
|
||||
</span>
|
||||
<span className="mt-1 block text-muted-foreground">{tpl.bodyText}</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<p className="rounded-lg bg-accent px-3 py-2 text-sm whitespace-pre-wrap text-accent-foreground">{fillTemplate(chosen.bodyText, params)}</p>
|
||||
{params.map((value, i) => (
|
||||
<Input
|
||||
key={i}
|
||||
aria-label={`{{${i + 1}}}`}
|
||||
placeholder={`{{${i + 1}}}`}
|
||||
value={value}
|
||||
onChange={(e) => setParams((ps) => ps.map((p, j) => (j === i ? e.target.value : p)))}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
|
||||
|
||||
<DialogFooter>
|
||||
{!chosen && admin && (
|
||||
<Button variant="outline" disabled={busy} onClick={sync} className="sm:mr-auto">
|
||||
{t("WaSyncTemplates")}
|
||||
</Button>
|
||||
)}
|
||||
{chosen && (
|
||||
<Button variant="outline" disabled={busy} onClick={() => setChosen(null)}>
|
||||
{t("Back")}
|
||||
</Button>
|
||||
)}
|
||||
{chosen && (
|
||||
<Button disabled={!complete || busy} onClick={send}>
|
||||
{t("WaSendTemplate")}
|
||||
</Button>
|
||||
)}
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -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<string, WhatsAppMessage>();
|
||||
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<WhatsAppConversation | null>(null);
|
||||
const [latest, setLatest] = useState<WhatsAppMessage[]>([]);
|
||||
const [older, setOlder] = useState<WhatsAppMessage[]>([]);
|
||||
const [local, setLocal] = useState<WhatsAppMessage[]>([]);
|
||||
const [hasOlder, setHasOlder] = useState(false);
|
||||
const [failed, setFailed] = useState(false);
|
||||
const [notice, setNotice] = useState<string | null>(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<HTMLDivElement>(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 <ErrorState message={t("WaThreadFailed")} onRetry={load} className="m-3" />;
|
||||
if (!conv) return <div className="m-3 h-24 animate-pulse rounded-lg bg-muted" />;
|
||||
|
||||
const hoursLeft = conv.lastInboundAt ? Math.ceil((Date.parse(conv.lastInboundAt) + 24 * HOUR - polledAt) / HOUR) : 0;
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col">
|
||||
<header className="flex flex-wrap items-center gap-x-3 gap-y-1 border-b px-3 py-2">
|
||||
<Button variant="ghost" size="icon-sm" onClick={onBack} aria-label={t("WaBack")} className="lg:hidden">
|
||||
<ArrowLeft aria-hidden="true" className="size-4" />
|
||||
</Button>
|
||||
<div className="min-w-0">
|
||||
<h2 className="truncate font-semibold">{contactLabel(conv)}</h2>
|
||||
<p className="truncate text-xs text-muted-foreground">
|
||||
{conv.contactName && <span className="tabular-nums">+{conv.contactWaId}</span>}
|
||||
{conv.leadUuid && (
|
||||
<>
|
||||
{conv.contactName && " · "}
|
||||
<Link href={`/leads/${conv.leadUuid}`} className="font-medium text-primary underline-offset-4 hover:underline">
|
||||
{conv.leadName || t("WaLead")}
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<div className="ml-auto flex flex-wrap items-center gap-2 text-xs text-muted-foreground">
|
||||
{admin ? (
|
||||
<OwnerSelect conv={conv} companyId={companyId} onChange={setConv} />
|
||||
) : (
|
||||
<span>{t("WaOwnerIs", { name: conv.ownerName ?? t("WaUnassigned") })}</span>
|
||||
)}
|
||||
<span className="rounded-full border px-2 py-0.5">
|
||||
{conv.windowOpen ? t("WaWindowOpen", { h: Math.max(hoursLeft, 1) }) : t("WaWindowClosed")}
|
||||
</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="scrollable min-h-0 flex-1 space-y-2 overflow-y-auto bg-background p-3">
|
||||
{hasOlder && (
|
||||
<div className="flex justify-center">
|
||||
<Button variant="outline" size="sm" onClick={loadOlder}>
|
||||
{t("WaLoadOlder")}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<ol className="flex flex-col gap-2">
|
||||
{messages.map((m) => (
|
||||
<Bubble key={m.uuid} m={m} companyId={companyId} onRetry={m.type === "text" && m.body ? () => send(m.body!, false) : undefined} />
|
||||
))}
|
||||
</ol>
|
||||
<div ref={bottom} />
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 border-t p-3">
|
||||
{notice && <p role="alert" className="text-sm text-destructive">{notice}</p>}
|
||||
{conv.windowOpen ? (
|
||||
<form
|
||||
className="flex items-end gap-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (text.trim()) send(text.trim(), true);
|
||||
}}
|
||||
>
|
||||
<textarea
|
||||
aria-label={t("WaMessage")}
|
||||
placeholder={t("WaMessage")}
|
||||
rows={2}
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
e.currentTarget.form?.requestSubmit();
|
||||
}
|
||||
}}
|
||||
className="min-h-9 flex-1 resize-none rounded-md border border-input bg-card px-3 py-2 text-sm shadow-sm focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none"
|
||||
/>
|
||||
<Button type="button" variant="outline" onClick={() => setPicker(true)}>
|
||||
{t("WaTemplate")}
|
||||
</Button>
|
||||
<Button type="submit" disabled={sending || !text.trim()}>
|
||||
{t("WaSend")}
|
||||
</Button>
|
||||
</form>
|
||||
) : (
|
||||
<div className="flex items-center gap-3">
|
||||
<p className="flex-1 text-sm text-muted-foreground">{t("WaWindowClosedHint")}</p>
|
||||
<Button onClick={() => setPicker(true)}>{t("WaTemplate")}</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TemplatePicker
|
||||
open={picker}
|
||||
onOpenChange={setPicker}
|
||||
conversationUuid={uuid}
|
||||
companyId={companyId}
|
||||
admin={admin}
|
||||
onSent={(m) => setLocal((l) => [...l, m])}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function OwnerSelect({ conv, companyId, onChange }: { conv: WhatsAppConversation; companyId: number | undefined; onChange: (c: WhatsAppConversation) => void }) {
|
||||
const t = useT();
|
||||
const [people, setPeople] = useState<{ id: number; name: string | null }[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
// The chat's own company: a super admin on "All companies" has no scope, and assignees need one.
|
||||
const scope = companyId ?? conv.companyId;
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
listAssignees(scope).then((p) => !cancelled && setPeople(p), () => {});
|
||||
return () => { cancelled = true; };
|
||||
}, [scope]);
|
||||
|
||||
const value = conv.ownerManual && conv.ownerUserId != null ? String(conv.ownerUserId) : "auto";
|
||||
return (
|
||||
<label className="flex items-center gap-1.5">
|
||||
<span>{t("WaOwner")}</span>
|
||||
<select
|
||||
aria-label={t("WaOwner")}
|
||||
value={value}
|
||||
disabled={busy}
|
||||
onChange={(e) => {
|
||||
const v = e.target.value;
|
||||
setBusy(true);
|
||||
assignConversation(conv.uuid, v === "auto" ? null : Number(v), companyId)
|
||||
.then(onChange, () => {})
|
||||
.finally(() => setBusy(false));
|
||||
}}
|
||||
className="h-8 rounded-md border border-input bg-card px-2 text-sm text-foreground shadow-sm"
|
||||
>
|
||||
<option value="auto">{conv.ownerManual || !conv.ownerName ? t("WaAutomatic") : t("WaAutomaticIs", { name: conv.ownerName })}</option>
|
||||
{people.map((p) => (
|
||||
<option key={p.id} value={String(p.id)}>
|
||||
{p.name ?? `#${p.id}`}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
const STATUS_ICON = { pending: Clock, sent: Check, delivered: CheckCheck, read: CheckCheck } as const;
|
||||
|
||||
function Bubble({ m, companyId, onRetry }: { m: WhatsAppMessage; companyId: number | undefined; onRetry?: () => void }) {
|
||||
const t = useT();
|
||||
const out = m.direction === "OUT";
|
||||
const Icon = m.status && m.status !== "failed" ? STATUS_ICON[m.status] : null;
|
||||
return (
|
||||
<li
|
||||
data-direction={m.direction}
|
||||
className={cn(
|
||||
"max-w-[85%] rounded-lg px-3 py-2 text-sm sm:max-w-[70%]",
|
||||
out ? "self-end bg-accent text-accent-foreground" : "self-start bg-muted text-foreground",
|
||||
)}
|
||||
>
|
||||
<Content m={m} companyId={companyId} />
|
||||
<span className="mt-1 flex items-center justify-end gap-1 text-xs opacity-80 tabular-nums">
|
||||
{shortTime(m.createdAt)}
|
||||
{Icon && (
|
||||
<>
|
||||
<Icon aria-hidden="true" className="size-3.5" />
|
||||
<span>{t(`WaStatus_${m.status}`)}</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
{m.status === "failed" && (
|
||||
<span className="mt-1 flex flex-wrap items-center gap-2 text-xs text-destructive">
|
||||
{t("WaNotDelivered", { title: m.errorTitle ?? "", code: m.errorCode ?? "" })}
|
||||
{onRetry && (
|
||||
<Button variant="outline" size="xs" onClick={onRetry}>
|
||||
{t("UiRetry")}
|
||||
</Button>
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function Content({ m, companyId }: { m: WhatsAppMessage; companyId: number | undefined }) {
|
||||
const t = useT();
|
||||
const [expired, setExpired] = useState(false);
|
||||
const src = mediaUrl(m.uuid, companyId);
|
||||
const caption = m.body && <p className="whitespace-pre-wrap [overflow-wrap:anywhere]">{m.body}</p>;
|
||||
if (expired) return <p className="text-muted-foreground italic">{t("WaMediaExpired")}</p>;
|
||||
|
||||
switch (m.type) {
|
||||
case "text":
|
||||
case "template":
|
||||
return caption;
|
||||
case "image":
|
||||
case "sticker":
|
||||
return (
|
||||
<>
|
||||
{/* eslint-disable-next-line @next/next/no-img-element -- streamed through the portal proxy, not a static asset */}
|
||||
<img src={src} alt={t(m.type === "image" ? "WaImage" : "WaSticker")} onError={() => setExpired(true)} className="max-h-64 rounded-md" />
|
||||
{caption}
|
||||
</>
|
||||
);
|
||||
case "audio":
|
||||
return <audio controls src={src} onError={() => setExpired(true)} className="max-w-full" />;
|
||||
case "video":
|
||||
return (
|
||||
<>
|
||||
<video controls src={src} onError={() => setExpired(true)} className="max-h-64 max-w-full rounded-md" />
|
||||
{caption}
|
||||
</>
|
||||
);
|
||||
case "document":
|
||||
return (
|
||||
<>
|
||||
<a href={src} download={m.mediaFilename ?? undefined} className="inline-flex items-center gap-1.5 font-medium text-primary underline-offset-4 hover:underline">
|
||||
<FileText aria-hidden="true" className="size-4" />
|
||||
{m.mediaFilename || t("WaDocument")}
|
||||
</a>
|
||||
{caption}
|
||||
</>
|
||||
);
|
||||
case "location":
|
||||
return (
|
||||
<a
|
||||
href={`https://www.google.com/maps?q=${m.locationLat},${m.locationLng}`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="inline-flex items-center gap-1.5 font-medium text-primary underline-offset-4 hover:underline"
|
||||
>
|
||||
<MapPin aria-hidden="true" className="size-4" />
|
||||
{m.locationName || `${m.locationLat}, ${m.locationLng}`}
|
||||
</a>
|
||||
);
|
||||
default:
|
||||
return <p className="text-muted-foreground italic">{t("WaUnsupported")}</p>;
|
||||
}
|
||||
}
|
||||
@@ -397,6 +397,46 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
WaUnread: "{n} unread",
|
||||
WaOwnedBy: "{name} owns this chat.",
|
||||
WaOpenChat: "Open chat",
|
||||
WaTabMine: "Mine",
|
||||
WaTabAll: "All",
|
||||
WaUnassigned: "Unassigned",
|
||||
WaSearch: "Search name or number",
|
||||
WaListFailed: "The chats could not be loaded.",
|
||||
WaNoChats: "No chats here yet",
|
||||
WaPickChat: "Pick a chat to read it",
|
||||
WaChat: "Chat",
|
||||
WaBack: "All chats",
|
||||
WaLead: "Lead",
|
||||
WaOwner: "Owner",
|
||||
WaOwnerIs: "Owner: {name}",
|
||||
WaAutomatic: "Automatic",
|
||||
WaAutomaticIs: "Automatic ({name})",
|
||||
WaWindowOpen: "Replies open for {h} h",
|
||||
WaWindowClosed: "Window closed: send a template",
|
||||
WaWindowClosedHint: "The contact has not written in the last 24 hours, so only an approved template can be sent.",
|
||||
WaWindowClosedNow: "The reply window has closed. Send a template instead.",
|
||||
WaMessage: "Message",
|
||||
WaSend: "Send",
|
||||
WaSendFailed: "The message could not be sent.",
|
||||
WaThreadFailed: "The chat could not be loaded.",
|
||||
WaLoadOlder: "Load older messages",
|
||||
WaTemplate: "Template",
|
||||
WaChooseTemplate: "Choose a template",
|
||||
WaSendTemplate: "Send template",
|
||||
WaTemplateUnsupported: "Not supported",
|
||||
WaTemplatesFailed: "The templates could not be loaded.",
|
||||
WaNoTemplates: "No approved templates yet.",
|
||||
WaSyncTemplates: "Sync from Meta",
|
||||
WaStatus_pending: "Sending",
|
||||
WaStatus_sent: "Sent",
|
||||
WaStatus_delivered: "Delivered",
|
||||
WaStatus_read: "Read",
|
||||
WaNotDelivered: "Not delivered: {title} ({code})",
|
||||
WaMediaExpired: "Media expired",
|
||||
WaUnsupported: "This message type is not shown here",
|
||||
WaImage: "Image",
|
||||
WaSticker: "Sticker",
|
||||
WaDocument: "Document",
|
||||
WaNotConfigured: "WhatsApp is not set up for this company.",
|
||||
WaStartFailed: "The chat could not be started.",
|
||||
BO_EMAILS: "Emails",
|
||||
|
||||
@@ -14,7 +14,7 @@ describe("routeModules", () => {
|
||||
it("leaves other routes ungated", () => {
|
||||
expect(requiredModuleFor("/")).toBeUndefined();
|
||||
expect(requiredModulesFor("/members")).toBeUndefined();
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/audit-log", "/emails", "/event-leads", "/events", "/interests", "/leads", "/login-security", "/roles", "/users"]);
|
||||
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/audit-log", "/emails", "/event-leads", "/events", "/interests", "/leads", "/login-security", "/roles", "/users", "/whatsapp"]);
|
||||
expect(requiredModuleFor("/emails")).toBe("BO_EMAILS");
|
||||
expect(requiredModuleFor("/leads")).toBe("BO_LEADS");
|
||||
});
|
||||
|
||||
@@ -12,6 +12,7 @@ export const ROUTE_MODULES: Record<string, string> = {
|
||||
"/emails": "BO_EMAILS",
|
||||
"/login-security": "BO_LOGIN_SECURITY",
|
||||
"/audit-log": "BO_AUDIT_LOG",
|
||||
"/whatsapp": "BO_WHATSAPP",
|
||||
};
|
||||
|
||||
export function requiredModuleFor(pathname: string): string | undefined {
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const m = vi.hoisted(() => ({
|
||||
modules: ["BO_WHATSAPP"] as string[],
|
||||
listConversations: vi.fn(),
|
||||
getThread: vi.fn(),
|
||||
sendText: vi.fn(),
|
||||
sendTemplate: vi.fn(),
|
||||
markRead: vi.fn(),
|
||||
assignConversation: vi.fn(),
|
||||
listTemplates: vi.fn(),
|
||||
syncTemplates: vi.fn(),
|
||||
listAssignees: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({
|
||||
useAdminAuth: () => ({ id: 7, loading: false, hasModule: (x: string) => m.modules.includes(x) }),
|
||||
}));
|
||||
vi.mock("@/app/lib/CompanyScope", () => ({ useCompanyScope: () => ({ companyId: undefined }) }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
vi.mock("@/app/lib/services/whatsapp", () => ({
|
||||
listConversations: m.listConversations,
|
||||
getThread: m.getThread,
|
||||
sendText: m.sendText,
|
||||
sendTemplate: m.sendTemplate,
|
||||
markRead: m.markRead,
|
||||
assignConversation: m.assignConversation,
|
||||
listTemplates: m.listTemplates,
|
||||
syncTemplates: m.syncTemplates,
|
||||
listAssignees: m.listAssignees,
|
||||
mediaUrl: (uuid: string) => `/api/whatsapp/media/${uuid}`,
|
||||
}));
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import { requiredModuleFor } from "@/app/lib/routeModules";
|
||||
import WhatsAppPage from "./page";
|
||||
|
||||
const HOUR = 3600_000;
|
||||
const conv = (over: Record<string, unknown> = {}) => ({
|
||||
uuid: "c-1", companyId: 1, contactWaId: "60123456701", contactName: "Aisyah", leadUuid: "l-1", leadName: "Aisyah Rahman",
|
||||
ownerUserId: 7, ownerName: "Me", ownerManual: false, lastInboundAt: new Date(Date.now() - 21 * HOUR).toISOString(),
|
||||
lastMessageAt: "2026-12-02T02:00:00Z", lastMessagePreview: "Hi there", windowOpen: true, unreadCount: 0, ...over,
|
||||
});
|
||||
const msg = (over: Record<string, unknown> = {}) => ({
|
||||
uuid: "m-1", direction: "IN", type: "text", body: "Hello", templateName: null, mediaMime: null, mediaFilename: null,
|
||||
locationLat: null, locationLng: null, locationName: null, status: null, errorCode: null, errorTitle: null,
|
||||
sentByUserId: null, createdAt: "2026-12-02T02:00:00Z", statusAt: null, ...over,
|
||||
});
|
||||
const TEMPLATES = [
|
||||
{ name: "expo_followup", language: "en", category: "MARKETING", bodyText: "Hi {{1}}, thanks for visiting {{2}}.", paramCount: 2, supported: true },
|
||||
{ name: "promo_header", language: "en", category: "MARKETING", bodyText: "Promo", paramCount: 0, supported: false },
|
||||
];
|
||||
|
||||
const page = (items: unknown[]) => ({ items, total: items.length, page: 0, size: 30 });
|
||||
const thread = (c = conv(), messages: unknown[] = [msg()], hasOlder = false) => ({ conversation: c, messages, hasOlder });
|
||||
const flush = () => act(async () => {});
|
||||
const open = async (qs = "c=c-1") => {
|
||||
memoryRouter.reset("/whatsapp", qs);
|
||||
render(<WhatsAppPage />);
|
||||
await flush();
|
||||
};
|
||||
const threadPane = () => screen.getByRole("region", { name: "Chat" });
|
||||
|
||||
beforeEach(() => {
|
||||
m.modules = ["BO_WHATSAPP"];
|
||||
for (const f of Object.values(m)) if (typeof f === "function" && "mockReset" in f) f.mockReset();
|
||||
m.listConversations.mockResolvedValue(page([conv()]));
|
||||
m.getThread.mockResolvedValue(thread());
|
||||
m.markRead.mockResolvedValue(null);
|
||||
m.listTemplates.mockResolvedValue(TEMPLATES);
|
||||
m.listAssignees.mockResolvedValue([{ id: 5, name: "Sam Lee" }, { id: 7, name: "Me" }]);
|
||||
});
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
describe("WhatsApp inbox: access", () => {
|
||||
it("is gated by BO_WHATSAPP", () => {
|
||||
expect(requiredModuleFor("/whatsapp")).toBe("BO_WHATSAPP");
|
||||
});
|
||||
});
|
||||
|
||||
describe("WhatsApp inbox: list", () => {
|
||||
it("shows staff only their own chats", async () => {
|
||||
await open("");
|
||||
expect(screen.getAllByRole("tab").map((t) => t.textContent)).toEqual(["Mine"]);
|
||||
expect(m.listConversations).toHaveBeenCalledWith("mine", "", 0, undefined);
|
||||
});
|
||||
|
||||
it("gives a WhatsApp Admin the Unassigned and All tabs", async () => {
|
||||
m.modules = ["BO_WHATSAPP", "BO_WHATSAPP_ADMIN"];
|
||||
await open("");
|
||||
expect(screen.getAllByRole("tab").map((t) => t.textContent)).toEqual(["Mine", "Unassigned", "All"]);
|
||||
await act(async () => fireEvent.mouseDown(screen.getByRole("tab", { name: "Unassigned" })));
|
||||
await waitFor(() => expect(m.listConversations).toHaveBeenLastCalledWith("unassigned", "", 0, undefined));
|
||||
});
|
||||
|
||||
it("shows name, lead, preview and an unread marker; the owner only to admins", async () => {
|
||||
m.listConversations.mockResolvedValue(page([conv({ unreadCount: 2, ownerName: "Sam Lee" })]));
|
||||
await open("");
|
||||
const row = screen.getByRole("button", { name: /Aisyah/ });
|
||||
for (const text of ["Aisyah", "Aisyah Rahman", "Hi there", "2 unread"]) expect(within(row).getByText(text)).toBeTruthy();
|
||||
expect(within(row).queryByText("Sam Lee")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows the owner, or Unassigned, to a WhatsApp Admin", async () => {
|
||||
m.modules = ["BO_WHATSAPP", "BO_WHATSAPP_ADMIN"];
|
||||
m.listConversations.mockResolvedValue(page([conv({ ownerName: "Sam Lee" }), conv({ uuid: "c-2", contactName: null, leadName: null, ownerUserId: null, ownerName: null })]));
|
||||
await open("");
|
||||
expect(within(screen.getByRole("button", { name: /Aisyah/ })).getByText("Sam Lee")).toBeTruthy();
|
||||
expect(within(screen.getByRole("button", { name: /60123456701/ })).getByText("Unassigned")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("searches by name or number", async () => {
|
||||
await open("");
|
||||
fireEvent.change(screen.getByRole("searchbox", { name: "Search name or number" }), { target: { value: "6012" } });
|
||||
await waitFor(() => expect(m.listConversations).toHaveBeenLastCalledWith("mine", "6012", 0, undefined));
|
||||
});
|
||||
|
||||
it("says WhatsApp is not set up when the company has no number", async () => {
|
||||
m.listConversations.mockRejectedValue(new ApiError("x", 409, { code: "WHATSAPP_NOT_CONFIGURED" }));
|
||||
await open("");
|
||||
expect(screen.getByText("WhatsApp is not set up for this company.")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("opens a chat from the list into the URL", async () => {
|
||||
await open("");
|
||||
await act(async () => fireEvent.click(screen.getByRole("button", { name: /Aisyah/ })));
|
||||
expect(memoryRouter.getSearch().get("c")).toBe("c-1");
|
||||
await waitFor(() => expect(m.getThread).toHaveBeenCalledWith("c-1", undefined, undefined));
|
||||
});
|
||||
|
||||
it("re-reads the list every 30 seconds and an open chat every 10", async () => {
|
||||
vi.useFakeTimers();
|
||||
await open();
|
||||
expect(m.listConversations).toHaveBeenCalledTimes(1);
|
||||
expect(m.getThread).toHaveBeenCalledTimes(1);
|
||||
await act(async () => vi.advanceTimersByTime(10_000));
|
||||
expect(m.getThread).toHaveBeenCalledTimes(2);
|
||||
await act(async () => vi.advanceTimersByTime(20_000));
|
||||
expect(m.listConversations).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("WhatsApp inbox: thread", () => {
|
||||
it("marks an unread chat read and tells the sidebar", async () => {
|
||||
m.getThread.mockResolvedValue(thread(conv({ unreadCount: 3 })));
|
||||
const heard = vi.fn();
|
||||
window.addEventListener("whatsapp-unread-changed", heard);
|
||||
await open();
|
||||
await waitFor(() => expect(m.markRead).toHaveBeenCalledWith("c-1", undefined));
|
||||
await waitFor(() => expect(heard).toHaveBeenCalled());
|
||||
window.removeEventListener("whatsapp-unread-changed", heard);
|
||||
});
|
||||
|
||||
it("does not mark a chat with nothing unread", async () => {
|
||||
await open();
|
||||
expect(m.markRead).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows the contact, a link to the lead and the reply window", async () => {
|
||||
await open();
|
||||
const pane = threadPane();
|
||||
expect(within(pane).getByRole("heading", { name: "Aisyah" })).toBeTruthy();
|
||||
expect(within(pane).getByRole("link", { name: "Aisyah Rahman" })).toHaveAttribute("href", "/leads/l-1");
|
||||
expect(within(pane).getByText("Replies open for 3 h")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows bubbles with their delivery state, and a failure with its reason and Retry", async () => {
|
||||
m.getThread.mockResolvedValue(thread(conv(), [
|
||||
msg(),
|
||||
msg({ uuid: "m-2", direction: "OUT", body: "Welcome", status: "read" }),
|
||||
msg({ uuid: "m-3", direction: "OUT", body: "Again", status: "failed", errorCode: "131026", errorTitle: "Message undeliverable" }),
|
||||
]));
|
||||
m.sendText.mockResolvedValue(msg({ uuid: "m-4", direction: "OUT", body: "Again", status: "sent" }));
|
||||
await open();
|
||||
const pane = threadPane();
|
||||
expect(within(pane).getByText("Hello").closest("[data-direction]")).toHaveAttribute("data-direction", "IN");
|
||||
expect(within(pane).getByText("Welcome").closest("[data-direction]")).toHaveAttribute("data-direction", "OUT");
|
||||
expect(within(pane).getByText("Read")).toBeTruthy();
|
||||
expect(within(pane).getByText("Not delivered: Message undeliverable (131026)")).toBeTruthy();
|
||||
await act(async () => fireEvent.click(within(pane).getByRole("button", { name: "Retry" })));
|
||||
expect(m.sendText).toHaveBeenCalledWith("c-1", "Again", undefined);
|
||||
});
|
||||
|
||||
it("sends a text inside the window and shows it", async () => {
|
||||
m.sendText.mockResolvedValue(msg({ uuid: "m-9", direction: "OUT", body: "On my way", status: "pending" }));
|
||||
await open();
|
||||
const pane = threadPane();
|
||||
fireEvent.change(within(pane).getByRole("textbox", { name: "Message" }), { target: { value: "On my way" } });
|
||||
await act(async () => fireEvent.click(within(pane).getByRole("button", { name: "Send" })));
|
||||
expect(m.sendText).toHaveBeenCalledWith("c-1", "On my way", undefined);
|
||||
expect(within(pane).getByText("On my way")).toBeTruthy();
|
||||
expect((within(pane).getByRole("textbox", { name: "Message" }) as HTMLTextAreaElement).value).toBe("");
|
||||
});
|
||||
|
||||
it("offers only templates once the window has closed", async () => {
|
||||
m.getThread.mockResolvedValue(thread(conv({ windowOpen: false, lastInboundAt: null })));
|
||||
await open();
|
||||
const pane = threadPane();
|
||||
expect(within(pane).queryByRole("textbox", { name: "Message" })).toBeNull();
|
||||
expect(within(pane).getByText("Window closed: send a template")).toBeTruthy();
|
||||
expect(within(pane).getByRole("button", { name: "Template" })).toBeTruthy();
|
||||
});
|
||||
|
||||
it("refreshes when a text is refused because the window just closed", async () => {
|
||||
m.sendText.mockRejectedValue(new ApiError("x", 409, { code: "WINDOW_CLOSED" }));
|
||||
await open();
|
||||
const pane = threadPane();
|
||||
fireEvent.change(within(pane).getByRole("textbox", { name: "Message" }), { target: { value: "late" } });
|
||||
m.getThread.mockResolvedValue(thread(conv({ windowOpen: false })));
|
||||
await act(async () => fireEvent.click(within(pane).getByRole("button", { name: "Send" })));
|
||||
expect(within(pane).getByText("The reply window has closed. Send a template instead.")).toBeTruthy();
|
||||
await waitFor(() => expect(within(pane).queryByRole("textbox", { name: "Message" })).toBeNull());
|
||||
});
|
||||
|
||||
it("sends a template with every field filled", async () => {
|
||||
m.sendTemplate.mockResolvedValue(msg({ uuid: "m-5", direction: "OUT", type: "template", body: "Hi Aisyah, thanks for visiting Expo.", templateName: "expo_followup", status: "pending" }));
|
||||
await open();
|
||||
await act(async () => fireEvent.click(within(threadPane()).getByRole("button", { name: "Template" })));
|
||||
const dialog = screen.getByRole("dialog");
|
||||
expect(within(dialog).getByRole("button", { name: /promo_header/ })).toBeDisabled();
|
||||
await act(async () => fireEvent.click(within(dialog).getByRole("button", { name: /expo_followup/ })));
|
||||
const send = within(dialog).getByRole("button", { name: "Send template" });
|
||||
expect(send).toBeDisabled();
|
||||
fireEvent.change(within(dialog).getByRole("textbox", { name: "{{1}}" }), { target: { value: "Aisyah" } });
|
||||
fireEvent.change(within(dialog).getByRole("textbox", { name: "{{2}}" }), { target: { value: "Expo" } });
|
||||
expect(within(dialog).getByText("Hi Aisyah, thanks for visiting Expo.")).toBeTruthy();
|
||||
await act(async () => fireEvent.click(send));
|
||||
expect(m.sendTemplate).toHaveBeenCalledWith("c-1", TEMPLATES[0], ["Aisyah", "Expo"], undefined);
|
||||
expect(screen.queryByRole("dialog")).toBeNull();
|
||||
});
|
||||
|
||||
it("lets a WhatsApp Admin reassign or hand back to automatic", async () => {
|
||||
m.modules = ["BO_WHATSAPP", "BO_WHATSAPP_ADMIN"];
|
||||
m.assignConversation.mockResolvedValue(conv({ ownerUserId: 5, ownerName: "Sam Lee", ownerManual: true }));
|
||||
await open();
|
||||
const select = await within(threadPane()).findByRole("combobox", { name: "Owner" });
|
||||
await waitFor(() => expect(within(select).getByRole("option", { name: "Sam Lee" })).toBeTruthy());
|
||||
await act(async () => fireEvent.change(select, { target: { value: "5" } }));
|
||||
expect(m.assignConversation).toHaveBeenCalledWith("c-1", 5, undefined);
|
||||
await act(async () => fireEvent.change(select, { target: { value: "auto" } }));
|
||||
expect(m.assignConversation).toHaveBeenLastCalledWith("c-1", null, undefined);
|
||||
});
|
||||
|
||||
it("gives staff no reassign control", async () => {
|
||||
await open();
|
||||
expect(within(threadPane()).queryByRole("combobox", { name: "Owner" })).toBeNull();
|
||||
expect(m.listAssignees).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows media through the portal and marks expired images", async () => {
|
||||
m.getThread.mockResolvedValue(thread(conv(), [
|
||||
msg({ uuid: "img", type: "image", body: null, mediaMime: "image/jpeg" }),
|
||||
msg({ uuid: "doc", type: "document", body: null, mediaMime: "application/pdf", mediaFilename: "brochure.pdf" }),
|
||||
msg({ uuid: "loc", type: "location", body: null, locationLat: 3.1, locationLng: 101.6, locationName: "KLCC" }),
|
||||
msg({ uuid: "odd", type: "unsupported", body: null }),
|
||||
]));
|
||||
await open();
|
||||
const pane = threadPane();
|
||||
const img = within(pane).getByRole("img", { name: "Image" });
|
||||
expect(img).toHaveAttribute("src", "/api/whatsapp/media/img");
|
||||
expect(within(pane).getByRole("link", { name: "brochure.pdf" })).toHaveAttribute("href", "/api/whatsapp/media/doc");
|
||||
expect(within(pane).getByRole("link", { name: "KLCC" })).toHaveAttribute("href", "https://www.google.com/maps?q=3.1,101.6");
|
||||
expect(within(pane).getByText("This message type is not shown here")).toBeTruthy();
|
||||
fireEvent.error(img);
|
||||
expect(within(pane).getByText("Media expired")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("loads older messages above the current ones", async () => {
|
||||
m.getThread.mockResolvedValueOnce(thread(conv(), [msg({ uuid: "m-10", body: "Newer" })], true));
|
||||
m.getThread.mockResolvedValueOnce(thread(conv(), [msg({ uuid: "m-9", body: "Older" })], false));
|
||||
await open();
|
||||
const pane = threadPane();
|
||||
await act(async () => fireEvent.click(within(pane).getByRole("button", { name: "Load older messages" })));
|
||||
expect(m.getThread).toHaveBeenLastCalledWith("c-1", "m-10", undefined);
|
||||
const texts = within(pane).getAllByText(/Older|Newer/).map((e) => e.textContent);
|
||||
expect(texts).toEqual(["Older", "Newer"]);
|
||||
expect(within(pane).queryByRole("button", { name: "Load older messages" })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
"use client";
|
||||
|
||||
import { MessageCircle } from "lucide-react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { PageHeader } from "@/app/components/ui/page-header";
|
||||
import { EmptyState } from "@/app/components/ui/states";
|
||||
import { ConversationList } from "@/app/components/whatsapp/ConversationList";
|
||||
import { Thread } from "@/app/components/whatsapp/Thread";
|
||||
import { RequireModule } from "@/app/lib/RequireModule";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { cn } from "@/app/lib/utils";
|
||||
|
||||
/** The inbox: list and chat side by side from lg; on phones the list, then the chat with a way back. */
|
||||
function Inbox() {
|
||||
const t = useT();
|
||||
const { hasModule } = useAdminAuth();
|
||||
const { companyId } = useCompanyScope();
|
||||
const admin = hasModule("BO_WHATSAPP_ADMIN");
|
||||
const router = useRouter();
|
||||
const selected = useSearchParams().get("c");
|
||||
const show = (uuid: string | null) => router.replace(uuid ? `/whatsapp?c=${encodeURIComponent(uuid)}` : "/whatsapp");
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title={t("BO_WHATSAPP")} />
|
||||
<div className="grid h-[calc(100svh-10rem)] min-h-[28rem] overflow-hidden rounded-lg border bg-card shadow-card lg:grid-cols-[22rem_1fr]">
|
||||
<aside className={cn("flex min-h-0 flex-col lg:border-r", selected && "max-lg:hidden")}>
|
||||
<ConversationList admin={admin} companyId={companyId} selected={selected} onSelect={show} />
|
||||
</aside>
|
||||
<section aria-label={t("WaChat")} className={cn("flex min-h-0 flex-col", !selected && "max-lg:hidden")}>
|
||||
{selected ? (
|
||||
<Thread key={selected} uuid={selected} companyId={companyId} admin={admin} onBack={() => show(null)} />
|
||||
) : (
|
||||
<EmptyState title={t("WaPickChat")} icon={<MessageCircle className="size-8" />} className="my-auto" />
|
||||
)}
|
||||
</section>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default function WhatsAppPage() {
|
||||
return (
|
||||
<RequireModule pathname="/whatsapp">
|
||||
<Inbox />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user