All files / services/partners referral.service.ts

85.18% Statements 46/54
84.44% Branches 38/45
83.33% Functions 5/6
86.53% Lines 45/52

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                                                                                                                                                                    34x         34x                                 29x 29x 29x             29x               31x       31x                               35x 35x 35x       35x 1x                   34x 3x           31x 31x 31x 31x 31x 2x                 29x 29x 29x                       29x       29x   35x                           29x                                                                                                                                                                 8x 8x     8x 8x 8x   7x 7x 7x 7x           5x         2x 1x     7x 5x   7x   1x 1x      
import { and, eq, sql } from "drizzle-orm";
import type { DrizzleD1Database } from "drizzle-orm/d1";
import {
	PROGRAM_CONFIG_DEFAULTS,
	PROGRAM_CONFIG_KEYS,
	ProgramConfigDal,
} from "../../dal/partners/config.dal";
import type { Partner } from "../../dal/partners/partners.dal";
import {
	IllegalTransitionError,
	type Referral,
	ReferralsDal,
} from "../../dal/partners/referrals.dal";
import * as schema from "../../db/schema";
import { logger } from "../../lib/logger";
import { DAY_MS, istDayStart } from "../../lib/rrm/time";
 
/**
 * Creating a referral: the rules, in one place.
 *
 * Open self-registration (owner, 30 Aug) is what makes these load-bearing now
 * rather than in B8. When anyone can enrol in ninety seconds, the only things
 * between a fraudulent signup and a payout are the checks below and the ops
 * queue — so each one is refused server-side and explained to the partner in a
 * form the client cannot invent (REQ-ARCH-2).
 */
 
export type CreateReferralResult =
	| { ok: true; referral: Referral; duplicate: false }
	/**
	 * Stored, not dropped. FR-P-3.6: the partner is told honestly, the row is
	 * kept for audit, and the FIRST referrer is unaffected.
	 */
	| { ok: true; referral: Referral; duplicate: true }
	| { ok: false; reason: "suspended"; detail: string }
	| { ok: false; reason: "self_referral" }
	| {
			ok: false;
			reason: "cap_reached";
			window: "day" | "month";
			limit: number;
			used: number;
	  };
 
export type ReferralServiceContext = {
	db: DrizzleD1Database<typeof schema>;
	now?: Date;
};
 
export type CreateReferralInput = {
	partner: Partner;
	contactName: string;
	contactPhoneNorm: string;
	society?: string | null;
	config?: string | null;
	possessionBand?: string | null;
	mode?: "direct" | "link";
	/**
	 * FR-F-6. The PARTNER's salted inbound-address digests, computed at the
	 * route boundary (`lib/partners/ip.ts`) so this service never sees an IP.
	 * Both null when there is no secret or no usable address — a missing fraud
	 * signal, never a reversible one.
	 */
	ipHash?: string | null;
	ipPrefixHash?: string | null;
};
 
/**
 * Is this number one of ours — a partner's own, or another partner's?
 *
 * FR-F-2. Two separate cases, and both matter:
 *   - the partner referring THEMSELVES, which is the obvious fraud and was
 *     previously possible and creditable;
 *   - the partner referring ANOTHER PARTNER, which is how two colleagues turn
 *     the programme into a loop that pays them both for introducing each other.
 *
 * A single query covers both, because the partner's own row is in the table.
 */
async function isPartnerNumber(
	db: DrizzleD1Database<typeof schema>,
	phoneNorm: string,
): Promise<boolean> {
	const rows = await db
		.select({ id: schema.partners.id })
		.from(schema.partners)
		.where(eq(schema.partners.phoneNorm, phoneNorm))
		.limit(1);
	return rows.length > 0;
}
 
/**
 * Has this number already reached us through the F-05 inquiry form?
 *
 * FR-F-1 dedupes against inquiries as well as prior referrals: a homeowner who
 * found us on their own is not an introduction, and paying for one would make
 * the programme a way to bill us for our own marketing.
 *
 * `customer_phone` is stored as typed, so the comparison strips separators on
 * the SQL side — the same shape `prospect-resolver.service.ts` already uses.
 */
