@simplelayer/graniteer-core 0.3.15 → 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.
- package/dist/bookingAgreementEmail.d.ts +34 -3
- package/dist/bookingAgreementEmail.js +100 -1
- package/dist/bookingEffects.d.ts +2 -0
- package/dist/bookingEffects.js +4 -3
- package/dist/checkoutSessionParams.d.ts +33 -0
- package/dist/checkoutSessionParams.js +71 -0
- package/dist/commonsSignedUnpaidCancellation.d.ts +154 -0
- package/dist/commonsSignedUnpaidCancellation.js +650 -0
- package/dist/functions/stripe-webhook.js +102 -0
- package/dist/supabaseTestFakes.js +7 -1
- package/package.json +5 -1
|
@@ -1,23 +1,54 @@
|
|
|
1
1
|
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
2
2
|
type SupabaseLike = SupabaseClient<any, 'public', any>;
|
|
3
3
|
export type BookingAgreementEmailResult = 'sent' | 'skipped' | 'failed_retryable' | 'failed_permanent';
|
|
4
|
-
type
|
|
4
|
+
export type BookingAgreementEmailOperator = {
|
|
5
5
|
name: string;
|
|
6
6
|
shortName: string;
|
|
7
7
|
supportEmail: string;
|
|
8
8
|
};
|
|
9
|
+
/** Options for `sendBookingPaymentReminderEmail`. */
|
|
10
|
+
export type BookingPaymentReminderEmailOptions = {
|
|
11
|
+
email: string;
|
|
12
|
+
name?: string | null;
|
|
13
|
+
roomName?: string | null;
|
|
14
|
+
bookingDuring?: string | null;
|
|
15
|
+
/** Agreement send time (`booking_agreements.created_at`) — anchors the deadline line. */
|
|
16
|
+
sentAt: string;
|
|
17
|
+
checkoutUrl?: string | null;
|
|
18
|
+
/** Staff inboxes to CC on the reminder (explicit; never inferred from env here). */
|
|
19
|
+
staffCcEmails?: readonly string[];
|
|
20
|
+
};
|
|
21
|
+
/** Options for `sendBookingCancelledUnpaidEmail` / idempotent wrapper. */
|
|
22
|
+
export type BookingCancelledUnpaidEmailOptions = {
|
|
23
|
+
bookingId: string;
|
|
24
|
+
email: string;
|
|
25
|
+
name?: string | null;
|
|
26
|
+
roomName?: string | null;
|
|
27
|
+
bookingDuring?: string | null;
|
|
28
|
+
};
|
|
9
29
|
/** Agreement signed — the customer may now pay for the held slot. */
|
|
10
30
|
export declare function sendBookingAgreementSignedEmail(supabase: SupabaseLike, { email, name, roomName, checkoutUrl }: {
|
|
11
31
|
email: string;
|
|
12
32
|
name?: string | null;
|
|
13
33
|
roomName?: string | null;
|
|
14
34
|
checkoutUrl?: string | null;
|
|
15
|
-
}, operator:
|
|
35
|
+
}, operator: BookingAgreementEmailOperator): Promise<BookingAgreementEmailResult>;
|
|
36
|
+
/** Daily (or cron) reminder — signed tier-3 Commons booking, payment still due. */
|
|
37
|
+
export declare function sendBookingPaymentReminderEmail(supabase: SupabaseLike, opts: BookingPaymentReminderEmailOptions, operator: BookingAgreementEmailOperator): Promise<BookingAgreementEmailResult>;
|
|
38
|
+
/** Cancelled for non-payment after the signed-unpaid deadline. */
|
|
39
|
+
export declare function sendBookingCancelledUnpaidEmail(supabase: SupabaseLike, opts: Omit<BookingCancelledUnpaidEmailOptions, 'bookingId'> & {
|
|
40
|
+
bookingDuring?: string | null;
|
|
41
|
+
}, operator: BookingAgreementEmailOperator): Promise<BookingAgreementEmailResult>;
|
|
16
42
|
/** Agreement declined/expired — the held slot was released. */
|
|
17
43
|
export declare function sendBookingAgreementNotCompletedEmail(supabase: SupabaseLike, { email, name, roomName, reason }: {
|
|
18
44
|
email: string;
|
|
19
45
|
name?: string | null;
|
|
20
46
|
roomName?: string | null;
|
|
21
47
|
reason: 'declined' | 'expired';
|
|
22
|
-
}, operator:
|
|
48
|
+
}, operator: BookingAgreementEmailOperator): Promise<BookingAgreementEmailResult>;
|
|
49
|
+
/**
|
|
50
|
+
* Idempotent customer cancel email — safe when both webhook and cron call cancel.
|
|
51
|
+
* Returns `already_sent` when an earlier path logged `booking_cancelled_unpaid_email_sent`.
|
|
52
|
+
*/
|
|
53
|
+
export declare function sendBookingCancelledUnpaidEmailOnce(supabase: SupabaseLike, opts: BookingCancelledUnpaidEmailOptions, operator: BookingAgreementEmailOperator): Promise<BookingAgreementEmailResult | 'already_sent'>;
|
|
23
54
|
export {};
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
import { logOps } from './ops.js';
|
|
2
|
+
import { formatBookingWhenPacific, parseTstzRange } from './bookingEffects.js';
|
|
3
|
+
import { signedUnpaidDeadline } from './commonsSignedUnpaidCancellation.js';
|
|
4
|
+
const BOOKING_CANCELLED_UNPAID_EMAIL_SENT = 'booking_cancelled_unpaid_email_sent';
|
|
2
5
|
function esc(v) {
|
|
3
6
|
return String(v ?? '')
|
|
4
7
|
.replace(/&/g, '&')
|
|
@@ -61,10 +64,17 @@ async function sendViaGhl(supabase, opts) {
|
|
|
61
64
|
<h2 style="margin:0 0 12px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:22px">${esc(opts.subject)}</h2>
|
|
62
65
|
${opts.body(esc(greetingName))}
|
|
63
66
|
</td></tr></table></td></tr></table></div>`;
|
|
67
|
+
const cc = (opts.staffCcEmails ?? []).map((e) => e.trim()).filter(Boolean);
|
|
64
68
|
const emailRes = await fetch(`${GHL_BASE}/conversations/messages`, {
|
|
65
69
|
method: 'POST', headers,
|
|
66
70
|
signal: AbortSignal.timeout(8000),
|
|
67
|
-
body: JSON.stringify({
|
|
71
|
+
body: JSON.stringify({
|
|
72
|
+
type: 'Email',
|
|
73
|
+
contactId,
|
|
74
|
+
subject: opts.subject,
|
|
75
|
+
html,
|
|
76
|
+
...(cc.length > 0 ? { cc } : {}),
|
|
77
|
+
}),
|
|
68
78
|
});
|
|
69
79
|
if (!emailRes.ok)
|
|
70
80
|
throw new Error(`ghl_email_${emailRes.status}: ${await emailRes.text()}`);
|
|
@@ -78,6 +88,14 @@ ${opts.body(esc(greetingName))}
|
|
|
78
88
|
}
|
|
79
89
|
}
|
|
80
90
|
const p = (t) => `<p style="margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:14px;line-height:22px">${t}</p>`;
|
|
91
|
+
function bookingDuringHuman(during) {
|
|
92
|
+
if (!during)
|
|
93
|
+
return null;
|
|
94
|
+
const range = parseTstzRange(during);
|
|
95
|
+
if (!range)
|
|
96
|
+
return null;
|
|
97
|
+
return formatBookingWhenPacific(range.startISO, range.endISO);
|
|
98
|
+
}
|
|
81
99
|
/** Agreement signed — the customer may now pay for the held slot. */
|
|
82
100
|
export function sendBookingAgreementSignedEmail(supabase, { email, name, roomName, checkoutUrl }, operator) {
|
|
83
101
|
const room = (roomName || '').trim();
|
|
@@ -96,6 +114,58 @@ export function sendBookingAgreementSignedEmail(supabase, { email, name, roomNam
|
|
|
96
114
|
].join(''),
|
|
97
115
|
});
|
|
98
116
|
}
|
|
117
|
+
/** Daily (or cron) reminder — signed tier-3 Commons booking, payment still due. */
|
|
118
|
+
export function sendBookingPaymentReminderEmail(supabase, opts, operator) {
|
|
119
|
+
const { email, name, roomName, bookingDuring, sentAt, checkoutUrl, staffCcEmails } = opts;
|
|
120
|
+
const room = (roomName || '').trim();
|
|
121
|
+
const deadline = signedUnpaidDeadline(sentAt);
|
|
122
|
+
const duringHuman = bookingDuringHuman(bookingDuring);
|
|
123
|
+
const subject = `Payment due for your ${operator.shortName} room booking`;
|
|
124
|
+
return sendViaGhl(supabase, {
|
|
125
|
+
email, name, subject, opsPrefix: 'booking_payment_reminder_email', operator, staffCcEmails,
|
|
126
|
+
body: (greeting) => {
|
|
127
|
+
const lines = [
|
|
128
|
+
p(`Hi ${greeting},`),
|
|
129
|
+
p(`Your room use agreement is signed, but we have not received payment yet.`),
|
|
130
|
+
];
|
|
131
|
+
if (duringHuman) {
|
|
132
|
+
lines.push(p(`Booking: ${esc(duringHuman)}${room ? ` (${esc(room)})` : ''}.`));
|
|
133
|
+
}
|
|
134
|
+
if (deadline.expires_at_human) {
|
|
135
|
+
lines.push(p(`Pay by <strong>${esc(deadline.expires_at_human)}</strong> or we will release the date.`));
|
|
136
|
+
}
|
|
137
|
+
if (checkoutUrl) {
|
|
138
|
+
lines.push(p(`<a href="${esc(checkoutUrl)}" style="color:#C98A5E">Complete your payment →</a>`));
|
|
139
|
+
}
|
|
140
|
+
else {
|
|
141
|
+
lines.push(p(`Reply to this email if you need a payment link.`));
|
|
142
|
+
}
|
|
143
|
+
lines.push(p(`This booking is not confirmed until payment is complete.`), p(`Questions? Reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`), p(`— The ${operator.name} team`));
|
|
144
|
+
return lines.join('');
|
|
145
|
+
},
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
/** Cancelled for non-payment after the signed-unpaid deadline. */
|
|
149
|
+
export function sendBookingCancelledUnpaidEmail(supabase, opts, operator) {
|
|
150
|
+
const { email, name, roomName, bookingDuring } = opts;
|
|
151
|
+
const room = (roomName || '').trim();
|
|
152
|
+
const duringHuman = bookingDuringHuman(bookingDuring);
|
|
153
|
+
const subject = `Your ${operator.shortName} booking was cancelled — payment not received`;
|
|
154
|
+
return sendViaGhl(supabase, {
|
|
155
|
+
email, name, subject, opsPrefix: 'booking_cancelled_unpaid_email', operator,
|
|
156
|
+
body: (greeting) => {
|
|
157
|
+
const lines = [
|
|
158
|
+
p(`Hi ${greeting},`),
|
|
159
|
+
p(`We cancelled your hold${room ? ` on ${esc(room)}` : ''} because payment was not received by the deadline.`),
|
|
160
|
+
];
|
|
161
|
+
if (duringHuman) {
|
|
162
|
+
lines.push(p(`The date was: ${esc(duringHuman)}.`));
|
|
163
|
+
}
|
|
164
|
+
lines.push(p(`The room use agreement is void and you have not been charged.`), p(`If you still need the space, you can book again.`), p(`Questions? Reach us at <a href="mailto:${operator.supportEmail}" style="color:#C98A5E">${operator.supportEmail}</a>.`), p(`— The ${operator.name} team`));
|
|
165
|
+
return lines.join('');
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
}
|
|
99
169
|
/** Agreement declined/expired — the held slot was released. */
|
|
100
170
|
export function sendBookingAgreementNotCompletedEmail(supabase, { email, name, roomName, reason }, operator) {
|
|
101
171
|
const room = (roomName || '').trim();
|
|
@@ -114,3 +184,32 @@ export function sendBookingAgreementNotCompletedEmail(supabase, { email, name, r
|
|
|
114
184
|
].join(''),
|
|
115
185
|
});
|
|
116
186
|
}
|
|
187
|
+
/**
|
|
188
|
+
* Idempotent customer cancel email — safe when both webhook and cron call cancel.
|
|
189
|
+
* Returns `already_sent` when an earlier path logged `booking_cancelled_unpaid_email_sent`.
|
|
190
|
+
*/
|
|
191
|
+
export async function sendBookingCancelledUnpaidEmailOnce(supabase, opts, operator) {
|
|
192
|
+
const dedupeKey = `${BOOKING_CANCELLED_UNPAID_EMAIL_SENT}:${opts.bookingId}`;
|
|
193
|
+
const { data: prior, error: priorErr } = await supabase
|
|
194
|
+
.from('ops_events')
|
|
195
|
+
.select('id')
|
|
196
|
+
.eq('booking_id', opts.bookingId)
|
|
197
|
+
.eq('kind', BOOKING_CANCELLED_UNPAID_EMAIL_SENT)
|
|
198
|
+
.limit(1)
|
|
199
|
+
.maybeSingle();
|
|
200
|
+
if (priorErr) {
|
|
201
|
+
await logOps(supabase, 'booking_cancelled_unpaid_email_failed', { booking_id: opts.bookingId, message: priorErr.message, phase: 'dedupe_lookup' }, { severity: 'warning', bookingId: opts.bookingId }).catch(() => { });
|
|
202
|
+
return 'failed_retryable';
|
|
203
|
+
}
|
|
204
|
+
if (prior)
|
|
205
|
+
return 'already_sent';
|
|
206
|
+
const result = await sendBookingCancelledUnpaidEmail(supabase, opts, operator);
|
|
207
|
+
if (result === 'sent') {
|
|
208
|
+
await logOps(supabase, BOOKING_CANCELLED_UNPAID_EMAIL_SENT, { email: opts.email }, {
|
|
209
|
+
severity: 'info',
|
|
210
|
+
bookingId: opts.bookingId,
|
|
211
|
+
dedupeKey,
|
|
212
|
+
}).catch(() => { });
|
|
213
|
+
}
|
|
214
|
+
return result;
|
|
215
|
+
}
|
package/dist/bookingEffects.d.ts
CHANGED
|
@@ -51,6 +51,8 @@ export declare function parseTstzRange(range: string): {
|
|
|
51
51
|
startISO: string;
|
|
52
52
|
endISO: string;
|
|
53
53
|
} | null;
|
|
54
|
+
/** Pacific-local human range for booking emails and ops copy (e.g. "Mon, Oct 5 · 9:00–1:00 PM PT"). */
|
|
55
|
+
export declare function formatBookingWhenPacific(startISO: string, endISO: string): string;
|
|
54
56
|
export declare function formatDollars(cents: number | null | undefined): string;
|
|
55
57
|
export declare function googleCalendarUrl(startISO: string, endISO: string, title: string, details: string, location: string): string;
|
|
56
58
|
/**
|
package/dist/bookingEffects.js
CHANGED
|
@@ -41,7 +41,8 @@ export function parseTstzRange(range) {
|
|
|
41
41
|
return null;
|
|
42
42
|
return { startISO: s.toISOString(), endISO: e.toISOString() };
|
|
43
43
|
}
|
|
44
|
-
|
|
44
|
+
/** Pacific-local human range for booking emails and ops copy (e.g. "Mon, Oct 5 · 9:00–1:00 PM PT"). */
|
|
45
|
+
export function formatBookingWhenPacific(startISO, endISO) {
|
|
45
46
|
const s = new Date(startISO);
|
|
46
47
|
const e = new Date(endISO);
|
|
47
48
|
const day = new Intl.DateTimeFormat('en-US', {
|
|
@@ -156,7 +157,7 @@ export async function notifyGhl(supabase, booking, config, doorAccess) {
|
|
|
156
157
|
const firstName = parts[0] || 'Guest';
|
|
157
158
|
const lastName = parts.slice(1).join(' ') || '';
|
|
158
159
|
const roomName = booking.rooms.name;
|
|
159
|
-
const whenStr =
|
|
160
|
+
const whenStr = formatBookingWhenPacific(startISO, endISO);
|
|
160
161
|
const amountStr = formatDollars(booking.charged_amount_cents ?? booking.list_amount_cents);
|
|
161
162
|
const gcalTitle = `${roomName} — ${operator.name}`;
|
|
162
163
|
const gcalDetails = `Your booking at ${operator.name}.\nRoom: ${roomName}\nWhen: ${whenStr}\nBooking ID: ${booking.id}`;
|
|
@@ -268,7 +269,7 @@ export async function notifyGhl(supabase, booking, config, doorAccess) {
|
|
|
268
269
|
let doorSection = '';
|
|
269
270
|
if (doorAccess?.pin) {
|
|
270
271
|
const activeLine = (doorAccess.validFromUtc && doorAccess.validToUtc)
|
|
271
|
-
? `<p style='margin:6px 0 0 0;color:#5f6c5d;font-size:13px'>Active ${
|
|
272
|
+
? `<p style='margin:6px 0 0 0;color:#5f6c5d;font-size:13px'>Active ${formatBookingWhenPacific(doorAccess.validFromUtc, doorAccess.validToUtc)}</p>`
|
|
272
273
|
: '';
|
|
273
274
|
doorSection = `<div style='margin:20px 0;padding:16px;border:1px solid #E5E1D8;border-radius:8px'><h3 style='margin:0 0 8px 0;color:#22263B;font-family:Inter,Arial,sans-serif;font-size:16px'>Door access</h3><p style='margin:0 0 8px 0;font-family:ui-monospace,Menlo,Consolas,monospace;font-size:22px;letter-spacing:4px;color:#22263B'><strong>${doorAccess.pin}</strong></p><p style='margin:0;color:#22263B;font-size:14px'>Your PIN works at the Commons Hub door — the building's main entrance. The other entrances are badge and mobile-unlock only.</p>${activeLine}</div>`;
|
|
274
275
|
}
|
|
@@ -8,6 +8,39 @@ import type Stripe from 'stripe';
|
|
|
8
8
|
* cents amount, so the product is rounded half-up.
|
|
9
9
|
*/
|
|
10
10
|
export declare function computeApplicationFeeCents(baseCents: number, feePercent: number | null | undefined): number;
|
|
11
|
+
/**
|
|
12
|
+
* Clamps a Checkout Session's `expires_at` (Unix seconds) to the booking's own
|
|
13
|
+
* hold window, within Stripe's allowed [30m, 24h] range.
|
|
14
|
+
*
|
|
15
|
+
* - `holdExpiresAtIso` present and parseable: the session expires at
|
|
16
|
+
* `min(hold_expires_at, now + 24h - 60s)` -- it can never outlive the hold,
|
|
17
|
+
* and never exceeds Stripe's ceiling.
|
|
18
|
+
* - `holdExpiresAtIso` absent/unparseable: treated as "no tighter bound than
|
|
19
|
+
* Stripe's own ceiling" -- `now + 24h - 60s` -- never as unbounded.
|
|
20
|
+
* - Either way, floored at `now + 30m` (Stripe's own minimum -- it rejects a
|
|
21
|
+
* session shorter than that outright). This means a hold shorter than 30m
|
|
22
|
+
* gets a session that OUTLIVES its own hold by design: there is no way to
|
|
23
|
+
* ask Stripe for a shorter one. That is the mirror image of the bug this
|
|
24
|
+
* function exists to fix (session dying before the hold, not after), and
|
|
25
|
+
* it is unreachable with every caller in this repo today -- the shortest
|
|
26
|
+
* hold any of them create is 1h (create-booking.ts, reschedule-booking.ts;
|
|
27
|
+
* admin-create-booking.ts uses up to 72h). If a future caller ever wants a
|
|
28
|
+
* sub-30-minute hold, it must independently guard against the session
|
|
29
|
+
* outliving it (e.g. a DB-level re-check at payment-completion time that
|
|
30
|
+
* the slot wasn't reclaimed/double-booked in the gap) -- this function
|
|
31
|
+
* cannot close that gap on its own, Stripe's minimum is a hard floor.
|
|
32
|
+
* - Either way, floored at `now + 30m`: a hold already shorter than that (or
|
|
33
|
+
* already past) still gets a usable, Stripe-legal session rather than a
|
|
34
|
+
* rejected `expires_at`.
|
|
35
|
+
*
|
|
36
|
+
* Pure -- no network, no Date.now() -- so it is exactly reproducible in tests
|
|
37
|
+
* and safe to call from both the booking-creation path (create-booking,
|
|
38
|
+
* reschedule-booking, admin-create-booking) and a reissue path (gc-connect's
|
|
39
|
+
* bookingAgreementWebhook, when the original session has gone stale).
|
|
40
|
+
*/
|
|
41
|
+
export declare function clampCheckoutExpiresAtSeconds(nowMs: number, holdExpiresAtIso: string | null | undefined,
|
|
42
|
+
/** When set (tier-3 agreement send time), also caps at sent + 48h for Kyle's policy. */
|
|
43
|
+
agreementSentAtIso?: string | null): number;
|
|
11
44
|
export declare function buildSubscriptionSessionParams(input: {
|
|
12
45
|
customerId: string;
|
|
13
46
|
lineItem: Stripe.Checkout.SessionCreateParams.LineItem;
|
|
@@ -11,6 +11,7 @@
|
|
|
11
11
|
// ONLY when a tenant supplies both a connected account and a non-zero fee. The
|
|
12
12
|
// platform account's own checkouts pass neither, so they take the untouched
|
|
13
13
|
// pre-Connect path -- an account is never charged an application fee on itself.
|
|
14
|
+
import { COMMONS_SIGNED_UNPAID_CANCEL_AFTER_MS } from './commonsSignedUnpaidCancellation.js';
|
|
14
15
|
/**
|
|
15
16
|
* Application fee in whole cents for a `feePercent` share of `baseCents`.
|
|
16
17
|
*
|
|
@@ -26,6 +27,76 @@ export function computeApplicationFeeCents(baseCents, feePercent) {
|
|
|
26
27
|
return 0;
|
|
27
28
|
return Math.round((baseCents * feePercent) / 100);
|
|
28
29
|
}
|
|
30
|
+
// Stripe allows a Checkout Session's `expires_at` to be set between 30
|
|
31
|
+
// minutes and 24 hours from creation (not "whatever we want"). A booking's own
|
|
32
|
+
// `hold_expires_at` can be anywhere outside that range -- shorter than 30
|
|
33
|
+
// minutes (about to lapse) or, for a tier-2/3 BoldSign-gated booking, a full
|
|
34
|
+
// 24 hours out. Root cause of the Commons lost-booking bug (Sep 14/30): every
|
|
35
|
+
// booking session was hardcoded to `now + 1h` regardless of the booking's
|
|
36
|
+
// real hold, so a Commons (tier 3) booking's 24h hold outlived its own
|
|
37
|
+
// Checkout Session by ~23 hours -- the session (and the "pay now" link built
|
|
38
|
+
// from it) went dead long before the hold did, and `checkout.session.expired`
|
|
39
|
+
// then flipped the booking to `expired` even though the hold -- and often the
|
|
40
|
+
// signed BoldSign agreement -- was still very much alive.
|
|
41
|
+
const STRIPE_SESSION_MAX_SECONDS = 24 * 60 * 60;
|
|
42
|
+
const STRIPE_SESSION_MIN_SECONDS = 30 * 60;
|
|
43
|
+
// Shaves a little off the 24h ceiling so a session created at t=0 can never
|
|
44
|
+
// race Stripe's own clock and land exactly on (or just past) the boundary.
|
|
45
|
+
const STRIPE_SESSION_MAX_SAFETY_SECONDS = 60;
|
|
46
|
+
/**
|
|
47
|
+
* Clamps a Checkout Session's `expires_at` (Unix seconds) to the booking's own
|
|
48
|
+
* hold window, within Stripe's allowed [30m, 24h] range.
|
|
49
|
+
*
|
|
50
|
+
* - `holdExpiresAtIso` present and parseable: the session expires at
|
|
51
|
+
* `min(hold_expires_at, now + 24h - 60s)` -- it can never outlive the hold,
|
|
52
|
+
* and never exceeds Stripe's ceiling.
|
|
53
|
+
* - `holdExpiresAtIso` absent/unparseable: treated as "no tighter bound than
|
|
54
|
+
* Stripe's own ceiling" -- `now + 24h - 60s` -- never as unbounded.
|
|
55
|
+
* - Either way, floored at `now + 30m` (Stripe's own minimum -- it rejects a
|
|
56
|
+
* session shorter than that outright). This means a hold shorter than 30m
|
|
57
|
+
* gets a session that OUTLIVES its own hold by design: there is no way to
|
|
58
|
+
* ask Stripe for a shorter one. That is the mirror image of the bug this
|
|
59
|
+
* function exists to fix (session dying before the hold, not after), and
|
|
60
|
+
* it is unreachable with every caller in this repo today -- the shortest
|
|
61
|
+
* hold any of them create is 1h (create-booking.ts, reschedule-booking.ts;
|
|
62
|
+
* admin-create-booking.ts uses up to 72h). If a future caller ever wants a
|
|
63
|
+
* sub-30-minute hold, it must independently guard against the session
|
|
64
|
+
* outliving it (e.g. a DB-level re-check at payment-completion time that
|
|
65
|
+
* the slot wasn't reclaimed/double-booked in the gap) -- this function
|
|
66
|
+
* cannot close that gap on its own, Stripe's minimum is a hard floor.
|
|
67
|
+
* - Either way, floored at `now + 30m`: a hold already shorter than that (or
|
|
68
|
+
* already past) still gets a usable, Stripe-legal session rather than a
|
|
69
|
+
* rejected `expires_at`.
|
|
70
|
+
*
|
|
71
|
+
* Pure -- no network, no Date.now() -- so it is exactly reproducible in tests
|
|
72
|
+
* and safe to call from both the booking-creation path (create-booking,
|
|
73
|
+
* reschedule-booking, admin-create-booking) and a reissue path (gc-connect's
|
|
74
|
+
* bookingAgreementWebhook, when the original session has gone stale).
|
|
75
|
+
*/
|
|
76
|
+
export function clampCheckoutExpiresAtSeconds(nowMs, holdExpiresAtIso,
|
|
77
|
+
/** When set (tier-3 agreement send time), also caps at sent + 48h for Kyle's policy. */
|
|
78
|
+
agreementSentAtIso) {
|
|
79
|
+
const nowSec = Math.floor(nowMs / 1000);
|
|
80
|
+
const maxBoundSec = nowSec + STRIPE_SESSION_MAX_SECONDS - STRIPE_SESSION_MAX_SAFETY_SECONDS;
|
|
81
|
+
const minBoundSec = nowSec + STRIPE_SESSION_MIN_SECONDS;
|
|
82
|
+
let holdSec = null;
|
|
83
|
+
if (holdExpiresAtIso) {
|
|
84
|
+
const parsed = Date.parse(holdExpiresAtIso);
|
|
85
|
+
if (Number.isFinite(parsed))
|
|
86
|
+
holdSec = Math.floor(parsed / 1000);
|
|
87
|
+
}
|
|
88
|
+
let policyCapSec = null;
|
|
89
|
+
if (agreementSentAtIso) {
|
|
90
|
+
const sentMs = Date.parse(agreementSentAtIso);
|
|
91
|
+
if (Number.isFinite(sentMs)) {
|
|
92
|
+
policyCapSec = Math.floor((sentMs + COMMONS_SIGNED_UNPAID_CANCEL_AFTER_MS) / 1000);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
let target = holdSec !== null ? Math.min(holdSec, maxBoundSec) : maxBoundSec;
|
|
96
|
+
if (policyCapSec !== null)
|
|
97
|
+
target = Math.min(target, policyCapSec);
|
|
98
|
+
return Math.max(target, minBoundSec);
|
|
99
|
+
}
|
|
29
100
|
export function buildSubscriptionSessionParams(input) {
|
|
30
101
|
const { applicationFeePercent, connectedAccountId } = input;
|
|
31
102
|
const subscriptionData = applicationFeePercent && connectedAccountId
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import type { SupabaseClient } from '@supabase/supabase-js';
|
|
2
|
+
type SupabaseLike = SupabaseClient<any, any, any>;
|
|
3
|
+
/**
|
|
4
|
+
* 48 hours, per Kyle's decision. Anchored to booking_agreements.created_at
|
|
5
|
+
* (send time), NOT completed_at (sign time) -- see the file header.
|
|
6
|
+
*/
|
|
7
|
+
export declare const COMMONS_SIGNED_UNPAID_CANCEL_AFTER_MS: number;
|
|
8
|
+
/**
|
|
9
|
+
* Pure: has the cancel-after window elapsed since `sentAtIso`, relative to
|
|
10
|
+
* `nowMs`? Shared by bookingHoldReclaim.ts (hold-extension cap) and
|
|
11
|
+
* stripe-webhook.ts (completed-tier-3-agreement guard) so neither can drift
|
|
12
|
+
* from this file's constant or get the date math slightly wrong twice.
|
|
13
|
+
* Null-safe and never throws: a missing/unparseable `sentAtIso` reads as
|
|
14
|
+
* "not due" (fails toward NOT cancelling on bad data), never as "infinitely
|
|
15
|
+
* overdue".
|
|
16
|
+
*/
|
|
17
|
+
export declare function isSignedUnpaidCancelDue(sentAtIso: string | null | undefined, nowMs: number): boolean;
|
|
18
|
+
/** Unix ms when the signed-unpaid cancel window ends (sent + 48h). Null if `sentAtIso` is missing/unparseable. */
|
|
19
|
+
export declare function signedUnpaidDeadlineMs(sentAtIso: string | null | undefined): number | null;
|
|
20
|
+
/** Human deadline for customer email copy (`expires_at_human`), Pacific-local. */
|
|
21
|
+
export declare function formatSignedUnpaidDeadlineHuman(sentAtIso: string | null | undefined): string | null;
|
|
22
|
+
/** Deadline anchor gc-connect #16 and customer emails share with `isSignedUnpaidCancelDue`. */
|
|
23
|
+
export declare function signedUnpaidDeadline(sentAtIso: string | null | undefined): {
|
|
24
|
+
atMs: number | null;
|
|
25
|
+
atIso: string | null;
|
|
26
|
+
expires_at_human: string | null;
|
|
27
|
+
};
|
|
28
|
+
/** Dry-run unless COMMONS_SIGNED_PAYMENT_LINK_DRY_RUN is exactly `"false"`. */
|
|
29
|
+
export declare function readCommonsSignedPaymentLinkDryRun(env?: {
|
|
30
|
+
get: (key: string) => string | undefined;
|
|
31
|
+
}): boolean;
|
|
32
|
+
/** Agreement row fields that distinguish self-serve tier-3 sends from staff sends. */
|
|
33
|
+
export interface CommonsSignedUnpaidAgreementContext {
|
|
34
|
+
sent_by_user_id?: string | null;
|
|
35
|
+
sent_by_email?: string | null;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Self-serve tier-3 agreements are sent by create-booking/reschedule with no
|
|
39
|
+
* staff actor. Staff Commons deposit agreements set sent_by_* on send-booking-agreement.
|
|
40
|
+
*/
|
|
41
|
+
export declare function isCommonsSelfServeTier3Agreement(ctx: CommonsSignedUnpaidAgreementContext | null | undefined): boolean;
|
|
42
|
+
export declare function isCommonsSignedUnpaidPolicyEligible(sentAtIso: string | null | undefined, agreementCtx?: CommonsSignedUnpaidAgreementContext | null, env?: {
|
|
43
|
+
get: (key: string) => string | undefined;
|
|
44
|
+
}): boolean;
|
|
45
|
+
/**
|
|
46
|
+
* BoldSign /document/revoke only works for sent-but-unsigned envelopes. A
|
|
47
|
+
* fully signed document returns 4xx — gc-connect must skip the API call and
|
|
48
|
+
* only void the local row (see cancelUnpaidSignedBooking).
|
|
49
|
+
*/
|
|
50
|
+
export declare function shouldRevokeBoldSignDocumentOnUnpaidCancel(agreementStatus: string): boolean;
|
|
51
|
+
export declare const COMMONS_SIGNED_UNPAID_CANCEL_STEP_MAX_ATTEMPTS = 5;
|
|
52
|
+
/** gc-connect poller: still retry unwind for revoked rows sent within this window. */
|
|
53
|
+
export declare const COMMONS_SIGNED_UNPAID_GC_REVOKED_RESUME_LOOKBACK_MS: number;
|
|
54
|
+
/**
|
|
55
|
+
* gc-connect's hourly poller normally selects tier-3 `booking_agreements` with
|
|
56
|
+
* status `completed`. After a crash mid-cancel the row may already be `revoked`
|
|
57
|
+
* while unwind markers are missing — include those for a bounded lookback.
|
|
58
|
+
*/
|
|
59
|
+
export declare function shouldIncludeAgreementInCommonsSignedUnpaidGcPoll(row: {
|
|
60
|
+
status: string;
|
|
61
|
+
created_at: string | null;
|
|
62
|
+
}, nowMs: number): boolean;
|
|
63
|
+
/**
|
|
64
|
+
* Minimal Stripe surface this needs: retrieve one Checkout Session, with
|
|
65
|
+
* `payment_intent` expanded so a payment that succeeded on the underlying
|
|
66
|
+
* PaymentIntent is detected even in the rare window before Stripe has also
|
|
67
|
+
* marked the session itself `complete`.
|
|
68
|
+
*/
|
|
69
|
+
export interface StripeSessionLookupClient {
|
|
70
|
+
checkout: {
|
|
71
|
+
sessions: {
|
|
72
|
+
retrieve(id: string, params?: {
|
|
73
|
+
expand?: string[];
|
|
74
|
+
}): Promise<{
|
|
75
|
+
status?: string | null;
|
|
76
|
+
payment_status?: string | null;
|
|
77
|
+
payment_intent?: string | {
|
|
78
|
+
status?: string | null;
|
|
79
|
+
} | null;
|
|
80
|
+
}>;
|
|
81
|
+
expire?(id: string): Promise<{
|
|
82
|
+
status?: string | null;
|
|
83
|
+
payment_status?: string | null;
|
|
84
|
+
payment_intent?: string | {
|
|
85
|
+
status?: string | null;
|
|
86
|
+
} | null;
|
|
87
|
+
}>;
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
/** Same shape as busClient.ts's own BusBooking -- redeclared locally so a
|
|
92
|
+
* caller (gc-connect) can satisfy this dependency without importing
|
|
93
|
+
* busClient.ts's full type graph just for this one shape. */
|
|
94
|
+
export interface BusCancelInput {
|
|
95
|
+
bookingId: string;
|
|
96
|
+
roomKey: string;
|
|
97
|
+
startUtc: string;
|
|
98
|
+
endUtc: string;
|
|
99
|
+
}
|
|
100
|
+
export interface CancelUnpaidSignedBookingDeps {
|
|
101
|
+
supabase: SupabaseLike;
|
|
102
|
+
stripe: StripeSessionLookupClient;
|
|
103
|
+
busCancel: (b: BusCancelInput, supabase: SupabaseLike) => Promise<unknown>;
|
|
104
|
+
/** For the coupon_reverse audit trail -- every other coupon_reverse call site in this repo requires a real actor identity. */
|
|
105
|
+
systemActorEmail: string;
|
|
106
|
+
/** Testability seam; defaults to `Date.now`. */
|
|
107
|
+
now?: () => number;
|
|
108
|
+
}
|
|
109
|
+
export type CancelUnpaidSignedBookingAction = 'cancelled' | 'cancel_in_progress' | 'already_cancelled' | 'already_paid' | 'not_eligible' | 'not_yet_due' | 'check_failed';
|
|
110
|
+
export interface CancelUnpaidSignedBookingResult {
|
|
111
|
+
ok: boolean;
|
|
112
|
+
dryRun: boolean;
|
|
113
|
+
action: CancelUnpaidSignedBookingAction;
|
|
114
|
+
bookingId: string;
|
|
115
|
+
reason: string;
|
|
116
|
+
agreementId?: string | null;
|
|
117
|
+
sentAt?: string | null;
|
|
118
|
+
contactEmail?: string | null;
|
|
119
|
+
contactName?: string | null;
|
|
120
|
+
bookingDuring?: string | null;
|
|
121
|
+
/** False when BoldSign revoke must be skipped (signed envelope). */
|
|
122
|
+
boldSignRevokeRecommended?: boolean;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Cancels one self-serve Commons (tier-3) booking that signed its BoldSign
|
|
126
|
+
* agreement but never paid, once COMMONS_SIGNED_UNPAID_CANCEL_AFTER_MS has
|
|
127
|
+
* elapsed since the agreement was SENT (booking_agreements.created_at).
|
|
128
|
+
*
|
|
129
|
+
* Checks Stripe FIRST, every time, regardless of what the local `bookings`
|
|
130
|
+
* row claims -- a `complete`/paid session or a `succeeded` PaymentIntent
|
|
131
|
+
* always wins and this refuses to cancel. `dryRun: true` runs every read and
|
|
132
|
+
* every check exactly as normal and returns what WOULD happen, with no
|
|
133
|
+
* booking mutations: no status change, no RPC call, no busCancel, no Slack
|
|
134
|
+
* alert; logs one deduped ops_event `commons_signed_unpaid_cancel_dry_run`.
|
|
135
|
+
*
|
|
136
|
+
* On an actual cancellation, runs the SAME unwind steps stripe-webhook.ts's
|
|
137
|
+
* checkout.session.expired handler runs for an ordinary expired booking
|
|
138
|
+
* (booking_credit_unwind, coupon_reverse if an unreversed redemption
|
|
139
|
+
* exists, busCancel) plus this policy's two additions: the booking_agreements
|
|
140
|
+
* row is marked 'revoked', and the release is a dedicated, error-severity,
|
|
141
|
+
* deduped ops_event + Slack alert (OPS_ALERTS_CHANNEL_ID) rather than the
|
|
142
|
+
* generic 'payment_failed' one, since staff -- and, via the returned
|
|
143
|
+
* contactEmail/contactName, gc-connect's customer email -- both need to know
|
|
144
|
+
* this specific booking was cancelled for non-payment, not merely that a
|
|
145
|
+
* session expired.
|
|
146
|
+
*/
|
|
147
|
+
/** Stable options object for `cancelUnpaidSignedBooking` (gc-connect cron / webhook). */
|
|
148
|
+
export interface CancelUnpaidSignedBookingOptions {
|
|
149
|
+
bookingId: string;
|
|
150
|
+
/** When `true`, run every check with zero writes. Omit/`false` performs cancel. */
|
|
151
|
+
dryRun?: boolean;
|
|
152
|
+
}
|
|
153
|
+
export declare function cancelUnpaidSignedBooking(opts: CancelUnpaidSignedBookingOptions, deps: CancelUnpaidSignedBookingDeps): Promise<CancelUnpaidSignedBookingResult>;
|
|
154
|
+
export {};
|
|
@@ -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
|
+
}
|
|
@@ -8,6 +8,8 @@ import { logWelcomeSkipped, WELCOME_OK_STATUSES, } from '../membershipWelcome.js
|
|
|
8
8
|
import { sendDunningEmail } from '../dunningEmails.js';
|
|
9
9
|
import { recordReferralFailure, maybeGrantReferralCredit } from '../referralGrant.js';
|
|
10
10
|
import { findBaseItem } from '../membershipSubscriptionItems.js';
|
|
11
|
+
import { cancelUnpaidSignedBooking, isSignedUnpaidCancelDue, isCommonsSignedUnpaidPolicyEligible, readCommonsSignedPaymentLinkDryRun } from '../commonsSignedUnpaidCancellation.js';
|
|
12
|
+
import { sendBookingCancelledUnpaidEmailOnce } from '../bookingAgreementEmail.js';
|
|
11
13
|
export function createStripeWebhookHandler(config) {
|
|
12
14
|
const { systemActorEmail, dayPassPortalRedirectUrl, teamSeatSlug, virtualOfficeSlug, siteConfig, busProvision, busCancel, notifyGhl, createCalendarEvent, handleCommonsDepositSession, sendVirtualOfficeWelcome, sendMembershipWelcome, sendPrivateOfficeWelcome, loadPrivateOfficeBilling, sendTeamSeatWelcome, maybeActivateAgreement, pacificMidnightUtc, maybeConvertTrialGrant, provisionDayPass, cancelDayPass, } = config;
|
|
13
15
|
// No CORS — this is called by Stripe, not the browser.
|
|
@@ -1990,6 +1992,101 @@ export function createStripeWebhookHandler(config) {
|
|
|
1990
1992
|
// reschedule's new booking to 'expired' (~15-20 min) BEFORE Stripe's own
|
|
1991
1993
|
// session expiry fires, so gating on 'pending' alone skipped the unwind.
|
|
1992
1994
|
if (booking && (booking.status === 'pending' || booking.status === 'expired')) {
|
|
1995
|
+
// Commons lost-booking fix: a stale Checkout Session must not
|
|
1996
|
+
// release a tier-3 booking whose BoldSign agreement is already
|
|
1997
|
+
// `completed` unless the self-serve signed-unpaid policy says
|
|
1998
|
+
// cancel (48h after agreement SENT). Staff-sent deposit agreements
|
|
1999
|
+
// are never policy-eligible and stay protected here.
|
|
2000
|
+
let lookupFailed = false;
|
|
2001
|
+
let completedTier3Agreement = false;
|
|
2002
|
+
let tier3AgreementSentAt = null;
|
|
2003
|
+
let agreementCtx = null;
|
|
2004
|
+
try {
|
|
2005
|
+
const { data: agreementRow, error: agreementErr } = await supabase
|
|
2006
|
+
.from('booking_agreements')
|
|
2007
|
+
.select('status,created_at,sent_by_user_id,sent_by_email')
|
|
2008
|
+
.eq('booking_id', booking.id)
|
|
2009
|
+
.eq('tier', 3)
|
|
2010
|
+
.order('created_at', { ascending: false })
|
|
2011
|
+
.limit(1)
|
|
2012
|
+
.maybeSingle();
|
|
2013
|
+
if (agreementErr)
|
|
2014
|
+
throw agreementErr;
|
|
2015
|
+
const row = agreementRow;
|
|
2016
|
+
completedTier3Agreement = row?.status === 'completed';
|
|
2017
|
+
tier3AgreementSentAt = row?.created_at ?? null;
|
|
2018
|
+
agreementCtx = row
|
|
2019
|
+
? { sent_by_user_id: row.sent_by_user_id, sent_by_email: row.sent_by_email }
|
|
2020
|
+
: null;
|
|
2021
|
+
}
|
|
2022
|
+
catch (e) {
|
|
2023
|
+
console.error('[stripe-webhook] checkout-expired tier-3 agreement lookup failed', e);
|
|
2024
|
+
lookupFailed = true;
|
|
2025
|
+
}
|
|
2026
|
+
const policyEligible = isCommonsSignedUnpaidPolicyEligible(tier3AgreementSentAt, agreementCtx);
|
|
2027
|
+
const signedUnpaidCancelDue = completedTier3Agreement && policyEligible &&
|
|
2028
|
+
isSignedUnpaidCancelDue(tier3AgreementSentAt, Date.now());
|
|
2029
|
+
const completedTier3StillProtected = completedTier3Agreement &&
|
|
2030
|
+
(!policyEligible || !signedUnpaidCancelDue);
|
|
2031
|
+
if (lookupFailed) {
|
|
2032
|
+
const alarm = await logOps(supabase, 'checkout_expired_lookup_failed', {
|
|
2033
|
+
event_type: event.type,
|
|
2034
|
+
}, {
|
|
2035
|
+
severity: 'error',
|
|
2036
|
+
bookingId: booking.id,
|
|
2037
|
+
dedupeKey: `checkout_expired_lookup_failed:${booking.id}:${event.id}`,
|
|
2038
|
+
});
|
|
2039
|
+
if (!alarm.ok) {
|
|
2040
|
+
console.error('[stripe-webhook] checkout_expired_lookup_failed ops_event failed to persist', alarm.error);
|
|
2041
|
+
}
|
|
2042
|
+
break;
|
|
2043
|
+
}
|
|
2044
|
+
if (completedTier3StillProtected) {
|
|
2045
|
+
const alarm = await logOps(supabase, 'checkout_expired_hold_live', {
|
|
2046
|
+
event_type: event.type,
|
|
2047
|
+
completed_tier3_agreement: true,
|
|
2048
|
+
}, {
|
|
2049
|
+
severity: 'warning',
|
|
2050
|
+
bookingId: booking.id,
|
|
2051
|
+
dedupeKey: `checkout_expired_hold_live:${booking.id}:${event.id}`,
|
|
2052
|
+
});
|
|
2053
|
+
if (!alarm.ok) {
|
|
2054
|
+
console.error('[stripe-webhook] checkout_expired_hold_live ops_event failed to persist', alarm.error);
|
|
2055
|
+
}
|
|
2056
|
+
break;
|
|
2057
|
+
}
|
|
2058
|
+
if (signedUnpaidCancelDue) {
|
|
2059
|
+
const dryRun = readCommonsSignedPaymentLinkDryRun();
|
|
2060
|
+
const result = await cancelUnpaidSignedBooking({ bookingId: booking.id, dryRun }, { supabase, stripe, busCancel, systemActorEmail });
|
|
2061
|
+
if (!result.ok) {
|
|
2062
|
+
console.error('[stripe-webhook] cancelUnpaidSignedBooking check failed', result.reason);
|
|
2063
|
+
await logOps(supabase, 'checkout_expired_lookup_failed', { event_type: event.type, reason: result.reason }, { severity: 'error', bookingId: booking.id,
|
|
2064
|
+
dedupeKey: `checkout_expired_lookup_failed:${booking.id}:${event.id}` }).catch(() => { });
|
|
2065
|
+
}
|
|
2066
|
+
else if (result.action === 'cancelled' && !result.dryRun && result.contactEmail?.trim()) {
|
|
2067
|
+
try {
|
|
2068
|
+
await sendBookingCancelledUnpaidEmailOnce(supabase, {
|
|
2069
|
+
bookingId: booking.id,
|
|
2070
|
+
email: result.contactEmail.trim(),
|
|
2071
|
+
name: result.contactName,
|
|
2072
|
+
roomName: null,
|
|
2073
|
+
bookingDuring: result.bookingDuring,
|
|
2074
|
+
}, {
|
|
2075
|
+
name: siteConfig.operatorName,
|
|
2076
|
+
shortName: siteConfig.operatorShortName,
|
|
2077
|
+
supportEmail: siteConfig.supportEmail,
|
|
2078
|
+
});
|
|
2079
|
+
}
|
|
2080
|
+
catch (e) {
|
|
2081
|
+
console.error('[stripe-webhook] sendBookingCancelledUnpaidEmailOnce threw', e);
|
|
2082
|
+
await logOps(supabase, 'booking_side_effect_failed', { step: 'sendBookingCancelledUnpaidEmailOnce', message: String(e) }, { severity: 'warning', bookingId: booking.id }).catch(() => { });
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
else if (result.action !== 'cancelled') {
|
|
2086
|
+
console.log('[stripe-webhook] cancelUnpaidSignedBooking no-op', result.action, result.reason);
|
|
2087
|
+
}
|
|
2088
|
+
break;
|
|
2089
|
+
}
|
|
1993
2090
|
if (booking.status === 'pending') {
|
|
1994
2091
|
await supabase.from('bookings').update({ status: 'expired' }).eq('id', booking.id);
|
|
1995
2092
|
}
|
|
@@ -2033,6 +2130,11 @@ export function createStripeWebhookHandler(config) {
|
|
|
2033
2130
|
console.error('[stripe-webhook] coupon_reverse failed', e);
|
|
2034
2131
|
await logOps(supabase, 'coupon_reverse_failed', { message: String(e) }, { severity: 'warning', bookingId: booking.id });
|
|
2035
2132
|
}
|
|
2133
|
+
// Reached only when signedUnpaidCancelDue is false (handled
|
|
2134
|
+
// above, via cancelUnpaidSignedBooking, if true) -- this is
|
|
2135
|
+
// always the GENERIC release (hold genuinely passed, no
|
|
2136
|
+
// tier-3-agreement protection at all), never the signed-unpaid
|
|
2137
|
+
// Commons case.
|
|
2036
2138
|
await logOps(supabase, 'payment_failed', { event_type: event.type }, { severity: 'warning', bookingId: booking.id });
|
|
2037
2139
|
try {
|
|
2038
2140
|
const { data: cancelInfo } = await supabase
|
|
@@ -18,7 +18,13 @@ class FakeQuery {
|
|
|
18
18
|
this.responder = responder;
|
|
19
19
|
this.log = log;
|
|
20
20
|
}
|
|
21
|
-
select(
|
|
21
|
+
// `.update(...).select(...)` must stay op `update`; only a bare chain starts as select.
|
|
22
|
+
select(columns) {
|
|
23
|
+
if (this.rec.op === 'none')
|
|
24
|
+
this.rec.op = 'select';
|
|
25
|
+
this.rec.columns = columns;
|
|
26
|
+
return this;
|
|
27
|
+
}
|
|
22
28
|
insert(payload) { this.rec.op = 'insert'; this.rec.payload = payload; return this; }
|
|
23
29
|
update(payload) { this.rec.op = 'update'; this.rec.payload = payload; return this; }
|
|
24
30
|
delete() { this.rec.op = 'delete'; return this; }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simplelayer/graniteer-core",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.16",
|
|
4
4
|
"description": "Shared platform core for Graniteer",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -117,6 +117,10 @@
|
|
|
117
117
|
"types": "./dist/commonsDepositWebhook.d.ts",
|
|
118
118
|
"default": "./dist/commonsDepositWebhook.js"
|
|
119
119
|
},
|
|
120
|
+
"./commonsSignedUnpaidCancellation": {
|
|
121
|
+
"types": "./dist/commonsSignedUnpaidCancellation.d.ts",
|
|
122
|
+
"default": "./dist/commonsSignedUnpaidCancellation.js"
|
|
123
|
+
},
|
|
120
124
|
"./conductorAdmin": {
|
|
121
125
|
"types": "./dist/conductorAdmin.d.ts",
|
|
122
126
|
"default": "./dist/conductorAdmin.js"
|