All files / src/pages/admin/whatsapp inbox.tsx

95.06% Statements 77/81
86.07% Branches 68/79
94.73% Functions 18/19
100% Lines 73/73

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455                                                                                                                              2x           2x     62x       62x     62x 62x     62x 62x 62x     62x     62x 62x 62x   62x 42x 42x           62x 372x 5x 5x               62x                     62x 62x                               62x       62x 62x   62x           62x 62x       62x 62x 9x 2x 2x   1x   1x                     62x 1x 1x 1x 1x 1x 1x 1x 1x     62x 62x 62x                 62x 62x 42x 42x 42x 42x       62x       43x 43x       62x   62x 52x       62x 62x 52x 1x       62x 1x 1x     62x         1x 1x           62x         62x                                                                                                                                                                                         1x                                                                                                                                                                                                                    
import { useEffect, useRef, useState } from "react";
import { Link, useSearch } from "@tanstack/react-router";
import { ArrowLeft, MessageCircle, Phone, TriangleAlert } from "lucide-react";
import { ConversationList } from "../../../components/whatsapp/ConversationList";
import { ContactTypeTag } from "../../../components/whatsapp/ContactTypeTag";
import { MessageThread } from "../../../components/whatsapp/MessageThread";
import { ReplyBox } from "../../../components/whatsapp/ReplyBox";
import { SlaStrip } from "../../../components/whatsapp/SlaStrip";
import { WhatsAppPageLayout } from "../../../components/whatsapp/WhatsAppPageLayout";
import { Separator } from "../../../components/ui/separator";
import { STATUS_CODE_TYPE, STATUS_INK } from "../../../components/ui/status-ink";
import { cn } from "../../../lib/utils";
import {
	useMarkConversationRead,
	useReplyToConversation,
	useStartProConversation,
	useWhatsAppConversation,
	useWhatsAppConversations,
	useWhatsAppStats,
	useWhatsAppTemplates,
} from "../../../hooks/queries/useWhatsAppQueries";
import { getErrorMessage } from "../../../lib/api";
import type { WaInboxRow } from "../../../lib/api/whatsapp";
import { notify } from "../../../lib/notify";
import {
	elapsedSince,
	formatAgeLong,
	formatAgeShort,
} from "../../../lib/whatsapp/triage";
 
/**
 * The one WhatsApp inbox, now doing the job the deleted RRM triage screen did.
 *
 * WHAT THIS SCREEN IS FOR
 * Not browsing conversations — answering the ones that are late. So it opens
 * on the backlog, server-ordered oldest-waiting-first, with the age leading
 * every row and three server-owned figures above it. Browsing is the `All`
 * mode, one chip away.
 *
 * ONE CLOCK
 * `now` is state on this page, ticked once a minute, and passed down to the
 * strip, the rows and the reply box. Every age, every countdown and every
 * threshold on screen is then computed from the same instant — a component
 * that called `Date.now()` itself could render "4h12m" next to "4h13m" and
 * look broken.
 *
 * A MINUTE, NOT A SECOND. Nothing on screen has second resolution, so a
 * per-second interval would re-render the whole inbox sixty times for no
 * visible change.
 *
 * TWO MOCKUP AFFORDANCES ARE DELIBERATELY ABSENT, because both need data or
 * write paths this inbox does not have:
 *
 * - **"Open lead ▸" in the thread header.** `wa_conversations.inquiry_id`
 *   points at an INQUIRY, and the admin surface for homeowner demand is the
 *   lead store (`/admin/web-leads`), keyed on a different row. There is no
 *   inquiry → lead mapping on the wire, so the link would be a guess.
 * - **The "⋯ more actions" menu (assign / mark answered / block).** All three
 *   are write paths that do not exist: no assignee column, no manual
 *   "answered" flag (and inventing one would be a second definition of
 *   `waitingOnUs`), and no block list outside the deleted RRM suppression
 *   table. A menu of three dead items is worse than no menu.
 */
const CLOCK_TICK_MS = 60_000;
 
/**
 * The left panel is narrow, so a page is short enough to scan without
 * scrolling past the fold. The API accepts up to 100.
 */
const PAGE_SIZE = 25;
 