async function existsAsInquiry(
	db: DrizzleD1Database<typeof schema>,
	phoneNorm: string,
): Promise<boolean> {
	const tail = phoneNorm.slice(-10);
	Iif (tail.length < 10) return false;
	const rows = await db
		.select({ id: schema.inquiries.id })
		.from(schema.inquiries)
		.where(
			sql`replace(replace(replace(replace(${schema.inquiries.customerPhone}, ' ', ''), '-', ''), '(', ''), ')', '') LIKE ${`%${tail}`}`,
		)
		.limit(1);
	return rows.length > 0;
}
 
/** The per-partner cap, falling back to the programme default. */
async function capsFor(
	config: ProgramConfigDal,
	partner: Partner,
): Promise<{ perDay: number; perMonth: number }> {
	const [dayDefault, monthDefault] = await Promise.all([
		config.getNumber(PROGRAM_CONFIG_KEYS.referralCapPerDay),
		config.getNumber(PROGRAM_CONFIG_KEYS.referralCapPerMonth),
	]);
	return {
		perDay:
			partner.capPerDay ??
			dayDefault ??
			PROGRAM_CONFIG_DEFAULTS[PROGRAM_CONFIG_KEYS.referralCapPerDay],
		perMonth:
			partner.capPerMonth ??
			monthDefault ??
			PROGRAM_CONFIG_DEFAULTS[PROGRAM_CONFIG_KEYS.referralCapPerMonth],
	};
}
 
export async function createReferral(
	ctx: ReferralServiceContext,
	input: CreateReferralInput,
): Promise<CreateReferralResult> {
	const now = ctx.now ?? new Date();
	const dal = new ReferralsDal(ctx.db);
	const { partner } = input;
 
	// 1. Suspension. FR-F-7 says the partner is told, with a reason — so the
	//    reason travels in the response rather than being logged and swallowed.
	if (partner.suspendedAt) {
		return {
			ok: false,
			reason: "suspended",
			detail: partner.suspendedReason ?? "",
		};
	}
 
	// 2. Self- and cross-partner referral. Checked BEFORE the caps, so a partner
	//    probing with their own number does not also burn their daily budget —
	//    the refusal should teach them the rule, not punish them twice for it.
	if (await isPartnerNumber(ctx.db, input.contactPhoneNorm)) {
		return { ok: false, reason: "self_referral" };
	}
 
	// 3. Caps. "Day" means an IST day: the partner is in Hyderabad, and a cap
	//    that rolled over at 05:30 local would be indefensible to them.
	//    `istDayStart` already exists for exactly this reason (lib/rrm/time.ts).
	const config = new ProgramConfigDal(ctx.db);
	const caps = await capsFor(config, partner);
	const dayStart = istDayStart(now);
	const usedToday = await dal.countCreatedSince(partner.id, dayStart);
	if (usedToday >= caps.perDay) {
		return {
			ok: false,
			reason: "cap_reached",
			window: "day",
			limit: caps.perDay,
			used: usedToday,
		};
	}
 
	const monthStart = new Date(dayStart.getTime() - 29 * DAY_MS);
	const usedThisMonth = await dal.countCreatedSince(partner.id, monthStart);
	Iif (usedThisMonth >= caps.perMonth) {
		return {
			ok: false,
			reason: "cap_reached",
			window: "month",
			limit: caps.perMonth,
			used: usedThisMonth,
		};
	}
 
	// 4. Dedupe. First referrer wins; the loser is STORED as `duplicate` so the
	//    decision is auditable and the partner can be shown something true.
	const [firstReferral, alreadyAnInquiry] = await Promise.all([
		dal.findFirstReferralOf(input.contactPhoneNorm),
		existsAsInquiry(ctx.db, input.contactPhoneNorm),
	]);
	const isDuplicate = Boolean(firstReferral) || alreadyAnInquiry;
 
	const referral = await dal.create({
		partnerId: partner.id,
		contactName: input.contactName,
		contactPhoneNorm: input.contactPhoneNorm,
		society: input.society ?? null,
		config: input.config ?? null,
		possessionBand: input.possessionBand ?? null,
		mode: input.mode ?? "direct",
		status: isDuplicate ? "duplicate" : "draft",
		firstReferrerReferralId: firstReferral?.id ?? null,
		ipHash: input.ipHash ?? null,
		ipPrefixHash: input.ipPrefixHash ?? null,
	});
 
	return { ok: true, referral, duplicate: isDuplicate };
}
 
