@simplelayer/graniteer-core 0.0.2 → 0.1.2

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.
Files changed (100) hide show
  1. package/index.js +2 -2
  2. package/package.json +98 -15
  3. package/src/adminBookingCredit.test.ts +451 -0
  4. package/src/adminBookingCredit.ts +239 -0
  5. package/src/availability.test.ts +25 -0
  6. package/src/availability.ts +201 -0
  7. package/src/bookingHoldReclaim.ts +94 -0
  8. package/src/checkoutSessionParams.ts +56 -0
  9. package/src/commonsContract.ts +175 -0
  10. package/src/conductorAdmin.ts +141 -0
  11. package/src/email-templates/email-change.tsx +92 -0
  12. package/src/email-templates/invite.tsx +79 -0
  13. package/src/email-templates/reauthentication.tsx +60 -0
  14. package/src/functions/admin-cancel-membership.ts +311 -0
  15. package/src/functions/admin-change-membership-plan.ts +308 -0
  16. package/src/functions/admin-charge-guest-print.ts +229 -0
  17. package/src/functions/admin-correct-booking.ts +333 -0
  18. package/src/functions/admin-create-commons-event.ts +244 -0
  19. package/src/functions/admin-debug-boldsign-doc.ts +93 -0
  20. package/src/functions/admin-door-write.ts +272 -0
  21. package/src/functions/admin-mark-booking-paid.ts +203 -0
  22. package/src/functions/admin-photo-upload.ts +128 -0
  23. package/src/functions/admin-remove-team-member.ts +150 -0
  24. package/src/functions/admin-reset-mfa.ts +138 -0
  25. package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
  26. package/src/functions/admin-send-commons-agreement.ts +214 -0
  27. package/src/functions/admin-set-credit-amount.ts +123 -0
  28. package/src/functions/admin-skip-commons-contract.ts +165 -0
  29. package/src/functions/admin-undo-membership-cancel.ts +144 -0
  30. package/src/functions/admin-wall-photo-write.ts +141 -0
  31. package/src/functions/boldsign-sender-identity.ts +114 -0
  32. package/src/functions/booking-availability.ts +419 -0
  33. package/src/functions/booking-member-preview.ts +136 -0
  34. package/src/functions/day-pass-status.ts +89 -0
  35. package/src/functions/dayStatus.ts +71 -0
  36. package/src/functions/diag-webpush-test.ts +45 -0
  37. package/src/functions/event-access-store.ts +309 -0
  38. package/src/functions/ezeep-print-webhook.ts +213 -0
  39. package/src/functions/ezeep-usage-reconcile.ts +299 -0
  40. package/src/functions/get-signing-link.ts +211 -0
  41. package/src/functions/guest-print-setup-confirm.ts +128 -0
  42. package/src/functions/guest-print-submit.ts +149 -0
  43. package/src/functions/luma-webhook.ts +165 -0
  44. package/src/functions/migration-collision-alert.copy.ts +232 -0
  45. package/src/functions/migration-collision-alert.test.ts +349 -0
  46. package/src/functions/migration-collision-alert.ts +232 -0
  47. package/src/functions/office-assignment-end.ts +146 -0
  48. package/src/functions/portal-booking-access.ts +95 -0
  49. package/src/functions/portal-list-invoices.ts +99 -0
  50. package/src/functions/print-billing-recover.ts +97 -0
  51. package/src/functions/print-billing-run.ts +183 -0
  52. package/src/functions/public-facts.ts +168 -0
  53. package/src/functions/space-availability-range.acceptance.test.ts +161 -0
  54. package/src/functions/space-availability-range.ts +142 -0
  55. package/src/functions/sync-gcal-blackouts.ts +298 -0
  56. package/src/functions/timetable-event-register.ts +162 -0
  57. package/src/functions/timetable-event-status.ts +90 -0
  58. package/src/functions/timetable-spaces.ts +219 -0
  59. package/src/functions/touch-pass-reconciler.ts +689 -0
  60. package/src/functions/virtual-onboarding-purge.ts +134 -0
  61. package/src/functions/virtual-onboarding-submit.ts +315 -0
  62. package/src/functions/voice-inquiry.test.ts +301 -0
  63. package/src/functions/voice-inquiry.ts +198 -0
  64. package/src/functions/voice-tour-availability.ts +204 -0
  65. package/src/gcalSync.ts +142 -0
  66. package/src/ghlNote.ts +34 -0
  67. package/src/ghlTask.ts +48 -0
  68. package/src/ghlVoiceInquiry.ts +90 -0
  69. package/src/guestPrintCapture.test.ts +722 -0
  70. package/src/guestPrintCapture.ts +538 -0
  71. package/src/lumaGhl.ts +195 -0
  72. package/src/membership.ts +109 -0
  73. package/src/money.ts +36 -0
  74. package/src/ops.ts +97 -0
  75. package/src/pacificDate.ts +34 -0
  76. package/src/policyAcknowledgment.test.ts +50 -0
  77. package/src/policyAcknowledgment.ts +96 -0
  78. package/src/portalSession.ts +46 -0
  79. package/src/pricing.test.ts +660 -0
  80. package/src/pricing.ts +1025 -0
  81. package/src/printBilling.test.ts +750 -0
  82. package/src/printBilling.ts +891 -0
  83. package/src/printBillingAdapters.ts +169 -0
  84. package/src/printCorrections.test.ts +348 -0
  85. package/src/printCorrections.ts +496 -0
  86. package/src/rateLimit.ts +82 -0
  87. package/src/referralCredits.test.ts +31 -0
  88. package/src/referralCredits.ts +34 -0
  89. package/src/referralGrant.ts +321 -0
  90. package/src/rescheduleCredit.test.ts +521 -0
  91. package/src/rescheduleCredit.ts +337 -0
  92. package/src/reservationWifiCode.test.ts +69 -0
  93. package/src/reservationWifiCode.ts +81 -0
  94. package/src/retellCallAnalyzed.test.ts +167 -0
  95. package/src/retellCallAnalyzed.ts +113 -0
  96. package/src/retellSignature.test.ts +137 -0
  97. package/src/retellSignature.ts +82 -0
  98. package/src/slackAlert.ts +38 -0
  99. package/src/supabaseTestFakes.ts +131 -0
  100. package/src/tier1Agreement.ts +125 -0
