All files / src/components/whatsapp ReplyBox.tsx

93.33% Statements 42/45
87.5% Branches 28/32
100% Functions 15/15
100% Lines 40/40

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                                                                                                                                                          57x 57x 57x   57x         57x   57x 57x 20x     57x     57x 57x   57x 7x   57x 3x 3x 3x 3x     57x 3x 3x   3x       3x 3x 3x     57x 2x 1x 1x       57x 6x 6x     57x                                                                                     7x                       156x 156x               2x                                                                                                                         6x   21x                                                     2x                      
import { useState } from "react";
import { Clock, FileText, Lock, Send } from "lucide-react";
import { cn } from "../../lib/utils";
import { Button } from "../ui/button";
import { Select } from "../ui/select";
import { Textarea } from "../ui/textarea";
import {
	STATUS_BAND_TINT,
	STATUS_CODE_TYPE,
	STATUS_INK,
} from "../ui/status-ink";
import type { WaConversation, WaTemplate } from "../../lib/api/whatsapp";
import { TemplateParameterFields } from "./TemplateParameterFields";
import {
	buildSendComponents,
	extractParameterSlots,
	isApprovedTemplate,
	parseTemplateComponents,
} from "../../lib/whatsapp/template";
import {
	appendQuickReply,
	firstLine,
	QUICK_REPLIES,
	QUICK_REPLY_ORDER,
} from "../../lib/whatsapp/quick-replies";
import {
	formatRemainingLong,
	formatRemainingShort,
	REPLY_WINDOW_HOURS,
	replyWindowExpiry,
} from "../../lib/whatsapp/triage";
 
/**
 * The composer, with Meta's 24-hour rule STATED rather than inferred.
 *
 * WHAT CHANGED AND WHY IT MATTERS
 * This used to recompute the window locally and print a banner once it had
 * already closed — no countdown, no statement of how much time was left. The
 * deadline governs whether a plain reply is LEGAL (the API refuses a late one;
 * Meta rejects it with 131047), so the page must say how long is left while
 * there is still time to act, and the figure must come from
 * `windowExpiresAt` on the detail response rather than from the browser clock.
 * `now` is passed in so the countdown ticks on the page's one clock and every
 * figure on screen agrees.
 *
 * QUICK REPLIES INSERT, THEY NEVER SEND
 * Tapping a chip appends its body below whatever is already in the draft, with
 * a blank line between, and leaves the cursor in the operator's hands. A chip
 * that sent on one tap would have no review step, and a message that has
 * already left is the one thing that cannot be taken back. The chips are
 * therefore absent entirely when the window is closed: that branch cannot send
 * free-form text at all, so offering a draft affordance would be a dead end.
 */
export type ReplyBoxProps = {
	conversation: WaConversation;
	/** Server-owned deadline. Null means closed; never a past instant. */
	windowExpiresAt?: string | null;
	templates: WaTemplate[];
	onSendText: (message: string) => void;
	onSendTemplate: (
		templateName: string,
		language: string,
		components?: unknown[],
	) => void;
	isSending: boolean;
	now: Date;
};
 
