All files / lib/rrm sequence.ts

98.97% Statements 97/98
97.75% Branches 87/89
100% Functions 16/16
100% Lines 92/92

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                                              3x           3x     3x               3x                                                                                               178x         3x                                 2x               3x                                                                                                           205x         205x   39x 39x                         39x         39x                   39x         22x   22x     22x         1994x       2221x       1115x 15x     1115x 1115x 2x 1113x   1113x 665x 1x 664x         1x 663x       877x       1x     662x             662x 439x 1x 438x   661x 658x   1315x   1x 657x   660x 220x 1x 219x   659x     448x 222x 1x 221x 221x 220x 220x 219x                 226x 225x 1x 224x         1x 223x           223x 220x 1x 219x   222x     1x                         244x 5x 239x 239x   238x 238x 1115x 1115x 1x       1099x 1099x   238x         23x 23x 21x         4x 4x 3x 4x 2x                       24x 23x 27x          
/**
 * The RRM automated ladder — sequence definition (`docs/operations/rrm-ladder-design.md` §2).
 *
 * This supersedes `step-schema.ts`'s `cp_recruit_v1` programme for Phase 1.
 * That file's `SequenceStep` / `parseSteps` / `computeDueAt` implement an
 * OLDER, richer ladder (Telugu switch, visit triggers, an on-submit welcome)
 * that the ladder design's decisions L3/L8 explicitly retire — no route or
 * service imports it (grep confirms; only its own test does), so it is left
 * in place, untouched, as dead code rather than repurposed. The type here is
 * a different, smaller shape (`StepDef`, not `SequenceStep`) on purpose: the
 * two are not meant to interoperate.
 *
 * `delayMs` on every timer-based step (`template` and `task`) is measured
 * from the RUN'S START (the N0 send), never from the previous step — see the
 * design doc §2, restated so nobody "fixes" this into a chain later.
 */
 
import { eq } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../../db/schema";
import type { RrmProspect, RrmSequence } from "../../db/schema/rrm";
import { generateId } from "../ids";
 
const SEQUENCES = schema.rrmSequences;
 
/** Milliseconds in a day. Not imported from `lib/rrm/time.ts` (an older,
 * superseded IST module — see this file's own header comment) or from
 * `lib/rrm/ist.ts` (the current one, but this constant has nothing to do
 * with IST arithmetic) — it is just a unit conversion. */
const DAY_MS = 86_400_000;
 
/** `rrm_sequences.key` for the programme below. */
export const PARTNER_V1_KEY = "partner_v1";
 
/**
 * What a template step's variables are filled in from. Deliberately a closed
 * vocabulary rather than free-form interpolation — the templates are fixed,
 * Meta-approved text with two variables at most (design §3), and a typo in a
 * free-form expression would only be discovered against a live template.
 */
export const VARIABLE_SOURCES = ["firstName", "firmOrMicroMarket"] as const;
export type VariableSource = (typeof VARIABLE_SOURCES)[number];
 
export type StepCancelReason = "replied" | "dnc";
 
export type TemplateStepDef = {
	key: string;
	kind: "template";
	template: string;
	/** Milliseconds from run start (N0's send instant). */
	delayMs: number;
	variables: VariableSource[];
	requires?: { noReply?: true };
	cancelOn?: StepCancelReason[];
	/**
	 * The ladder's only end-of-run action (N7). `snoozeDays` is deliberately
	 * NOT stored here — it is `rrm_config`'s `snooze_days`, read at apply time,
	 * so raising it on Ramp & pacing changes the very next run it applies to
	 * without a step-definition edit.
	 */
	onComplete?: { stage: "not_now" };
};
 
export type FreeformStepDef = {
	key: string;
	kind: "freeform";
	trigger: "on_reply";
	/** Names the acknowledgement copy; see `N1_ACK_TEXT` below. */
	copyKey: string;
	/** `rrm_config` key gating whether this step fires at all. */
	configFlag: string;
};
 
export type TaskStepDef = {
	key: string;
	kind: "task";
	taskType: "call";
	/** Milliseconds from run start. */
	delayMs: number;
	requires?: { noReply?: true };
};
 
export type StepDef = TemplateStepDef | FreeformStepDef | TaskStepDef;
 
/** Steps with a `delayMs` — i.e. everything the scheduler puts on a timer. */
export type TimerStepDef = TemplateStepDef | TaskStepDef;
 
export function isTimerStep(step: StepDef): step is TimerStepDef {
	return step.kind === "template" || step.kind === "task";
}
 
/** The N1 acknowledgement (design §2 / §8): not a template, no variables. */
export const N1_ACK_TEXT =
	"Thanks — here's the page: https://go.interioring.com/partners. A real person replies here within the day.";
 
