All files / dal/rrm config.dal.ts

100% Statements 59/59
100% Branches 36/36
100% Functions 11/11
100% Lines 50/50

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        22x                                                                     22x                                                                                                                     22x                                                                           22x                                                                 9x 9x 9x             4x   4x     4x               22x 22x     33x 32x 17x       16x 1x   15x   1x       320x       1114x         1114x                     689x 689x 82x     82x 81x 81x       150x 150x 16x 16x 8x 1x                                 157x 157x 5x 5x         2x                                       40x 40x 40x 7x     33x 33x 33x                                               115x 115x 15x         21x      
import { eq } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import * as schema from "../../db/schema";
 
const CONFIG = schema.rrmConfig;
 
/**
 * Operational settings for the recruitment campaign, and the kill switch.
 *
 * These live in D1 rather than in `wrangler.jsonc` vars because every one of
 * them is a number an operator changes *during* a campaign — the ramp raises
 * the daily cap, a holiday gets added, a bad hour gets the send window
 * narrowed, an account warning stops everything. A deploy is the wrong unit of
 * change for any of that, and "stop sending" must not be gated on CI being
 * green.
 *
 * NO KV CACHE HERE — deliberately, and please do not add one.
 *
 *   - The halt flag is a safety stop. A 60-second-stale read has exactly the
 *     wrong failure mode: the window in which it is wrong is the window in
 *     which someone is urgently trying to make it right.
 *   - Every read carries `reason` and `actorId`. A cached kill switch loses
 *     the attribution that makes it trustworthy.
 *   - The volume does not justify it. At the ramp's ceiling of 150 sends/day
 *     this is a handful of primary-key lookups per cron tick, not a hot path.
 *
 * Writes are attributed in the row itself (`reason`, `actor_id`,
 * `date_updated`), which is the audit trail for config. The halt *event* and
 * the operator alert that §13.2 requires are the halt service's job, not the
 * DAL's — this layer only records what the value is and who set it.
 */
 
/**
 * The key namespace, as a typed map rather than free strings.
 *
 * A typo in a free string is not a compile error, it is a silently-absent key,
 * and a silently-absent key here means "fall back to the default" — i.e. a
 * misspelled `halt` read would report "not halted" forever.
 */
export const RRM_CONFIG_KEYS = {
	halt: "halt",
	/** Hard ceiling on ALL template sends per IST day — openers AND follow-ups. */
	dailySendCap: "daily_send_cap",
	/**
	 * Ceiling on NEW openers (N0) enrolled per IST day, counted on its own.
	 *
	 * Separate from `daily_send_cap` because the two count different things and
	 * one number cannot do both jobs. `daily_send_cap` counts every template
	 * step, so from day 4 of a steady campaign it is also paying for that day's
	 * N2s and, from day 8, its N7s — three sends per prospect over the ladder's
	 * life. Paced against that single number, opener throughput silently decays
	 * to a third as the follow-ups arrive, and nothing errors: the operator just
	 * sees fewer sends. This key paces enrolment by itself, so the total cap goes
	 * back to being what it is good at — protecting the number.
	 */
	dailyOpenerCap: "daily_opener_cap",
	/** Ceiling on openers per IST clock hour. Smoothed across ticks — see the scheduler. */
	hourlySendRate: "hourly_send_rate",
	sendWindowStartHour: "send_window_start_hour",
	sendWindowEndHour: "send_window_end_hour",
	holidays: "holidays",
	/** Due follow-ups win the day's remaining cap over new openers. */
	followupsFirst: "followups_first",
	/** Send the N1 acknowledgement the moment a prospect replies. */
	autoReply: "auto_reply",
	/** Days a prospect rests in `not_now` after the final nudge. */
	snoozeDays: "snooze_days",
	/** Arms the lagging reply-rate auto-halt trigger. Off until week 1 is read. */
	autoHaltReplyRateArmed: "auto_halt_reply_rate_armed",
 
	// ── Money. Paise, always integers. See rrm_earnings. ──────────────────
	/** Paid once a referred contact is confirmed real and planning interiors. */
	validatedAmountPaise: "validated_amount_paise",
	/** Paid when that contact goes ahead with a matched professional. */
	convertedAmountPaise: "converted_amount_paise",
	/** Balance at which released earnings become payable. */
	payoutThresholdPaise: "payout_threshold_paise",
	/** Days an earning is held before it can be released. */
	holdDays: "hold_days",
} as const;
 
export type RrmConfigKey =
	(typeof RRM_CONFIG_KEYS)[keyof typeof RRM_CONFIG_KEYS];
 
/**
 * The owner's confirmed starting values (build spec §18).
 *
 * `daily_send_cap: 30` is not a typo for the spec's headline 150 — 30 is ramp
 * step 1 of the `[30, 60, 120, 150, 150]` schedule. The cap is *raised through
 * this table* as a human opens each ramp step, which is the whole reason the
 * value is a row and not a constant. 150 is where it ends up, not where it
 * starts.
 *
 * The send window matches `DEFAULT_QUIET_HOURS` in lib/rrm/time.ts. Holidays
 * are absent on purpose: there is no safe default for "which days must we not
 * send", so the caller supplies the list explicitly or gets `null` and has to
 * decide. See the comment on `getJson` below.
 */
