All files / src/pages/admin/whatsapp/campaigns create.tsx

96% Statements 96/100
91.93% Branches 57/62
96.55% Functions 28/29
98.87% Lines 88/89

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                                                    177x 177x 177x 177x   177x 177x 177x     177x 177x 177x 177x     177x   177x     177x 177x 177x 177x 177x 177x 177x   177x   177x 177x       177x     177x 177x                     177x   177x       177x 53x 4x               177x 66x   13x 13x 13x     13x 2x 2x               13x   9x     13x     177x 29x           29x   29x 1x     29x   26x 26x 26x     1x       177x 5x   5x   5x     6x   5x   5x 4x   5x   5x   5x       2x 2x   1x         177x 3x 3x   2x       1x 1x     1x 1x           177x 4x   4x   2x 2x     2x   1x       177x 33x 33x         177x                                               1x         9x 3x            
import { useState, useEffect } from "react";
import { useNavigate, useSearch } from "@tanstack/react-router";
import { notify } from "../../../../lib/notify";
import { useQueryClient } from "@tanstack/react-query";
import {
	useWhatsAppTemplates,
	useWhatsAppCampaign,
	useCreateCampaign,
	useLaunchCampaign,
	useCampaignRecipients,
	useAddRecipientsManual,
	useAddRecipientsCSV,
} from "../../../../hooks/queries/useWhatsAppQueries";
import { getErrorMessage } from "../../../../lib/api";
import { DEFAULT_COUNTRY_CODE } from "../../../../components/whatsapp/country-codes";
import {
	parseTemplateComponents,
	extractParameterSlots,
	isApprovedTemplate,
} from "../../../../lib/whatsapp/template";
import { queryKeys } from "../../../../lib/query-keys";
import { CampaignWizard } from "./CampaignWizardSteps.subcomponent";
 
type Recipient = { phone: string; name?: string };
 