/**
 * FR-F-2's retroactive half, run when a partner enrols.
 *
 * Someone refers a number; that number later signs up as a partner. The
 * forward check cannot catch this — at submission time the referred person was
 * not yet one of ours. Without the sweep, a pair who enrol in the right order
 * can pay each other indefinitely.
 *
 * FLAGS rather than rejects: by the time this runs the referral may legitimately
 * have progressed, and silently voiding someone's earned money on a heuristic
 * is worse than putting it in front of an operator. Reversal, if warranted, is
 * an attributed human decision.
 */
export async function flagRetroactiveSelfReferrals(
	ctx: ReferralServiceContext,
	newPartner: Partner,
): Promise<number> {
	const now = ctx.now ?? new Date();
	const dal = new ReferralsDal(ctx.db);
 
	const affected = await ctx.db
		.select({ id: schema.referrals.id })
		.from(schema.referrals)
		.where(
			and(
				eq(schema.referrals.contactPhoneNorm, newPartner.phoneNorm),
				sql`${schema.referrals.status} NOT IN ('duplicate','rejected','expired')`,
			),
		)
		.limit(50);
 
	for (const row of affected) {
		await dal.addEvent({
			referralId: row.id,
			type: "referral.flagged_self_referral",
			actorType: "system",
			payload: {
				rule: "FR-F-2 retroactive",
				partnerId: newPartner.id,
				detail:
					"The referred number has since enrolled as a partner. Needs an operator decision.",
			},
			now,
		});
	}
 
	return affected.length;
}
 
/**
 * FR-P-3.5: a draft nobody forwarded expires.
 *
 * Until this ran, nothing wrote `expired`. That mattered more than a stale
 * chip: `findFirstReferralOf` skips expired rows but not drafts, so a draft
 * left unforwarded was a PERMANENT first referrer for that number — every
 * later add by anyone was stored `duplicate` and earned nothing, the opposite
 * of what partner/referring.md promises. Expiring the draft is what frees the
 * number again.
 *
 * One `transition` per row, deliberately, rather than one set-based UPDATE:
 * the transition is what writes the `referral.expired` event the partner's
 * timeline is built from (FR-ST-2). It is still safe against itself, the way
 * the earnings sweep is: `transition` predicates its writes on the row still
 * being a draft, so one the partner forwards between this select and its
 * turn in the loop — or one an overlapping tick already expired — is refused
 * rather than clobbered, and no second event is written.
 *
 * Rides the RRM scheduler's 5-minute tick, next to `releaseDueEarnings`, and
 * shares its guard shape: a failure here never throws into that shared
 * caller, and a bad row is logged and skipped rather than stopping the loop.
 *
 * @param now the tick's clock, so every sweep in one tick agrees on the time.
 * @returns how many drafts were expired; `0` if the sweep failed.
 */
export async function expireStaleDrafts(
	ctx: Pick<ReferralServiceContext, "db">,
	now = new Date(),
): Promise<number> {
	try {
		const hours = await new ProgramConfigDal(ctx.db).getNumber(
			PROGRAM_CONFIG_KEYS.draftExpiryHours,
		);
		const cutoff = new Date(now.getTime() - hours * 3_600_000);
		const dal = new ReferralsDal(ctx.db);
		const stale = await dal.listStaleDrafts(cutoff);
 
		let expired = 0;
		for (const referral of stale) {
			try {
				await dal.transition({
					referral,
					to: "expired",
					actorType: "system",
					now,
				});
				expired += 1;
			} catch (err) {
				// The only refusal a draft -> expired move can meet is the row
				// having moved on since the select. That is a partner forwarding
				// at the deadline, not a fault.
				if (err instanceof IllegalTransitionError) continue;
				logger.error("[referral expiry] could not expire", referral.id, err);
			}
		}
		if (expired > 0) {
			logger.info("[referral expiry] expired unforwarded drafts:", expired);
		}
		return expired;
	} catch (err) {
		logger.error("[referral expiry] sweep failed:", err);
		return 0;
	}
}