export const RRM_CONFIG_DEFAULTS = {
	[RRM_CONFIG_KEYS.dailySendCap]: 30,
	// The opener cap starts at the same ramp step 1 as the total cap: on day 1
	// every send IS an opener, so the two are the same number until follow-ups
	// exist. They part company the moment either is raised, and a human raises
	// them separately — the ramp-step release endpoint writes neither. Raising
	// `daily_send_cap` alone therefore buys follow-up headroom and no extra
	// openers, which is exactly what `enrolLimit: "daily_openers"` in the tick
	// result is there to tell whoever raised it.
	[RRM_CONFIG_KEYS.dailyOpenerCap]: 30,
	[RRM_CONFIG_KEYS.hourlySendRate]: 5,
	[RRM_CONFIG_KEYS.sendWindowStartHour]: 10,
	[RRM_CONFIG_KEYS.sendWindowEndHour]: 19,
	[RRM_CONFIG_KEYS.followupsFirst]: true,
	[RRM_CONFIG_KEYS.autoReply]: true,
	[RRM_CONFIG_KEYS.snoozeDays]: 60,
	[RRM_CONFIG_KEYS.autoHaltReplyRateArmed]: false,
 
	// The amounts the partner page promises, in PAISE. They live here rather
	// than as constants because `apps/go/src/lib/campaign.ts` says so in as
	// many words: "In v1 they move to the API's rrm_config table so they are
	// editable from the RRM dashboard without a deploy." The partner page is
	// prerendered, so its copy still needs a deploy to change — but what the
	// LEDGER credits must not, or a rate change would silently disagree with
	// every row already written.
	[RRM_CONFIG_KEYS.validatedAmountPaise]: 10_000, // ₹100
	[RRM_CONFIG_KEYS.convertedAmountPaise]: 100_000, // ₹1,000
	[RRM_CONFIG_KEYS.payoutThresholdPaise]: 100_000, // ₹1,000
	[RRM_CONFIG_KEYS.holdDays]: 5,
} as const;
 
/**
 * Keys that may not be written without saying who and why.
 *
 * Only `halt` today. Both directions are covered — §13.2 makes resume manual
 * only, and an unattributed *resume* is the more dangerous of the two: it puts
 * sends back on an account that something stopped.
 */
const ATTRIBUTION_REQUIRED_KEYS: ReadonlySet<RrmConfigKey> = new Set([
	RRM_CONFIG_KEYS.halt,
	// Behaviour switches, not tuning knobs: turning the acknowledgement off, or
	// arming a halt trigger, changes what a stranger receives. A change nobody
	// can attribute is the one that cannot be reconstructed afterwards.
	RRM_CONFIG_KEYS.followupsFirst,
	RRM_CONFIG_KEYS.autoReply,
	RRM_CONFIG_KEYS.autoHaltReplyRateArmed,
	// Changing what a referral is worth is a commercial decision with a
	// paper trail attached. Rows already written keep the rate they were
	// created at; only future earnings move. Both facts need a name on them.
	RRM_CONFIG_KEYS.validatedAmountPaise,
	RRM_CONFIG_KEYS.convertedAmountPaise,
	RRM_CONFIG_KEYS.payoutThresholdPaise,
	RRM_CONFIG_KEYS.holdDays,
]);
 
/** What `set` accepts. Everything is stored as TEXT; this is the wire format. */
export type RrmConfigValue =
	| string
	| number
	| boolean
	| readonly unknown[]
	| Record<string, unknown>;
 
export type SetConfigOptions = {
	/** Why this changed. Required for `halt`. */
	reason?: string;
	/** The user id behind the change. Required for `halt`. */
	actorId?: string;
};
 
export class ConfigAttributionRequiredError extends Error {
	code = "ATTRIBUTION_REQUIRED";
	constructor(public key: RrmConfigKey) {
		super(
			`Config key "${key}" cannot be changed without a non-empty reason and actorId`,
		);
	}
}
 
export class ConfigValueError extends Error {
	code = "INVALID_CONFIG_VALUE";
	constructor(
		public key: RrmConfigKey,
		detail: string,
	) {
		super(`Config key "${key}": ${detail}`);
	}
}
 
/**
 * Recognised falsey spellings. Anything else in the `halt` row counts as
 * halted — see `isHalted`.
 */
const FALSE_VALUES: ReadonlySet<string> = new Set(["false", "0", "off", "no"]);
const TRUE_VALUES: ReadonlySet<string> = new Set(["true", "1", "on", "yes"]);
 
function serialise(key: RrmConfigKey, value: RrmConfigValue): string {
	if (typeof value === "string") return value;
	if (typeof value === "boolean") return String(value);
	if (typeof value === "number") {
		// `String(NaN)` is "NaN", which `getNumber` would read back as the
		// fallback — a bad write would look like an absent key. Reject it at the
		// boundary so the caller finds out.
		if (!Number.isFinite(value)) {
			throw new ConfigValueError(key, `${value} is not a finite number`);
		}
		return String(value);
	}
	return JSON.stringify(value);
}
 
