All files / src/components/whatsapp MessageThread.tsx

96.26% Statements 103/107
88.23% Branches 105/119
100% Functions 14/14
97.97% Lines 97/99

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                                      38x             38x 38x 38x 38x   38x 36x 35x                 18x   2x   8x   3x   4x   1x                             27x 27x 27x 27x     23x 12x     11x 6x             5x 2x 2x           3x 3x 3x         2x                               6x   6x     6x     6x           6x 6x 3x 3x 3x 5x 5x           6x 6x 2x 2x 2x 2x         4x 4x 1x     3x       4x                   13x 13x 13x 13x         13x 13x       13x 11x       2x 1x   1x     4x                 3x                               13x 13x   13x       13x 3x               10x 4x           1x               6x 3x             1x                       3x 13x   13x                                         42x 42x 42x 2x   42x     42x 1x             41x 4x               37x 37x 37x 38x 38x 38x 38x           37x     38x                     38x                                                                                                                                  
import { whatsAppErrorCopy } from "@interioring/utils/whatsapp/errors";
import { AlertCircle, Check, CheckCheck, FileText, Mic } from "lucide-react";
import { useMemo, useState } from "react";
import type { WaMessage, WaTemplate } from "../../lib/api/whatsapp";
import { getWaMediaUrl } from "../../lib/api/whatsapp";
import { cn } from "../../lib/utils";
import {
	getTemplateBodyText,
	parseTemplateComponents,
	renderPreviewText,
} from "./template-utils";
 
type MessageThreadProps = {
	messages: WaMessage[];
	templates?: WaTemplate[];
	isLoading: boolean;
};
 
function formatTime(dateStr: string): string {
	return new Date(dateStr).toLocaleTimeString("en-IN", {
		hour: "2-digit",
		minute: "2-digit",
	});
}
 
function formatDate(dateStr: string): string {
	const date = new Date(dateStr);
	const today = new Date();
	const yesterday = new Date(today);
	yesterday.setDate(yesterday.getDate() - 1);
 
	if (date.toDateString() === today.toDateString()) return "Today";
	if (date.toDateString() === yesterday.toDateString()) return "Yesterday";
	return date.toLocaleDateString("en-IN", {
		day: "numeric",
		month: "short",
		year: "numeric",
	});
}
 
/** Exported: the RRM referral screen renders the same ticks on its own thread. */
export function StatusIcon({ status }: { status: string }) {
	switch (status) {
		case "sent":
			return <Check className="h-3 w-3 text-foreground-subtle" />;
		case "delivered":
			return <CheckCheck className="h-3 w-3 text-foreground-subtle" />;
		case "read":
			return <CheckCheck className="h-3 w-3 text-info" />;
		case "failed":
			return <AlertCircle className="h-3 w-3 text-error" />;
		default:
			return null;
	}
}
 
type SentComponent = {
	type?: string;
	parameters?: Array<{ text?: string; type?: string }>;
};
 
function parseContent(
	content: string | null,
	type: string,
	templateMap?: Map<string, WaTemplate>,
	templateName?: string | null,
): string {
	Iif (!content) return "";
	try {
		const parsed = JSON.parse(content);
		if (typeof parsed === "string") return parsed;
 
		// Text messages
		if (parsed.body) return parsed.body;
		if (parsed.text?.body) return parsed.text.body;
 
		// Template messages — resolve body text with parameter values
		if (type === "template") {
			return resolveTemplateMessage(parsed, templateMap, templateName);
		}
 
		// Media (image/video/document/audio) never reaches here — MediaBubble
		// renders those types with the real bytes.
 
		// Location
		if (type === "location") {
			const parts = [parsed.name, parsed.address].filter(Boolean);
			return parts.length > 0
				? `[Location] ${parts.join(", ")}`
				: `[Location] ${parsed.latitude}, ${parsed.longitude}`;
		}
 
		// Interactive (button/list replies)
		Eif (type === "interactive") {
			const title = parsed.buttonReply?.title ?? parsed.listReply?.title ?? "";
			return title ? `[Reply] ${title}` : "[Interactive message]";
		}
 
		return parsed.body ?? content;
	} catch {
		return content;
	}
}
 
/**
 * Resolve a template message into the text the customer would see.
 * Looks up the template definition to get the body text with {{N}} placeholders,
 * then substitutes the parameter values that were sent with the message.
 */