export function WhatsAppInboxPage() {
	const searchParams = useSearch({ strict: false }) as {
		id?: number;
		view?: "unread";
	};
	const [selectedId, setSelectedId] = useState<number | null>(
		searchParams?.id ?? null,
	);
	const [search, setSearch] = useState("");
	const [contactTypeFilter, setContactTypeFilter] = useState("");
	// `?view=unread` is the dashboard's Unread card. Read once, as the initial
	// value, so the operator can then clear it like any other filter.
	const [hasUnread, setHasUnread] = useState(searchParams?.view === "unread");
	const [hasCustomerReply, setHasCustomerReply] = useState(false);
	const [answeredByUs, setAnsweredByUs] = useState(false);
	// Opens on the backlog. A triage screen that opens on "everything, newest
	// first" has buried its own purpose under the most recent conversation.
	const [waitingOnly, setWaitingOnly] = useState(
		searchParams?.view !== "unread",
	);
	const [offset, setOffset] = useState(0);
	const [now, setNow] = useState(() => new Date());
	const messageEndRef = useRef<HTMLDivElement>(null);
 
	useEffect(() => {
		const timer = setInterval(() => setNow(new Date()), CLOCK_TICK_MS);
		return () => clearInterval(timer);
	}, []);
 
	// Every filter change narrows or widens the result set, so an offset carried
	// over from the previous one can land past the end and show an empty panel
	// that looks like "no conversations".
	const changeFilter = <T,>(set: (value: T) => void) => {
		return (value: T) => {
			set(value);
			setOffset(0);
		};
	};
 
	const {
		data: conversationPage,
		isLoading: convsLoading,
		isError: convsError,
	} = useWhatsAppConversations({
		search: search || undefined,
		contactType: contactTypeFilter || undefined,
		// Sent only when on, so the query key and the request URL stay clean.
		hasUnread: hasUnread || undefined,
		hasCustomerReply: hasCustomerReply || undefined,
		answeredByUs: answeredByUs || undefined,
		waitingOnUs: waitingOnly || undefined,
		limit: PAGE_SIZE,
		offset,
	});
	const conversations = conversationPage?.conversations ?? [];
	const total = conversationPage?.total ?? 0;
 
	/**
	 * The backlog probe: one row, unfiltered, from the waiting branch.
	 *
	 * It answers three questions at once and all three are server-owned. Its
	 * `total` is the inbox-wide "waiting on us" count, which the visible page
	 * cannot derive — 25 rows describe the page, not the inbox. Its single row
	 * is, by construction, the oldest waiter, because that branch is ordered
	 * `last_customer_message_at ASC` on the server; so it supplies the name for
	 * the strip's sentence and the id for "Jump to it".
	 *
	 * Unfiltered on purpose: the strip must keep describing the WHOLE inbox
	 * while the list beside it is narrowed, or filtering would appear to fix
	 * the backlog.
	 */
	const { data: backlog } = useWhatsAppConversations({
		waitingOnUs: true,
		limit: 1,
	});
	const waitingCount = backlog?.total ?? 0;
	const oldestWaiter = backlog?.conversations[0];
 
	const { data: stats } = useWhatsAppStats();
 
	const {
		data: conversationData,
		isLoading: detailLoading,
		isError: detailError,
	} = useWhatsAppConversation(selectedId);
	const pro = conversationData?.conversation.pro;
 
	// A pro we have never messaged has no conversation yet; open one (nothing
	// is sent) so the thread and the template reply box work as usual.
	const startProConversation = useStartProConversation();
	const handleSelect = (row: WaInboxRow) => {
		if (row.id !== null) return setSelectedId(row.id);
		Iif (!row.proId || startProConversation.isPending) return;
		startProConversation.mutate(row.proId, {
			onSuccess: (conversation) => {
				Eif (conversation) setSelectedId(conversation.id);
			},
			onError: (err) => notify.error(getErrorMessage(err)),
		});
	};
 
	/**
	 * Jump to the oldest waiter — and widen the list first.
	 *
	 * Without the reset, a thread opens on the right while no row matches it on
	 * the left, which reads as a bug. Clearing to the unfiltered waiting view
	 * also guarantees the row is on screen: it is that view's first row.
	 */
	const handleJump = (id: number) => {
		setSearch("");
		setContactTypeFilter("");
		setHasUnread(false);
		setHasCustomerReply(false);
		setAnsweredByUs(false);
		setWaitingOnly(true);
		setOffset(0);
		setSelectedId(id);
	};
 
	const { data: templates = [] } = useWhatsAppTemplates();
	const replyMutation = useReplyToConversation();
	const { mutate: markAsRead } = useMarkConversationRead();
 
	/**
	 * The backlog in the tab title.
	 *
	 * A backgrounded tab that reads `(7)` is the cheapest backlog alarm
	 * available. The original title is captured once, on mount, so the effect
	 * cannot capture its own output and compound the prefix on every tick.
	 */
	const originalTitle = useRef<string | null>(null);
	useEffect(() => {
		originalTitle.current ??= document.title;
		return () => {
			Eif (originalTitle.current !== null) {
				document.title = originalTitle.current;
			}
		};
	}, []);
	useEffect(() => {
		// `??`, not `||`: an empty captured title is still the captured title,
		// and falling back to `document.title` here would re-read a value this
		// effect may already have prefixed — which is how `(7) (7) …` happens.
		const base = originalTitle.current ?? document.title;
		document.title = waitingCount > 0 ? `(${waitingCount}) ${base}` : base;
	}, [waitingCount]);
 
	// Auto-scroll to bottom when messages change
	const messageCount = conversationData?.messages?.length;
	// biome-ignore lint/correctness/useExhaustiveDependencies: messageCount is an intentional trigger to scroll on new messages
	useEffect(() => {
		messageEndRef.current?.scrollIntoView({ behavior: "smooth" });
	}, [messageCount]);
 
	// Mark conversation as read when selected and has unread messages
	const unreadCount = conversationData?.conversation?.unreadCount ?? 0;
	useEffect(() => {
		if (selectedId && unreadCount > 0) {
			markAsRead(selectedId);
		}
	}, [selectedId, unreadCount, markAsRead]);
 
	const handleSendText = (message: string) => {
		Iif (!selectedId) return;
		replyMutation.mutate({ id: selectedId, body: { message } });
	};
 
	const handleSendTemplate = (
		templateName: string,
		language: string,
		components?: unknown[],
	) => {
		Iif (!selectedId) return;
		replyMutation.mutate({
			id: selectedId,
			body: { templateName, language, components },
		});
	};
 
	const inboundAgeMs = elapsedSince(
		conversationData?.conversation.lastCustomerMessageAt,
		now,
	);
 
	return (
		<WhatsAppPageLayout fullHeight>
			<div className="flex h-full flex-col">
				<div className="px-4 pt-3 pb-2">
					{/* ~1.375rem is the page-title cap; Display sizes are for empty
					    states and auth, not for a working screen. */}
					<h1 className="text-xl font-semibold text-foreground-default">
						Inbox
					</h1>
				</div>
				{/* The page rule carries this screen's one index-red marker. */}
				<Separator marked />
 
				<SlaStrip
					waitingCount={waitingCount}
					oldestWaitingAt={stats?.oldestWaitingAt ?? null}
					answeredToday={stats?.answeredToday}
					oldest={
						oldestWaiter
							? {
									id: oldestWaiter.id,
									name:
										oldestWaiter.pro?.businessName ||
										oldestWaiter.contactName ||
										oldestWaiter.phoneNumber,
								}
							: null
					}
					onJump={handleJump}
					search={search}
					onSearchChange={changeFilter(setSearch)}
					now={now}
				/>
 
				<div className="flex min-h-0 flex-1">
					{/* Left Panel: the triage list */}
					<div
						className={`w-80 flex-shrink-0 ${selectedId ? "hidden md:flex md:flex-col" : "flex w-full flex-col md:w-80"}`}
					>
						<ConversationList
							conversations={conversations}
							selectedId={selectedId}
							onSelect={handleSelect}
							waitingOnly={waitingOnly}
							onWaitingOnlyChange={changeFilter(setWaitingOnly)}
							contactTypeFilter={contactTypeFilter}
							onContactTypeFilterChange={changeFilter(setContactTypeFilter)}
							hasUnread={hasUnread}
							onHasUnreadChange={changeFilter(setHasUnread)}
							hasCustomerReply={hasCustomerReply}
							onHasCustomerReplyChange={changeFilter(setHasCustomerReply)}
							answeredByUs={answeredByUs}
							onAnsweredByUsChange={changeFilter(setAnsweredByUs)}
							total={total}
							offset={offset}
							pageSize={PAGE_SIZE}
							onOffsetChange={setOffset}
							isLoading={convsLoading}
							isError={convsError}
							hasActiveFilters={
								Boolean(search) ||
								Boolean(contactTypeFilter) ||
								hasUnread ||
								hasCustomerReply ||
								answeredByUs
							}
							now={now}
						/>
					</div>
 
					{/* Right Panel: the thread */}
					<div
						className={`flex flex-1 flex-col ${selectedId ? "flex" : "hidden md:flex"}`}
					>
						{selectedId && detailError ? (
							<div className="flex flex-1 flex-col items-center justify-center gap-2 px-6 text-center">
								<TriangleAlert
									aria-hidden="true"
									className={cn("h-8 w-8", STATUS_INK.error)}
								/>
								<p className="text-sm font-semibold text-foreground-default">
									Could not load this conversation
								</p>
								<p className="text-xs text-foreground-muted">
									Nothing has been sent. Reload the page and try again.
								</p>
							</div>
						) : selectedId && conversationData ? (
							<>
								{/* Contact header */}
								<div className="flex items-start gap-3 border-b border-border-default px-4 py-3">
									<button
										type="button"
										onClick={() => setSelectedId(null)}
										aria-label="Back to the list"
										className="p-1 text-foreground-muted hover:text-foreground-default md:hidden"
									>
										<ArrowLeft aria-hidden="true" className="h-5 w-5" />
									</button>
									<div className="min-w-0 flex-1">
										<p className="truncate text-sm font-semibold text-foreground-default">
											<span className="tabular-nums">
												{conversationData.conversation.phoneNumber}
											</span>
											{" · "}
											{pro ? (
												<Link
													to="/admin/pros/$proId"
													params={{ proId: pro.id }}
													className="hover:underline"
												>
													{pro.businessName}
												</Link>
											) : (
												conversationData.conversation.contactName ||
												"Unknown contact"
											)}
										</p>
										<div className="mt-0.5 flex items-center gap-2 text-xs text-foreground-muted">
											<Phone aria-hidden="true" className="h-3 w-3" />
											{/*
											 * Factual, and deliberately NOT the words "waiting on
											 * us". That predicate is defined once, on the server
											 * (`waitingOnUs`), and spelling it a second time in
											 * the browser is exactly how the badge that disagreed
											 * with the screen next to it shipped last time. The
											 * age of their last inbound is a fact about this row.
											 */}
											{inboundAgeMs === null ? (
												<span>They have not written yet</span>
											) : (
												<span>
													<span aria-hidden="true">
														Their last message · {formatAgeShort(inboundAgeMs)}{" "}
														ago
													</span>
													<span className="sr-only">
														Their last message was{" "}
														{formatAgeLong(inboundAgeMs)} ago
													</span>
												</span>
											)}
										</div>
										{pro && (
											<p className="truncate text-xs text-foreground-subtle">
												{[
													pro.ownerName,
													pro.ownerEmail ?? pro.email,
													pro.city,
													pro.status,
												]
													.filter(Boolean)
													.join(" · ")}
											</p>
										)}
									</div>
									<ContactTypeTag
										contactType={conversationData.conversation.contactType}
										className="mt-0.5 shrink-0"
									/>
								</div>
 
								{/* Messages */}
								<div className="flex-1 overflow-y-auto">
									<MessageThread
										messages={conversationData.messages}
										templates={templates}
										isLoading={detailLoading}
									/>
									<div ref={messageEndRef} />
								</div>
 
								<ReplyBox
									conversation={conversationData.conversation}
									windowExpiresAt={conversationData.windowExpiresAt}
									templates={templates}
									onSendText={handleSendText}
									onSendTemplate={handleSendTemplate}
									isSending={replyMutation.isPending}
									now={now}
								/>
							</>
						) : (
							<div className="flex flex-1 flex-col items-center justify-center gap-2 text-center text-foreground-muted">
								<MessageCircle aria-hidden="true" className="h-10 w-10" />
								<p className="text-sm font-semibold text-foreground-default">
									Select a conversation
								</p>
								<p className={cn(STATUS_CODE_TYPE, "text-foreground-subtle")}>
									Oldest waiting first
								</p>
							</div>
						)}
					</div>
				</div>
			</div>
		</WhatsAppPageLayout>
	);
}