export class RrmConfigDal {
	constructor(private db: DrizzleD1Database<typeof schema>) {}
 
	/** Raw stored text, or null when the key has never been written. */
	async get(key: RrmConfigKey): Promise<string | null> {
		const rows = await this.db
			.select({ value: CONFIG.value })
			.from(CONFIG)
			.where(eq(CONFIG.key, key))
			.limit(1);
		return rows[0]?.value ?? null;
	}
 
	/**
	 * An unparseable value yields the fallback rather than throwing, which is
	 * only safe because every default in {@link RRM_CONFIG_DEFAULTS} is the
	 * *conservative* direction — a cap of 30 and a rate of 5 send less, not
	 * more. Do not reuse this reader for a number where "the default" would be
	 * the permissive answer.
	 */
	async getNumber(key: RrmConfigKey, fallback: number): Promise<number> {
		const raw = await this.get(key);
		if (raw === null) return fallback;
		const trimmed = raw.trim();
		// `Number("")` is 0, not NaN. Left unguarded, an empty row would read as
		// a cap of zero rather than as a missing value.
		if (trimmed === "") return fallback;
		const parsed = Number(trimmed);
		return Number.isFinite(parsed) ? parsed : fallback;
	}
 
	async getBoolean(key: RrmConfigKey, fallback: boolean): Promise<boolean> {
		const raw = await this.get(key);
		if (raw === null) return fallback;
		const value = raw.trim().toLowerCase();
		if (TRUE_VALUES.has(value)) return true;
		if (FALSE_VALUES.has(value)) return false;
		return fallback;
	}
 
	/**
	 * Absent key → `null`. Malformed JSON → **throws**.
	 *
	 * The asymmetry is the point. This key's real consumer is the holiday list,
	 * and lib/rrm/time.ts already spells out why defaulting it is unsafe:
	 * "Defaulting the config would turn a missing holiday list into a silent
	 * holiday send." Returning `[]` for corrupt JSON would do exactly that, and
	 * the campaign would message four hundred people on Diwali while every log
	 * line looked healthy. A thrown error fails the cron tick loudly instead.
	 *
	 * `null` for an absent key is a different signal — "never configured" — and
	 * the caller must decide what that means for it.
	 */
	async getJson<T>(key: RrmConfigKey): Promise<T | null> {
		const raw = await this.get(key);
		if (raw === null) return null;
		try {
			return JSON.parse(raw) as T;
		} catch (error) {
			// `String(error)` rather than `error.message` — JSON.parse only ever
			// throws SyntaxError, and the class name is the useful half of the
			// log line.
			throw new ConfigValueError(
				key,
				`stored value is not valid JSON (${String(error)})`,
			);
		}
	}
 
	/**
	 * Upsert one key.
	 *
	 * `reason` and `actorId` are optional for ordinary settings and mandatory
	 * for `halt` — a kill switch nobody can attribute is a kill switch nobody
	 * trusts, and the first question after an unexplained stop is always "who
	 * did this and why". A rejected write touches nothing.
	 */
	async set(
		key: RrmConfigKey,
		value: RrmConfigValue,
		options: SetConfigOptions = {},
	): Promise<void> {
		const reason = options.reason?.trim() || null;
		const actorId = options.actorId?.trim() || null;
		if (ATTRIBUTION_REQUIRED_KEYS.has(key) && (!reason || !actorId)) {
			throw new ConfigAttributionRequiredError(key);
		}
 
		const stored = serialise(key, value);
		const now = new Date();
		await this.db
			.insert(CONFIG)
			.values({ key, value: stored, reason, actorId, dateUpdated: now })
			.onConflictDoUpdate({
				target: CONFIG.key,
				set: { value: stored, reason, actorId, dateUpdated: now },
			});
	}
 
	/**
	 * Is marketing sending stopped?
	 *
	 * Fails **closed**. An absent row means the switch was never thrown, so the
	 * campaign runs. But a row holding anything other than a recognised falsey
	 * spelling counts as halted, including junk and the empty string: someone
	 * wrote *something* into the halt row, and the cost of stopping a campaign
	 * that should have run (an operator notices within minutes) is nothing next
	 * to the cost of running one that should have stopped (a restricted
	 * WhatsApp Business account, which is not reversible on our timetable).
	 *
	 * This is why it does not just call `getBoolean(halt, false)` — that reader
	 * resolves ambiguity to the fallback, which here would be "keep sending".
	 */
	async isHalted(): Promise<boolean> {
		const raw = await this.get(RRM_CONFIG_KEYS.halt);
		if (raw === null) return false;
		return !FALSE_VALUES.has(raw.trim().toLowerCase());
	}
 
	/** @throws {ConfigAttributionRequiredError} if `reason` or `actorId` is blank. */
	async setHalt(on: boolean, reason: string, actorId: string): Promise<void> {
		await this.set(RRM_CONFIG_KEYS.halt, on, { reason, actorId });
	}
}