Files
co-lite/solvway-admin-portal/app/components/whatsapp/Thread.tsx
T
ngqileandClaude Opus 5.5 8984c7c1ae fix(portal): inbox fixes from the live check
- The list stayed on its skeleton under StrictMode: an unmount flag never
  reset. Dropped it; a late result on an unmounted list is harmless.
- A message sent from the page kept its first status: the server's copy
  now wins, so ticks move on.
- Templates and their sync use the chat's company when a super admin has
  no company picked.
- A manual owner outside the assignee list (a super admin) shows in the
  Owner select.
- The chat column can shrink to a 360 px screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
2026-12-02 11:31:01 +08:00

347 lines
13 KiB
TypeScript

"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 no poll has returned yet; each uuid once.
* The server's copy wins over the one kept from the send, so delivery ticks move on.
*/
function merge(older: WhatsAppMessage[], latest: WhatsAppMessage[], local: WhatsAppMessage[]) {
const byUuid = new Map<string, WhatsAppMessage>();
for (const m of [...older, ...latest]) byUuid.set(m.uuid, m);
for (const m of local) if (!byUuid.has(m.uuid)) 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 min-w-0 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 ?? conv.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>
{value !== "auto" && !people.some((p) => String(p.id) === value) && <option value={value}>{conv.ownerName ?? `#${value}`}</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>;
}
}