@hogsend/engine 0.66.0 → 0.67.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,712 @@
1
+ import type {
2
+ BeforeBindContext,
3
+ BeforeQualifyContext,
4
+ BeforeTouchContext,
5
+ DefinedReferral,
6
+ ReferralVerdict,
7
+ } from "@hogsend/core";
8
+ import { DEFAULT_REFERRAL_ID, days, durationToMs } from "@hogsend/core";
9
+ import { type Database, referralTouches } from "@hogsend/db";
10
+ import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm";
11
+
12
+ /**
13
+ * The referral store (PRD 05 stage 2): the ONE place a `referral_touches` row
14
+ * is ever written. It records touches, stamps the bind at identity-adoption
15
+ * time, applies the self / window / veto rejections, and promotes a bound touch
16
+ * to qualified.
17
+ *
18
+ * House style follows {@link file://./account-links.ts}: single-object-in /
19
+ * result-object-out, `db` injected, typed error classes, and mutation FACTS
20
+ * returned so callers can emit.
21
+ *
22
+ * THIS MODULE NEVER EMITS (PRD 05 §6, DECISIONS §15.7 for the account-link
23
+ * twin). It touches neither the outbound spine nor the journey plane nor
24
+ * analytics: it returns what changed, and the intent layer above it emits
25
+ * `referral.*` outbound AND re-ingests for journeys, side by side. Two tests in
26
+ * `referrals-no-emit.test.ts` pin that - one scans this file for emit symbols,
27
+ * one pins its runtime import list, so the NEXT emit surface fails there
28
+ * whatever it ends up being called.
29
+ */
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // Types
33
+ // ---------------------------------------------------------------------------
34
+
35
+ export type ReferralTouchStatus =
36
+ | "touched"
37
+ | "bound"
38
+ | "qualified"
39
+ | "rejected";
40
+
41
+ /** The vocabulary of `referral_touches.rejected_reason`. */
42
+ export type ReferralRejectReason =
43
+ | "self"
44
+ | "window"
45
+ | "veto"
46
+ | "bot"
47
+ | "duplicate";
48
+
49
+ export type ReferralTouchSource =
50
+ | "link"
51
+ | "slug_entry"
52
+ | "invite"
53
+ | "manual"
54
+ | "import";
55
+
56
+ export interface ReferralTouchRecord {
57
+ id: string;
58
+ referralId: string;
59
+ referrerContactId: string;
60
+ refereeKey: string;
61
+ refereeContactId: string | null;
62
+ linkId: string | null;
63
+ clickId: string | null;
64
+ source: string;
65
+ touchedAt: Date;
66
+ boundAt: Date | null;
67
+ status: ReferralTouchStatus;
68
+ rejectedReason: ReferralRejectReason | null;
69
+ qualifiedAt: Date | null;
70
+ qualifiedConversionId: string | null;
71
+ properties: Record<string, unknown>;
72
+ }
73
+
74
+ type TouchRow = typeof referralTouches.$inferSelect;
75
+
76
+ function toRecord(row: TouchRow): ReferralTouchRecord {
77
+ return {
78
+ id: row.id,
79
+ referralId: row.referralId,
80
+ referrerContactId: row.referrerContactId,
81
+ refereeKey: row.refereeKey,
82
+ refereeContactId: row.refereeContactId,
83
+ linkId: row.linkId,
84
+ clickId: row.clickId,
85
+ source: row.source,
86
+ touchedAt: row.touchedAt,
87
+ boundAt: row.boundAt,
88
+ status: row.status as ReferralTouchStatus,
89
+ rejectedReason: row.rejectedReason as ReferralRejectReason | null,
90
+ qualifiedAt: row.qualifiedAt,
91
+ qualifiedConversionId: row.qualifiedConversionId,
92
+ properties: (row.properties ?? {}) as Record<string, unknown>,
93
+ };
94
+ }
95
+
96
+ /**
97
+ * The property key the caller's idempotency key is filed under. A PROPERTY and
98
+ * not a column: `click_id` already covers the only high-volume path (a click),
99
+ * and the manual/invite paths are low-rate operator writes whose key is
100
+ * usefully visible next to the rest of their bag.
101
+ */
102
+ export const REFERRAL_IDEMPOTENCY_PROPERTY = "idempotencyKey";
103
+
104
+ /** Where a hook's own free-text reason is kept when the row records `veto`. */
105
+ export const REFERRAL_VETO_REASON_PROPERTY = "vetoReason";
106
+
107
+ /**
108
+ * True when a DB error is the Postgres unique_violation on the referral EDGE
109
+ * index. Walks the cause chain - drizzle wraps the driver's PostgresError in a
110
+ * DrizzleQueryError whose `cause` carries the code/constraint.
111
+ */
112
+ function isEdgeUniqueViolation(err: unknown): boolean {
113
+ const constraint = "referral_touches_edge_idx";
114
+ for (let e: unknown = err, depth = 0; e && depth < 5; depth++) {
115
+ const candidate = e as {
116
+ code?: string;
117
+ constraint_name?: string;
118
+ message?: string;
119
+ cause?: unknown;
120
+ };
121
+ if (
122
+ candidate.code === "23505" &&
123
+ (candidate.constraint_name === constraint ||
124
+ (candidate.message?.includes(constraint) ?? false))
125
+ ) {
126
+ return true;
127
+ }
128
+ e = candidate.cause;
129
+ }
130
+ return false;
131
+ }
132
+
133
+ /** Resolve the referral's bind window, defaulting to 30 days. */
134
+ function bindWindowMs(referral: DefinedReferral | undefined): number {
135
+ return durationToMs(referral?.bindWindow ?? days(30));
136
+ }
137
+
138
+ async function verdict(
139
+ hook:
140
+ | ((ctx: never) => ReferralVerdict | Promise<ReferralVerdict>)
141
+ | undefined,
142
+ ctx: unknown,
143
+ ): Promise<ReferralVerdict> {
144
+ if (!hook) return { ok: true };
145
+ return await hook(ctx as never);
146
+ }
147
+
148
+ // ---------------------------------------------------------------------------
149
+ // recordTouch
150
+ // ---------------------------------------------------------------------------
151
+
152
+ export interface RecordTouchInput {
153
+ db: Database;
154
+ /** Defaults to `"default"`, matching `defineReferral`. */
155
+ referralId?: string;
156
+ /** `links.owner_contact_id` READ AT TOUCH TIME (never re-read later). */
157
+ referrerContactId: string;
158
+ /** The toucher's canonical key - an anonymous id on a cold touch. */
159
+ refereeKey: string;
160
+ /** Set only when the toucher was ALREADY identified; the touch binds now. */
161
+ refereeContactId?: string | null;
162
+ linkId?: string | null;
163
+ /** `link_clicks.id`. Doubles as the touch's replay key when present. */
164
+ clickId?: string | null;
165
+ source: ReferralTouchSource;
166
+ properties?: Record<string, unknown>;
167
+ /**
168
+ * Explicit replay key for the paths with no click (invite/manual/import).
169
+ * A repeat is a NO-OP returning the existing row, never a second edge.
170
+ */
171
+ idempotencyKey?: string;
172
+ /** The definition, for `beforeTouch`. Absent = no veto configured. */
173
+ referral?: DefinedReferral;
174
+ touchedAt?: Date;
175
+ }
176
+
177
+ export interface RecordTouchResult {
178
+ touch: ReferralTouchRecord;
179
+ /** True only when THIS call inserted the row. */
180
+ created: boolean;
181
+ /** True when the call recovered a prior row (replay or same-pair re-touch). */
182
+ existing: boolean;
183
+ /** True when the row was written already-rejected. */
184
+ rejected: boolean;
185
+ /** The rejection's vocabulary reason, or the hook's free text for a veto. */
186
+ reason?: string;
187
+ }
188
+
189
+ /**
190
+ * Record one referral touch. Returns mutation FACTS; it emits nothing.
191
+ *
192
+ * Replay: a touch carrying a `clickId` (or an explicit `idempotencyKey`) is
193
+ * looked up first, so a redelivered click writes no second edge. Same-pair
194
+ * re-touch is a no-op at the DATABASE - the partial-unique edge index is the
195
+ * arbiter, not a judgement call here - which is what keeps a DIFFERENT
196
+ * referrer's touch a genuinely new row for last-touch models to see.
197
+ */
198
+ export async function recordTouch(
199
+ input: RecordTouchInput,
200
+ ): Promise<RecordTouchResult> {
201
+ const {
202
+ db,
203
+ referrerContactId,
204
+ refereeKey,
205
+ source,
206
+ referral,
207
+ idempotencyKey,
208
+ } = input;
209
+ const referralId = input.referralId ?? referral?.id ?? DEFAULT_REFERRAL_ID;
210
+ const refereeContactId = input.refereeContactId ?? null;
211
+ const clickId = input.clickId ?? null;
212
+ const linkId = input.linkId ?? null;
213
+ const touchedAt = input.touchedAt ?? new Date();
214
+ const properties: Record<string, unknown> = { ...(input.properties ?? {}) };
215
+ if (idempotencyKey) {
216
+ properties[REFERRAL_IDEMPOTENCY_PROPERTY] = idempotencyKey;
217
+ }
218
+
219
+ // --- Replay short-circuit -------------------------------------------------
220
+ const replayFilter = idempotencyKey
221
+ ? and(
222
+ eq(referralTouches.referralId, referralId),
223
+ sql`${referralTouches.properties}->>${REFERRAL_IDEMPOTENCY_PROPERTY} = ${idempotencyKey}`,
224
+ )
225
+ : clickId
226
+ ? and(
227
+ eq(referralTouches.referralId, referralId),
228
+ eq(referralTouches.clickId, clickId),
229
+ )
230
+ : null;
231
+ if (replayFilter) {
232
+ const [prior] = await db
233
+ .select()
234
+ .from(referralTouches)
235
+ .where(replayFilter)
236
+ .limit(1);
237
+ if (prior) {
238
+ const record = toRecord(prior);
239
+ return {
240
+ touch: record,
241
+ created: false,
242
+ existing: true,
243
+ rejected: record.status === "rejected",
244
+ reason: record.rejectedReason ?? undefined,
245
+ };
246
+ }
247
+ }
248
+
249
+ // --- Vetoes ---------------------------------------------------------------
250
+ // Self-referral falls out of IDENTITY, not a fraud heuristic: if the toucher
251
+ // is already known to be the owner, there is no edge to write.
252
+ let reject: { reason: ReferralRejectReason; detail?: string } | null =
253
+ refereeContactId && refereeContactId === referrerContactId
254
+ ? { reason: "self" }
255
+ : null;
256
+
257
+ if (!reject && referral?.meta.beforeTouch) {
258
+ const ctx: BeforeTouchContext = {
259
+ referralId,
260
+ referrerContactId,
261
+ refereeKey,
262
+ refereeContactId,
263
+ source,
264
+ linkId,
265
+ clickId,
266
+ properties,
267
+ };
268
+ const v = await verdict(referral.meta.beforeTouch, ctx);
269
+ if (!v.ok) reject = { reason: "veto", detail: v.reason };
270
+ }
271
+
272
+ if (reject?.detail) {
273
+ properties[REFERRAL_VETO_REASON_PROPERTY] = reject.detail;
274
+ }
275
+
276
+ const bound = !reject && refereeContactId !== null;
277
+ const values = {
278
+ referralId,
279
+ referrerContactId,
280
+ refereeKey,
281
+ refereeContactId,
282
+ linkId,
283
+ clickId,
284
+ source,
285
+ touchedAt,
286
+ boundAt: bound ? touchedAt : null,
287
+ status: reject ? "rejected" : bound ? "bound" : "touched",
288
+ rejectedReason: reject?.reason ?? null,
289
+ properties,
290
+ };
291
+
292
+ try {
293
+ const [row] = await db.insert(referralTouches).values(values).returning();
294
+ if (!row) throw new Error("recordTouch: insert returned no row");
295
+ return {
296
+ touch: toRecord(row),
297
+ created: true,
298
+ existing: false,
299
+ rejected: reject !== null,
300
+ reason: reject?.detail ?? reject?.reason,
301
+ };
302
+ } catch (err) {
303
+ if (!isEdgeUniqueViolation(err)) throw err;
304
+ // The SAME (referral, referee, referrer) triple already has a live edge.
305
+ // A re-touch is a no-op on the edge (PRD 05 §9.3), so recover the winner
306
+ // rather than minting a duplicate the report would double-count.
307
+ const [winner] = await db
308
+ .select()
309
+ .from(referralTouches)
310
+ .where(
311
+ and(
312
+ eq(referralTouches.referralId, referralId),
313
+ eq(referralTouches.referrerContactId, referrerContactId),
314
+ refereeContactId
315
+ ? eq(referralTouches.refereeContactId, refereeContactId)
316
+ : isNull(referralTouches.refereeContactId),
317
+ // Match the partial unique index the 23505 came from: rejected rows
318
+ // are NOT edges, so a stale veto row must not win the recovery.
319
+ sql`${referralTouches.status} <> 'rejected'`,
320
+ ),
321
+ )
322
+ .limit(1);
323
+ if (!winner) throw err;
324
+ return {
325
+ touch: toRecord(winner),
326
+ created: false,
327
+ existing: true,
328
+ rejected: winner.status === "rejected",
329
+ reason: winner.rejectedReason ?? undefined,
330
+ };
331
+ }
332
+ }
333
+
334
+ // ---------------------------------------------------------------------------
335
+ // bindTouches
336
+ // ---------------------------------------------------------------------------
337
+
338
+ export interface BindTouchesInput {
339
+ db: Database;
340
+ /** The anonymous/canonical key the visitor touched under. */
341
+ refereeKey: string;
342
+ /** The contact that key just resolved to (identity adoption). */
343
+ contactId: string;
344
+ /** Narrow to one program; default = every unbound touch for the key. */
345
+ referralId?: string;
346
+ /**
347
+ * Definition lookup for `beforeBind` + `bindWindow`. Absent means the
348
+ * defaults apply (no veto, 30-day window) - binding must never depend on a
349
+ * definition being registered, or a redeploy that drops one would silently
350
+ * stop binding.
351
+ */
352
+ resolveReferral?: (referralId: string) => DefinedReferral | undefined;
353
+ now?: Date;
354
+ }
355
+
356
+ export interface BindTouchesResult {
357
+ /** Touches that gained their second end. */
358
+ bound: ReferralTouchRecord[];
359
+ /** Touches refused, with the vocabulary reason. */
360
+ rejected: Array<{
361
+ touch: ReferralTouchRecord;
362
+ reason: ReferralRejectReason;
363
+ detail?: string;
364
+ }>;
365
+ }
366
+
367
+ /**
368
+ * Stamp `referee_contact_id` / `bound_at` on every UNBOUND touch for a key, at
369
+ * identity-adoption time. Self, out-of-window and vetoed touches are rejected
370
+ * in place rather than deleted: an edge that was refused is itself a fact the
371
+ * report and the operator want to see.
372
+ */
373
+ export async function bindTouches(
374
+ input: BindTouchesInput,
375
+ ): Promise<BindTouchesResult> {
376
+ const { db, refereeKey, contactId, resolveReferral } = input;
377
+ const now = input.now ?? new Date();
378
+
379
+ const pending = await db
380
+ .select()
381
+ .from(referralTouches)
382
+ .where(
383
+ and(
384
+ eq(referralTouches.refereeKey, refereeKey),
385
+ isNull(referralTouches.refereeContactId),
386
+ eq(referralTouches.status, "touched"),
387
+ ...(input.referralId
388
+ ? [eq(referralTouches.referralId, input.referralId)]
389
+ : []),
390
+ ),
391
+ )
392
+ .orderBy(desc(referralTouches.touchedAt));
393
+
394
+ const result: BindTouchesResult = { bound: [], rejected: [] };
395
+
396
+ for (const row of pending) {
397
+ const referral = resolveReferral?.(row.referralId);
398
+ let reject: { reason: ReferralRejectReason; detail?: string } | null = null;
399
+
400
+ // The merge is the fraud check: if the referee turns out to BE the
401
+ // referrer, the edge is a self-referral no matter how it was created.
402
+ if (row.referrerContactId === contactId) {
403
+ reject = { reason: "self" };
404
+ } else if (
405
+ now.getTime() - row.touchedAt.getTime() >
406
+ bindWindowMs(referral)
407
+ ) {
408
+ reject = { reason: "window" };
409
+ } else if (referral?.meta.beforeBind) {
410
+ const ctx: BeforeBindContext = {
411
+ referralId: row.referralId,
412
+ touchId: row.id,
413
+ referrerContactId: row.referrerContactId,
414
+ refereeKey: row.refereeKey,
415
+ refereeContactId: contactId,
416
+ touchedAt: row.touchedAt,
417
+ properties: (row.properties ?? {}) as Record<string, unknown>,
418
+ };
419
+ const v = await verdict(referral.meta.beforeBind, ctx);
420
+ if (!v.ok) reject = { reason: "veto", detail: v.reason };
421
+ }
422
+
423
+ if (reject) {
424
+ const rejected = await rejectTouch({
425
+ db,
426
+ touchId: row.id,
427
+ reason: reject.reason,
428
+ detail: reject.detail,
429
+ });
430
+ if (rejected.touch) {
431
+ result.rejected.push({
432
+ touch: rejected.touch,
433
+ reason: reject.reason,
434
+ detail: reject.detail,
435
+ });
436
+ }
437
+ continue;
438
+ }
439
+
440
+ try {
441
+ // `refereeContactId IS NULL` in the predicate makes the stamp itself the
442
+ // race arbiter: two concurrent adoptions cannot both bind the same row.
443
+ const [updated] = await db
444
+ .update(referralTouches)
445
+ .set({
446
+ refereeContactId: contactId,
447
+ boundAt: now,
448
+ status: "bound",
449
+ })
450
+ .where(
451
+ and(
452
+ eq(referralTouches.id, row.id),
453
+ isNull(referralTouches.refereeContactId),
454
+ ),
455
+ )
456
+ .returning();
457
+ if (updated) result.bound.push(toRecord(updated));
458
+ } catch (err) {
459
+ if (!isEdgeUniqueViolation(err)) throw err;
460
+ // This contact ALREADY has a live edge from this referrer (an earlier
461
+ // touch under a different anon key). One pair is one edge, so the later
462
+ // row is a duplicate rather than a second referral.
463
+ const dup = await rejectTouch({
464
+ db,
465
+ touchId: row.id,
466
+ reason: "duplicate",
467
+ });
468
+ if (dup.touch) {
469
+ result.rejected.push({ touch: dup.touch, reason: "duplicate" });
470
+ }
471
+ }
472
+ }
473
+
474
+ return result;
475
+ }
476
+
477
+ // ---------------------------------------------------------------------------
478
+ // qualifyTouch / rejectTouch
479
+ // ---------------------------------------------------------------------------
480
+
481
+ export interface QualifyTouchInput {
482
+ db: Database;
483
+ touchId: string;
484
+ /** The event that triggered the evaluation (for `beforeQualify`). */
485
+ event?: string;
486
+ eventProperties?: Record<string, unknown>;
487
+ conversionId?: string | null;
488
+ referral?: DefinedReferral;
489
+ at?: Date;
490
+ }
491
+
492
+ export interface QualifyTouchResult {
493
+ touch: ReferralTouchRecord | null;
494
+ /** True only when THIS call promoted the row. */
495
+ qualified: boolean;
496
+ /** True when the row was already qualified (a replay). */
497
+ existing: boolean;
498
+ rejected: boolean;
499
+ reason?: string;
500
+ }
501
+
502
+ /**
503
+ * Promote a BOUND touch to qualified, exactly once. The `qualified_at IS NULL`
504
+ * predicate is the replay guard, so a redelivered qualify event returns
505
+ * `existing: true` instead of re-firing the reward journey downstream.
506
+ */
507
+ export async function qualifyTouch(
508
+ input: QualifyTouchInput,
509
+ ): Promise<QualifyTouchResult> {
510
+ const { db, touchId, referral } = input;
511
+ const at = input.at ?? new Date();
512
+
513
+ const [row] = await db
514
+ .select()
515
+ .from(referralTouches)
516
+ .where(eq(referralTouches.id, touchId))
517
+ .limit(1);
518
+ if (!row)
519
+ return { touch: null, qualified: false, existing: false, rejected: false };
520
+ if (row.status === "qualified" || row.qualifiedAt !== null) {
521
+ return {
522
+ touch: toRecord(row),
523
+ qualified: false,
524
+ existing: true,
525
+ rejected: false,
526
+ };
527
+ }
528
+ if (row.status !== "bound" || !row.refereeContactId) {
529
+ // Only a BOUND edge can qualify: an unbound touch has no known referee, so
530
+ // there is nobody to reward and nothing to report against.
531
+ return {
532
+ touch: toRecord(row),
533
+ qualified: false,
534
+ existing: false,
535
+ rejected: false,
536
+ reason: "not_bound",
537
+ };
538
+ }
539
+
540
+ if (referral?.meta.beforeQualify) {
541
+ const ctx: BeforeQualifyContext = {
542
+ referralId: row.referralId,
543
+ touchId: row.id,
544
+ referrerContactId: row.referrerContactId,
545
+ refereeContactId: row.refereeContactId,
546
+ event: input.event ?? "",
547
+ eventProperties: input.eventProperties ?? {},
548
+ conversionId: input.conversionId ?? null,
549
+ properties: (row.properties ?? {}) as Record<string, unknown>,
550
+ };
551
+ const v = await verdict(referral.meta.beforeQualify, ctx);
552
+ if (!v.ok) {
553
+ const rejected = await rejectTouch({
554
+ db,
555
+ touchId,
556
+ reason: "veto",
557
+ detail: v.reason,
558
+ });
559
+ return {
560
+ touch: rejected.touch,
561
+ qualified: false,
562
+ existing: false,
563
+ rejected: true,
564
+ reason: v.reason,
565
+ };
566
+ }
567
+ }
568
+
569
+ const [updated] = await db
570
+ .update(referralTouches)
571
+ .set({
572
+ status: "qualified",
573
+ qualifiedAt: at,
574
+ qualifiedConversionId: input.conversionId ?? null,
575
+ })
576
+ .where(
577
+ and(
578
+ eq(referralTouches.id, touchId),
579
+ isNull(referralTouches.qualifiedAt),
580
+ eq(referralTouches.status, "bound"),
581
+ ),
582
+ )
583
+ .returning();
584
+
585
+ if (!updated) {
586
+ // Lost the race to a concurrent qualify; the winner's row is the truth.
587
+ const [winner] = await db
588
+ .select()
589
+ .from(referralTouches)
590
+ .where(eq(referralTouches.id, touchId))
591
+ .limit(1);
592
+ return {
593
+ touch: winner ? toRecord(winner) : null,
594
+ qualified: false,
595
+ existing: true,
596
+ rejected: false,
597
+ };
598
+ }
599
+
600
+ return {
601
+ touch: toRecord(updated),
602
+ qualified: true,
603
+ existing: false,
604
+ rejected: false,
605
+ };
606
+ }
607
+
608
+ export interface RejectTouchInput {
609
+ db: Database;
610
+ touchId: string;
611
+ reason: ReferralRejectReason;
612
+ /** A hook's free text, filed alongside the vocabulary reason. */
613
+ detail?: string;
614
+ }
615
+
616
+ export interface RejectTouchResult {
617
+ touch: ReferralTouchRecord | null;
618
+ /** True only when THIS call flipped the row to rejected. */
619
+ rejected: boolean;
620
+ }
621
+
622
+ /**
623
+ * Mark a touch rejected. Idempotent: an already-rejected row is returned as-is
624
+ * with `rejected: false`, so a re-run cannot rewrite the ORIGINAL reason (which
625
+ * is the only record of why the edge was thrown away).
626
+ */
627
+ export async function rejectTouch(
628
+ input: RejectTouchInput,
629
+ ): Promise<RejectTouchResult> {
630
+ const { db, touchId, reason, detail } = input;
631
+
632
+ const [updated] = await db
633
+ .update(referralTouches)
634
+ .set({
635
+ status: "rejected",
636
+ rejectedReason: reason,
637
+ ...(detail
638
+ ? {
639
+ properties: sql`coalesce(${referralTouches.properties}, '{}'::jsonb) || ${JSON.stringify(
640
+ { [REFERRAL_VETO_REASON_PROPERTY]: detail },
641
+ )}::jsonb`,
642
+ }
643
+ : {}),
644
+ })
645
+ .where(
646
+ and(
647
+ eq(referralTouches.id, touchId),
648
+ sql`${referralTouches.status} <> 'rejected'`,
649
+ ),
650
+ )
651
+ .returning();
652
+
653
+ if (updated) return { touch: toRecord(updated), rejected: true };
654
+
655
+ const [existing] = await db
656
+ .select()
657
+ .from(referralTouches)
658
+ .where(eq(referralTouches.id, touchId))
659
+ .limit(1);
660
+ return { touch: existing ? toRecord(existing) : null, rejected: false };
661
+ }
662
+
663
+ // ---------------------------------------------------------------------------
664
+ // Reads
665
+ // ---------------------------------------------------------------------------
666
+
667
+ export interface ListTouchesInput {
668
+ db: Database;
669
+ contactId: string;
670
+ referralId?: string;
671
+ status?: ReferralTouchStatus[];
672
+ limit?: number;
673
+ }
674
+
675
+ /** Every touch where this contact is the REFEREE (who referred me). */
676
+ export async function listTouchesForReferee(
677
+ input: ListTouchesInput,
678
+ ): Promise<ReferralTouchRecord[]> {
679
+ return listTouches(input, referralTouches.refereeContactId);
680
+ }
681
+
682
+ /** Every touch where this contact is the REFERRER (who I referred). */
683
+ export async function listTouchesForReferrer(
684
+ input: ListTouchesInput,
685
+ ): Promise<ReferralTouchRecord[]> {
686
+ return listTouches(input, referralTouches.referrerContactId);
687
+ }
688
+
689
+ async function listTouches(
690
+ input: ListTouchesInput,
691
+ column:
692
+ | typeof referralTouches.refereeContactId
693
+ | typeof referralTouches.referrerContactId,
694
+ ): Promise<ReferralTouchRecord[]> {
695
+ const rows = await input.db
696
+ .select()
697
+ .from(referralTouches)
698
+ .where(
699
+ and(
700
+ eq(column, input.contactId),
701
+ ...(input.referralId
702
+ ? [eq(referralTouches.referralId, input.referralId)]
703
+ : []),
704
+ ...(input.status?.length
705
+ ? [inArray(referralTouches.status, input.status)]
706
+ : []),
707
+ ),
708
+ )
709
+ .orderBy(desc(referralTouches.touchedAt))
710
+ .limit(input.limit ?? 200);
711
+ return rows.map(toRecord);
712
+ }