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
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-12-02 11:31:01 +08:00
1 parent 62d919941b
commit 8984c7c1ae
4 files changed
+59 -14

No files matched your search

@@ -1,6 +1,6 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useEffect, useState } from "react";
import { MessageCircle } from "lucide-react";
import { Input } from "@/app/components/ui/input";
import { Tabs, TabsList, TabsTrigger } from "@/app/components/ui/tabs";
@@ -66,18 +66,13 @@ function Rows({ tab, query, companyId, admin, selected, onSelect }: Props & { ta
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");
},
@@ -24,10 +24,14 @@ 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[][]) {
/**
* 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 list of lists) for (const m of list) byUuid.set(m.uuid, m);
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()];
}
@@ -177,7 +181,7 @@ export function Thread({ uuid, companyId, admin, onBack }: Props) {
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"
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")}
@@ -198,7 +202,7 @@ export function Thread({ uuid, companyId, admin, onBack }: Props) {
open={picker}
onOpenChange={setPicker}
conversationUuid={uuid}
companyId={companyId}
companyId={companyId ?? conv.companyId}
admin={admin}
onSent={(m) => setLocal((l) => [...l, m])}
/>
@@ -236,6 +240,7 @@ function OwnerSelect({ conv, companyId, onChange }: { conv: WhatsAppConversation
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}`}
@@ -1,5 +1,6 @@
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { StrictMode } from "react";
import { ApiError } from "@/app/lib/clientApi";
const m = vi.hoisted(() => ({
@@ -80,6 +81,17 @@ describe("WhatsApp inbox: access", () => {
});
});
describe("WhatsApp inbox: phone layout", () => {
// jsdom applies no CSS, so this guards the classes that keep the chat inside a 360 px screen.
it("lets the chat column shrink below its content width", async () => {
await open();
const pane = threadPane();
expect(pane.className).toContain("min-w-0");
expect(pane.parentElement!.className).toContain("grid-cols-[minmax(0,1fr)]");
expect(within(pane).getByRole("textbox", { name: "Message" }).className).toContain("min-w-0");
});
});
describe("WhatsApp inbox: list", () => {
it("shows staff only their own chats", async () => {
await open("");
@@ -111,6 +123,13 @@ describe("WhatsApp inbox: list", () => {
expect(within(screen.getByRole("button", { name: /60123456701/ })).getByText("Unassigned")).toBeTruthy();
});
it("shows the chats under React StrictMode, as the dev server renders them", async () => {
memoryRouter.reset("/whatsapp", "");
render(<StrictMode><WhatsAppPage /></StrictMode>);
await flush();
expect(screen.getByRole("button", { name: /Aisyah/ })).toBeTruthy();
});
it("searches by name or number", async () => {
await open("");
fireEvent.change(screen.getByRole("searchbox", { name: "Search name or number" }), { target: { value: "6012" } });
@@ -194,6 +213,20 @@ describe("WhatsApp inbox: thread", () => {
expect((within(pane).getByRole("textbox", { name: "Message" }) as HTMLTextAreaElement).value).toBe("");
});
it("shows the server's newer state for a message sent here", async () => {
vi.useFakeTimers();
m.sendText.mockResolvedValue(msg({ uuid: "m-9", direction: "OUT", body: "On my way", status: "sent" }));
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(within(pane).getByText("Sent")).toBeTruthy();
m.getThread.mockResolvedValue(thread(conv(), [msg(), msg({ uuid: "m-9", direction: "OUT", body: "On my way", status: "read" })]));
await act(async () => vi.advanceTimersByTime(10_000));
expect(within(pane).getByText("Read")).toBeTruthy();
expect(within(pane).getAllByText("On my way")).toHaveLength(1);
});
it("offers only templates once the window has closed", async () => {
m.getThread.mockResolvedValue(thread(conv({ windowOpen: false, lastInboundAt: null })));
await open();
@@ -227,7 +260,9 @@ describe("WhatsApp inbox: thread", () => {
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);
// No company picked (super admin on All companies): templates belong to the chat's company.
expect(m.listTemplates).toHaveBeenCalledWith(1);
expect(m.sendTemplate).toHaveBeenCalledWith("c-1", TEMPLATES[0], ["Aisyah", "Expo"], 1);
expect(screen.queryByRole("dialog")).toBeNull();
});
@@ -243,6 +278,16 @@ describe("WhatsApp inbox: thread", () => {
expect(m.assignConversation).toHaveBeenLastCalledWith("c-1", null, undefined);
});
it("shows a manual owner who is not on the assignee list", async () => {
m.modules = ["BO_WHATSAPP", "BO_WHATSAPP_ADMIN"];
m.getThread.mockResolvedValue(thread(conv({ ownerUserId: 1, ownerName: "Admin", ownerManual: true })));
await open();
const select = (await within(threadPane()).findByRole("combobox", { name: "Owner" })) as HTMLSelectElement;
await waitFor(() => expect(within(select).getByRole("option", { name: "Sam Lee" })).toBeTruthy());
expect(select.value).toBe("1");
expect(within(select).getByRole("option", { name: "Admin" })).toBeTruthy();
});
it("gives staff no reassign control", async () => {
await open();
expect(within(threadPane()).queryByRole("combobox", { name: "Owner" })).toBeNull();
+2 -2
View File
@@ -25,11 +25,11 @@ function Inbox() {
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]">
<div className="grid h-[calc(100svh-10rem)] min-h-[28rem] grid-cols-[minmax(0,1fr)] overflow-hidden rounded-lg border bg-card shadow-card lg:grid-cols-[22rem_minmax(0,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")}>
<section aria-label={t("WaChat")} className={cn("flex min-h-0 min-w-0 flex-col", !selected && "max-lg:hidden")}>
{selected ? (
<Thread key={selected} uuid={selected} companyId={companyId} admin={admin} onBack={() => show(null)} />
) : (