function resolveTemplateMessage(
	parsed: Record<string, unknown>,
	templateMap?: Map<string, WaTemplate>,
	templateName?: string | null,
): string {
	// Extract sent parameters from the message content
	// Format 1: { templateName, language, components: [...] }
	const sentComponents = (parsed.components ?? []) as SentComponent[];
	// Format 2: full payload { template: { name, components: [...] } }
	const nestedTemplate = parsed.template as
		| { name?: string; components?: SentComponent[] }
		| undefined;
	const msgComponents = nestedTemplate?.components ?? sentComponents;
 
	const name =
		templateName ??
		(parsed.templateName as string) ??
		nestedTemplate?.name ??
		"";
 
	// Build parameter values map from sent components
	const values: Record<string, string> = {};
	for (const comp of msgComponents) {
		const compType = (comp.type ?? "").toUpperCase();
		Iif (compType !== "BODY" && compType !== "HEADER") continue;
		for (const [idx, param] of (comp.parameters ?? []).entries()) {
			Eif (param.text) {
				values[`${compType}_${idx + 1}`] = param.text;
			}
		}
	}
 
	// Look up the template definition to get the body text with placeholders
	const template = name ? templateMap?.get(name) : undefined;
	if (template?.components) {
		const defComponents = parseTemplateComponents(template.components);
		const bodyText = getTemplateBodyText(defComponents);
		Eif (bodyText) {
			return renderPreviewText(bodyText, "BODY", values);
		}
	}
 
	// Fallback: show parameter values if template definition unavailable
	const paramTexts = Object.values(values);
	if (paramTexts.length > 0) {
		return paramTexts.join(", ");
	}
 
	return name ? `[Template: ${name}]` : "[Template message]";
}
 
/** The four types whose payload is a file rather than text. */
const MEDIA_TYPES = new Set(["image", "video", "document", "audio"]);
 
type ParsedMedia = {
	/** Where the bytes come from, or null when the row records none. */
	src: string | null;
	caption: string | null;
	filename: string | null;
};
 
function parseMedia(msg: WaMessage): ParsedMedia {
	let parsed: Record<string, unknown> = {};
	try {
		const raw: unknown = msg.content ? JSON.parse(msg.content) : {};
		Eif (raw && typeof raw === "object") parsed = raw as Record<string, unknown>;
	} catch {
		// A malformed row still renders as "unavailable" rather than crashing.
	}
 
	const caption = typeof parsed.caption === "string" ? parsed.caption : null;
	const filename = typeof parsed.filename === "string" ? parsed.filename : null;
 
	// Inbound: Meta gave us a media id, and the API proxies the bytes — the
	// lookaside URL needs our bearer token, so a browser cannot fetch it.
	if (typeof parsed.mediaId === "string" && parsed.mediaId.length > 0) {
		return { src: getWaMediaUrl(msg.id), caption, filename };
	}
	// Outbound: we handed Meta a public link and never held a media id, so the
	// proxy has nothing to fetch — show the link we sent.
	if (typeof parsed.link === "string" && parsed.link.length > 0) {
		return { src: parsed.link, caption, filename };
	}
	return { src: null, caption, filename };
}
 
const MEDIA_LABEL: Record<string, string> = {
	image: "Photo",
	video: "Video",
	document: "File",
	audio: "Voice message",
};
 
/** Shown when the bytes are gone — Meta expires media, and old rows will 404. */
function MediaUnavailable({ type }: { type: string }) {
	return (
		<p className="text-sm italic text-foreground-muted">
			{MEDIA_LABEL[type] ?? "Attachment"} is no longer available — WhatsApp
			removes media after a while.
		</p>
	);
}
 
/**
 * Render what the customer actually sent.
 *
 * Every source can fail: Meta expires media, the access token may be unset,
 * and rows predating the media endpoint carry no bytes at all. Each branch
 * degrades to readable text rather than a browser's broken-image glyph.
 */