/**
 * The sign-up acknowledgement (S0) — what a prospect with NO ladder run gets
 * on their first message, which is every organic sign-up off the go form.
 *
 * Not a step in `PARTNER_V1_STEPS`: it is not on a timer, has no run to hang
 * off, and adding it there would change what `parseSteps` and the scheduler
 * see. It lives here because this is where the ladder's copy lives, and
 * because it is gated by the same `auto_reply` flag N1 is.
 *
 * The URL is passed in (`PARTNER_APP_URL`) rather than hardcoded like N1's:
 * the partner app has a different host per environment, and a dev prospect
 * being told to sign in at the production app is exactly the kind of thing
 * nobody notices until a real partner is stuck.
 */
export function signupAckText(url: string): string {
	return `Thanks for getting in touch. Your partner app is at ${url} — sign in with this same WhatsApp number and we'll send a 6-digit code to this chat.`;
}
 
/**
 * The default recruitment ladder (design §2). Code-defined, not editable
 * through the admin UI in this phase (`ensureDefaultSequence` below is the
 * only writer).
 */
export const PARTNER_V1_STEPS: readonly StepDef[] = [
	{
		key: "N0",
		kind: "template",
		template: "rrm_partner_opener_v1",
		delayMs: 0,
		variables: ["firstName", "firmOrMicroMarket"],
		cancelOn: ["replied", "dnc"],
	},
	{
		key: "N1",
		kind: "freeform",
		trigger: "on_reply",
		copyKey: "n1_ack",
		configFlag: "auto_reply",
	},
	{
		key: "N2",
		kind: "template",
		template: "rrm_partner_nudge_v1",
		delayMs: 3 * DAY_MS,
		variables: ["firstName"],
		requires: { noReply: true },
		cancelOn: ["replied", "dnc"],
	},
	{
		key: "N6",
		kind: "task",
		taskType: "call",
		delayMs: 4 * DAY_MS,
		requires: { noReply: true },
	},
	{
		key: "N7",
		kind: "template",
		template: "rrm_partner_final_v1",
		delayMs: 7 * DAY_MS,
		variables: ["firstName"],
		requires: { noReply: true },
		cancelOn: ["replied", "dnc"],
		onComplete: { stage: "not_now" },
	},
];
 
/**
 * Returns the `partner_v1` row, inserting the code-defined default the first
 * time anyone asks (design §2: "inserted on first use if the row is
 * missing"). `onConflictDoNothing` + re-select makes two concurrent scheduler
 * ticks racing this call safe — whichever insert wins, both callers read back
 * the same row.
 */
export async function ensureDefaultSequence(
	db: DrizzleD1Database<typeof schema>,
): Promise<RrmSequence> {
	const existing = await db
		.select()
		.from(SEQUENCES)
		.where(eq(SEQUENCES.key, PARTNER_V1_KEY))
		.limit(1);
	if (existing[0]) return existing[0];
 
	const now = new Date();
	await db
		.insert(SEQUENCES)
		.values({
			id: generateId(),
			key: PARTNER_V1_KEY,
			name: "Partner recruitment v1",
			status: "active",
			steps: PARTNER_V1_STEPS as unknown[],
			dateCreated: now,
			dateUpdated: now,
		})
		.onConflictDoNothing();
 
	const rows = await db
		.select()
		.from(SEQUENCES)
		.where(eq(SEQUENCES.key, PARTNER_V1_KEY))
		.limit(1);
	const row = rows[0];
	/* v8 ignore start -- defensive: the insert above either succeeds or loses
	 * a race to another insert of the SAME row, either of which leaves a row
	 * behind for this re-select to find. */
	if (!row) {
		throw new Error(
			`ensureDefaultSequence: failed to read back "${PARTNER_V1_KEY}" after insert`,
		);
	}
	/* v8 ignore stop */
	return row;
}
 
/** Thrown by `parseSteps` on anything that is not a well-formed `StepDef[]`. */
export class RrmSequenceStepsError extends Error {
	code = "INVALID_SEQUENCE_STEPS" as const;
	constructor(
		public sequenceId: string,
		detail: string,
	) {
		super(`rrm_sequences ${sequenceId}: invalid steps JSON (${detail})`);
	}
}
 
function isPlainObject(value: unknown): value is Record<string, unknown> {
	return typeof value === "object" && value !== null && !Array.isArray(value);
}
 
function isNonEmptyString(value: unknown): value is string {
	return typeof value === "string" && value.trim().length > 0;
}
 