@@ -0,0 +1,891 @@
1
+ // print-usage-bill P2 — the decision core for `print-billing-run` and
2
+ // `print-billing-recover`.
3
+ //
4
+ // Design: PRINT-USAGE-BILL-DESIGN.md v19, sections 4.2, 4.3, 4.4 and 5.
5
+ //
6
+ // THIS MODULE MAKES NO NETWORK CALLS AND IMPORTS NOTHING. Stripe and the
7
+ // database both arrive as injected, structurally-typed dependencies, so the
8
+ // whole of the money logic is exercisable against hand-rolled stubs. That is
9
+ // deliberate and it is what section 8.5 means by "run it against a mocked Stripe
10
+ // client first"; section 8.5's live half is GATED and is not reachable from here.
11
+ //
12
+ // C-03 is the reason the shape is like this at all: there is no synchronous HTTP
13
+ // extension in this Postgres (pg_net is async, dispatch-after-commit), so a
14
+ // plpgsql function cannot call Stripe and branch on the result. The edge function
15
+ // makes the Stripe calls; the DB does short transactions only.
16
+
17
+ // ---------------------------------------------------------------- constants --
18
+
19
+ /** C-10 / Stripe's documented minimum. Applied at RUN level only — never per period. */
20
+ export const STRIPE_MIN_CENTS = 50;
21
+
22
+ /** R-08, KYLE-RATIFIED 2026-08-22. Strictly greater-than: exactly $75.00 bills. */
23
+ export const HARD_CAP_CENTS = 7500;
24
+
25
+ /** R-08, KYLE-RATIFIED. ">= 10x" matches the ratified wording "10x or more". */
26
+ export const ANOMALY_MULTIPLIER = 10;
27
+
28
+ /** [RE-DERIVED] — Kyle ratified the multiplier, NOT this threshold. */
29
+ export const MIN_QUALIFYING_PERIODS = 3;
30
+
31
+ /** [RE-DERIVED] — window size for the baseline. See R-08's row in section 12. */
32
+ export const BASELINE_WINDOW = 6;
33
+
34
+ // Deterministic idempotency keys. R2 found v6's "idempotency key" was a DB
35
+ // uniqueness constraint that was never sent to Stripe. These strings are stored
36
+ // in print_billing_runs.idempotency_key AND sent in the Idempotency-Key header.
37
+ export const runKey = (runId: string) => `gc-p2-run-${runId}`;
38
+ export const itemKey = (runId: string, periodId: string) => `gc-p2-item-${runId}-${periodId}`;
39
+ export const finalizeKey = (runId: string) => `gc-p2-fin-${runId}`;
40
+ export const creditKey = (correctionId: string) => `gc-p2-cn-${correctionId}`;
41
+
42
+ // -------------------------------------------------------------------- types --
43
+
44
+ export interface StripeInvoice {
45
+ id: string;
46
+ status?: string | null;
47
+ metadata?: Record<string, string> | null;
48
+ livemode?: boolean;
49
+ }
50
+
51
+ export interface StripeInvoiceLine {
52
+ id: string;
53
+ parent?: { invoice_item_details?: { invoice_item?: string | null } | null } | null;
54
+ }
55
+
56
+ export interface StripeAccount {
57
+ id: string;
58
+ livemode?: boolean;
59
+ }
60
+
61
+ /** A payment method reference as Stripe returns it: a bare id when unexpanded,
62
+ * or an expanded object carrying one. Either shape must resolve to the id. */
63
+ export type StripePaymentMethodRef = string | { id: string } | null | undefined;
64
+
65
+ export interface StripeSubscription {
66
+ id: string;
67
+ default_payment_method?: StripePaymentMethodRef;
68
+ }
69
+
70
+ export interface StripeCustomer {
71
+ id: string;
72
+ invoice_settings?: { default_payment_method?: StripePaymentMethodRef } | null;
73
+ }
74
+
75
+ /** Only the surface this design touches. Structural on purpose: a test's fake
76
+ * client satisfies it without pulling in the Stripe SDK. */
77
+ export interface PrintStripeLike {
78
+ account: {
79
+ retrieve(): Promise<StripeAccount>;
80
+ };
81
+ invoices: {
82
+ create(params: Record<string, unknown>, opts?: { idempotencyKey?: string }): Promise<StripeInvoice>;
83
+ retrieve(id: string): Promise<StripeInvoice>;
84
+ list(params: Record<string, unknown>): Promise<{ data: StripeInvoice[]; has_more?: boolean }>;
85
+ finalize(id: string, params: Record<string, unknown>, opts?: { idempotencyKey?: string }): Promise<StripeInvoice>;
86
+ listLines(id: string, params: Record<string, unknown>): Promise<{ data: StripeInvoiceLine[]; has_more?: boolean }>;
87
+ };
88
+ invoiceItems: {
89
+ create(params: Record<string, unknown>, opts?: { idempotencyKey?: string }): Promise<{ id: string }>;
90
+ };
91
+ /** STEP 0.4 branch (a) — C-13. */
92
+ subscriptions: {
93
+ retrieve(id: string): Promise<StripeSubscription>;
94
+ };
95
+ /** STEP 0.4 branch (b) — C-13. */
96
+ customers: {
97
+ retrieve(id: string): Promise<StripeCustomer>;
98
+ };
99
+ }
100
+
101
+ export interface PeriodRow {
102
+ id: string;
103
+ charge_cents_total: number;
104
+ bw_billable: number;
105
+ color_pages: number;
106
+ period_month: string;
107
+ billing_run_id: string | null;
108
+ billed_run_id: string | null;
109
+ stripe_invoice_item_id: string | null;
110
+ stripe_invoice_id: string | null;
111
+ }
112
+
113
+ export interface RunRow {
114
+ id: string;
115
+ membership_id: string;
116
+ status: string;
117
+ stripe_customer_id: string;
118
+ stripe_invoice_id: string | null;
119
+ period_ids: string[];
120
+ attempt_count: number;
121
+ created_at: string;
122
+ }
123
+
124
+ export interface ClaimResult {
125
+ run_id: string;
126
+ lease_token: string;
127
+ lease_expires_at: string;
128
+ }
129
+
130
+ /** Every DB path goes through a private SECURITY DEFINER function (C-09).
131
+ * service_role holds no direct write privilege on any of these tables. */
132
+ export interface PrintDbLike {
133
+ claim(args: {
134
+ runId: string; periodMonths: string[]; periodIds: string[];
135
+ customerId: string; amountCents: number; idempotencyKey: string;
136
+ }): Promise<ClaimResult>;
137
+ attemptBump(runId: string, leaseToken: string): Promise<number>;
138
+ leaseRenew(runId: string, leaseToken: string): Promise<string>;
139
+ leaseAcquire(runId: string): Promise<{ lease_token: string; lease_expires_at: string } | null>;
140
+ writeback(runId: string, leaseToken: string, status: string,
141
+ invoiceId: string | null, detail: Record<string, unknown>): Promise<void>;
142
+ hold(runId: string, leaseToken: string, reason: string): Promise<void>;
143
+ releaseRun(runId: string, leaseToken: string, reason: string, listVerifiedEmpty: boolean): Promise<void>;
144
+ paymentStatus(invoiceId: string, status: string, detail?: Record<string, unknown>): Promise<void>;
145
+ getPeriod(periodId: string): Promise<PeriodRow | null>;
146
+ baseline(membershipId: string): Promise<{ baseline_cents: number; qualifying_periods: number }>;
147
+ recoverySelect(limit: number): Promise<RunRow[]>;
148
+ opsEvent(kind: string, severity: string, detail: Record<string, unknown>, dedupeKey?: string): Promise<void>;
149
+ }
150
+
151
+ export interface GcError extends Error {
152
+ gcCode?: string;
153
+ }
154
+
155
+ /** GC001..GC011 are raised by the migrations with `using errcode = ...`.
156
+ * Everything branches on these, never on message text. */
157
+ export function gcCodeOf(e: unknown): string | null {
158
+ const anyE = e as { gcCode?: string; code?: string } | null;
159
+ return anyE?.gcCode ?? anyE?.code ?? null;
160
+ }
161
+
162
+ // ------------------------------------------------------- section 4.2 queries --
163
+
164
+ /** The eligibility query, verbatim from section 4.2.
165
+ * Note the two DIFFERENT predicates and keep them distinct (v15/S5):
166
+ * - `charge_cents_total > 0` is PER PERIOD and excludes $0.00 lines.
167
+ * - `having sum(...) >= 50` is RUN LEVEL and is the ONLY place the Stripe
168
+ * minimum is applied on this side. v14 also had a per-period `>= 50` inside
169
+ * M-11's claim UPDATE; that predicate is DELETED, because it silently billed
170
+ * a member who owed $9.30 nothing at all, every month (T-85). */
171
+ export const ELIGIBILITY_SQL = `
172
+ select p.membership_id,
173
+ array_agg(p.id order by p.period_month) as period_ids,
174
+ array_agg(distinct p.period_month) as period_months,
175
+ sum(p.charge_cents_total)::integer as amount_cents
176
+ from public.print_usage_periods p
177
+ where p.status = 'pending_bill'
178
+ and p.billing_run_id is null
179
+ and p.billed_run_id is null
180
+ and p.charge_cents_total > 0
181
+ group by p.membership_id
182
+ having sum(p.charge_cents_total) >= ${STRIPE_MIN_CENTS}
183
+ and not exists (
184
+ select 1 from public.print_billing_runs r
185
+ where r.membership_id = p.membership_id
186
+ and r.completed_at is null
187
+ )`;
188
+
189
+ /** [v18/B12-1] The baseline query. The ORDER BY and LIMIT MUST live in a
190
+ * subquery: v6..v17 printed an ungrouped avg() with a bare ORDER BY, which
191
+ * PostgreSQL rejects outright with 42803 (T-46), and deleting the ORDER BY to
192
+ * "fix" it silently widens the window to the membership's entire history —
193
+ * a 25x baseline error on the v18 fixture (T-46b). Returns BOTH operands rule 2
194
+ * needs; the old form returned no count at all, so the rule was unimplementable
195
+ * from its own stated input. */
196
+ export const BASELINE_SQL = `
197
+ select coalesce(avg(b.billed_amount_cents), 0)::numeric as baseline_cents,
198
+ count(*)::integer as qualifying_periods
199
+ from (
200
+ select p.billed_amount_cents, p.period_month
201
+ from public.print_usage_periods p
202
+ where p.membership_id = $1
203
+ and p.status = 'billed'
204
+ and p.billed_amount_cents > 0
205
+ order by p.period_month desc
206
+ limit ${BASELINE_WINDOW}
207
+ ) b`;
208
+
209
+ /** section 5.3's escalation ladder. A held run gets louder rather than expiring —
210
+ * an automatic expiry that frees the periods is exactly what created the
211
+ * double-charge hole in R7 F4 / R8 F2. */
212
+ export const STUCK_ESCALATION_SQL = `
213
+ insert into public.ops_events (kind, severity, detail, dedupe_key)
214
+ select
215
+ 'print_billing_run_stuck',
216
+ case
217
+ when r.updated_at < now() - interval '7 days' then 'critical'
218
+ when r.updated_at < now() - interval '24 hours' then 'error'
219
+ else 'warning'
220
+ end,
221
+ jsonb_build_object(
222
+ 'run_id', r.id, 'membership_id', r.membership_id, 'status', r.status,
223
+ 'hold_reason', r.hold_reason, 'amount_cents', r.amount_cents,
224
+ 'stripe_invoice_id', r.stripe_invoice_id,
225
+ 'stuck_for', now() - r.updated_at,
226
+ 'blocking_future_runs_for_membership', true),
227
+ 'print_billing_run_stuck:' || r.id::text || ':'
228
+ || (now() at time zone 'UTC')::date::text
229
+ from public.print_billing_runs r
230
+ where r.completed_at is null
231
+ and r.status = 'held'
232
+ on conflict (dedupe_key) where dedupe_key is not null do nothing`;
233
+
234
+ // ------------------------------------------- section 4.2 anomaly / cap gate --
235
+
236
+ export interface GateInput {
237
+ amountCents: number;
238
+ baselineCents: number;
239
+ qualifyingPeriods: number;
240
+ }
241
+
242
+ export interface GateResult {
243
+ overCap: boolean;
244
+ anomaly: boolean;
245
+ blocked: boolean;
246
+ }
247
+
248
+ /** Rules 1-3 of section 4.2's gate. The two gates are INDEPENDENT and both are
249
+ * evaluated — a run can trip the cap without the ratio and vice versa, and
250
+ * staff need to know which rule caught it, so this never short-circuits. */
251
+ export function evaluateGate(input: GateInput): GateResult {
252
+ const overCap = input.amountCents > HARD_CAP_CENTS;
253
+
254
+ // With fewer than 3 qualifying periods the relative check is SKIPPED entirely
255
+ // (R2's finding): a member's first real charge must not trip a ratio against an
256
+ // empty or all-zero history.
257
+ const anomaly =
258
+ input.qualifyingPeriods >= MIN_QUALIFYING_PERIODS &&
259
+ input.amountCents >= ANOMALY_MULTIPLIER * input.baselineCents;
260
+
261
+ return { overCap, anomaly, blocked: overCap || anomaly };
262
+ }
263
+
264
+ // ------------------------------------------------ section 4.3 — THE ORACLE --
265
+
266
+ export type OracleResult =
267
+ | { found: "yes"; invoice: StripeInvoice }
268
+ | { found: "no"; via404: boolean }
269
+ | { found: "unknown" }
270
+ | { found: "conflict" };
271
+
272
+ export interface OracleInput {
273
+ runId: string;
274
+ customerId: string;
275
+ storedInvoiceId: string | null;
276
+ }
277
+
278
+ function isNotFound(e: unknown): boolean {
279
+ const anyE = e as { statusCode?: number; status?: number; code?: string } | null;
280
+ return anyE?.statusCode === 404 || anyE?.status === 404 || anyE?.code === "resource_missing";
281
+ }
282
+
283
+ /**
284
+ * section 4.3.1, in strict order.
285
+ *
286
+ * LAYER 1 is the stored id. A 404 there is NEVER, by itself, evidence that no
287
+ * invoice exists — it is only ever a reason to run LAYER 2 (section 4.3.2, round 8
288
+ * blocking finding 3). A wrong-account key or a corrupted write-back would also
289
+ * 404 a real, live invoice, and the v13 design would have released and re-billed it.
290
+ *
291
+ * LAYER 2 is List Invoices — NOT Search (C-05). Stripe's own docs warn against
292
+ * Search for read-after-write, and the one window where stripe_invoice_id is NULL
293
+ * on an incomplete run is the seconds right after creation, which is Search's
294
+ * worst case. There is deliberately NO status filter: a status=draft filter makes
295
+ * "not found" unsound, because an already-finalized invoice is invisible to it and
296
+ * the not-found branch then draws the stronger "never happened" conclusion.
297
+ */
298
+ export async function runOracle(
299
+ stripe: PrintStripeLike,
300
+ input: OracleInput,
301
+ ): Promise<OracleResult> {
302
+ let via404 = false;
303
+
304
+ // ---- LAYER 1 -----------------------------------------------------------
305
+ if (input.storedInvoiceId) {
306
+ try {
307
+ const inv = await stripe.invoices.retrieve(input.storedInvoiceId);
308
+ return { found: "yes", invoice: inv };
309
+ } catch (e) {
310
+ if (isNotFound(e)) {
311
+ via404 = true; // fall through to LAYER 2 — do NOT conclude "no invoice"
312
+ } else {
313
+ return { found: "unknown" }; // transient; retry next sweep
314
+ }
315
+ }
316
+ }
317
+
318
+ // ---- LAYER 2 -----------------------------------------------------------
319
+ const matches: StripeInvoice[] = [];
320
+ let startingAfter: string | undefined;
321
+ for (let page = 0; page < 20; page++) {
322
+ let res: { data: StripeInvoice[]; has_more?: boolean };
323
+ try {
324
+ res = await stripe.invoices.list({
325
+ customer: input.customerId,
326
+ limit: 100,
327
+ ...(startingAfter ? { starting_after: startingAfter } : {}),
328
+ });
329
+ } catch {
330
+ return { found: "unknown" };
331
+ }
332
+ for (const inv of res.data) {
333
+ if (inv.metadata?.gc_run_id === input.runId) matches.push(inv);
334
+ }
335
+ if (!res.has_more || res.data.length === 0) break;
336
+ startingAfter = res.data[res.data.length - 1].id;
337
+ }
338
+
339
+ if (matches.length === 1) return { found: "yes", invoice: matches[0] };
340
+ if (matches.length > 1) return { found: "conflict" }; // never expected; HOLD
341
+ return { found: "no", via404 };
342
+ }
343
+
344
+ // ------------------------------------------ section 4.4 state-transition table --
345
+
346
+ export type RecoveryAction =
347
+ | { kind: "release_run" }
348
+ | { kind: "adopt_draft" } // writeback invoice_created, resume STEP 3
349
+ | { kind: "adopt_finalized"; paid: boolean }
350
+ | { kind: "resume_items" }
351
+ | { kind: "refinalize" }
352
+ | { kind: "retry" }
353
+ | { kind: "hold"; reason: string }
354
+ | { kind: "noop" };
355
+
356
+ const IN_FLIGHT = ["claimed", "invoice_created", "items_posted", "finalizing"];
357
+
358
+ export function isInFlight(status: string): boolean {
359
+ return IN_FLIGHT.includes(status);
360
+ }
361
+
362
+ /**
363
+ * section 4.4, encoded. Given a run in this state and this oracle result, do exactly
364
+ * this. `failureOrigin` is deliberately NOT a parameter: it exists only inside one
365
+ * invocation and is gone the moment the process is (section 4.4.1). Every decision
366
+ * below is driven by the ORACLE RESULT and the RUN'S PERSISTED STATUS, both of
367
+ * which survive the process — which is why rows 23-25 (no recorded origin) are the
368
+ * COMMON case and need no separate branch.
369
+ */
370
+ export function decideRecoveryAction(
371
+ runStatus: string,
372
+ storedInvoiceId: string | null,
373
+ oracle: OracleResult,
374
+ ): RecoveryAction {
375
+ // Rows 19-22: terminal states are no-ops for automation.
376
+ if (!isInFlight(runStatus)) return { kind: "noop" };
377
+
378
+ if (oracle.found === "unknown") return { kind: "retry" }; // rows 4, 9, 15
379
+ if (oracle.found === "conflict") return { kind: "hold", reason: "duplicate_invoices_for_run" }; // row 5
380
+
381
+ if (oracle.found === "no") {
382
+ // section 4.3.2: automatic release is reachable from EXACTLY ONE state —
383
+ // claimed AND no stored id AND LAYER 2 verified empty. Anything else is a
384
+ // data-integrity event, not a routine retry.
385
+ if (runStatus === "claimed" && !storedInvoiceId && !oracle.via404) {
386
+ return { kind: "release_run" }; // row 1
387
+ }
388
+ return { kind: "hold", reason: "invoice_404_unverified" }; // rows 8, 14
389
+ }
390
+
391
+ // oracle.found === "yes"
392
+ const st = oracle.invoice.status ?? "draft";
393
+
394
+ if (st === "void" || st === "uncollectible") {
395
+ return { kind: "hold", reason: "invoice_terminal_out_of_band" }; // row 13
396
+ }
397
+
398
+ if (st === "draft") {
399
+ if (runStatus === "claimed") return { kind: "adopt_draft" }; // row 2
400
+ if (runStatus === "invoice_created") return { kind: "resume_items" }; // row 6
401
+ return { kind: "refinalize" }; // row 10
402
+ }
403
+
404
+ // open / paid — the invoice finalized behind us. Do not post more items.
405
+ return { kind: "adopt_finalized", paid: st === "paid" }; // rows 3, 7, 11, 12
406
+ }
407
+
408
+ // --------------------------------------------------- the run itself (4.2) --
409
+
410
+ export interface RunInput {
411
+ runId: string;
412
+ membershipId: string;
413
+ customerId: string;
414
+ periodIds: string[];
415
+ periodMonths: string[];
416
+ amountCents: number;
417
+ /** C-13: standalone customer-scoped invoices do NOT inherit
418
+ * subscription.default_payment_method. Resolved at STEP 0.4. */
419
+ defaultPaymentMethod: string | null;
420
+ expectedAccountId: string;
421
+ expectedLivemode: boolean;
422
+ }
423
+
424
+ export interface RunOutcome {
425
+ ok: boolean;
426
+ exitCode: number;
427
+ status: string;
428
+ detail?: string;
429
+ invoiceId?: string;
430
+ }
431
+
432
+ const MONTHS = ["January", "February", "March", "April", "May", "June", "July",
433
+ "August", "September", "October", "November", "December"];
434
+
435
+ export function monthName(periodMonth: string): string {
436
+ const m = Number(periodMonth.slice(5, 7));
437
+ return `${MONTHS[m - 1]} ${periodMonth.slice(0, 4)}`;
438
+ }
439
+
440
+ export function itemDescription(p: PeriodRow): string {
441
+ return `Print & copy usage - ${monthName(p.period_month)} ` +
442
+ `(${p.bw_billable} b/w, ${p.color_pages} color)`;
443
+ }
444
+
445
+ /**
446
+ * STEP 0.2 — verify the key's account BEFORE anything else.
447
+ * This is what makes a later 404 interpretable at all (R8 F3): without it,
448
+ * "404" and "we are looking in the wrong Stripe account" are the same observation.
449
+ */
450
+ export async function preflightAccount(
451
+ stripe: PrintStripeLike, expectedAccountId: string, expectedLivemode: boolean,
452
+ ): Promise<{ ok: boolean; detail?: string }> {
453
+ const acct = await stripe.account.retrieve();
454
+ if (acct.id !== expectedAccountId) {
455
+ return { ok: false, detail: `stripe account mismatch: got ${acct.id}, expected ${expectedAccountId}` };
456
+ }
457
+ if (acct.livemode !== undefined && acct.livemode !== expectedLivemode) {
458
+ return { ok: false, detail: `stripe livemode mismatch: got ${acct.livemode}, expected ${expectedLivemode}` };
459
+ }
460
+ return { ok: true };
461
+ }
462
+
463
+ function pmId(ref: StripePaymentMethodRef): string | null {
464
+ if (!ref) return null;
465
+ return typeof ref === "string" ? ref : ref.id;
466
+ }
467
+
468
+ export interface CustomerResolution {
469
+ stripeCustomerId: string;
470
+ /** NULL if the member has no live subscription (e.g. C-12's canceled member,
471
+ * or one who never subscribed). */
472
+ stripeSubscriptionId: string | null;
473
+ }
474
+
475
+ /**
476
+ * STEP 0.4 / C-13, resolved for real. Standalone customer-scoped invoices do
477
+ * NOT inherit subscription.default_payment_method, and 3 of 20 live
478
+ * subscriptions have a different card there than the customer's own default.
479
+ * Preference order, exactly as the design states it:
480
+ * a) subscription.default_payment_method (if the member has a live sub)
481
+ * b) customer.invoice_settings.default_payment_method
482
+ * c) none -> caller sets nothing on the invoice; it still finalizes and duns.
483
+ *
484
+ * This MUST live here, not in the DB (private.print_billing_resolve_customer):
485
+ * there is no synchronous HTTP extension in this Postgres (C-03), so a SQL/
486
+ * stable function cannot call Stripe to ask a subscription what its payment
487
+ * method is. The DB function resolves identifiers only; this resolves the
488
+ * actual preference order against a live Stripe client.
489
+ *
490
+ * A subscription that fails to retrieve (deleted, canceled and purged, wrong
491
+ * account) falls through to (b) rather than aborting the run — a stale
492
+ * subscription id must not block billing a member who otherwise owes money.
493
+ */
494
+ export async function resolveDefaultPaymentMethod(
495
+ stripe: PrintStripeLike,
496
+ resolution: CustomerResolution,
497
+ ): Promise<string | null> {
498
+ if (resolution.stripeSubscriptionId) {
499
+ try {
500
+ const sub = await stripe.subscriptions.retrieve(resolution.stripeSubscriptionId);
501
+ const fromSub = pmId(sub?.default_payment_method);
502
+ if (fromSub) return fromSub;
503
+ } catch {
504
+ // fall through to (b) — a bad/stale subscription id must not block billing
505
+ }
506
+ }
507
+
508
+ try {
509
+ const cust = await stripe.customers.retrieve(resolution.stripeCustomerId);
510
+ const fromCust = pmId(cust?.invoice_settings?.default_payment_method);
511
+ if (fromCust) return fromCust;
512
+ } catch {
513
+ // fall through to (c)
514
+ }
515
+
516
+ return null;
517
+ }
518
+
519
+ /**
520
+ * section 4.2 STEP 1 through STEP 4, with every Stripe failure routed to
521
+ * section 4.3's oracle rather than to "release and retry" (R4).
522
+ */
523
+ export async function executeBillingRun(
524
+ stripe: PrintStripeLike, db: PrintDbLike, input: RunInput,
525
+ ): Promise<RunOutcome> {
526
+ // ---- STEP 0.2 preflight -------------------------------------------------
527
+ const pre = await preflightAccount(stripe, input.expectedAccountId, input.expectedLivemode);
528
+ if (!pre.ok) {
529
+ // Aborts before any claim. Nothing is written. (T-56)
530
+ return { ok: false, exitCode: 1, status: "aborted_preflight", detail: pre.detail };
531
+ }
532
+
533
+ // ---- STEP 1: T1 claim ---------------------------------------------------
534
+ let claimed: ClaimResult;
535
+ try {
536
+ claimed = await db.claim({
537
+ runId: input.runId,
538
+ periodMonths: input.periodMonths,
539
+ periodIds: input.periodIds,
540
+ customerId: input.customerId,
541
+ amountCents: input.amountCents,
542
+ idempotencyKey: runKey(input.runId),
543
+ });
544
+ } catch (e) {
545
+ const code = gcCodeOf(e);
546
+ if (code === "GC002") {
547
+ // Benign: another run is in flight for this membership, or the key was
548
+ // reused. Recovery (section 5) owns the other run.
549
+ return { ok: true, exitCode: 0, status: "already_in_flight" };
550
+ }
551
+ if (code === "GC003") {
552
+ // PARTIAL CLAIM or AMOUNT DRIFT. The transaction rolled back, so nothing
553
+ // exists — this insert happens from OUTSIDE the failed transaction.
554
+ // Handling is identical for both causes DELIBERATELY: both mean "the
555
+ // picture this invocation was working from is no longer true", and the
556
+ // correct next action is to re-derive eligibility on a later invocation,
557
+ // never to patch up the numbers in-process.
558
+ await db.opsEvent("print_billing_partial_claim", "error", {
559
+ run_id: input.runId,
560
+ membership_id: input.membershipId,
561
+ requested: input.periodIds.length,
562
+ amount_cents: input.amountCents,
563
+ sqlerrm: String((e as Error)?.message ?? e),
564
+ });
565
+ return { ok: false, exitCode: 1, status: "partial_claim" };
566
+ }
567
+ return { ok: false, exitCode: 1, status: "claim_failed", detail: String((e as Error)?.message ?? e) };
568
+ }
569
+
570
+ const lease = claimed.lease_token;
571
+ return await driveFromClaimed(stripe, db, input, lease);
572
+ }
573
+
574
+ /** STEP 2 onward. Shared by the fresh run and by recovery's resume path. */
575
+ export async function driveFromClaimed(
576
+ stripe: PrintStripeLike, db: PrintDbLike, input: RunInput, lease: string,
577
+ ): Promise<RunOutcome> {
578
+ // ---- STEP 2: create the draft invoice -----------------------------------
579
+ let attempts: number;
580
+ try {
581
+ attempts = await db.attemptBump(input.runId, lease);
582
+ } catch (e) {
583
+ // GC005 == we lost the lease. EXIT immediately, write nothing (row 18).
584
+ if (gcCodeOf(e) === "GC005") return { ok: true, exitCode: 0, status: "lease_lost" };
585
+ throw e;
586
+ }
587
+
588
+ if (attempts > 3) {
589
+ await db.hold(input.runId, lease, "attempt_count exceeded before invoice creation");
590
+ return { ok: false, exitCode: 1, status: "held", detail: "attempt_count_exceeded" };
591
+ }
592
+
593
+ await db.leaseRenew(input.runId, lease);
594
+
595
+ let invoice: StripeInvoice;
596
+ try {
597
+ invoice = await stripe.invoices.create({
598
+ customer: input.customerId,
599
+ collection_method: "charge_automatically",
600
+ // C-06: NOT true here. Setting auto_advance at creation lets Stripe
601
+ // auto-finalize and charge an incomplete draft on its own after ~1hr,
602
+ // bypassing verification (R3). It is passed to FINALIZE instead.
603
+ auto_advance: false,
604
+ pending_invoice_items_behavior: "exclude",
605
+ ...(input.defaultPaymentMethod ? { default_payment_method: input.defaultPaymentMethod } : {}),
606
+ description: "Print & copy usage",
607
+ metadata: {
608
+ gc_run_id: input.runId,
609
+ gc_feature: "print_usage_bill",
610
+ gc_membership_id: input.membershipId,
611
+ gc_period_ids: input.periodIds.join(","),
612
+ },
613
+ }, { idempotencyKey: runKey(input.runId) });
614
+ } catch {
615
+ return await recoveryRoute(stripe, db, input, lease);
616
+ }
617
+
618
+ // ---- STEP 2.5: T2 write-back -------------------------------------------
619
+ // [v16/B10-1] NOTE THE EMPTY p_detail AND WHAT M-14 DOES WITH IT. There are no
620
+ // line items yet, but M-14 no longer treats "no detail" as "nothing to stamp":
621
+ // it sets stripe_invoice_id on EVERY period this run claimed, right here,
622
+ // because from this instant a real Stripe object exists and the period-level
623
+ // money guards in M-04 and M-17 must be able to see it. Before v16 they could
624
+ // not, and section 2.3.2 is the double charge that window allowed.
625
+ await db.writeback(input.runId, lease, "invoice_created", invoice.id, {});
626
+
627
+ return await postItemsAndFinalize(stripe, db, input, lease, invoice.id);
628
+ }
629
+
630
+ /** STEP 3 (items) + STEP 4 (finalize). Also recovery's resume point. */
631
+ export async function postItemsAndFinalize(
632
+ stripe: PrintStripeLike, db: PrintDbLike, input: RunInput, lease: string, invoiceId: string,
633
+ /** How many times THIS invocation has already re-entered the item/finalize loop
634
+ * via the recovery route. See the note on `applyRecoveryAction`. */
635
+ depth = 0,
636
+ ): Promise<RunOutcome> {
637
+ for (const periodId of input.periodIds) {
638
+ // ---- STEP 3.1: DB-SIDE dedup (C-17) ----------------------------------
639
+ const p = await db.getPeriod(periodId);
640
+ if (!p) {
641
+ await db.hold(input.runId, lease, `period_missing: ${periodId}`);
642
+ return { ok: false, exitCode: 1, status: "held", detail: "period_missing" };
643
+ }
644
+
645
+ // [v16/B10-1] The oracle reads stripe_invoice_ITEM_id (ii_), NOT
646
+ // stripe_invoice_id. That distinction is load-bearing: M-14 now stamps
647
+ // stripe_invoice_id on every claimed period at STEP 2.5, so an oracle keyed
648
+ // on THAT column would report every period as already-posted, skip the whole
649
+ // loop, and finalize a $0.00 invoice. Do not "simplify" this to read
650
+ // stripe_invoice_id. (T-26h)
651
+ if (p.stripe_invoice_item_id) continue;
652
+
653
+ // [v17/B11-1] THE THIRD LEG OF THE FIX, and the only one standing at the
654
+ // layer where the MONEY actually moves. This loop is driven by the RUN's
655
+ // period_ids snapshot, taken at claim time and never revised. Until v17
656
+ // nothing between that snapshot and POST /v1/invoiceitems re-checked that the
657
+ // period was still ours — so a period released out from under a live run was
658
+ // still invoiced, then missed every one of M-14's `where billing_run_id =
659
+ // p_run_id` write-backs, ending with no Stripe trace and both run ids NULL.
660
+ // HOLD rather than skip: a period vanishing from a live run's claim set is a
661
+ // data-integrity event, not a routine condition.
662
+ if (p.billing_run_id !== input.runId || p.billed_run_id !== input.runId) {
663
+ await db.hold(input.runId, lease, `period_no_longer_claimed_by_this_run: ${periodId}`);
664
+ return { ok: false, exitCode: 1, status: "held", detail: "period_no_longer_claimed_by_this_run" };
665
+ }
666
+
667
+ await db.leaseRenew(input.runId, lease);
668
+
669
+ let item: { id: string };
670
+ try {
671
+ item = await stripe.invoiceItems.create({
672
+ customer: input.customerId,
673
+ invoice: invoiceId,
674
+ currency: "usd",
675
+ // [v16/S10-4] THIS VALUE COMES FROM THE ROW RE-READ ABOVE, never from the
676
+ // section 4.2 eligibility snapshot, which was computed in a different
677
+ // transaction and may be minutes old.
678
+ amount: p.charge_cents_total,
679
+ description: itemDescription(p),
680
+ metadata: { gc_period_id: periodId, gc_run_id: input.runId },
681
+ }, { idempotencyKey: itemKey(input.runId, periodId) });
682
+ } catch {
683
+ // The run is at `invoice_created` and HAS a stored invoice id. Both must be
684
+ // passed: the oracle keys LAYER 1 on the id, and section 4.4 keys the routing on
685
+ // the status. Defaulting either one turns rows 6-9 into rows 1-5.
686
+ return await recoveryRoute(stripe, db, input, lease, "invoice_created", invoiceId, depth);
687
+ }
688
+
689
+ // ---- STEP 3.5: write back the ii_ IMMEDIATELY, not batched -------------
690
+ // The dedup oracle at 3.1 is only sound if this is written before the next
691
+ // call can crash.
692
+ await db.writeback(input.runId, lease, "items_posted", invoiceId,
693
+ { [periodId]: { item_id: item.id } });
694
+ }
695
+
696
+ await db.writeback(input.runId, lease, "items_posted", invoiceId, {});
697
+
698
+ // ---- STEP 4: finalize, ONE call (C-06) ---------------------------------
699
+ await db.leaseRenew(input.runId, lease);
700
+ let finalized: StripeInvoice;
701
+ try {
702
+ finalized = await stripe.invoices.finalize(invoiceId, {
703
+ // Passed DIRECTLY to finalize. Not set at creation (R3), not a second
704
+ // call (R4). With auto_advance:false here Stripe never attempts payment
705
+ // and the run would report success having collected nothing (R1).
706
+ auto_advance: true,
707
+ }, { idempotencyKey: finalizeKey(input.runId) });
708
+ } catch {
709
+ // THIS IS THE MOST DANGEROUS BRANCH IN THE SYSTEM. It must never route to
710
+ // "release and let it retry" — R4's finding. It routes to "check what
711
+ // actually happened".
712
+ //
713
+ // Passing the real status AND the real invoice id is what makes that true.
714
+ // With the defaults, the oracle would look for no stored id, LAYER 2 would
715
+ // come back empty for a customer whose invoice is right there, and section 4.4
716
+ // would take row 1 and RELEASE a run that already has a finalized invoice —
717
+ // clearing billed_run_id and re-billing the member next sweep. T-54 is that
718
+ // regression test.
719
+ return await recoveryRoute(stripe, db, input, lease, "items_posted", invoiceId, depth);
720
+ }
721
+
722
+ const detail = await resolveLineIds(stripe, db, input, invoiceId);
723
+ await db.writeback(input.runId, lease, "billed", invoiceId, detail);
724
+ return { ok: true, exitCode: 0, status: "billed", invoiceId };
725
+ }
726
+
727
+ /**
728
+ * STEP 4.4 — resolve the il_ line ids that section 6 will need.
729
+ * R8 should-fix: a credit note needs an il_, NOT an ii_. The link back to the
730
+ * invoice item lives at line.parent.invoice_item_details.invoice_item, and the
731
+ * invoice-LINE object carries its own (empty) metadata — which is why the
732
+ * Stripe-side diff oracle was unsound (R7 F2) and the DB is the dedup oracle.
733
+ */
734
+ export async function resolveLineIds(
735
+ stripe: PrintStripeLike, db: PrintDbLike, input: RunInput, invoiceId: string,
736
+ ): Promise<Record<string, { line_id: string }>> {
737
+ const detail: Record<string, { line_id: string }> = {};
738
+ let lines: { data: StripeInvoiceLine[] };
739
+ try {
740
+ lines = await stripe.invoices.listLines(invoiceId, { limit: 100 });
741
+ } catch {
742
+ return detail; // best effort; section 6 can re-resolve later
743
+ }
744
+
745
+ const itemToLine = new Map<string, string>();
746
+ for (const l of lines.data) {
747
+ const ii = l.parent?.invoice_item_details?.invoice_item;
748
+ if (ii) itemToLine.set(ii, l.id);
749
+ }
750
+
751
+ for (const periodId of input.periodIds) {
752
+ const p = await db.getPeriod(periodId);
753
+ if (p?.stripe_invoice_item_id) {
754
+ const lineId = itemToLine.get(p.stripe_invoice_item_id);
755
+ if (lineId) detail[periodId] = { line_id: lineId };
756
+ }
757
+ }
758
+ return detail;
759
+ }
760
+
761
+ /** section 4.3 RECOVERY-ROUTE: consult the oracle, then act per section 4.4. */
762
+ export async function recoveryRoute(
763
+ stripe: PrintStripeLike, db: PrintDbLike, input: RunInput, lease: string,
764
+ runStatus = "claimed", storedInvoiceId: string | null = null, depth = 0,
765
+ ): Promise<RunOutcome> {
766
+ const oracle = await runOracle(stripe, {
767
+ runId: input.runId,
768
+ customerId: input.customerId,
769
+ storedInvoiceId,
770
+ });
771
+ const action = decideRecoveryAction(runStatus, storedInvoiceId, oracle);
772
+ return await applyRecoveryAction(stripe, db, input, lease, action, oracle, depth);
773
+ }
774
+
775
+ /**
776
+ * `depth` bounds re-entry into the item/finalize loop WITHIN A SINGLE INVOCATION.
777
+ *
778
+ * Without it, a persistently failing POST /v1/invoiceitems recurses forever:
779
+ * item fails -> recoveryRoute -> oracle says the draft is still there ->
780
+ * resume_items -> item fails -> ... This is not the production retry path. Each
781
+ * section 5.2 recovery sweep is a SEPARATE invocation five minutes later, and that is
782
+ * where a genuine retry belongs (rows 4/9/15, "retry next sweep"); attempt_count
783
+ * and the lease are what bound it across invocations. Re-entering in-process
784
+ * would also spin against Stripe with no backoff.
785
+ */
786
+ const MAX_RESUME_DEPTH = 1;
787
+
788
+ export async function applyRecoveryAction(
789
+ stripe: PrintStripeLike, db: PrintDbLike, input: RunInput, lease: string,
790
+ action: RecoveryAction, oracle: OracleResult, depth = 0,
791
+ ): Promise<RunOutcome> {
792
+ const wouldReenter =
793
+ action.kind === "adopt_draft" || action.kind === "resume_items" || action.kind === "refinalize";
794
+ if (wouldReenter && depth >= MAX_RESUME_DEPTH) {
795
+ return { ok: true, exitCode: 0, status: "retry_next_sweep" };
796
+ }
797
+
798
+ switch (action.kind) {
799
+ case "release_run":
800
+ // The ONLY automatic path that clears billed_run_id (row 1).
801
+ await db.releaseRun(input.runId, lease,
802
+ "no Stripe object exists: List Invoices by customer returned no match for this run",
803
+ true);
804
+ return { ok: true, exitCode: 0, status: "released" };
805
+
806
+ case "hold":
807
+ await db.hold(input.runId, lease, action.reason);
808
+ return { ok: false, exitCode: 1, status: "held", detail: action.reason };
809
+
810
+ case "retry":
811
+ // Transient. Leave it; the next sweep picks it up by lease age.
812
+ return { ok: true, exitCode: 0, status: "retry_next_sweep" };
813
+
814
+ case "adopt_draft": {
815
+ const inv = (oracle as { invoice: StripeInvoice }).invoice;
816
+ await db.writeback(input.runId, lease, "invoice_created", inv.id, {});
817
+ return await postItemsAndFinalize(stripe, db, input, lease, inv.id, depth + 1);
818
+ }
819
+
820
+ case "resume_items": {
821
+ const inv = (oracle as { invoice: StripeInvoice }).invoice;
822
+ return await postItemsAndFinalize(stripe, db, input, lease, inv.id, depth + 1);
823
+ }
824
+
825
+ case "refinalize": {
826
+ const inv = (oracle as { invoice: StripeInvoice }).invoice;
827
+ return await postItemsAndFinalize(stripe, db, input, lease, inv.id, depth + 1);
828
+ }
829
+
830
+ case "adopt_finalized": {
831
+ const inv = (oracle as { invoice: StripeInvoice }).invoice;
832
+ const detail = await resolveLineIds(stripe, db, input, inv.id);
833
+ await db.writeback(input.runId, lease, "billed", inv.id, detail);
834
+ if (action.paid) await db.paymentStatus(inv.id, "paid");
835
+ return { ok: true, exitCode: 0, status: "billed", invoiceId: inv.id };
836
+ }
837
+
838
+ case "noop":
839
+ return { ok: true, exitCode: 0, status: "noop" };
840
+ }
841
+ }
842
+
843
+ // -------------------------------------------------- section 5 — the recovery sweep --
844
+
845
+ export interface RecoverDeps {
846
+ stripe: PrintStripeLike;
847
+ db: PrintDbLike;
848
+ expectedAccountId: string;
849
+ expectedLivemode: boolean;
850
+ /** Resolves the per-run detail the run machinery needs to resume. */
851
+ loadRunInput(run: RunRow): Promise<RunInput>;
852
+ }
853
+
854
+ /**
855
+ * section 5.2. Selects abandoned runs through private.print_billing_recovery_select
856
+ * — a FUNCTION, and that is a fix (v18/B12-2): printed bare, the statement raises
857
+ * 42501 for the actor that actually runs it, because M-08 grants service_role
858
+ * SELECT only and `for update skip locked` needs UPDATE as well. Recovery could
859
+ * not select a single run.
860
+ */
861
+ export async function runRecoverySweep(deps: RecoverDeps, limit = 50): Promise<RunOutcome[]> {
862
+ const pre = await preflightAccount(deps.stripe, deps.expectedAccountId, deps.expectedLivemode);
863
+ if (!pre.ok) return [{ ok: false, exitCode: 1, status: "aborted_preflight", detail: pre.detail }];
864
+
865
+ const runs = await deps.db.recoverySelect(limit);
866
+ const out: RunOutcome[] = [];
867
+
868
+ for (const run of runs) {
869
+ // Acquire the lease. If it returns no row the run was picked up by someone
870
+ // else between the select and the acquire: skip it SILENTLY. Do not treat
871
+ // 0 rows as an error, and do not proceed without a token — that is round 7
872
+ // finding 1's failure shape.
873
+ const lease = await deps.db.leaseAcquire(run.id);
874
+ if (!lease) {
875
+ out.push({ ok: true, exitCode: 0, status: "skipped_not_acquired" });
876
+ continue;
877
+ }
878
+
879
+ const input = await deps.loadRunInput(run);
880
+ const oracle = await runOracle(deps.stripe, {
881
+ runId: run.id,
882
+ customerId: run.stripe_customer_id,
883
+ storedInvoiceId: run.stripe_invoice_id,
884
+ });
885
+ const action = decideRecoveryAction(run.status, run.stripe_invoice_id, oracle);
886
+ out.push(await applyRecoveryAction(
887
+ deps.stripe, deps.db, input, lease.lease_token, action, oracle));
888
+ }
889
+
890
+ return out;
891
+ }