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

92.64% Statements 63/68
93.5% Branches 72/77
90% Functions 18/20
98.38% Lines 61/62

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                                                      82x 82x 82x 82x 82x 82x     82x 82x   82x       82x 43x 27x 27x   16x 16x 16x     82x       82x 34x 4x       82x 82x   82x   82x 104x       82x     82x 82x   82x 6x   82x             5x       5x 3x 3x   2x 2x 2x 2x 2x 1x             5x   1x 1x 1x 1x   1x       82x 7x 7x       82x           82x                                                                 2x 2x 2x             17x                                                                                                                                                                             6x                                                           3x                                   7x         39x                         2x                                                  
import { useState, useEffect } from "react";
import { Send, CheckCircle, AlertTriangle, Loader2 } from "lucide-react";
import { notify } from "../../../lib/notify";
import {
	Card,
	CardContent,
	CardHeader,
	CardTitle,
} from "../../../components/ui/card";
import {
	useCheckPhone,
	useSendMessage,
	useWhatsAppTemplates,
} from "../../../hooks/queries/useWhatsAppQueries";
import { getErrorMessage } from "../../../lib/api";
import { TemplateParameterFields } from "../../../components/whatsapp/TemplateParameterFields";
import {
	parseTemplateComponents,
	extractParameterSlots,
	buildSendComponents,
	isApprovedTemplate,
} from "../../../components/whatsapp/template-utils";
import { WhatsAppPageLayout } from "../../../components/whatsapp/WhatsAppPageLayout";
import { CountryCodeSelect } from "../../../components/whatsapp/CountryCodeSelect";
import { DEFAULT_COUNTRY_CODE } from "../../../components/whatsapp/country-codes";
 
