@simplelayer/graniteer-core 0.3.14 → 0.3.16

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,650 @@
1
+ // Core-side half of the self-serve Commons (tier-3) "signed, unpaid" release
2
+ // policy decided 2026-10-02. gc-connect #16 owns the other half: sending the
3
+ // agreement, the staff Slack ping when it's SENT, the fresh payment link in
4
+ // the signed email, the daily reminder, and the cron that calls
5
+ // cancelUnpaidSignedBooking on a schedule. Nothing in this file sends an
6
+ // email or a reminder, and nothing here talks to BoldSign's API directly.
7
+ //
8
+ // Re-invocation (partial cancels resume on the next call):
9
+ // - stripe-webhook.ts `checkout.session.expired` (policy-eligible tier-3)
10
+ // - gc-connect hourly poller (see `shouldIncludeAgreementInCommonsSignedUnpaidGcPoll`)
11
+ //
12
+ // Policy (full text in the PR body):
13
+ // 1. Staff Slack ping when the agreement is sent -- gc-connect.
14
+ // 2. Fresh payment link in the signed email, then a daily reminder --
15
+ // gc-connect. Same no-double-charge rule as everywhere else in this
16
+ // repo: never create a new session once the old one is complete/paid.
17
+ // 3. 48h after the contract was SENT (not signed -- see "WHEN WAS IT
18
+ // SENT" below) with no payment: cancel the booking, revoke our
19
+ // booking_agreements row, release the date, unwind credit/coupon,
20
+ // busCancel, and surface it to staff. THIS function does the booking
21
+ // side of that; the customer-facing cancellation email is gc-connect's
22
+ // job (this function returns contactEmail/contactName so it can send
23
+ // one, but never sends one itself).
24
+ // 4. Dry-run: this function's own `dryRun` option. gc-connect reads
25
+ // COMMONS_SIGNED_PAYMENT_LINK_DRY_RUN (an env var in gc-connect, not
26
+ // read here) and passes `dryRun: true` through when it's set.
27
+ // 5. bookingHoldReclaim.ts's hold-extension cap uses the same
28
+ // COMMONS_SIGNED_UNPAID_CANCEL_AFTER_MS / isSignedUnpaidCancelDue this
29
+ // file exports, so the two paths can never disagree about the deadline.
30
+ // 6. stripe-webhook.ts's checkout.session.expired guard calls THIS
31
+ // function once the 48h window has passed, rather than duplicating the
32
+ // unwind inline -- "the 48h job does the cancellation" is then literally
33
+ // true regardless of whether a cron or a stray webhook event triggers it.
34
+ //
35
+ // WHEN WAS THE CONTRACT "SENT"? booking_agreements.created_at -- the row is
36
+ // created by send-booking-agreement (gc-connect) at send time, for both the
37
+ // self-serve path (create-booking.ts's internal invoke) and the staff-send
38
+ // path (admin-send-commons-agreement.ts). Confirmed by inspecting both call
39
+ // sites and admin-send-commons-agreement.ts's own stuck-row recovery logic,
40
+ // which already measures `Date.now() - Date.parse(existingAgreement.
41
+ // created_at)` for exactly this reason. No new column, no migration: this is
42
+ // an EXISTING timestamp gc-connect's own send-booking-agreement already
43
+ // writes, read here (and documented here) as the source of truth for "sent".
44
+ // Deliberately NOT completed_at: an agreement that is sent but never signed
45
+ // is at least as overdue as one that's signed-but-unpaid, and anchoring to
46
+ // completed_at would give an unresponsive signer an indefinite extension on
47
+ // top of the 24h hold create-booking.ts already grants them.
48
+ //
49
+ // IDEMPOTENT AND SAFE TO CALL REPEATEDLY, from a cron, a webhook, or by hand:
50
+ // every check (tier-3, agreement completed, 48h elapsed, Stripe unpaid,
51
+ // booking still pending) is re-verified from scratch on every call, with no
52
+ // assumption that the caller already confirmed any of it. A second call
53
+ // after a successful cancellation (or after someone else's payment lands in
54
+ // the gap) is a safe no-op, not a double-unwind or a cancelled-after-paid bug.
55
+ import { logOps } from './ops.js';
56
+ import { sendSlackAlert, OPS_ALERTS_CHANNEL_ID } from './slackAlert.js';
57
+ import { parseTstzRange } from './bookingEffects.js';
58
+ /**
59
+ * 48 hours, per Kyle's decision. Anchored to booking_agreements.created_at
60
+ * (send time), NOT completed_at (sign time) -- see the file header.
61
+ */
62
+ export const COMMONS_SIGNED_UNPAID_CANCEL_AFTER_MS = 48 * 60 * 60 * 1000;
63
+ /**
64
+ * Pure: has the cancel-after window elapsed since `sentAtIso`, relative to
65
+ * `nowMs`? Shared by bookingHoldReclaim.ts (hold-extension cap) and
66
+ * stripe-webhook.ts (completed-tier-3-agreement guard) so neither can drift
67
+ * from this file's constant or get the date math slightly wrong twice.
68
+ * Null-safe and never throws: a missing/unparseable `sentAtIso` reads as
69
+ * "not due" (fails toward NOT cancelling on bad data), never as "infinitely
70
+ * overdue".
71
+ */
72
+ export function isSignedUnpaidCancelDue(sentAtIso, nowMs) {
73
+ if (!sentAtIso)
74
+ return false;
75
+ const sentMs = Date.parse(sentAtIso);
76
+ if (!Number.isFinite(sentMs))
77
+ return false;
78
+ return nowMs - sentMs >= COMMONS_SIGNED_UNPAID_CANCEL_AFTER_MS;
79
+ }
80
+ /** Unix ms when the signed-unpaid cancel window ends (sent + 48h). Null if `sentAtIso` is missing/unparseable. */
81
+ export function signedUnpaidDeadlineMs(sentAtIso) {
82
+ if (!sentAtIso)
83
+ return null;
84
+ const sentMs = Date.parse(sentAtIso);
85
+ if (!Number.isFinite(sentMs))
86
+ return null;
87
+ return sentMs + COMMONS_SIGNED_UNPAID_CANCEL_AFTER_MS;
88
+ }
89
+ /** Human deadline for customer email copy (`expires_at_human`), Pacific-local. */
90
+ export function formatSignedUnpaidDeadlineHuman(sentAtIso) {
91
+ const atMs = signedUnpaidDeadlineMs(sentAtIso);
92
+ if (atMs === null)
93
+ return null;
94
+ const formatted = new Intl.DateTimeFormat('en-US', {
95
+ timeZone: 'America/Los_Angeles',
96
+ weekday: 'short', month: 'short', day: 'numeric',
97
+ hour: 'numeric', minute: '2-digit', hour12: true,
98
+ }).format(new Date(atMs)).replace(/[\u202F\u00A0]/g, ' ');
99
+ return `${formatted} PT`;
100
+ }
101
+ /** Deadline anchor gc-connect #16 and customer emails share with `isSignedUnpaidCancelDue`. */
102
+ export function signedUnpaidDeadline(sentAtIso) {
103
+ const atMs = signedUnpaidDeadlineMs(sentAtIso);
104
+ return {
105
+ atMs,
106
+ atIso: atMs === null ? null : new Date(atMs).toISOString(),
107
+ expires_at_human: formatSignedUnpaidDeadlineHuman(sentAtIso),
108
+ };
109
+ }
110
+ /** Dry-run unless COMMONS_SIGNED_PAYMENT_LINK_DRY_RUN is exactly `"false"`. */
111
+ export function readCommonsSignedPaymentLinkDryRun(env = Deno.env) {
112
+ return env.get('COMMONS_SIGNED_PAYMENT_LINK_DRY_RUN') !== 'false';
113
+ }
114
+ /**
115
+ * Self-serve tier-3 agreements are sent by create-booking/reschedule with no
116
+ * staff actor. Staff Commons deposit agreements set sent_by_* on send-booking-agreement.
117
+ */
118
+ export function isCommonsSelfServeTier3Agreement(ctx) {
119
+ const uid = ctx?.sent_by_user_id?.trim();
120
+ const email = ctx?.sent_by_email?.trim();
121
+ return !uid && !email;
122
+ }
123
+ /**
124
+ * Tier-3 signed-unpaid automation applies only when:
125
+ * - the agreement is from the self-serve tier-3 flow (no sent_by_*), and
126
+ * - it was SENT (`created_at`) on/after COMMONS_SIGNED_PAYMENT_LINK_ENABLED_AFTER.
127
+ * When the cutoff env is unset, nobody is eligible (same contract as gc-connect).
128
+ */
129
+ function commonsSignedPaymentLinkCutoffMs(env) {
130
+ const cutoffRaw = env.get('COMMONS_SIGNED_PAYMENT_LINK_ENABLED_AFTER')?.trim();
131
+ if (!cutoffRaw)
132
+ return null;
133
+ const cutMs = Date.parse(cutoffRaw);
134
+ return Number.isFinite(cutMs) ? cutMs : null;
135
+ }
136
+ export function isCommonsSignedUnpaidPolicyEligible(sentAtIso, agreementCtx, env = Deno.env) {
137
+ if (!isCommonsSelfServeTier3Agreement(agreementCtx ?? {}))
138
+ return false;
139
+ const cutMs = commonsSignedPaymentLinkCutoffMs(env);
140
+ if (cutMs === null)
141
+ return false;
142
+ if (!sentAtIso)
143
+ return false;
144
+ const sentMs = Date.parse(sentAtIso);
145
+ if (!Number.isFinite(sentMs))
146
+ return false;
147
+ return sentMs >= cutMs;
148
+ }
149
+ /**
150
+ * BoldSign /document/revoke only works for sent-but-unsigned envelopes. A
151
+ * fully signed document returns 4xx — gc-connect must skip the API call and
152
+ * only void the local row (see cancelUnpaidSignedBooking).
153
+ */
154
+ export function shouldRevokeBoldSignDocumentOnUnpaidCancel(agreementStatus) {
155
+ return agreementStatus !== 'completed';
156
+ }
157
+ export const COMMONS_SIGNED_UNPAID_CANCEL_STEP_MAX_ATTEMPTS = 5;
158
+ /** gc-connect poller: still retry unwind for revoked rows sent within this window. */
159
+ export const COMMONS_SIGNED_UNPAID_GC_REVOKED_RESUME_LOOKBACK_MS = 14 * 24 * 60 * 60 * 1000;
160
+ /**
161
+ * gc-connect's hourly poller normally selects tier-3 `booking_agreements` with
162
+ * status `completed`. After a crash mid-cancel the row may already be `revoked`
163
+ * while unwind markers are missing — include those for a bounded lookback.
164
+ */
165
+ export function shouldIncludeAgreementInCommonsSignedUnpaidGcPoll(row, nowMs) {
166
+ if (row.status === 'completed')
167
+ return true;
168
+ if (row.status !== 'revoked')
169
+ return false;
170
+ if (!row.created_at)
171
+ return false;
172
+ const sentMs = Date.parse(row.created_at);
173
+ if (!Number.isFinite(sentMs))
174
+ return false;
175
+ return nowMs - sentMs <= COMMONS_SIGNED_UNPAID_GC_REVOKED_RESUME_LOOKBACK_MS;
176
+ }
177
+ const CANCEL_DRY_RUN_LOG = 'commons_signed_unpaid_cancel_dry_run';
178
+ const CANCEL_STEP_CHECKOUT_SESSION_EXPIRED = 'commons_signed_unpaid_cancel_step_checkout_session_expired';
179
+ const CANCEL_STEP_STRIPE_PAYMENT_RECHECKED = 'commons_signed_unpaid_cancel_step_stripe_payment_rechecked';
180
+ const CANCEL_STEP_AGREEMENT_REVOKED = 'commons_signed_unpaid_cancel_step_agreement_revoked';
181
+ const CANCEL_STEP_BOOKING_EXPIRED = 'commons_signed_unpaid_cancel_step_booking_expired';
182
+ const CANCEL_STEP_CREDIT_UNWIND = 'commons_signed_unpaid_cancel_step_credit_unwind';
183
+ const CANCEL_STEP_COUPON_REVERSE = 'commons_signed_unpaid_cancel_step_coupon_reverse';
184
+ const CANCEL_STEP_BUS_CANCEL = 'commons_signed_unpaid_cancel_step_bus_cancel';
185
+ const CANCEL_STEP_STAFF_NOTIFIED = 'commons_signed_unpaid_hold_released';
186
+ async function checkStripePaymentSucceeded(stripe, sessionId) {
187
+ if (!sessionId) {
188
+ return { succeeded: false, failed: false, reason: 'no stripe_session_id on this booking' };
189
+ }
190
+ try {
191
+ const session = await stripe.checkout.sessions.retrieve(sessionId, { expand: ['payment_intent'] });
192
+ const sessionPaid = session.status === 'complete' &&
193
+ (session.payment_status === 'paid' || session.payment_status === 'no_payment_required');
194
+ const piStatus = typeof session.payment_intent === 'object' && session.payment_intent
195
+ ? session.payment_intent.status ?? null
196
+ : null;
197
+ const piSucceeded = piStatus === 'succeeded';
198
+ if (sessionPaid || piSucceeded) {
199
+ return {
200
+ succeeded: true,
201
+ failed: false,
202
+ reason: `stripe session ${sessionId} is paid (status=${session.status ?? 'n/a'}, payment_status=${session.payment_status ?? 'n/a'}, payment_intent_status=${piStatus ?? 'n/a'})`,
203
+ };
204
+ }
205
+ return {
206
+ succeeded: false,
207
+ failed: false,
208
+ reason: `stripe session ${sessionId} not paid (status=${session.status ?? 'n/a'}, payment_status=${session.payment_status ?? 'n/a'})`,
209
+ };
210
+ }
211
+ catch (e) {
212
+ return { succeeded: false, failed: true, reason: `stripe check failed: ${e instanceof Error ? e.message : String(e)}` };
213
+ }
214
+ }
215
+ export async function cancelUnpaidSignedBooking(opts, deps) {
216
+ const dryRun = opts.dryRun === true;
217
+ const bookingId = opts.bookingId;
218
+ const nowMs = deps.now ? deps.now() : Date.now();
219
+ const fail = (reason) => ({ ok: false, dryRun, action: 'check_failed', bookingId, reason });
220
+ const { data: bookingData, error: bErr } = await deps.supabase
221
+ .from('bookings')
222
+ .select('id,status,contact_email,contact_name,stripe_session_id,during,rooms(slug)')
223
+ .eq('id', bookingId)
224
+ .maybeSingle();
225
+ if (bErr)
226
+ return fail(`booking_lookup_failed: ${bErr.message}`);
227
+ if (!bookingData)
228
+ return fail('booking_not_found');
229
+ const booking = bookingData;
230
+ const { data: agreementData, error: aErr } = await deps.supabase
231
+ .from('booking_agreements')
232
+ .select('id,status,created_at,sent_by_user_id,sent_by_email')
233
+ .eq('booking_id', bookingId)
234
+ .eq('tier', 3)
235
+ .order('created_at', { ascending: false })
236
+ .limit(1)
237
+ .maybeSingle();
238
+ if (aErr)
239
+ return fail(`agreement_lookup_failed: ${aErr.message}`);
240
+ const agreement = agreementData;
241
+ if (!agreement) {
242
+ return {
243
+ ok: true, dryRun, action: 'not_eligible', bookingId,
244
+ reason: 'no tier-3 booking_agreements row for this booking',
245
+ };
246
+ }
247
+ const agreementRow = agreement;
248
+ async function cancelFullyDone() {
249
+ const { data, error } = await deps.supabase
250
+ .from('ops_events')
251
+ .select('id')
252
+ .eq('booking_id', bookingId)
253
+ .eq('kind', CANCEL_STEP_STAFF_NOTIFIED)
254
+ .limit(1)
255
+ .maybeSingle();
256
+ if (error)
257
+ return false;
258
+ return !!data;
259
+ }
260
+ if (await cancelFullyDone()) {
261
+ return {
262
+ ok: true, dryRun, action: 'already_cancelled', bookingId,
263
+ reason: 'cancellation already completed (hold released)',
264
+ agreementId: agreementRow.id, sentAt: agreementRow.created_at,
265
+ boldSignRevokeRecommended: shouldRevokeBoldSignDocumentOnUnpaidCancel(agreementRow.status),
266
+ };
267
+ }
268
+ if (agreementRow.status !== 'completed' && agreementRow.status !== 'revoked') {
269
+ return {
270
+ ok: true, dryRun, action: 'not_eligible', bookingId,
271
+ reason: `latest tier-3 agreement status is "${agreement.status}", not "completed"`,
272
+ agreementId: agreement.id, sentAt: agreement.created_at,
273
+ boldSignRevokeRecommended: shouldRevokeBoldSignDocumentOnUnpaidCancel(agreement.status),
274
+ };
275
+ }
276
+ const agreementCtx = {
277
+ sent_by_user_id: agreement.sent_by_user_id,
278
+ sent_by_email: agreement.sent_by_email,
279
+ };
280
+ if (!isCommonsSignedUnpaidPolicyEligible(agreement.created_at, agreementCtx)) {
281
+ const staffSent = !isCommonsSelfServeTier3Agreement(agreementCtx);
282
+ return {
283
+ ok: true, dryRun, action: 'not_eligible', bookingId,
284
+ reason: staffSent
285
+ ? 'staff-sent tier-3 agreement (not self-serve signed-unpaid policy)'
286
+ : 'agreement sent before COMMONS_SIGNED_PAYMENT_LINK_ENABLED_AFTER (pre-cutoff; no cancel)',
287
+ agreementId: agreement.id, sentAt: agreement.created_at,
288
+ boldSignRevokeRecommended: shouldRevokeBoldSignDocumentOnUnpaidCancel(agreement.status),
289
+ };
290
+ }
291
+ const boldSignRevokeRecommended = shouldRevokeBoldSignDocumentOnUnpaidCancel(agreement.status);
292
+ const cancelStepsDoneThisRun = new Set();
293
+ const stepFailuresThisRun = new Map();
294
+ async function cancelStepDone(kind) {
295
+ if (cancelStepsDoneThisRun.has(kind))
296
+ return true;
297
+ const { data, error } = await deps.supabase
298
+ .from('ops_events')
299
+ .select('id')
300
+ .eq('booking_id', bookingId)
301
+ .eq('kind', kind)
302
+ .limit(1)
303
+ .maybeSingle();
304
+ if (error)
305
+ return false;
306
+ if (data)
307
+ cancelStepsDoneThisRun.add(kind);
308
+ return !!data;
309
+ }
310
+ const unwindStepSpecs = [
311
+ { done: CANCEL_STEP_CHECKOUT_SESSION_EXPIRED, failed: `${CANCEL_STEP_CHECKOUT_SESSION_EXPIRED}_failed`, label: 'checkout session expire' },
312
+ { done: CANCEL_STEP_STRIPE_PAYMENT_RECHECKED, failed: `${CANCEL_STEP_STRIPE_PAYMENT_RECHECKED}_failed`, label: 'stripe payment recheck' },
313
+ { done: CANCEL_STEP_AGREEMENT_REVOKED, failed: `${CANCEL_STEP_AGREEMENT_REVOKED}_failed`, label: 'agreement revoke' },
314
+ { done: CANCEL_STEP_BOOKING_EXPIRED, failed: `${CANCEL_STEP_BOOKING_EXPIRED}_failed`, label: 'booking expire' },
315
+ { done: CANCEL_STEP_CREDIT_UNWIND, failed: `${CANCEL_STEP_CREDIT_UNWIND}_failed`, label: 'credit unwind' },
316
+ { done: CANCEL_STEP_COUPON_REVERSE, failed: `${CANCEL_STEP_COUPON_REVERSE}_failed`, label: 'coupon reverse' },
317
+ { done: CANCEL_STEP_BUS_CANCEL, failed: `${CANCEL_STEP_BUS_CANCEL}_failed`, label: 'bus cancel' },
318
+ ];
319
+ async function hasPartialCancelProgress() {
320
+ for (const spec of unwindStepSpecs) {
321
+ if (await cancelStepDone(spec.done))
322
+ return true;
323
+ }
324
+ return agreementRow.status === 'revoked' || booking.status === 'expired';
325
+ }
326
+ const resumableAfterPartialCancel = await hasPartialCancelProgress();
327
+ if (booking.status !== 'pending' && !resumableAfterPartialCancel) {
328
+ const action = booking.status === 'paid' || booking.status === 'deposit_paid' ? 'already_paid' : 'already_cancelled';
329
+ return {
330
+ ok: true, dryRun, action, bookingId, reason: `booking.status is "${booking.status}"`,
331
+ agreementId: agreement.id, sentAt: agreement.created_at, boldSignRevokeRecommended,
332
+ };
333
+ }
334
+ if (!isSignedUnpaidCancelDue(agreement.created_at, nowMs)) {
335
+ return {
336
+ ok: true, dryRun, action: 'not_yet_due', bookingId,
337
+ reason: 'the 48h-since-sent window has not elapsed yet',
338
+ agreementId: agreement.id, sentAt: agreement.created_at, boldSignRevokeRecommended,
339
+ };
340
+ }
341
+ async function stepFailureCount(failureKind) {
342
+ const local = stepFailuresThisRun.get(failureKind) ?? 0;
343
+ const { count, error } = await deps.supabase
344
+ .from('ops_events')
345
+ .select('id', { count: 'exact', head: true })
346
+ .eq('booking_id', bookingId)
347
+ .eq('kind', failureKind);
348
+ if (error)
349
+ return local;
350
+ return local + (count ?? 0);
351
+ }
352
+ async function recordCancelStep(kind, detail = {}) {
353
+ cancelStepsDoneThisRun.add(kind);
354
+ await logOps(deps.supabase, kind, detail, {
355
+ severity: 'info',
356
+ bookingId,
357
+ dedupeKey: `${kind}:${bookingId}`,
358
+ }).catch(() => { });
359
+ }
360
+ async function recordStepFailure(failureKind, detail) {
361
+ stepFailuresThisRun.set(failureKind, (stepFailuresThisRun.get(failureKind) ?? 0) + 1);
362
+ await logOps(deps.supabase, failureKind, detail, {
363
+ severity: 'warning',
364
+ bookingId,
365
+ }).catch(() => { });
366
+ }
367
+ async function unwindStepSatisfied(doneKind, failureKind) {
368
+ if (await cancelStepDone(doneKind))
369
+ return true;
370
+ return (await stepFailureCount(failureKind)) >= COMMONS_SIGNED_UNPAID_CANCEL_STEP_MAX_ATTEMPTS;
371
+ }
372
+ async function unwindStepsCompleteOrExhausted() {
373
+ for (const spec of unwindStepSpecs) {
374
+ if (!(await unwindStepSatisfied(spec.done, spec.failed)))
375
+ return false;
376
+ }
377
+ return true;
378
+ }
379
+ async function listIncompleteUnwindStepLabels() {
380
+ const incomplete = [];
381
+ for (const spec of unwindStepSpecs) {
382
+ if (!(await cancelStepDone(spec.done)))
383
+ incomplete.push(spec.label);
384
+ }
385
+ return incomplete;
386
+ }
387
+ if (dryRun) {
388
+ if (await cancelFullyDone()) {
389
+ return {
390
+ ok: true, dryRun: true, action: 'already_cancelled', bookingId,
391
+ reason: 'dry_run: cancellation already completed (no customer email)',
392
+ agreementId: agreement.id, sentAt: agreement.created_at, boldSignRevokeRecommended,
393
+ };
394
+ }
395
+ await logOps(deps.supabase, CANCEL_DRY_RUN_LOG, {
396
+ would_expire_checkout_session: !!booking.stripe_session_id,
397
+ would_recheck_stripe_payment: !!booking.stripe_session_id,
398
+ would_revoke_local_agreement: true,
399
+ would_release_booking_date: booking.status === 'pending',
400
+ would_unwind_credit: true,
401
+ would_reverse_coupon_if_any: true,
402
+ would_bus_cancel: true,
403
+ would_notify_staff: true,
404
+ agreement_id: agreement.id,
405
+ agreement_sent_at: agreement.created_at,
406
+ }, {
407
+ severity: 'info',
408
+ bookingId,
409
+ dedupeKey: `${CANCEL_DRY_RUN_LOG}:${bookingId}`,
410
+ }).catch(() => { });
411
+ return {
412
+ ok: true, dryRun: true, action: 'cancelled', bookingId,
413
+ reason: 'dry_run: would cancel self-serve tier-3 signed-unpaid booking (no Stripe expire, no state change, no customer email)',
414
+ agreementId: agreement.id, sentAt: agreement.created_at,
415
+ boldSignRevokeRecommended,
416
+ };
417
+ }
418
+ let paidCheck = await checkStripePaymentSucceeded(deps.stripe, booking.stripe_session_id);
419
+ if (paidCheck.failed)
420
+ return fail(paidCheck.reason);
421
+ if (paidCheck.succeeded) {
422
+ return {
423
+ ok: true, dryRun: false, action: 'already_paid', bookingId, reason: paidCheck.reason,
424
+ agreementId: agreement.id, sentAt: agreement.created_at, boldSignRevokeRecommended,
425
+ };
426
+ }
427
+ if (!(await cancelStepDone(CANCEL_STEP_CHECKOUT_SESSION_EXPIRED))) {
428
+ const checkoutFailures = await stepFailureCount(`${CANCEL_STEP_CHECKOUT_SESSION_EXPIRED}_failed`);
429
+ if (checkoutFailures < COMMONS_SIGNED_UNPAID_CANCEL_STEP_MAX_ATTEMPTS) {
430
+ const sessionId = booking.stripe_session_id;
431
+ const expireFn = deps.stripe.checkout.sessions.expire;
432
+ if (sessionId && expireFn) {
433
+ try {
434
+ const session = await deps.stripe.checkout.sessions.retrieve(sessionId, { expand: ['payment_intent'] });
435
+ if (session.status === 'open') {
436
+ await expireFn(sessionId);
437
+ }
438
+ await recordCancelStep(CANCEL_STEP_CHECKOUT_SESSION_EXPIRED, { session_id: sessionId });
439
+ }
440
+ catch (e) {
441
+ await recordStepFailure(`${CANCEL_STEP_CHECKOUT_SESSION_EXPIRED}_failed`, {
442
+ session_id: sessionId,
443
+ message: e instanceof Error ? e.message : String(e),
444
+ attempt: checkoutFailures + 1,
445
+ });
446
+ }
447
+ }
448
+ else {
449
+ await recordCancelStep(CANCEL_STEP_CHECKOUT_SESSION_EXPIRED, { skipped: 'no_open_session' });
450
+ }
451
+ }
452
+ }
453
+ if (!(await cancelStepDone(CANCEL_STEP_STRIPE_PAYMENT_RECHECKED))) {
454
+ paidCheck = await checkStripePaymentSucceeded(deps.stripe, booking.stripe_session_id);
455
+ if (paidCheck.failed)
456
+ return fail(paidCheck.reason);
457
+ if (paidCheck.succeeded) {
458
+ return {
459
+ ok: true, dryRun: false, action: 'already_paid', bookingId, reason: paidCheck.reason,
460
+ agreementId: agreement.id, sentAt: agreement.created_at, boldSignRevokeRecommended,
461
+ };
462
+ }
463
+ await recordCancelStep(CANCEL_STEP_STRIPE_PAYMENT_RECHECKED);
464
+ }
465
+ if (!(await cancelStepDone(CANCEL_STEP_AGREEMENT_REVOKED))) {
466
+ if (agreement.status === 'revoked') {
467
+ await recordCancelStep(CANCEL_STEP_AGREEMENT_REVOKED, {
468
+ already_revoked: true,
469
+ boldsign_revoke_skipped: !boldSignRevokeRecommended,
470
+ });
471
+ }
472
+ else {
473
+ const failures = await stepFailureCount(`${CANCEL_STEP_AGREEMENT_REVOKED}_failed`);
474
+ if (failures < COMMONS_SIGNED_UNPAID_CANCEL_STEP_MAX_ATTEMPTS) {
475
+ const { error: revokeErr } = await deps.supabase
476
+ .from('booking_agreements')
477
+ .update({ status: 'revoked' })
478
+ .eq('id', agreement.id)
479
+ .eq('status', 'completed');
480
+ if (revokeErr) {
481
+ await recordStepFailure(`${CANCEL_STEP_AGREEMENT_REVOKED}_failed`, {
482
+ agreement_id: agreement.id,
483
+ message: revokeErr.message,
484
+ attempt: failures + 1,
485
+ });
486
+ }
487
+ else {
488
+ await recordCancelStep(CANCEL_STEP_AGREEMENT_REVOKED, {
489
+ boldsign_revoke_skipped: !boldSignRevokeRecommended,
490
+ });
491
+ }
492
+ }
493
+ }
494
+ }
495
+ if (!(await cancelStepDone(CANCEL_STEP_BOOKING_EXPIRED))) {
496
+ if (booking.status === 'pending') {
497
+ const { data: cas, error: casErr } = await deps.supabase
498
+ .from('bookings')
499
+ .update({ status: 'expired' })
500
+ .eq('id', bookingId)
501
+ .eq('status', 'pending')
502
+ .select('id')
503
+ .maybeSingle();
504
+ if (casErr)
505
+ return fail(`status_update_failed: ${casErr.message}`);
506
+ if (!cas) {
507
+ const { data: refreshed, error: refErr } = await deps.supabase
508
+ .from('bookings')
509
+ .select('status')
510
+ .eq('id', bookingId)
511
+ .maybeSingle();
512
+ if (refErr)
513
+ return fail(`status_recheck_failed: ${refErr.message}`);
514
+ const refreshedStatus = refreshed?.status;
515
+ if (refreshedStatus !== 'expired') {
516
+ return {
517
+ ok: true, dryRun: false, action: 'already_cancelled', bookingId,
518
+ reason: 'booking.status changed concurrently', agreementId: agreement.id, sentAt: agreement.created_at,
519
+ boldSignRevokeRecommended,
520
+ };
521
+ }
522
+ }
523
+ }
524
+ await recordCancelStep(CANCEL_STEP_BOOKING_EXPIRED, { resumed: booking.status !== 'pending' });
525
+ }
526
+ if (!(await cancelStepDone(CANCEL_STEP_CREDIT_UNWIND))) {
527
+ const failures = await stepFailureCount(`${CANCEL_STEP_CREDIT_UNWIND}_failed`);
528
+ if (failures < COMMONS_SIGNED_UNPAID_CANCEL_STEP_MAX_ATTEMPTS) {
529
+ try {
530
+ const { error: unwErr } = await deps.supabase.rpc('booking_credit_unwind', {
531
+ p_booking_id: bookingId,
532
+ p_reason: 'commons_signed_unpaid_cancelled',
533
+ });
534
+ if (unwErr)
535
+ throw unwErr;
536
+ await recordCancelStep(CANCEL_STEP_CREDIT_UNWIND);
537
+ }
538
+ catch (e) {
539
+ await recordStepFailure(`${CANCEL_STEP_CREDIT_UNWIND}_failed`, {
540
+ message: String(e),
541
+ attempt: failures + 1,
542
+ });
543
+ }
544
+ }
545
+ }
546
+ if (!(await cancelStepDone(CANCEL_STEP_COUPON_REVERSE))) {
547
+ const failures = await stepFailureCount(`${CANCEL_STEP_COUPON_REVERSE}_failed`);
548
+ if (failures < COMMONS_SIGNED_UNPAID_CANCEL_STEP_MAX_ATTEMPTS) {
549
+ try {
550
+ const { data: redRow } = await deps.supabase
551
+ .from('coupon_redemptions')
552
+ .select('id,status')
553
+ .eq('applied_to_type', 'booking')
554
+ .eq('applied_to_id', bookingId)
555
+ .maybeSingle();
556
+ if (redRow && redRow.status !== 'reversed') {
557
+ const { error: cvErr } = await deps.supabase.rpc('coupon_reverse', {
558
+ p_redemption_id: redRow.id,
559
+ p_reason: 'commons_signed_unpaid_cancelled',
560
+ p_actor_email: deps.systemActorEmail,
561
+ });
562
+ if (cvErr)
563
+ throw cvErr;
564
+ }
565
+ await recordCancelStep(CANCEL_STEP_COUPON_REVERSE, { had_redemption: !!redRow });
566
+ }
567
+ catch (e) {
568
+ await recordStepFailure(`${CANCEL_STEP_COUPON_REVERSE}_failed`, {
569
+ message: String(e),
570
+ attempt: failures + 1,
571
+ });
572
+ }
573
+ }
574
+ }
575
+ if (!(await cancelStepDone(CANCEL_STEP_BUS_CANCEL))) {
576
+ const failures = await stepFailureCount(`${CANCEL_STEP_BUS_CANCEL}_failed`);
577
+ if (failures < COMMONS_SIGNED_UNPAID_CANCEL_STEP_MAX_ATTEMPTS) {
578
+ try {
579
+ const range = booking.during ? parseTstzRange(booking.during) : null;
580
+ const slug = booking.rooms?.slug ?? null;
581
+ if (range && slug) {
582
+ await deps.busCancel({ bookingId, roomKey: slug, startUtc: range.startISO, endUtc: range.endISO }, deps.supabase);
583
+ }
584
+ await recordCancelStep(CANCEL_STEP_BUS_CANCEL);
585
+ }
586
+ catch (e) {
587
+ await recordStepFailure(`${CANCEL_STEP_BUS_CANCEL}_failed`, {
588
+ message: String(e),
589
+ attempt: failures + 1,
590
+ });
591
+ }
592
+ }
593
+ }
594
+ const readyForStaffNotify = await unwindStepsCompleteOrExhausted();
595
+ if (!readyForStaffNotify) {
596
+ return {
597
+ ok: true, dryRun: false, action: 'cancel_in_progress', bookingId,
598
+ reason: 'cancel in progress: unwind steps incomplete — will resume on next run',
599
+ agreementId: agreement.id, sentAt: agreement.created_at,
600
+ boldSignRevokeRecommended,
601
+ };
602
+ }
603
+ if (!(await cancelStepDone(CANCEL_STEP_STAFF_NOTIFIED))) {
604
+ const unwoundLabels = [];
605
+ for (const spec of unwindStepSpecs) {
606
+ if (await cancelStepDone(spec.done))
607
+ unwoundLabels.push(spec.label);
608
+ }
609
+ const incompleteLabels = await listIncompleteUnwindStepLabels();
610
+ const unwoundText = unwoundLabels.length > 0
611
+ ? `Completed steps: ${unwoundLabels.join(', ')}.`
612
+ : 'No cancel steps recorded yet — check ops_events.';
613
+ const failedText = incompleteLabels.length > 0
614
+ ? ` Steps that failed after ${COMMONS_SIGNED_UNPAID_CANCEL_STEP_MAX_ATTEMPTS} attempts: ${incompleteLabels.join(', ')}.`
615
+ : '';
616
+ const alarm = await logOps(deps.supabase, CANCEL_STEP_STAFF_NOTIFIED, {
617
+ agreement_id: agreement.id,
618
+ agreement_sent_at: agreement.created_at,
619
+ cancel_after_ms: COMMONS_SIGNED_UNPAID_CANCEL_AFTER_MS,
620
+ boldsign_revoke_skipped: !boldSignRevokeRecommended,
621
+ completed_steps: unwoundLabels,
622
+ failed_steps_after_max_attempts: incompleteLabels,
623
+ }, {
624
+ severity: 'error',
625
+ bookingId,
626
+ dedupeKey: `${CANCEL_STEP_STAFF_NOTIFIED}:${bookingId}`,
627
+ });
628
+ if (!alarm.ok) {
629
+ console.error('[commonsSignedUnpaidCancellation] staff notify ops_event failed to persist', alarm.error);
630
+ }
631
+ else {
632
+ cancelStepsDoneThisRun.add(CANCEL_STEP_STAFF_NOTIFIED);
633
+ }
634
+ await sendSlackAlert(OPS_ALERTS_CHANNEL_ID, `:rotating_light: Commons booking ${bookingId} (${booking.contact_name ?? 'customer'}) cancelled for non-payment after the payment deadline. `
635
+ + `Agreement voided in our system only — the signed PDF remains on BoldSign. `
636
+ + unwoundText + failedText).catch(() => { });
637
+ }
638
+ const notifyDone = await cancelStepDone(CANCEL_STEP_STAFF_NOTIFIED);
639
+ return {
640
+ ok: true, dryRun: false, action: 'cancelled', bookingId,
641
+ reason: notifyDone
642
+ ? 'cancelled: tier-3 agreement completed, unpaid, 48h-since-sent window elapsed, Stripe confirmed unpaid'
643
+ : 'cancelled: unwind finished but staff notify marker missing — retry safe',
644
+ agreementId: agreement.id, sentAt: agreement.created_at,
645
+ contactEmail: notifyDone ? booking.contact_email : null,
646
+ contactName: notifyDone ? booking.contact_name : null,
647
+ bookingDuring: notifyDone ? booking.during : null,
648
+ boldSignRevokeRecommended,
649
+ };
650
+ }