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 | 1x 1x 1x 1x 1x 1x 1x 2x 2x 7x 3x 2x 1x 9x 9x 9x 5x 5x 1x 1x 2x 1x 1x 7x 7x 7x 7x 15x 7x 5x 5x 5x 3x 3x 5x 5x 7x 7x 7x 7x 7x 2x 1x 26x 23x 26x 51x 26x 26x 4x 4x 4x 4x 3x 4x 23x 23x 23x 2x 3x 1x 1x 5x 5x 5x 4x 4x 16x 16x 4x 1x 1x 6x 6x 6x 6x 3x 3x 3x 3x 3x 12x 12x 9x 9x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 2x | import { and, desc, eq, gte, inArray, lt, sql } from "drizzle-orm";
import { Hono } from "hono";
import {
getTemplateSpec,
RRM_LADDER_TEMPLATE_NAMES,
TPL_RRM_PARTNER_REFERRAL_UPDATE,
} from "../../../config/whatsapp-templates";
import type { Dal } from "../../../dal";
import { RRM_CONFIG_DEFAULTS, RRM_CONFIG_KEYS } from "../../../dal/rrm";
import * as schema from "../../../db/schema";
import { RRM_LOCALES } from "../../../db/schema/enums";
import type { RrmScheduledStep, RrmTemplate } from "../../../db/schema/rrm";
import { ValidationError } from "../../../lib/errors";
import { generateId } from "../../../lib/ids";
import { error, handleError, success } from "../../../lib/response";
import {
DAY_MS,
istDayStart,
istParts,
remainingDailySends,
} from "../../../lib/rrm/time";
import {
requireWhatsAppClient,
WhatsAppConfigError,
} from "../../../lib/whatsapp/client";
import type { WhatsAppTemplateFromMeta } from "../../../lib/whatsapp/types";
import type { Services } from "../../../services";
/**
* The ladder's admin surface — F-21, `/api/admin/rrm/{schedule,templates}`.
*
* Auth: the parent admin router applies `contextMiddleware` and
* `requirePlatformAdmin`. Nothing is re-applied per route (see ramp.routes.ts,
* which documents the same thing for the release gate).
*
* `/config` lives in ramp.routes.ts, not here — it already owned the pacing
* table before the ladder existed, and this file only extends the surface
* with what the sequence engine needs an operator to see: today's schedule
* and the three templates it cannot enrol anyone without.
*/
type Env = {
Bindings: CloudflareBindings;
Variables: {
user: { id: string; name: string; email: string } | null;
session: unknown;
dal: Dal;
services: Services;
};
};
const STEPS = schema.rrmScheduledSteps;
const PROSPECTS = schema.rrmProspects;
const EVENTS = schema.rrmProspectEvents;
const TEMPLATES = schema.rrmTemplates;
const ladder = new Hono<Env>();
// ── GET /api/admin/rrm/schedule ─────────────────────────────────────────────
/** A schedule page longer than this is a queue nobody is reading, not a list. */
const MAX_SCHEDULE_ITEMS = 200;
const DAY_RE = /^\d{4}-\d{2}-\d{2}$/;
export type ScheduleItem = {
stepId: string;
runId: string;
prospectId: string;
prospectName: string | null;
phoneNorm: string;
stepKey: string;
state: RrmScheduledStep["state"];
dueAt: string;
enqueuedAt: string | null;
};
/** Rejects calendar nonsense (`2024-02-30`) that the regex alone lets through. */
function isValidCalendarDateISO(iso: string): boolean {
const parsed = new Date(`${iso}T00:00:00.000Z`);
return (
!Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === iso
);
}
/** `?day=` defaults to today, IST — never the Worker's UTC "today". */
function parseDayParam(raw: string | undefined): string {
if (raw === undefined) return istParts(Date.now()).dateISO;
if (!DAY_RE.test(raw) || !isValidCalendarDateISO(raw)) {
throw new ValidationError("day must be a valid YYYY-MM-DD date");
}
return raw;
}
/**
* The `[start, end)` instant range covering the IST calendar day `dayISO`.
*
* Anchored at noon UTC on `dayISO` because an IST day spans 18:30 UTC the
* previous day to 18:30 UTC that day — noon UTC on the date itself always
* falls inside it, so `istDayStart` floors from a point that is guaranteed to
* be in the right day regardless of the anchor's own UTC/IST date mismatch.
*/
export function istDayBounds(dayISO: string): { start: Date; end: Date } {
const anchor = new Date(`${dayISO}T12:00:00.000Z`);
const start = istDayStart(anchor);
return { start, end: new Date(start.getTime() + DAY_MS) };
}
async function loadProspectInfo(
dal: Dal,
ids: string[],
): Promise<Map<string, { name: string | null; phoneNorm: string }>> {
const info = new Map<string, { name: string | null; phoneNorm: string }>();
if (ids.length === 0) return info;
const rows = await dal.db
.select({
id: PROSPECTS.id,
name: PROSPECTS.name,
phoneNorm: PROSPECTS.phoneNorm,
})
.from(PROSPECTS)
.where(inArray(PROSPECTS.id, ids));
for (const row of rows) {
info.set(row.id, { name: row.name, phoneNorm: row.phoneNorm });
}
return info;
}
// GET /api/admin/rrm/schedule
ladder.get("/schedule", async (c) => {
try {
const dal = c.get("dal");
const dayISO = parseDayParam(c.req.query("day"));
const { start, end } = istDayBounds(dayISO);
const inDay = (column: typeof STEPS.dueAt | typeof EVENTS.occurredAt) =>
and(gte(column, start), lt(column, end));
const [countRows, blockedRows, itemRows, dailyCap] = await Promise.all([
// One aggregate pass rather than deriving counts from `itemRows` below —
// `itemRows` is capped at MAX_SCHEDULE_ITEMS and a busy day would
// otherwise undercount silently.
dal.db
.select({
sent: sql<number>`coalesce(sum(case when ${STEPS.state} = 'sent' then 1 else 0 end), 0)`,
enqueued: sql<number>`coalesce(sum(case when ${STEPS.state} = 'enqueued' then 1 else 0 end), 0)`,
pendingDue: sql<number>`coalesce(sum(case when ${STEPS.state} = 'pending' then 1 else 0 end), 0)`,
skipped: sql<number>`coalesce(sum(case when ${STEPS.state} = 'skipped' then 1 else 0 end), 0)`,
})
.from(STEPS)
.where(inDay(STEPS.dueAt)),
dal.db
.select({ blocked: sql<number>`count(*)` })
.from(EVENTS)
.where(and(eq(EVENTS.type, "send_blocked"), inDay(EVENTS.occurredAt))),
dal.db
.select({
id: STEPS.id,
runId: STEPS.runId,
prospectId: STEPS.prospectId,
stepKey: STEPS.stepKey,
state: STEPS.state,
dueAt: STEPS.dueAt,
enqueuedAt: STEPS.enqueuedAt,
})
.from(STEPS)
.where(inDay(STEPS.dueAt))
.orderBy(desc(STEPS.dueAt))
.limit(MAX_SCHEDULE_ITEMS),
dal.rrmConfig.getNumber(
RRM_CONFIG_KEYS.dailySendCap,
RRM_CONFIG_DEFAULTS[RRM_CONFIG_KEYS.dailySendCap],
),
]);
const prospectIds = [...new Set(itemRows.map((row) => row.prospectId))];
const prospects = await loadProspectInfo(dal, prospectIds);
const items: ScheduleItem[] = itemRows.map((row) => {
const prospect = prospects.get(row.prospectId);
return {
stepId: row.id,
runId: row.runId,
prospectId: row.prospectId,
prospectName: prospect?.name ?? null,
phoneNorm: prospect?.phoneNorm ?? "",
stepKey: row.stepKey,
state: row.state,
dueAt: row.dueAt.toISOString(),
enqueuedAt: row.enqueuedAt ? row.enqueuedAt.toISOString() : null,
};
});
const countRow = countRows[0];
const sent = Number(countRow?.sent ?? 0);
const enqueued = Number(countRow?.enqueued ?? 0);
const pendingDue = Number(countRow?.pendingDue ?? 0);
const skipped = Number(countRow?.skipped ?? 0);
const blocked = Number(blockedRows[0]?.blocked ?? 0);
return success(c, {
day: dayISO,
counts: { sent, enqueued, pendingDue, blocked, skipped },
cap: {
dailySendCap: dailyCap,
usedToday: sent,
remaining: remainingDailySends(sent, dailyCap),
},
items,
});
} catch (err) {
return handleError(c, err);
}
});
// ── GET /api/admin/rrm/templates, POST /api/admin/rrm/templates/sync ───────
/** Meta template bodies run long; the admin list only needs a taste of one. */
const BODY_PREVIEW_MAX = 160;
export type RrmLadderTemplateSummary = {
name: string;
language: string;
category: string;
/** One of `RRM_TEMPLATE_STATUS`, or `NOT_SUBMITTED` for a name with no row. */
status: string;
metaTemplateId: string | null;
/**
* `rrm_templates` has no `rejected_reason` column (unlike the sibling
* `wa_templates` table, which does) — see the comment inside the
* `POST /templates/sync` handler below. Always `null` here; that handler
* fills it in from the live Meta response for that one call only.
*/
rejectedReason: string | null;
bodyPreview: string | null;
variableCount: number;
updatedAt: string | null;
};
function truncate(text: string, max: number): string {
if (text.length <= max) return text;
return `${text.slice(0, max - 1)}…`;
}
/** Meta's templates use sequential `{{1}}`, `{{2}}`, ... placeholders. */
function countVariables(bodyText: string): number {
const indices = [...bodyText.matchAll(/\{\{(\d+)\}\}/g)].map((m) =>
Number(m[1]),
);
return indices.length > 0 ? Math.max(...indices) : 0;
}
/**
* Shared by the not-yet-submitted preview and the post-sync summary so the
* "no BODY component" fallback is exercised — and covered — from one place
* regardless of which caller happens to hit it.
*/
function extractBodyText(
components: ReadonlyArray<{ type: string; text?: string }>,
): string {
return components.find((component) => component.type === "BODY")?.text ?? "";
}
/** The columns the admin list actually needs — narrower than `RrmTemplate` so
* a raw D1 row and a freshly-synced Meta row can share one formatter. */
type TemplateRow = Pick<
RrmTemplate,
| "name"
| "language"
| "category"
| "status"
| "metaTemplateId"
| "rejectedReason"
| "bodyPreview"
| "variableCount"
| "dateUpdated"
>;
/** The stored row wins; a name with several rows (language/version) uses the
* most recently synced one. */
function latestByName(rows: TemplateRow[]): Map<string, TemplateRow> {
const byName = new Map<string, TemplateRow>();
for (const row of rows) {
const existing = byName.get(row.name);
if (
!existing ||
row.dateUpdated.getTime() > existing.dateUpdated.getTime()
) {
byName.set(row.name, row);
}
}
return byName;
}
/** Before anything is ever submitted, show what WILL be submitted. */
function notSubmittedSummary(name: string): RrmLadderTemplateSummary {
const spec = getTemplateSpec(name);
const bodyText = extractBodyText(spec.components);
return {
name,
language: spec.language,
category: spec.category,
status: "NOT_SUBMITTED",
metaTemplateId: null,
rejectedReason: null,
bodyPreview: truncate(bodyText, BODY_PREVIEW_MAX),
variableCount: countVariables(bodyText),
updatedAt: null,
};
}
function storedSummary(row: TemplateRow): RrmLadderTemplateSummary {
return {
name: row.name,
language: row.language,
category: row.category,
status: row.status,
metaTemplateId: row.metaTemplateId,
rejectedReason: row.rejectedReason,
bodyPreview: row.bodyPreview,
variableCount: row.variableCount,
updatedAt: row.dateUpdated.toISOString(),
};
}
/** Meta's language codes aren't guaranteed to be one we recognise; fall back
* to `en` rather than write a value the `rrm_templates` enum column rejects. */
function normalizeLocale(language: string): (typeof RRM_LOCALES)[number] {
return (RRM_LOCALES as readonly string[]).includes(language)
? (language as (typeof RRM_LOCALES)[number])
: "en";
}
/**
* What the Ramp screen LISTS, which is not what the ladder is GATED on.
*
* `RRM_LADDER_TEMPLATE_NAMES` is the gate: `areLadderTemplatesApproved` holds
* enrolment and every due step shut until all of them are APPROVED. The
* partner-update template sends to partners about their own referrals and has
* nothing to do with recruitment — putting it in that tuple would keep the
* ladder closed waiting on a template the ladder never sends. It belongs in
* the inventory an operator reads, and nowhere near the gate.
*/
const RRM_TRACKED_TEMPLATE_NAMES = [
...RRM_LADDER_TEMPLATE_NAMES,
TPL_RRM_PARTNER_REFERRAL_UPDATE,
] as const;
// GET /api/admin/rrm/templates
ladder.get("/templates", async (c) => {
try {
const dal = c.get("dal");
const rows = await dal.db
.select({
name: TEMPLATES.name,
language: TEMPLATES.language,
category: TEMPLATES.category,
status: TEMPLATES.status,
metaTemplateId: TEMPLATES.metaTemplateId,
rejectedReason: TEMPLATES.rejectedReason,
bodyPreview: TEMPLATES.bodyPreview,
variableCount: TEMPLATES.variableCount,
dateUpdated: TEMPLATES.dateUpdated,
})
.from(TEMPLATES)
.where(inArray(TEMPLATES.name, [...RRM_TRACKED_TEMPLATE_NAMES]));
const byName = latestByName(rows);
const data = RRM_TRACKED_TEMPLATE_NAMES.map((name) => {
const row = byName.get(name);
return row ? storedSummary(row) : notSubmittedSummary(name);
});
return success(c, data);
} catch (err) {
return handleError(c, err);
}
});
// POST /api/admin/rrm/templates/sync
ladder.post("/templates/sync", async (c) => {
try {
const dal = c.get("dal");
const client = requireWhatsAppClient(c.env);
const response = await client.listTemplates();
const byName = new Map<string, WhatsAppTemplateFromMeta>(
response.data.map((template) => [template.name, template]),
);
const now = new Date();
const data: RrmLadderTemplateSummary[] = [];
for (const name of RRM_TRACKED_TEMPLATE_NAMES) {
const meta = byName.get(name);
if (!meta) {
data.push(notSubmittedSummary(name));
continue;
}
const bodyText = extractBodyText(meta.components);
const bodyPreview = truncate(bodyText, BODY_PREVIEW_MAX);
const variableCount = countVariables(bodyText);
const language = normalizeLocale(meta.language);
// Meta only ever hands us MARKETING/UTILITY/AUTHENTICATION; the ladder's
// three templates are always submitted as MARKETING (see
// config/whatsapp-templates.ts), and `rrm_templates.category` has no
// AUTHENTICATION member. Cast rather than widen the column for a value
// these three templates cannot actually return.
const category = meta.category as RrmTemplate["category"];
await dal.db
.insert(TEMPLATES)
.values({
id: generateId(),
name: meta.name,
version: 1,
language,
category,
status: meta.status,
metaTemplateId: meta.id,
bodyPreview,
variableCount,
rejectedReason: meta.rejected_reason ?? null,
dateUpdated: now,
})
.onConflictDoUpdate({
target: [TEMPLATES.name, TEMPLATES.version, TEMPLATES.language],
set: {
category,
status: meta.status,
metaTemplateId: meta.id,
bodyPreview,
variableCount,
rejectedReason: meta.rejected_reason ?? null,
dateUpdated: now,
},
});
// `rejected_reason` is persisted by the upsert above (column added in
// migration 0008), so a later plain GET still tells the operator WHY
// a template was rejected — approval is the ladder's critical path.
data.push({
name: meta.name,
language,
category,
status: meta.status,
metaTemplateId: meta.id,
rejectedReason: meta.rejected_reason ?? null,
bodyPreview,
variableCount,
updatedAt: now.toISOString(),
});
}
return success(c, data);
} catch (err) {
if (err instanceof WhatsAppConfigError) {
// The shared `error()` envelope, not a bare string: the portal reads
// `error.code` / `error.message`, so a raw string reached the operator
// as "An error occurred" — the one message that cannot tell them the
// WABA credentials are missing, which is the whole content here.
return error(
c,
"WHATSAPP_NOT_CONFIGURED",
"WhatsApp is not configured for this environment",
503,
);
}
return handleError(c, err);
}
});
export default ladder;
|