export function WhatsAppCampaignCreatePage() {
	const navigate = useNavigate();
	const queryClient = useQueryClient();
	const search = useSearch({ strict: false }) as { viewId?: number };
	const viewId = search.viewId ?? null;
 
	const [step, setStep] = useState(1);
	const [campaignName, setCampaignName] = useState("");
	const [selectedTemplateId, setSelectedTemplateId] = useState<number | null>(
		null,
	);
	const [campaignId, setCampaignId] = useState<number | null>(viewId);
	const [countryCode, setCountryCode] = useState(DEFAULT_COUNTRY_CODE);
	const [manualInput, setManualInput] = useState("");
	const [templateParamValues, setTemplateParamValues] = useState<
		Record<string, string>
	>({});
	const [initialized, setInitialized] = useState(!viewId);
 
	const { data: templates = [] } = useWhatsAppTemplates();
	// The detail envelope, not a bare campaign row: `.campaign` is the row the
	// wizard edits. A non-draft is not editable at all — see the redirect below.
	const { data: campaignDetail } = useWhatsAppCampaign(viewId);
	const existingCampaign = campaignDetail?.campaign;
	const createMutation = useCreateCampaign();
	const launchMutation = useLaunchCampaign();
	const addManualMutation = useAddRecipientsManual();
	const csvUploadMutation = useAddRecipientsCSV();
	const { data: recipients = [] } = useCampaignRecipients(campaignId);
 
	const approvedTemplates = templates.filter(isApprovedTemplate);
 
	const selectedTemplate = approvedTemplates.find(
		(t) => t.id === selectedTemplateId,
	);
 
	// Detect template variables for campaign template params
	const templateComponents = selectedTemplate
		? parseTemplateComponents(selectedTemplate.components)
		: [];
	const templateSlots = extractParameterSlots(templateComponents);
	const hasTemplateVariables = templateSlots.length > 0;
 
	/**
	 * A launched campaign is not editable, so `?viewId=` on a non-draft is not
	 * a mode of this wizard — it is the old URL for a read view that now has
	 * its own route. Redirect, replacing history so Back does not bounce.
	 *
	 * Kept rather than deleted because the old link shape is in bookmarks and
	 * in anything an admin pasted into Slack.
	 */
	const isLaunched =
		viewId !== null && existingCampaign && existingCampaign.status !== "draft";
	const isDraftEdit =
		viewId !== null &&
		existingCampaign &&
		existingCampaign.status === "draft";
 
	useEffect(() => {
		if (!isLaunched || !existingCampaign) return;
		navigate({
			to: "/admin/whatsapp/campaigns/$campaignId",
			params: { campaignId: String(existingCampaign.id) },
			replace: true,
		});
	}, [isLaunched, existingCampaign, navigate]);
 
	// Initialize state from existing campaign
	useEffect(() => {
		if (!existingCampaign || initialized) return;
 
		setCampaignName(existingCampaign.name);
		setSelectedTemplateId(existingCampaign.templateId);
		setCampaignId(existingCampaign.id);
 
		// Load saved template params
		if (existingCampaign.templateParams) {
			try {
				setTemplateParamValues(
					JSON.parse(existingCampaign.templateParams),
				);
			} catch {
				// ignore parse errors
			}
		}
 
		if (existingCampaign.status === "draft") {
			// Draft with recipients → step 2, otherwise step 1
			setStep(existingCampaign.statsTotal > 0 ? 2 : 1);
		}
 
		setInitialized(true);
	}, [existingCampaign, initialized]);
 
	const handleCreateCampaign = async () => {
		Iif (!campaignName || !selectedTemplateId) return;
 
		const payload: {
			name: string;
			templateId: number;
			templateParams?: string;
		} = { name: campaignName, templateId: selectedTemplateId };
 
		if (hasTemplateVariables && Object.keys(templateParamValues).length > 0) {
			payload.templateParams = JSON.stringify(templateParamValues);
		}
 
		createMutation.mutate(payload, {
			onSuccess: (res) => {
				Eif (res.data?.campaign) {
					setCampaignId(res.data.campaign.id);
					setStep(2);
				}
			},
			onError: (err) => notify.error(getErrorMessage(err)),
		});
	};
 
	const handleAddManualRecipients = () => {
		Iif (!campaignId || !manualInput.trim()) return;
 
		const newRecipients: Recipient[] = manualInput
			.split("\n")
			.map((line) => line.trim())
			.filter(Boolean)
			.map((line) => {
				const [rawPhone, name] = line.split(",").map((s) => s.trim());
				// Strip all non-digits
				let digits = rawPhone.replace(/\D/g, "");
				// Only prepend country code if it's exactly 10 digits (Indian mobile)
				if (digits.length === 10) {
					digits = `${countryCode}${digits}`;
				}
				return { phone: digits, name: name || undefined };
			})
			.filter((r) => r.phone && r.phone.length >= 10);
 
		addManualMutation.mutate(
			{ campaignId, recipients: newRecipients },
			{
				onSuccess: () => {
					setManualInput("");
					notify.success(`${newRecipients.length} recipients added`);
				},
				onError: (err) => notify.error(getErrorMessage(err)),
			},
		);
	};
 
	const handleCsvUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
		const file = e.target.files?.[0];
		if (!file || !campaignId) return;
 
		csvUploadMutation.mutate(
			{ campaignId, file },
			{
				onSuccess: () => {
					notify.success("CSV recipients uploaded");
					e.target.value = "";
				},
				onError: (err) => {
					notify.error(getErrorMessage(err));
					e.target.value = "";
				},
			},
		);
	};
 
	const handleLaunch = async () => {
		Iif (!campaignId) return;
 
		launchMutation.mutate(campaignId, {
			onSuccess: async () => {
				notify.success("Campaign launched!");
				await queryClient.invalidateQueries({
					queryKey: queryKeys.admin.whatsapp.campaigns(),
				});
				navigate({ to: "/admin/whatsapp/campaigns" });
			},
			onError: (err) => notify.error(getErrorMessage(err)),
		});
	};
 
	const handleTemplateChange = (id: number | null) => {
		setSelectedTemplateId(id);
		setTemplateParamValues({});
	};
 
	// ── Create / Draft Edit wizard ────────────────────────────────────────
 
	return (
		<CampaignWizard
			step={step as 1 | 2 | 3}
			// The server's answer to "can this be stopped once launched". It
			// cannot, and step 3 says so before the button is pressed rather
			// than after. Defaults to the truth while the draft is still being
			// created and there is no detail response yet.
			stoppable={campaignDetail?.stoppable ?? false}
			isDraftEdit={!!isDraftEdit}
			campaignName={campaignName}
			selectedTemplateId={selectedTemplateId}
			approvedTemplates={approvedTemplates}
			selectedTemplate={selectedTemplate}
			hasTemplateVariables={hasTemplateVariables}
			templateParamValues={templateParamValues}
			templateSlotsCount={templateSlots.length}
			countryCode={countryCode}
			manualInput={manualInput}
			recipients={recipients}
			createPending={createMutation.isPending}
			csvUploadPending={csvUploadMutation.isPending}
			launchPending={launchMutation.isPending}
			onCampaignNameChange={setCampaignName}
			onTemplateChange={handleTemplateChange}
			onParamChange={(key, value) => setTemplateParamValues((prev) => ({ ...prev, [key]: value }))}
			onCountryCodeChange={setCountryCode}
			onManualInputChange={setManualInput}
			onAddManual={handleAddManualRecipients}
			onCsvUpload={handleCsvUpload}
			onNext={isDraftEdit ? () => setStep((s) => (s === 1 ? 2 : 3)) : step === 1 ? handleCreateCampaign : () => setStep(3)}
			onBack={() => setStep((s) => (s === 2 ? 1 : 2))}
			onLaunch={handleLaunch}
			onNavigateBack={() => navigate({ to: "/admin/whatsapp/campaigns" })}
		/>
	);
}