export function WhatsAppSendPage() {
	const [phone, setPhone] = useState("");
	const [countryCode, setCountryCode] = useState(DEFAULT_COUNTRY_CODE);
	const [messageType, setMessageType] = useState<"text" | "template">("text");
	const [message, setMessage] = useState("");
	const [selectedTemplate, setSelectedTemplate] = useState("");
	const [paramValues, setParamValues] = useState<Record<string, string>>({});
 
	// Debounce the phone number for the check query
	const [debouncedPhone, setDebouncedPhone] = useState<string | null>(null);
	const normalizedPhone = phone.replace(/\D/g, "");
	const isValidPhone =
		countryCode === "91"
			? /^[6-9]\d{9}$/.test(normalizedPhone)
			: normalizedPhone.length >= 4 && normalizedPhone.length <= 15;
 
	useEffect(() => {
		if (!isValidPhone) {
			setDebouncedPhone(null);
			return;
		}
		const fullPhone = `${countryCode}${normalizedPhone}`;
		const timer = setTimeout(() => setDebouncedPhone(fullPhone), 500);
		return () => clearTimeout(timer);
	}, [countryCode, normalizedPhone, isValidPhone]);
 
	const { data: phoneCheck, isFetching: isCheckingPhone } =
		useCheckPhone(debouncedPhone);
 
	// Auto-switch to template when the 24hr window is closed
	useEffect(() => {
		if (phoneCheck && !phoneCheck.canSendText && messageType === "text") {
			setMessageType("template");
		}
	}, [phoneCheck, messageType]);
 
	const { data: templates = [] } = useWhatsAppTemplates();
	const sendMutation = useSendMessage();
 
	const approvedTemplates = templates.filter(isApprovedTemplate);
 
	const currentTemplate = approvedTemplates.find(
		(t) => t.name === selectedTemplate,
	);
 
	// Detect template variables
	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 handleSend = () => {
		const payload: {
			phone: string;
			message?: string;
			templateName?: string;
			language?: string;
			components?: unknown[];
		} = {
			phone: `${countryCode}${normalizedPhone}`,
		};
 
		if (messageType === "text") {
			Iif (!message.trim()) return;
			payload.message = message.trim();
		} else {
			Iif (!selectedTemplate || !currentTemplate) return;
			Iif (hasVariables && !allParamsFilled) return;
			payload.templateName = currentTemplate.name;
			payload.language = currentTemplate.language;
			if (hasVariables) {
				payload.components = buildSendComponents(
					templateComponents,
					paramValues,
				);
			}
		}
 
		sendMutation.mutate(payload, {
			onSuccess: () => {
				notify.success("Message sent successfully!");
				setMessage("");
				setSelectedTemplate("");
				setParamValues({});
			},
			onError: (err) => notify.error(getErrorMessage(err)),
		});
	};
 
	const handleTemplateChange = (name: string) => {
		setSelectedTemplate(name);
		setParamValues({});
	};
 
	const canSend =
		isValidPhone &&
		!sendMutation.isPending &&
		(messageType === "text"
			? !!message.trim()
			: !!selectedTemplate && allParamsFilled);
 
	return (
		<WhatsAppPageLayout>
		<div className="space-y-6 max-w-xl">
			{/* Header */}
			<div>
				<h1 className="text-2xl font-bold text-foreground-default">
					Quick Send
				</h1>
				<p className="mt-1 text-foreground-muted">
					Send a WhatsApp message to any phone number.
				</p>
			</div>
 
			<Card>
				<CardHeader>
					<CardTitle className="flex items-center gap-2">
						<Send className="h-5 w-5 text-green-600" />
						Send Message
					</CardTitle>
				</CardHeader>
				<CardContent className="space-y-4">
					{/* Phone Number */}
					<div>
						<label
							htmlFor="send-phone"
							className="block text-sm font-medium text-foreground-default mb-1"
						>
							Phone Number
						</label>
						<div className="flex">
							<CountryCodeSelect
								value={countryCode}
								onChange={(code) => {
									setCountryCode(code);
									setSelectedTemplate("");
									setParamValues({});
								}}
							/>
							<input
								id="send-phone"
								type="tel"
								value={phone}
								onChange={(e) => setPhone(e.target.value)}
								placeholder={countryCode === "91" ? "9876543210" : "Phone number"}
								maxLength={countryCode === "91" ? 10 : 15}
								className="flex-1 rounded-r-md border border-border-default px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-green-500"
							/>
						</div>
						{phone && !isValidPhone && (
							<p className="mt-1 text-xs text-red-500">
								{countryCode === "91"
									? "Enter a valid 10-digit Indian mobile number"
									: "Enter a valid phone number (at least 4 digits)"}
							</p>
						)}
 
						{/* Phone check status */}
						{isValidPhone && isCheckingPhone && (
							<div className="mt-2 flex items-center gap-2 text-xs text-foreground-muted">
								<Loader2 className="h-3.5 w-3.5 animate-spin" />
								Checking number...
							</div>
						)}
						{isValidPhone && !isCheckingPhone && phoneCheck && (
							<div
								className={`mt-2 flex items-start gap-2 rounded-md px-3 py-2 text-xs ${
									phoneCheck.canSendText
										? "bg-green-50 text-green-700"
										: "bg-amber-50 text-amber-700"
								}`}
							>
								{phoneCheck.canSendText ? (
									<CheckCircle className="h-3.5 w-3.5 mt-0.5 shrink-0" />
								) : (
									<AlertTriangle className="h-3.5 w-3.5 mt-0.5 shrink-0" />
								)}
								<div>
									{phoneCheck.canSendText ? (
										<>
											<span className="font-medium">24hr window open</span>
											{" — you can send text or template messages."}
											{phoneCheck.contactName && (
												<span className="block mt-0.5 text-green-600">
													Contact: {phoneCheck.contactName}
												</span>
											)}
										</>
									) : phoneCheck.exists ? (
										<>
											<span className="font-medium">24hr window expired</span>
											{" — only template messages can be sent."}
											{phoneCheck.contactName && (
												<span className="block mt-0.5 text-amber-600">
													Contact: {phoneCheck.contactName}
												</span>
											)}
										</>
									) : (
										<>
											<span className="font-medium">New number</span>
											{" — no prior conversation. Only template messages can be sent."}
										</>
									)}
								</div>
							</div>
						)}
					</div>
 
					{/* Message Type Toggle */}
					<fieldset>
						<legend className="block text-sm font-medium text-foreground-default mb-2">
							Message Type
						</legend>
						<div className="flex gap-2">
							<button
								type="button"
								aria-pressed={messageType === "text"}
								onClick={() => setMessageType("text")}
								className={`flex-1 px-3 py-2 text-sm rounded-md border transition-colors ${
									messageType === "text"
										? "border-green-600 bg-green-50 text-green-700 font-medium"
										: "border-border-default text-foreground-muted hover:bg-background-muted"
								}`}
							>
								Text Message
							</button>
							<button
								type="button"
								aria-pressed={messageType === "template"}
								onClick={() => setMessageType("template")}
								className={`flex-1 px-3 py-2 text-sm rounded-md border transition-colors ${
									messageType === "template"
										? "border-green-600 bg-green-50 text-green-700 font-medium"
										: "border-border-default text-foreground-muted hover:bg-background-muted"
								}`}
							>
								Template
							</button>
						</div>
						{messageType === "text" && (
							<p className="mt-2 text-xs text-foreground-subtle">
								Text messages only work if the recipient has messaged you within
								the last 24 hours.
							</p>
						)}
					</fieldset>
 
					{/* Message Input */}
					{messageType === "text" ? (
						<div>
							<label
								htmlFor="send-message"
								className="block text-sm font-medium text-foreground-default mb-1"
							>
								Message
							</label>
							<textarea
								id="send-message"
								value={message}
								onChange={(e) => setMessage(e.target.value)}
								placeholder="Type your message..."
								rows={4}
								className="w-full rounded-md border border-border-default px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-green-500 resize-none"
							/>
						</div>
					) : (
						<div className="space-y-4">
							<div>
								<label
									htmlFor="send-template"
									className="block text-sm font-medium text-foreground-default mb-1"
								>
									Template
								</label>
								<select
									id="send-template"
									value={selectedTemplate}
									onChange={(e) => handleTemplateChange(e.target.value)}
									className="w-full rounded-md border border-border-default px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-green-500"
								>
									<option value="">Select an approved template...</option>
									{approvedTemplates.map((t) => (
										<option key={t.id} value={t.name}>
											{t.name} ({t.language})
										</option>
									))}
								</select>
							</div>
 
							{/* Template parameter fields + preview */}
							{currentTemplate && (
								<TemplateParameterFields
									template={currentTemplate}
									paramValues={paramValues}
									onParamChange={(key, value) =>
										setParamValues((prev) => ({ ...prev, [key]: value }))
									}
								/>
							)}
						</div>
					)}
 
					{/* Send Button */}
					<div className="pt-2">
						<button
							type="button"
							onClick={handleSend}
							disabled={!canSend}
							className="w-full inline-flex items-center justify-center gap-2 rounded-md bg-green-600 px-4 py-2.5 text-sm font-medium text-white hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
						>
							<Send className="h-4 w-4" />
							{sendMutation.isPending ? "Sending..." : "Send Message"}
						</button>
					</div>
				</CardContent>
			</Card>
		</div>
		</WhatsAppPageLayout>
	);
}