@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.
@@ -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 Operator = {
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: Operator): Promise<BookingAgreementEmailResult>;
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: Operator): Promise<BookingAgreementEmailResult>;
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, '&amp;')
@@ -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({ type: 'Email', contactId, subject: opts.subject, html }),
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
+ }
@@ -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
  /**
@@ -41,7 +41,8 @@ export function parseTstzRange(range) {
41
41
  return null;
42
42
  return { startISO: s.toISOString(), endISO: e.toISOString() };
43
43
  }
44
- function formatWhen(startISO, endISO) {
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 = formatWhen(startISO, endISO);
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 ${formatWhen(doorAccess.validFromUtc, doorAccess.validToUtc)}</p>`
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 &mdash; 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 {};