function assertStep(raw: unknown, sequenceId: string, index: number): StepDef {
	const fail = (detail: string): never => {
		throw new RrmSequenceStepsError(sequenceId, `step ${index}: ${detail}`);
	};
 
	Iif (!isPlainObject(raw)) return fail("step must be an object");
	if (!isNonEmptyString(raw.key))
		return fail("`key` must be a non-empty string");
	const key = raw.key;
 
	if (raw.kind === "template") {
		if (!isNonEmptyString(raw.template))
			return fail("`template` step requires a `template` name");
		if (
			typeof raw.delayMs !== "number" ||
			!Number.isFinite(raw.delayMs) ||
			raw.delayMs < 0
		)
			return fail("`delayMs` must be a non-negative number");
		if (
			!Array.isArray(raw.variables) ||
			!raw.variables.every(
				(v): v is VariableSource =>
					typeof v === "string" &&
					(VARIABLE_SOURCES as readonly string[]).includes(v),
			)
		)
			return fail(
				`\`variables\` must be an array drawn from ${VARIABLE_SOURCES.join(", ")}`,
			);
		const step: TemplateStepDef = {
			key,
			kind: "template",
			template: raw.template,
			delayMs: raw.delayMs,
			variables: raw.variables as VariableSource[],
		};
		if (raw.requires !== undefined) {
			if (!isPlainObject(raw.requires) || raw.requires.noReply !== true)
				return fail("`requires` must be `{ noReply: true }` when present");
			step.requires = { noReply: true };
		}
		if (raw.cancelOn !== undefined) {
			if (
				!Array.isArray(raw.cancelOn) ||
				!raw.cancelOn.every((c) => c === "replied" || c === "dnc")
			)
				return fail('`cancelOn` must contain only "replied" | "dnc"');
			step.cancelOn = raw.cancelOn as StepCancelReason[];
		}
		if (raw.onComplete !== undefined) {
			if (!isPlainObject(raw.onComplete) || raw.onComplete.stage !== "not_now")
				return fail('`onComplete` must be `{ stage: "not_now" }` when present');
			step.onComplete = { stage: "not_now" };
		}
		return step;
	}
 
	if (raw.kind === "freeform") {
		if (raw.trigger !== "on_reply")
			return fail('`freeform` step requires `trigger: "on_reply"`');
		if (!isNonEmptyString(raw.copyKey))
			return fail("`freeform` step requires a non-empty `copyKey`");
		if (!isNonEmptyString(raw.configFlag))
			return fail("`freeform` step requires a non-empty `configFlag`");
		return {
			key,
			kind: "freeform",
			trigger: "on_reply",
			copyKey: raw.copyKey,
			configFlag: raw.configFlag,
		};
	}
 
	if (raw.kind === "task") {
		if (raw.taskType !== "call")
			return fail('`task` step requires `taskType: "call"`');
		if (
			typeof raw.delayMs !== "number" ||
			!Number.isFinite(raw.delayMs) ||
			raw.delayMs < 0
		)
			return fail("`delayMs` must be a non-negative number");
		const step: TaskStepDef = {
			key,
			kind: "task",
			taskType: "call",
			delayMs: raw.delayMs,
		};
		if (raw.requires !== undefined) {
			if (!isPlainObject(raw.requires) || raw.requires.noReply !== true)
				return fail("`requires` must be `{ noReply: true }` when present");
			step.requires = { noReply: true };
		}
		return step;
	}
 
	return fail('`kind` must be one of "template" | "freeform" | "task"');
}
 
/**
 * Validates and types `row.steps`. Throws {@link RrmSequenceStepsError} on any
 * malformed step rather than returning a partial/best-effort program — a
 * sequence that means something other than what it says must never run
 * silently. Unlike `step-schema.ts`'s `parseSteps` (which reports every
 * error and lets the caller decide), the scheduler has no UI to show errors
 * to; the correct response to a corrupt program is to fail the tick loudly
 * and leave everything as it was.
 */
export function parseSteps(row: RrmSequence): StepDef[] {
	if (!Array.isArray(row.steps))
		throw new RrmSequenceStepsError(row.id, "steps must be an array");
	if (row.steps.length === 0)
		throw new RrmSequenceStepsError(row.id, "steps must not be empty");
 
	const seen = new Set<string>();
	const steps = row.steps.map((raw, index) => {
		const step = assertStep(raw, row.id, index);
		if (seen.has(step.key))
			throw new RrmSequenceStepsError(
				row.id,
				`duplicate step key "${step.key}"`,
			);
		seen.add(step.key);
		return step;
	});
	return steps;
}
 
/** First word of a name, trimmed. Never empty when `name` is non-blank. */
function firstNameOf(name: string | null | undefined): string {
	const trimmed = name?.trim();
	if (!trimmed) return "there";
	return trimmed.split(/\s+/)[0] ?? "there";
}
 
/** Firm name, else the first micro-market, else "Hyderabad" (design §3). */
function firmOrMicroMarketOf(prospect: RrmProspect): string {
	const firm = prospect.firmName?.trim();
	if (firm) return firm;
	const market = prospect.microMarkets?.[0]?.trim();
	if (market) return market;
	return "Hyderabad";
}
 
/**
 * Renders a template step's `{{n}}` values, in order, from the prospect row.
 * `[]` for a non-template step — there is nothing to render for a freeform
 * or task step.
 */
export function renderVariables(
	step: StepDef,
	prospect: RrmProspect,
): string[] {
	if (step.kind !== "template") return [];
	return step.variables.map((source) =>
		source === "firstName"
			? firstNameOf(prospect.name)
			: firmOrMicroMarketOf(prospect),
	);
}