export function ReplyBox({
	conversation,
	windowExpiresAt,
	templates,
	onSendText,
	onSendTemplate,
	isSending,
	now,
}: ReplyBoxProps) {
	const [message, setMessage] = useState("");
	const [selectedTemplate, setSelectedTemplate] = useState("");
	const [paramValues, setParamValues] = useState<Record<string, string>>({});
 
	const expiry = replyWindowExpiry(
		windowExpiresAt,
		conversation.lastCustomerMessageAt,
		now,
	);
	const windowOpen = expiry !== null;
 
	const approvedTemplates = templates.filter(isApprovedTemplate);
	const currentTemplate = approvedTemplates.find(
		(t) => t.name === selectedTemplate,
	);
 
	const templateComponents = currentTemplate
		? parseTemplateComponents(currentTemplate.components)
		: [];
	const slots = extractParameterSlots(templateComponents);
	const hasVariables = slots.length > 0;
	const allParamsFilled =
		!hasVariables ||
		slots.every((s) => paramValues[`${s.componentType}_${s.index}`]?.trim());
 
	const handleSendText = () => {
		const text = message.trim();
		Iif (!text) return;
		onSendText(text);
		setMessage("");
	};
 
	const handleSendTemplate = () => {
		Iif (!selectedTemplate || !currentTemplate) return;
		Iif (hasVariables && !allParamsFilled) return;
 
		const components = hasVariables
			? buildSendComponents(templateComponents, paramValues)
			: undefined;
 
		onSendTemplate(currentTemplate.name, currentTemplate.language, components);
		setSelectedTemplate("");
		setParamValues({});
	};
 
	const handleKeyDown = (e: React.KeyboardEvent) => {
		if (e.key === "Enter" && !e.shiftKey) {
			e.preventDefault();
			handleSendText();
		}
	};
 
	const handleTemplateChange = (name: string) => {
		setSelectedTemplate(name);
		setParamValues({});
	};
 
	return (
		<div className="border-t border-border-default">
			{windowOpen ? (
				<>
					<div
						className={cn(
							"flex flex-wrap items-center gap-x-2 gap-y-1 border-b border-border-default px-4 py-1.5",
							STATUS_BAND_TINT.info,
						)}
					>
						<Clock
							aria-hidden="true"
							className={cn("h-4 w-4 shrink-0", STATUS_INK.info)}
						/>
						<span className={cn(STATUS_CODE_TYPE, STATUS_INK.info)}>
							Reply window open
						</span>
						<span aria-hidden="true" className="text-foreground-subtle">
							·
						</span>
						<span className={cn(STATUS_CODE_TYPE, "text-foreground-default")}>
							<span aria-hidden="true">
								{formatRemainingShort(expiry, now)} left
							</span>
							<span className="sr-only">
								{formatRemainingLong(expiry, now)} left
							</span>
						</span>
						<span className="ml-auto hidden text-xs text-foreground-subtle sm:block">
							Free-form replies close {REPLY_WINDOW_HOURS} hours after their
							last message
						</span>
					</div>
 
					<div className="p-3">
						<label className="sr-only" htmlFor="wa-reply">
							Reply to{" "}
							{conversation.contactName || conversation.phoneNumber}
						</label>
						<Textarea
							id="wa-reply"
							rows={3}
							value={message}
							onChange={(e) => setMessage(e.target.value)}
							onKeyDown={handleKeyDown}
							placeholder="Type a reply…"
						/>
 
						<div className="mt-2 flex flex-wrap items-center gap-1.5">
							<span
								className={cn(STATUS_CODE_TYPE, "text-foreground-muted")}
							>
								Quick
							</span>
							{QUICK_REPLY_ORDER.map((key) => {
								const reply = QUICK_REPLIES[key];
								return (
									<button
										key={key}
										type="button"
										// The operator can read what a chip will put in the
										// draft before pressing it.
										title={firstLine(reply.body)}
										onClick={() =>
											setMessage((draft) =>
												appendQuickReply(draft, reply.body),
											)
										}
										className={cn(
											"h-6 rounded-sm border border-border-default px-1.5 text-foreground-muted transition-colors hover:border-border-strong hover:text-foreground-default focus-visible:ring-2 focus-visible:ring-primary-500 focus-visible:outline-none pointer-coarse:min-h-11",
											STATUS_CODE_TYPE,
										)}
									>
										{reply.label}
									</button>
								);
							})}
							<Button
								type="button"
								size="sm"
								onClick={handleSendText}
								disabled={!message.trim() || isSending}
								className="ml-auto"
							>
								<Send aria-hidden="true" />
								Send
							</Button>
						</div>
					</div>
				</>
			) : (
				<>
					<div
						className={cn(
							"flex flex-wrap items-start gap-2 border-b border-border-default px-4 py-2",
							STATUS_BAND_TINT.warning,
						)}
					>
						<Lock
							aria-hidden="true"
							className={cn("mt-0.5 h-4 w-4 shrink-0", STATUS_INK.warning)}
						/>
						<span className={cn(STATUS_CODE_TYPE, STATUS_INK.warning)}>
							Reply window closed
						</span>
						{/* Name the consequence, not the rule. */}
						<p className="min-w-0 text-xs text-foreground-default">
							Only an approved template can reach this person now — the API
							will refuse a plain reply.
						</p>
					</div>
 
					<div className="space-y-3 p-3">
						<div className="flex items-center gap-2">
							<FileText
								aria-hidden="true"
								className="h-4 w-4 shrink-0 text-foreground-muted"
							/>
							<label className="sr-only" htmlFor="wa-template">
								Approved template to send
							</label>
							<Select
								id="wa-template"
								tier="dense"
								value={selectedTemplate}
								onChange={(e) => handleTemplateChange(e.target.value)}
								placeholder="Select a template…"
								options={approvedTemplates.map((t) => ({
									value: t.name,
									label: `${t.name} (${t.language})`,
								}))}
							/>
							<Button
								type="button"
								size="sm"
								onClick={handleSendTemplate}
								disabled={
									!selectedTemplate ||
									isSending ||
									(hasVariables && !allParamsFilled)
								}
								aria-label="Send template"
								className="shrink-0"
							>
								<Send aria-hidden="true" />
							</Button>
						</div>
 
						{currentTemplate && (
							<div className="max-h-64 overflow-y-auto">
								<TemplateParameterFields
									template={currentTemplate}
									paramValues={paramValues}
									onParamChange={(key, value) =>
										setParamValues((prev) => ({ ...prev, [key]: value }))
									}
								/>
							</div>
						)}
					</div>
				</>
			)}
		</div>
	);
}