function MediaBubble({ msg }: { msg: WaMessage }) {
	const [failed, setFailed] = useState(false);
	const { src, caption, filename } = parseMedia(msg);
 
	const captionEl = caption ? (
		<p className="mt-1 text-sm whitespace-pre-wrap break-words">{caption}</p>
	) : null;
 
	if (!src || failed) {
		return (
			<>
				<MediaUnavailable type={msg.type} />
				{captionEl}
			</>
		);
	}
 
	if (msg.type === "image") {
		return (
			<>
				<img
					src={src}
					alt={caption ?? "Photo sent on WhatsApp"}
					loading="lazy"
					onError={() => setFailed(true)}
					className="max-h-72 h-auto max-w-full rounded object-contain"
				/>
				{captionEl}
			</>
		);
	}
 
	if (msg.type === "video") {
		return (
			<>
				{/* biome-ignore lint/a11y/useMediaCaption: a customer's clip has no caption track to offer */}
				<video
					src={src}
					controls
					preload="metadata"
					onError={() => setFailed(true)}
					className="max-h-72 max-w-full rounded"
				/>
				{captionEl}
			</>
		);
	}
 
	// Document and audio: a labelled link through the same endpoint. The API
	// sets Content-Disposition, because a cross-origin `download` attribute is
	// ignored by the browser.
	const label =
		msg.type === "document" ? (filename ?? "Document") : "Voice message";
	const Icon = msg.type === "document" ? FileText : Mic;
 
	return (
		<>
			<a
				href={src}
				target="_blank"
				rel="noopener noreferrer"
				className="flex items-center gap-2 text-sm underline break-all"
			>
				<Icon className="h-4 w-4 shrink-0" />
				{label}
			</a>
			{captionEl}
		</>
	);
}
 
export function MessageThread({
	messages,
	templates,
	isLoading,
}: MessageThreadProps) {
	const templateMap = useMemo(() => {
		const map = new Map<string, WaTemplate>();
		for (const t of templates ?? []) {
			map.set(t.name, t);
		}
		return map;
	}, [templates]);
 
	if (isLoading) {
		return (
			<div className="flex-1 flex items-center justify-center">
				<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-whatsapp-green" />
			</div>
		);
	}
 
	if (messages.length === 0) {
		return (
			<div className="flex-1 flex items-center justify-center text-foreground-muted">
				<p className="text-sm">No messages yet</p>
			</div>
		);
	}
 
	// Group messages by date
	const groupedMessages: { date: string; messages: WaMessage[] }[] = [];
	let currentDate = "";
	for (const msg of messages) {
		const date = formatDate(msg.dateCreated);
		if (date !== currentDate) {
			currentDate = date;
			groupedMessages.push({ date, messages: [msg] });
		} else E{
			groupedMessages[groupedMessages.length - 1].messages.push(msg);
		}
	}
 
	return (
		<div className="flex-1 overflow-y-auto p-4 space-y-4">
			{groupedMessages.map((group) => (
				<div key={group.date}>
					{/* Date Separator */}
					<div className="flex items-center justify-center my-4">
						<span className="bg-background-muted text-foreground-muted text-xs px-3 py-1 rounded-full">
							{group.date}
						</span>
					</div>
 
					{/* Messages */}
					<div className="space-y-2">
						{group.messages.map((msg) => (
							<div
								key={msg.id}
								className={cn(
									"flex",
									msg.direction === "outbound"
										? "justify-end"
										: "justify-start",
								)}
							>
								<div
									className={cn(
										"max-w-[75%] rounded-lg px-3 py-2 shadow-sm",
										msg.direction === "outbound"
											? "bg-whatsapp-bubble-sent dark:bg-whatsapp-green/20 text-foreground-default"
											: "bg-background-default border border-border-default text-foreground-default",
									)}
								>
									{/* Template badge */}
									{msg.templateName && (
										<p className="text-xs font-medium text-whatsapp-green dark:text-whatsapp-green mb-1">
											Template: {msg.templateName}
										</p>
									)}
 
									{/* Message content */}
									{MEDIA_TYPES.has(msg.type) ? (
										<MediaBubble msg={msg} />
									) : (
										<p className="text-sm whitespace-pre-wrap break-words">
											{parseContent(
												msg.content,
												msg.type,
												templateMap,
												msg.templateName,
											)}
										</p>
									)}
 
									{/* Time and status */}
									<div className="flex items-center justify-end gap-1 mt-1">
										<span className="text-xs text-foreground-subtle">
											{formatTime(msg.dateCreated)}
										</span>
										{msg.direction === "outbound" && (
											<StatusIcon status={msg.status} />
										)}
									</div>
 
									{/* A red dot alone reads as "still sending". Say what
									    Meta actually did, so a failure is a fact rather
									    than a suspicion. */}
									{msg.direction === "outbound" && msg.status === "failed" && (
										<p className="mt-1 text-xs text-error">
											{whatsAppErrorCopy(msg.errorCode)}
										</p>
									)}
								</div>
							</div>
						))}
					</div>
				</div>
			))}
		</div>
	);
}