feat(portal): WhatsApp sidebar entry with unread badge, start-chat buttons on leads
The badge polls the unread count every 30 s and on whatsapp-unread-changed, only for users holding BO_WHATSAPP. The button sits next to the mobile number on Leads and Event leads; it opens the chat when the starter owns it and otherwise says who does. 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
1d5e792e3d
commit
f7bfea44c7
11 files changed
+402
-11
No files matched your search
@@ -12,6 +12,8 @@ import { cn } from "@/app/lib/utils";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@/app/components/ui/popover";
|
||||
import PoweredBy from "./PoweredBy";
|
||||
import { usePolling } from "@/app/lib/hooks/usePolling";
|
||||
import { unreadCount } from "@/app/lib/services/whatsapp";
|
||||
|
||||
// The wordmark is the brand name: data, not translatable copy.
|
||||
const BRAND = "Co-Lite";
|
||||
@@ -26,7 +28,26 @@ const BRAND = "Co-Lite";
|
||||
|
||||
type NavProps = { trail: SidebarLink[]; onNavigate?: () => void };
|
||||
|
||||
function NavNode({ link, depth, trail, onNavigate }: { link: SidebarLink; depth: number } & NavProps) {
|
||||
const WHATSAPP = "BO_WHATSAPP";
|
||||
|
||||
/** Unread WhatsApp chats for the signed-in user; 0 without the module. A failed read keeps the last count. */
|
||||
function useWhatsAppUnread(enabled: boolean) {
|
||||
const [count, setCount] = useState(0);
|
||||
usePolling(
|
||||
() => {
|
||||
unreadCount().then((r) => setCount(r?.count ?? 0), () => {});
|
||||
},
|
||||
30_000,
|
||||
"whatsapp-unread-changed",
|
||||
enabled,
|
||||
);
|
||||
return enabled ? count : 0;
|
||||
}
|
||||
|
||||
const badgeText = (n: number) => (n > 99 ? "99+" : String(n));
|
||||
const badgeClass = "rounded-full bg-primary px-1.5 text-xs leading-5 font-semibold text-primary-foreground tabular-nums";
|
||||
|
||||
function NavNode({ link, depth, trail, onNavigate, badge = 0 }: { link: SidebarLink; depth: number; badge?: number } & NavProps) {
|
||||
const t = useT();
|
||||
const Icon = iconFor(link.iconName);
|
||||
const hasChildren = link.children.length > 0;
|
||||
@@ -38,6 +59,7 @@ function NavNode({ link, depth, trail, onNavigate }: { link: SidebarLink; depth:
|
||||
<Link
|
||||
href={link.url}
|
||||
aria-current={active ? "page" : undefined}
|
||||
aria-label={badge > 0 ? `${t(link.name)} ${t("WaUnread", { n: badge })}` : undefined}
|
||||
onClick={onNavigate}
|
||||
className={cn(
|
||||
"flex items-center gap-3 rounded-lg px-3 transition-colors",
|
||||
@@ -53,6 +75,11 @@ function NavNode({ link, depth, trail, onNavigate }: { link: SidebarLink; depth:
|
||||
reference it returns is stable across renders for a given iconName. */}
|
||||
{Icon && <Icon aria-hidden="true" className="size-5 shrink-0" />}
|
||||
<span className="truncate">{t(link.name)}</span>
|
||||
{badge > 0 && (
|
||||
<span aria-hidden="true" className={cn("ml-auto", badgeClass)}>
|
||||
{badgeText(badge)}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
@@ -125,10 +152,11 @@ const railItemClass = cn(
|
||||
const railIdleClass = "text-muted-foreground hover:bg-muted hover:text-foreground";
|
||||
const railActiveClass = "bg-sidebar-accent text-sidebar-accent-foreground";
|
||||
|
||||
function RailNode({ link, trail }: { link: SidebarLink; trail: SidebarLink[] }) {
|
||||
function RailNode({ link, trail, badge = 0 }: { link: SidebarLink; trail: SidebarLink[]; badge?: number }) {
|
||||
const t = useT();
|
||||
const Icon = iconFor(link.iconName);
|
||||
const label = t(link.name);
|
||||
const named = badge > 0 ? `${label} ${t("WaUnread", { n: badge })}` : label;
|
||||
|
||||
if (link.children.length === 0) {
|
||||
const active = trail[trail.length - 1] === link;
|
||||
@@ -137,12 +165,17 @@ function RailNode({ link, trail }: { link: SidebarLink; trail: SidebarLink[] })
|
||||
<Link
|
||||
href={link.url}
|
||||
aria-current={active ? "page" : undefined}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className={cn(railItemClass, active ? railActiveClass : railIdleClass)}
|
||||
aria-label={named}
|
||||
title={named}
|
||||
className={cn("relative", railItemClass, active ? railActiveClass : railIdleClass)}
|
||||
>
|
||||
{/* eslint-disable-next-line react-hooks/static-components -- stable icon-map lookup, as in NavNode. */}
|
||||
{Icon && <Icon aria-hidden="true" className="size-5 shrink-0" />}
|
||||
{badge > 0 && (
|
||||
<span aria-hidden="true" className={cn("absolute -top-1 -right-1 min-w-5 text-center", badgeClass)}>
|
||||
{badgeText(badge)}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
</li>
|
||||
);
|
||||
@@ -216,14 +249,22 @@ export function SidebarNav({ onNavigate, collapsed = false }: { onNavigate?: ()
|
||||
const t = useT();
|
||||
const links = useAclSidebar();
|
||||
const sections = groupSidebar(links);
|
||||
const unread = useWhatsAppUnread(links.some((l) => l.name === WHATSAPP));
|
||||
// Trail from the grouped links: groupSidebar copies them, and active matching is by identity.
|
||||
const trail = currentTrail(sections.flatMap((s) => s.links), usePathname());
|
||||
const idBase = useId();
|
||||
const render = (link: SidebarLink) =>
|
||||
collapsed ? (
|
||||
<RailNode key={link.url || link.name} link={link} trail={trail} />
|
||||
<RailNode key={link.url || link.name} link={link} trail={trail} badge={link.name === WHATSAPP ? unread : 0} />
|
||||
) : (
|
||||
<NavNode key={link.url || link.name} link={link} depth={0} trail={trail} onNavigate={onNavigate} />
|
||||
<NavNode
|
||||
key={link.url || link.name}
|
||||
link={link}
|
||||
depth={0}
|
||||
trail={trail}
|
||||
onNavigate={onNavigate}
|
||||
badge={link.name === WHATSAPP ? unread : 0}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { act, render, screen, within } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
|
||||
import type { SidebarLink } from "@/app/lib/aclSidebar";
|
||||
|
||||
const state = vi.hoisted(() => ({ links: [] as SidebarLink[], unread: vi.fn() }));
|
||||
|
||||
vi.mock("next/navigation", () => ({ usePathname: () => "/" }));
|
||||
vi.mock("@/app/lib/useAclSidebar", () => ({ useAclSidebar: () => state.links }));
|
||||
vi.mock("@/app/lib/services/whatsapp", () => ({ unreadCount: state.unread }));
|
||||
|
||||
import { SidebarNav } from "./Sidebar";
|
||||
import { iconFor } from "./icon-map";
|
||||
|
||||
const link = (name: string, iconName = "Users"): SidebarLink => ({ name, url: `/${name}`, iconName, children: [] });
|
||||
const LEADS = [link("BO_LEADS"), link("BO_INTERESTS"), link("BO_WHATSAPP", "MessageCircle")];
|
||||
const hrefs = (list: HTMLElement) => within(list).getAllByRole("link").map((a) => a.getAttribute("href")?.slice(1));
|
||||
const flush = () => act(async () => {});
|
||||
|
||||
beforeEach(() => {
|
||||
state.unread.mockReset();
|
||||
state.unread.mockResolvedValue({ count: 0 });
|
||||
});
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
describe("Sidebar WhatsApp entry", () => {
|
||||
it("sits in the Leads section after Leads", async () => {
|
||||
state.links = [...LEADS].reverse();
|
||||
render(<SidebarNav />);
|
||||
await flush();
|
||||
expect(hrefs(screen.getByRole("list", { name: "Leads" }))).toEqual(["BO_LEADS", "BO_WHATSAPP", "BO_INTERESTS"]);
|
||||
});
|
||||
|
||||
it("has its own icon, not the fallback", () => {
|
||||
expect(iconFor("MessageCircle")).not.toBe(iconFor(undefined));
|
||||
});
|
||||
|
||||
it("shows the unread count as a badge", async () => {
|
||||
state.links = LEADS;
|
||||
state.unread.mockResolvedValue({ count: 3 });
|
||||
render(<SidebarNav />);
|
||||
await flush();
|
||||
const entry = screen.getByRole("link", { name: /WhatsApp/ });
|
||||
expect(entry).toHaveAccessibleName("WhatsApp 3 unread");
|
||||
expect(within(entry).getByText("3")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("shows no badge at zero", async () => {
|
||||
state.links = LEADS;
|
||||
render(<SidebarNav />);
|
||||
await flush();
|
||||
expect(screen.getByRole("link", { name: /WhatsApp/ })).toHaveAccessibleName("WhatsApp");
|
||||
});
|
||||
|
||||
it("caps a large count at 99+", async () => {
|
||||
state.links = LEADS;
|
||||
state.unread.mockResolvedValue({ count: 250 });
|
||||
render(<SidebarNav />);
|
||||
await flush();
|
||||
expect(within(screen.getByRole("link", { name: /WhatsApp/ })).getByText("99+")).toBeTruthy();
|
||||
});
|
||||
|
||||
it("does not ask for the count without the WhatsApp module", async () => {
|
||||
state.links = [link("BO_LEADS")];
|
||||
render(<SidebarNav />);
|
||||
await flush();
|
||||
expect(state.unread).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps quiet when the count cannot be read", async () => {
|
||||
state.links = LEADS;
|
||||
state.unread.mockRejectedValue(new Error("WHATSAPP_NOT_CONFIGURED"));
|
||||
render(<SidebarNav />);
|
||||
await flush();
|
||||
expect(screen.getByRole("link", { name: /WhatsApp/ })).toHaveAccessibleName("WhatsApp");
|
||||
});
|
||||
|
||||
it("re-reads every 30 seconds and when the inbox marks a chat read", async () => {
|
||||
vi.useFakeTimers();
|
||||
state.links = LEADS;
|
||||
render(<SidebarNav />);
|
||||
await flush();
|
||||
expect(state.unread).toHaveBeenCalledTimes(1);
|
||||
await act(async () => vi.advanceTimersByTime(30_000));
|
||||
expect(state.unread).toHaveBeenCalledTimes(2);
|
||||
state.unread.mockResolvedValue({ count: 1 });
|
||||
await act(async () => window.dispatchEvent(new Event("whatsapp-unread-changed")));
|
||||
expect(state.unread).toHaveBeenCalledTimes(3);
|
||||
expect(screen.getByRole("link", { name: /WhatsApp/ })).toHaveAccessibleName("WhatsApp 1 unread");
|
||||
});
|
||||
|
||||
it("shows the badge in the collapsed rail too", async () => {
|
||||
state.links = LEADS;
|
||||
state.unread.mockResolvedValue({ count: 2 });
|
||||
render(<SidebarNav collapsed />);
|
||||
await flush();
|
||||
const entry = screen.getByRole("link", { name: /WhatsApp/ });
|
||||
expect(entry).toHaveAccessibleName("WhatsApp 2 unread");
|
||||
expect(within(entry).getByText("2")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import { act, fireEvent, render, screen } from "@testing-library/react";
|
||||
import { beforeEach, describe, it, expect, vi } from "vitest";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
|
||||
const m = vi.hoisted(() => ({ modules: ["BO_WHATSAPP"] as string[], push: vi.fn(), startChat: vi.fn() }));
|
||||
|
||||
vi.mock("next/navigation", () => ({ useRouter: () => ({ push: m.push }) }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({
|
||||
useAdminAuth: () => ({ id: 7, hasModule: (x: string) => m.modules.includes(x) }),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/whatsapp", () => ({ startChat: m.startChat }));
|
||||
|
||||
import { WhatsAppButton } from "./WhatsAppButton";
|
||||
|
||||
const conv = (ownerUserId: number | null, ownerName: string | null = null) => ({ uuid: "c-1", ownerUserId, ownerName });
|
||||
const press = () => act(async () => fireEvent.click(screen.getByRole("button", { name: "WhatsApp" })));
|
||||
|
||||
beforeEach(() => {
|
||||
m.modules = ["BO_WHATSAPP"];
|
||||
m.push.mockReset();
|
||||
m.startChat.mockReset();
|
||||
});
|
||||
|
||||
describe("WhatsAppButton", () => {
|
||||
it("is hidden without the WhatsApp module", () => {
|
||||
m.modules = [];
|
||||
render(<WhatsAppButton target={{ leadUuid: "L1" }} mobile="+60123" />);
|
||||
expect(screen.queryByRole("button", { name: "WhatsApp" })).toBeNull();
|
||||
});
|
||||
|
||||
it("is hidden when the lead has no mobile number", () => {
|
||||
render(<WhatsAppButton target={{ leadUuid: "L1" }} mobile={null} />);
|
||||
expect(screen.queryByRole("button", { name: "WhatsApp" })).toBeNull();
|
||||
});
|
||||
|
||||
it("starts the chat and opens it when the starter owns it", async () => {
|
||||
m.startChat.mockResolvedValue(conv(7));
|
||||
render(<WhatsAppButton target={{ eventLeadUuid: "E1" }} mobile="+60123" />);
|
||||
await press();
|
||||
expect(m.startChat).toHaveBeenCalledWith({ eventLeadUuid: "E1" });
|
||||
expect(m.push).toHaveBeenCalledWith("/whatsapp?c=c-1");
|
||||
});
|
||||
|
||||
it("says who owns the chat when someone else does, and stays put", async () => {
|
||||
m.startChat.mockResolvedValue(conv(9, "Sam Lee"));
|
||||
render(<WhatsAppButton target={{ leadUuid: "L1" }} mobile="+60123" />);
|
||||
await press();
|
||||
expect(m.push).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole("status")).toHaveTextContent("Sam Lee owns this chat.");
|
||||
});
|
||||
|
||||
it("says WhatsApp is not set up when the company has no number", async () => {
|
||||
m.startChat.mockRejectedValue(new ApiError("x", 409, { code: "WHATSAPP_NOT_CONFIGURED" }));
|
||||
render(<WhatsAppButton target={{ leadUuid: "L1" }} mobile="+60123" />);
|
||||
await press();
|
||||
expect(screen.getByRole("status")).toHaveTextContent("WhatsApp is not set up for this company.");
|
||||
});
|
||||
|
||||
it("reports any other failure", async () => {
|
||||
m.startChat.mockRejectedValue(new Error("boom"));
|
||||
render(<WhatsAppButton target={{ leadUuid: "L1" }} mobile="+60123" />);
|
||||
await press();
|
||||
expect(screen.getByRole("status")).toHaveTextContent("The chat could not be started.");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,60 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { MessageCircle } from "lucide-react";
|
||||
import { Button } from "@/app/components/ui/button";
|
||||
import { Popover, PopoverAnchor, PopoverContent } from "@/app/components/ui/popover";
|
||||
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
||||
import { ApiError } from "@/app/lib/clientApi";
|
||||
import { startChat } from "@/app/lib/services/whatsapp";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
|
||||
type Target = { leadUuid: string } | { eventLeadUuid: string };
|
||||
|
||||
/** Starts (or reopens) a WhatsApp chat with a lead. Opens it when the starter owns it; otherwise says who does. */
|
||||
export function WhatsAppButton({ target, mobile }: { target: Target; mobile: string | null | undefined }) {
|
||||
const t = useT();
|
||||
const router = useRouter();
|
||||
const { id, hasModule } = useAdminAuth();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
if (!hasModule("BO_WHATSAPP") || !mobile) return null;
|
||||
|
||||
const start = () => {
|
||||
setBusy(true);
|
||||
setMessage(null);
|
||||
startChat(target)
|
||||
.then((c) => {
|
||||
if (c.ownerUserId != null && c.ownerUserId !== id) setMessage(t("WaOwnedBy", { name: c.ownerName ?? "" }));
|
||||
else router.push(`/whatsapp?c=${encodeURIComponent(c.uuid)}`);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined;
|
||||
setMessage(t(code === "WHATSAPP_NOT_CONFIGURED" ? "WaNotConfigured" : "WaStartFailed"));
|
||||
})
|
||||
.finally(() => setBusy(false));
|
||||
};
|
||||
|
||||
return (
|
||||
<Popover open={message !== null} onOpenChange={(open) => !open && setMessage(null)}>
|
||||
<PopoverAnchor asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
aria-label={t("BO_WHATSAPP")}
|
||||
title={t("BO_WHATSAPP")}
|
||||
disabled={busy}
|
||||
onClick={start}
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<MessageCircle aria-hidden="true" className="size-4" />
|
||||
</Button>
|
||||
</PopoverAnchor>
|
||||
<PopoverContent className="w-64 text-sm">
|
||||
<p role="status">{message}</p>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CalendarDays, Circle, ClipboardList, LayoutDashboard, LockKeyhole, Mail, ScrollText, Shield, ShieldCheck, Store, Tags, UserCog, Users } from "lucide-react";
|
||||
import { CalendarDays, Circle, ClipboardList, LayoutDashboard, LockKeyhole, Mail, MessageCircle, ScrollText, Shield, ShieldCheck, Store, Tags, UserCog, Users } from "lucide-react";
|
||||
import type { LucideIcon } from "lucide-react";
|
||||
|
||||
// Maps the aclMenu tree's `iconName` (a plain string served by
|
||||
@@ -23,6 +23,7 @@ const ICONS: Record<string, LucideIcon> = {
|
||||
Mail,
|
||||
ScrollText,
|
||||
Store,
|
||||
MessageCircle,
|
||||
};
|
||||
|
||||
/** Neutral fallback for an absent or unrecognised `iconName` (spec: "The
|
||||
|
||||
@@ -21,6 +21,7 @@ import type { EventLeadRow, InterestOption, SalespersonOption } from "@/app/lib/
|
||||
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { formatDmy } from "@/app/lib/date-input";
|
||||
import { WhatsAppButton } from "@/app/components/app/WhatsAppButton";
|
||||
|
||||
const DEFAULTS = { salespersonId: "", temperature: "", status: "", interestId: "", leadType: "", attended: "" };
|
||||
const TEMPERATURE_OPTIONS = [{ value: "HOT", label: "LeadHot" }, { value: "WARM", label: "LeadWarm" }, { value: "COLD", label: "LeadCold" }];
|
||||
@@ -161,7 +162,12 @@ function EventLeadsDetailPageContent() {
|
||||
{
|
||||
accessorKey: "mobile",
|
||||
header: t("LeadMobile"),
|
||||
cell: ({ row }) => <span>{row.original.mobile || "—"}</span>,
|
||||
cell: ({ row }) => (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
{row.original.mobile || "—"}
|
||||
<WhatsAppButton target={{ eventLeadUuid: row.original.eventLeadUuid }} mobile={row.original.mobile} />
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "email",
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { act, fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
listEventLeads: vi.fn(), listEventSalespeople: vi.fn(), listEventLeadInterests: vi.fn(), listEventLeadEvents: vi.fn(),
|
||||
useAdminAuth: vi.fn(), startChat: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
|
||||
listEventLeads: mocks.listEventLeads,
|
||||
listEventSalespeople: mocks.listEventSalespeople,
|
||||
listEventLeadInterests: mocks.listEventLeadInterests,
|
||||
listEventLeadEvents: mocks.listEventLeadEvents,
|
||||
}));
|
||||
vi.mock("@/app/lib/services/whatsapp", () => ({ startChat: mocks.startChat }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => ({
|
||||
...(await import("@/test/memoryRouter")).navigationMock,
|
||||
useParams: () => ({ eventUuid: "evt-1" }),
|
||||
}));
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import EventLeadsDetailPage from "./page";
|
||||
|
||||
const ROW = {
|
||||
eventLeadUuid: "el-1", eventUuid: "evt-1", leadUuid: "lead-1", name: "John Doe", mobile: "+60123456789", email: null,
|
||||
companyName: null, jobTitle: null, leadType: "NEW", salesperson: null, temperature: null, status: "OPEN",
|
||||
interests: [], nextFollowUpDate: null, notes: null, capturedAt: "2025-06-01", attended: true, source: "INVITE",
|
||||
};
|
||||
const auth = (modules: string[]) => ({ id: 7, loading: false, hasModule: (m: string) => modules.includes(m) });
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/event-leads/evt-1");
|
||||
mocks.listEventLeads.mockReset().mockResolvedValue({ items: [ROW], total: 1 });
|
||||
mocks.listEventSalespeople.mockReset().mockResolvedValue([]);
|
||||
mocks.listEventLeadInterests.mockReset().mockResolvedValue([]);
|
||||
mocks.listEventLeadEvents.mockReset().mockResolvedValue([{ uuid: "evt-1", name: "Test Event", location: null, startDate: "2025-06-01", endDate: "2025-06-02" }]);
|
||||
mocks.startChat.mockReset().mockResolvedValue({ uuid: "c-3", ownerUserId: 7, ownerName: "Me" });
|
||||
});
|
||||
|
||||
describe("EventLeadsDetailPage WhatsApp", { timeout: 20000 }, () => {
|
||||
it("starts a chat from the event lead's row", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue(auth(["BO_EVENT_LEADS", "BO_WHATSAPP"]));
|
||||
render(<EventLeadsDetailPage />);
|
||||
const row = (await screen.findAllByText("John Doe"))[0].closest("tr")!;
|
||||
await act(async () => fireEvent.click(within(row).getByRole("button", { name: "WhatsApp" })));
|
||||
expect(mocks.startChat).toHaveBeenCalledWith({ eventLeadUuid: "el-1" });
|
||||
expect(memoryRouter.push).toHaveBeenCalledWith("/whatsapp?c=c-3");
|
||||
});
|
||||
|
||||
it("has no WhatsApp button without the module", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue(auth(["BO_EVENT_LEADS"]));
|
||||
render(<EventLeadsDetailPage />);
|
||||
await screen.findAllByText("John Doe");
|
||||
expect(screen.queryByRole("button", { name: "WhatsApp" })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -19,6 +19,7 @@ import { useCompanyScope } from "@/app/lib/CompanyScope";
|
||||
import { exportLeads, listLeads } from "@/app/lib/services/adminLeads";
|
||||
import type { LeadRow } from "@/app/lib/types";
|
||||
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
||||
import { WhatsAppButton } from "@/app/components/app/WhatsAppButton";
|
||||
|
||||
const DEFAULTS = { q: "" };
|
||||
|
||||
@@ -77,7 +78,17 @@ function LeadsPageContent() {
|
||||
),
|
||||
},
|
||||
...(showCompanyColumn ? [{ id: "company", cell: ({ row }) => codeOf(row.original.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<LeadRow, unknown>] : []),
|
||||
{ accessorKey: "mobile", header: t("LeadMobile"), enableSorting: false },
|
||||
{
|
||||
accessorKey: "mobile",
|
||||
header: t("LeadMobile"),
|
||||
enableSorting: false,
|
||||
cell: ({ row }) => (
|
||||
<span className="inline-flex items-center gap-1">
|
||||
{row.original.mobile}
|
||||
<WhatsAppButton target={{ leadUuid: row.original.leadUuid }} mobile={row.original.mobile} />
|
||||
</span>
|
||||
),
|
||||
},
|
||||
{ accessorKey: "email", header: t("Email"), enableSorting: false },
|
||||
{ accessorKey: "companyName", header: t("LeadsLeadCompany"), enableSorting: false },
|
||||
{ accessorKey: "eventCount", header: t("LeadsEvents"), enableSorting: false },
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { act, fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ listLeads: vi.fn(), useAdminAuth: vi.fn(), startChat: vi.fn() }));
|
||||
vi.mock("@/app/lib/services/adminLeads", async (importActual) => ({
|
||||
...(await importActual<typeof import("@/app/lib/services/adminLeads")>()),
|
||||
listLeads: mocks.listLeads,
|
||||
}));
|
||||
vi.mock("@/app/lib/services/whatsapp", () => ({ startChat: mocks.startChat }));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
||||
|
||||
import { memoryRouter } from "@/test/memoryRouter";
|
||||
import LeadsPage from "./page";
|
||||
|
||||
const ROW = {
|
||||
leadUuid: "l-1", name: "Aisyah", mobile: "+60123456701", email: "a@x.test", companyName: null, jobTitle: null,
|
||||
eventCount: 1, lastEvent: null, lastCapturedAt: null, latestSalesperson: null,
|
||||
};
|
||||
const auth = (modules: string[]) => ({ id: 7, loading: false, hasModule: (m: string) => modules.includes(m) });
|
||||
|
||||
beforeEach(() => {
|
||||
memoryRouter.reset("/leads");
|
||||
mocks.listLeads.mockReset().mockResolvedValue({ items: [ROW], total: 1 });
|
||||
mocks.startChat.mockReset().mockResolvedValue({ uuid: "c-9", ownerUserId: 7, ownerName: "Me" });
|
||||
});
|
||||
|
||||
describe("LeadsPage WhatsApp", () => {
|
||||
it("starts a chat from the lead's row and opens it", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue(auth(["BO_LEADS", "BO_WHATSAPP"]));
|
||||
render(<LeadsPage />);
|
||||
const row = (await screen.findByRole("link", { name: "Aisyah" })).closest("tr")!;
|
||||
await act(async () => fireEvent.click(within(row).getByRole("button", { name: "WhatsApp" })));
|
||||
expect(mocks.startChat).toHaveBeenCalledWith({ leadUuid: "l-1" });
|
||||
expect(memoryRouter.push).toHaveBeenCalledWith("/whatsapp?c=c-9");
|
||||
});
|
||||
|
||||
it("has no WhatsApp button without the module", async () => {
|
||||
mocks.useAdminAuth.mockReturnValue(auth(["BO_LEADS"]));
|
||||
render(<LeadsPage />);
|
||||
await screen.findByRole("link", { name: "Aisyah" });
|
||||
expect(screen.queryByRole("button", { name: "WhatsApp" })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -17,7 +17,7 @@ export interface SidebarLink {
|
||||
export const SIDEBAR_SECTIONS: { label?: string; modules: string[] }[] = [
|
||||
{ modules: ["BO_DASHBOARD"] },
|
||||
{ label: "SidebarSectionEvents", modules: ["BO_EVENTS", "BO_EVENT_LEADS"] },
|
||||
{ label: "SidebarSectionLeads", modules: ["BO_LEADS", "BO_INTERESTS"] },
|
||||
{ label: "SidebarSectionLeads", modules: ["BO_LEADS", "BO_WHATSAPP", "BO_INTERESTS"] },
|
||||
{ label: "SidebarSectionAccess", modules: ["BO_USERS", "BO_ROLES", "BO_LOGIN_SECURITY"] },
|
||||
{ label: "SidebarSectionSystem", modules: ["BO_COMPANIES", "BO_EMAILS", "BO_AUDIT_LOG"] },
|
||||
];
|
||||
|
||||
@@ -392,6 +392,12 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
LeadNotFound: "Lead not found",
|
||||
LeadGetFailed: "Failed to load the lead",
|
||||
BO_LEADS: "Leads",
|
||||
BO_WHATSAPP: "WhatsApp",
|
||||
BO_WHATSAPP_ADMIN: "WhatsApp admin",
|
||||
WaUnread: "{n} unread",
|
||||
WaOwnedBy: "{name} owns this chat.",
|
||||
WaNotConfigured: "WhatsApp is not set up for this company.",
|
||||
WaStartFailed: "The chat could not be started.",
|
||||
BO_EMAILS: "Emails",
|
||||
EmlDate: "Date",
|
||||
EmlRecipient: "Recipient",
|
||||
|
||||
Reference in new issue
Block a user