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 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 | 12x 12x 12x 12x 179x 2x 177x 14x 14x 163x 12x 12x 13x 8x 8x 64x 3x 3x 2x 5x 5x 4x 1x 3x 5x 4x 3x 3x 3x 3x 10x 10x 9x 1x 8x 8x 8x 1x 7x 7x 13x 6x 6x 1x 5x 5x 5x 5x 6x 6x 6x 1x 1x 5x 5x 11x 2x 5x 5x 5x 5x 5x 16x 16x 15x 1x 14x 14x 1x 13x 1x 12x 12x 1x 11x 11x 1x 10x 10x 10x 10x 9x 9x 10x 10x 3x 3x 10x 11x 12x 12x 12x 5x 12x 11x 11x 12x 11x 14x 13x 14x 14x 14x 14x 14x 11x 14x 11x 2x 2x 2x 13x 13x 7x 7x 5x 5x 4x 4x 2x 2x 2x 12x 12x 12x 8x 8x 7x 6x 6x 5x 6x 1x 5x 6x 6x 6x 5x 12x 11x 9x 9x | import {
isValidIndianMobile,
normalizeToE164,
} from "@interioring/utils/validation/phone";
import type { Dal } from "../../dal";
import type {
NewWaCampaignRecipient,
WaCampaign,
WaCampaignRecipient,
WaTemplate,
} from "../../db/schema";
import { applySafetyGuard } from "../../lib/communication/adapters/whatsapp.adapter";
import { NotFoundError, ValidationError } from "../../lib/errors";
import type {
WhatsAppClient,
WhatsAppOutboundPayload,
WhatsAppQueueMessage,
WhatsAppTemplateComponent,
} from "../../lib/whatsapp";
import {
createDryRunWhatsAppClient,
shouldDryRunWhatsAppSend,
} from "../../lib/whatsapp/client";
/** Simple CSV line parser that handles quoted fields */
function parseCsvLine(line: string): string[] {
const result: string[] = [];
let current = "";
let inQuotes = false;
for (const char of line) {
if (char === '"') {
inQuotes = !inQuotes;
} else if (char === "," && !inQuotes) {
result.push(current.trim());
current = "";
} else {
current += char;
}
}
result.push(current.trim());
return result;
}
/**
* Replace the recipient on an outbound payload, leaving the one payload shape
* that has no recipient (a read receipt) alone.
*/
function withRecipient(
payload: WhatsAppOutboundPayload,
to: string,
): WhatsAppOutboundPayload {
if (!("to" in payload)) return payload;
return { ...payload, to };
}
/**
* Whether a campaign can be stopped once it has been launched. It cannot, and
* this constant exists so the server says so rather than the page assuming it.
*
* `launch()` enqueues every recipient onto `wa-send` in one pass, so the moment
* the request returns the work lives in the queue, not in the campaign row.
* Stopping it would mean `processQueueMessage` re-reading campaign status
* before every send, a `cancelled` status, and a cancel route — a new
* capability with in-flight-message semantics, not a read view. It is
* deliberately not built.
*
* What is built is the honesty: an admin should learn this BEFORE launching,
* which is why it rides on the detail response a draft campaign is read
* through. The day a cancel path lands, this flag becomes the only thing the
* page has to re-read.
*/
export const CAMPAIGN_STOPPABLE = false;
export class CampaignService {
constructor(private dal: Dal) {}
async create(
name: string,
templateId: number,
createdBy: string,
templateParams?: string,
): Promise<WaCampaign> {
const template = await this.dal.waTemplates.findById(templateId);
if (!template) throw new NotFoundError("Template", String(templateId));
return this.dal.waCampaigns.create({
name,
templateId,
createdBy,
templateParams: templateParams ?? null,
status: "draft",
statsTotal: 0,
statsSent: 0,
statsDelivered: 0,
statsRead: 0,
statsFailed: 0,
});
}
async addRecipientsManual(
campaignId: number,
recipients: Array<{
phone: string;
name?: string;
params?: Record<string, string>;
}>,
): Promise<number> {
const campaign = await this.dal.waCampaigns.findById(campaignId);
if (!campaign) throw new NotFoundError("Campaign", String(campaignId));
if (campaign.status !== "draft") {
throw new ValidationError("Can only add recipients to draft campaigns");
}
const dbRecipients: NewWaCampaignRecipient[] = recipients
.filter((r) => this.isValidPhone(r.phone))
.map((r) => ({
campaignId,
phoneNumber: this.normalizePhone(r.phone),
contactName: r.name ?? null,
templateParams: r.params ? JSON.stringify(r.params) : null,
status: "pending" as const,
}));
await this.dal.waCampaigns.addRecipients(dbRecipients);
// Update total count
const count = await this.dal.waCampaigns.getRecipientCount(campaignId);
await this.dal.waCampaigns.update(campaignId, { statsTotal: count });
return dbRecipients.length;
}
async addRecipientsFromCSV(
campaignId: number,
csvContent: string,
): Promise<{ added: number; skipped: number }> {
const campaign = await this.dal.waCampaigns.findById(campaignId);
if (!campaign) throw new NotFoundError("Campaign", String(campaignId));
if (campaign.status !== "draft") {
throw new ValidationError("Can only add recipients to draft campaigns");
}
const MAX_CSV_ROWS = 10_000;
const lines = csvContent
.replace(/\r\n/g, "\n")
.replace(/\r/g, "\n")
.trim()
.split("\n");
if (lines.length < 2)
throw new ValidationError("CSV must have at least a header and one row");
if (lines.length - 1 > MAX_CSV_ROWS)
throw new ValidationError(
`CSV has too many rows (${lines.length - 1}). Maximum is ${MAX_CSV_ROWS}.`,
);
const header = parseCsvLine(lines[0]).map((h) => h.toLowerCase());
const phoneIdx = header.indexOf("phone");
if (phoneIdx === -1)
throw new ValidationError("CSV must have a 'phone' column");
const nameIdx = header.indexOf("name");
const recipients: NewWaCampaignRecipient[] = [];
let skipped = 0;
for (let i = 1; i < lines.length; i++) {
const cols = parseCsvLine(lines[i]);
const phone = cols[phoneIdx];
if (!phone || !this.isValidPhone(phone)) {
skipped++;
continue;
}
// Collect param columns (any column that isn't phone or name)
const params: Record<string, string> = {};
for (let j = 0; j < header.length; j++) {
if (j !== phoneIdx && j !== nameIdx && cols[j]) {
params[header[j]] = cols[j];
}
}
recipients.push({
campaignId,
phoneNumber: this.normalizePhone(phone),
contactName: nameIdx >= 0 ? (cols[nameIdx] ?? null) : null,
templateParams:
Object.keys(params).length > 0 ? JSON.stringify(params) : null,
status: "pending",
});
}
await this.dal.waCampaigns.addRecipients(recipients);
const count = await this.dal.waCampaigns.getRecipientCount(campaignId);
await this.dal.waCampaigns.update(campaignId, { statsTotal: count });
return { added: recipients.length, skipped };
}
/**
* Launch campaign: validate, set status to sending, enqueue all recipients.
*/
async launch(campaignId: number, queue: Queue): Promise<void> {
const campaign = await this.dal.waCampaigns.findById(campaignId);
if (!campaign) throw new NotFoundError("Campaign", String(campaignId));
if (campaign.status !== "draft") {
throw new ValidationError("Campaign must be in draft status to launch");
}
// Validate template is approved
const template = await this.dal.waTemplates.findById(campaign.templateId);
if (!template)
throw new NotFoundError("Template", String(campaign.templateId));
if (template.status !== "APPROVED") {
throw new ValidationError("Template must be APPROVED before sending");
}
// Check we have recipients
const recipientCount =
await this.dal.waCampaigns.getRecipientCount(campaignId);
if (recipientCount === 0) {
throw new ValidationError("Campaign has no recipients");
}
// Atomically set campaign to sending — prevents double-launch race condition
const transitioned = await this.dal.waCampaigns.atomicStatusTransition(
campaignId,
"draft",
"sending",
);
if (!transitioned) {
throw new ValidationError(
"Campaign is already being sent or has been modified",
);
}
// Enqueue all pending recipients in batches.
// Uses status-based pagination: each batch fetches "pending" rows, then
// transitions them to "queued" before the next fetch — no offset needed.
const batchSize = 50;
let batch = await this.dal.waCampaigns.getPendingRecipients(
campaignId,
batchSize,
);
let templateComponents: Array<{
type: string;
text?: string;
format?: string;
}> = [];
if (template.components) {
try {
templateComponents = JSON.parse(template.components);
} catch {
throw new Error(
"Campaign template components data is corrupted. Please re-sync templates.",
);
}
}
// Parse campaign-level default template params
let campaignParams: Record<string, string> = {};
if (campaign.templateParams) {
try {
campaignParams = JSON.parse(campaign.templateParams);
} catch {
throw new Error("Campaign template parameters data is corrupted.");
}
}
while (batch.length > 0) {
const messages: MessageSendRequest<WhatsAppQueueMessage>[] = batch.map(
(recipient) => {
// Build template components with parameter values
const components = this.buildTemplateComponents(
templateComponents,
recipient,
campaignParams,
);
const tpl: {
name: string;
language: {
code: string;
policy: "deterministic";
};
components?: WhatsAppTemplateComponent[];
} = {
name: template.name,
language: {
code: template.language,
policy: "deterministic",
},
};
if (components.length > 0) {
tpl.components = components;
}
return {
body: {
type: "campaign_send" as const,
campaignId,
recipientId: recipient.id,
phone: recipient.phoneNumber,
payload: {
messaging_product: "whatsapp" as const,
to: recipient.phoneNumber,
type: "template" as const,
template: tpl,
},
},
};
},
);
await queue.sendBatch(messages);
// Mark recipients as queued in a single query
await this.dal.waCampaigns.updateRecipientStatusBatch(
batch.map((r) => r.id),
"queued",
);
batch = await this.dal.waCampaigns.getPendingRecipients(
campaignId,
batchSize,
);
}
}
/**
* Process a single campaign queue message: send template and update status.
*
* `whatsAppClient` is the LIVE client for the environment. Whether this
* message is allowed to touch it is decided below, per recipient.
*/
async processQueueMessage(
msg: WhatsAppQueueMessage,
whatsAppClient: WhatsAppClient,
env: CloudflareBindings,
): Promise<void> {
if (!msg.campaignId || !msg.recipientId) return;
// SAFETY — both halves of it, here, immediately before the send.
//
// The guard has to be applied HERE rather than by the caller, because
// the thing that actually reaches Meta is `msg.payload`, and `launch()`
// built that payload at enqueue time with `to: recipient.phoneNumber`
// read straight out of `wa_campaign_recipients`. A recipient guarded
// upstream but not written back into the payload would be silently
// discarded by the `sendRaw` below — the exact failure this guards
// against. So: derive the recipient from the payload, guard it, and put
// the guarded value back. Nothing after this point re-reads a recipient;
// if you add a lookup, it must not reach `sendRaw`.
const requestedRecipient = "to" in msg.payload ? msg.payload.to : msg.phone;
const recipient = applySafetyGuard(requestedRecipient, env);
const payload = withRecipient(msg.payload, recipient);
// Which client may see it follows from the guard's outcome, so it is a
// per-recipient decision and cannot be made once per batch by the queue
// handler. Same rule as `WhatsAppAdapter.send` — one function, not two
// doctrines.
const client = shouldDryRunWhatsAppSend(
env,
recipient !== requestedRecipient,
)
? createDryRunWhatsAppClient(
env.ENVIRONMENT ?? "unknown",
env.WHATSAPP_ACCESS_TOKEN,
)
: whatsAppClient;
try {
const result = await client.sendRaw(payload);
const wamid = result.messages[0]?.id;
await this.dal.waCampaigns.updateRecipientStatus(
msg.recipientId,
"sent",
wamid,
);
await this.dal.waCampaigns.incrementStat(msg.campaignId, "statsSent");
} catch (error) {
const errorCode = error instanceof Error ? error.message : "unknown";
await this.dal.waCampaigns.updateRecipientStatus(
msg.recipientId,
"failed",
undefined,
errorCode,
);
await this.dal.waCampaigns.incrementStat(msg.campaignId, "statsFailed");
}
// Auto-complete campaign when all messages are processed
await this.checkCampaignCompletion(msg.campaignId);
}
private async checkCampaignCompletion(campaignId: number): Promise<void> {
// Atomic: only transitions to completed if still sending and all messages processed
await this.dal.waCampaigns.completeIfDone(campaignId);
}
async getById(id: number): Promise<WaCampaign> {
const campaign = await this.dal.waCampaigns.findById(id);
if (!campaign) throw new NotFoundError("Campaign", String(id));
return campaign;
}
/**
* Everything a campaign detail screen renders, in one request.
*
* The campaign row carries `templateId` but not the template's name, and
* `statsTotal` is a counter the send path maintains rather than a count of
* recipient rows. A detail view built on `getById` alone therefore had to
* fetch the whole template list to resolve one id, and print "Recipients
* (N)" where N was a page size. Both are read-model gaps, so both are
* closed here rather than on the page.
*/
async getDetail(id: number): Promise<{
campaign: WaCampaign;
template: WaTemplate | null;
recipientTotal: number;
stoppable: typeof CAMPAIGN_STOPPABLE;
}> {
const campaign = await this.getById(id);
const [template, recipientTotal] = await Promise.all([
this.dal.waTemplates.findById(campaign.templateId),
this.dal.waCampaigns.getRecipientCount(id),
]);
return {
campaign,
template: template ?? null,
recipientTotal,
stoppable: CAMPAIGN_STOPPABLE,
};
}
async list(filters: { status?: string }, offset: number, limit: number) {
const [campaigns, total] = await Promise.all([
this.dal.waCampaigns.findAll(filters, offset, limit),
this.dal.waCampaigns.count(filters),
]);
return { campaigns, total };
}
async getRecipients(
campaignId: number,
filters: { status?: string },
offset: number,
limit: number,
) {
return this.dal.waCampaigns.getRecipients(
campaignId,
filters,
offset,
limit,
);
}
/**
* Build WhatsApp API components array with parameter values for a recipient.
* Per-recipient params override campaign-level defaults.
*/
private buildTemplateComponents(
templateComponents: Array<{
type: string;
text?: string;
format?: string;
}>,
recipient: WaCampaignRecipient,
campaignParams: Record<string, string>,
): WhatsAppTemplateComponent[] {
const recipientParams: Record<string, string> = recipient.templateParams
? JSON.parse(recipient.templateParams)
: {};
const result: WhatsAppTemplateComponent[] = [];
for (const comp of templateComponents) {
const compType = comp.type?.toUpperCase();
if (compType !== "HEADER" && compType !== "BODY") continue;
if (!comp.text) continue;
const matches = comp.text.match(/\{\{(\d+)\}\}/g);
if (!matches) continue;
const indices = [
...new Set(
matches.map((m) => Number.parseInt(m.replace(/\{|\}/g, ""), 10)),
),
].sort((a, b) => a - b);
const parameters = indices.map((idx) => {
const key = `${compType}_${idx}`;
// Per-recipient params take priority, then campaign defaults
const value =
recipientParams[key] ||
campaignParams[key] ||
recipientParams[String(idx)] ||
campaignParams[String(idx)] ||
"";
return { type: "text" as const, text: value };
});
result.push({
type: compType.toLowerCase() as "header" | "body",
parameters,
});
}
return result;
}
private isValidPhone(phone: string): boolean {
return isValidIndianMobile(phone);
}
private normalizePhone(phone: string): string {
// WhatsApp recipients are stored without the leading "+" (e.g. "919876543210")
// for backward compat with existing campaign rows.
const e164 = normalizeToE164(phone);
return e164 ? e164.slice(1) : phone.replace(/\D/g, "");
}
}
|