@simplelayer/graniteer-core 0.3.18 → 0.3.19-referral.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/functions/admin-create-booking.d.ts +0 -3
  2. package/dist/functions/admin-create-booking.js +2 -15
  3. package/dist/functions/admin-mark-booking-paid.d.ts +1 -6
  4. package/dist/functions/admin-mark-booking-paid.js +3 -27
  5. package/dist/functions/admin-request-trial.js +1 -1
  6. package/dist/functions/booking-availability.d.ts +1 -2
  7. package/dist/functions/booking-availability.js +5 -14
  8. package/dist/functions/create-booking.d.ts +0 -5
  9. package/dist/functions/create-booking.js +4 -22
  10. package/dist/functions/create-subscription-checkout.js +4 -1
  11. package/dist/functions/manage-booking.d.ts +0 -6
  12. package/dist/functions/manage-booking.js +12 -29
  13. package/dist/functions/reschedule-booking.d.ts +0 -5
  14. package/dist/functions/reschedule-booking.js +2 -28
  15. package/dist/functions/space-availability-range.d.ts +1 -2
  16. package/dist/functions/space-availability-range.js +1 -8
  17. package/dist/functions/stripe-webhook.d.ts +0 -4
  18. package/dist/functions/stripe-webhook.js +9 -182
  19. package/dist/functions/sync-gcal-blackouts.js +1 -1
  20. package/dist/gcalSync.d.ts +0 -1
  21. package/dist/gcalSync.js +0 -5
  22. package/dist/pricing.d.ts +2 -10
  23. package/dist/pricing.js +9 -14
  24. package/dist/referralCodeLookup.d.ts +1 -0
  25. package/dist/referralCodeLookup.js +3 -0
  26. package/dist/referralCredits.d.ts +5 -0
  27. package/dist/referralCredits.js +5 -0
  28. package/dist/referralGrant.d.ts +4 -31
  29. package/dist/referralGrant.js +14 -234
  30. package/package.json +2 -26
  31. package/dist/bookingSource.d.ts +0 -2
  32. package/dist/bookingSource.js +0 -11
  33. package/dist/businessHours.d.ts +0 -11
  34. package/dist/businessHours.js +0 -55
  35. package/dist/connectBookingCharge.d.ts +0 -49
  36. package/dist/connectBookingCharge.js +0 -68
  37. package/dist/functions/booking-access-revoke-backstop.d.ts +0 -11
  38. package/dist/functions/booking-access-revoke-backstop.js +0 -121
  39. package/dist/functions/booking-access-revoke-door-state.d.ts +0 -22
  40. package/dist/functions/booking-access-revoke-door-state.js +0 -61
  41. package/dist/functions/booking-access-revoke.d.ts +0 -35
  42. package/dist/functions/booking-access-revoke.js +0 -279
  43. package/dist/gcalBookingEvents.d.ts +0 -59
  44. package/dist/gcalBookingEvents.js +0 -182
  45. package/dist/stripeConnectEvents.d.ts +0 -11
  46. package/dist/stripeConnectEvents.js +0 -37
  47. package/dist/tenant-config.d.ts +0 -8
  48. package/dist/tenant-config.js +0 -24
@@ -1,38 +1,15 @@
1
- // Referral program grant logic + failure recorder.
1
+ // Referral program failure recorder + SUPERSEDED grant entry point.
2
2
  //
3
- // Originally moved verbatim out of stripe-webhook/index.ts so the SAME
4
- // grant logic could be re-invoked on demand by admin-referral-retry (a
5
- // grant_failed referral needs to re-run this exact function, not a second
6
- // hand-written copy of Stripe balance-transaction logic that could drift
7
- // from it over time). Since then (second-model review, 2026-08-24) it has
8
- // picked up real behavioral fixes on top of that extraction -- it is no
9
- // longer byte-identical to the original inline version, and should not be
10
- // described that way again:
11
- // - `fromStatuses` is now a parameter (default ['signed_up'], the
12
- // webhook's original single case) instead of a hardcoded 'signed_up'
13
- // literal, so admin-referral-retry can call this SAME function on a
14
- // grant_failed row directly -- no separate reset-to-signed_up step,
15
- // no window where the row sits in a state nothing recognizes.
16
- // - A failed persist of either side's Stripe transaction id is now a
17
- // hard stop with a loud last_error, not a console.error-and-continue
18
- // (see the two `partialUpdErr` blocks below) -- see "24h idempotency
19
- // key" comment for why this matters.
20
- // The Supabase and Stripe clients are explicit parameters (same convention
21
- // as _shared/membershipWelcome.ts and _shared/bookingEffects.ts) instead of
22
- // closure captures, and console.error tags read [referralGrant] instead of
23
- // [stripe-webhook] since this code now runs from two different callers.
3
+ // maybeGrantReferralCredit is now an immediate no-op. Referral credits are no
4
+ // longer paid at first-invoice-paid under the old terms; gc-io's
5
+ // referral-qualify-daily job pays 50% of the referred member's first-month
6
+ // plan price to each side, 30 days after signup. The export and its signature
7
+ // are kept only because other repos import them from the published package.
8
+ // It never touches Stripe or the database.
24
9
  //
25
- // The two clawback functions (maybeClawbackReferralCredit and
26
- // maybeClawbackReferralCreditForRefundOrDispute) stay in stripe-webhook/
27
- // index.ts -- they're deliberately NOT extracted here. There are two
28
- // different clawback code paths and a clawback_failed row alone doesn't
29
- // say which one failed, so clawback retry is a human decision for now
30
- // (see AdminReferrals.tsx), not an automated one. recordReferralFailure is
31
- // still exported here since both index.ts's clawback functions and this
32
- // file's grant function need it -- index.ts imports it from here rather
33
- // than keeping a second copy.
10
+ // recordReferralFailure is still live: the clawback functions in
11
+ // stripe-webhook.ts use it to mark a referrals row clawback_failed.
34
12
  import { logOps } from './ops.js';
35
- import { computeReferralCredits } from './referralCredits.js';
36
13
  /**
37
14
  * Records a permanent grant/clawback failure on the referrals row itself
38
15
  * (fix #4 from the round-2 review) instead of only console.error/warn --
@@ -62,207 +39,10 @@ export async function recordReferralFailure(supabase, referralId, fromStatus, to
62
39
  await logOps(supabase, 'referral_' + toStatus, { referral_id: referralId, message }, { severity: 'error' }).catch(() => { });
63
40
  }
64
41
  /**
65
- * Referral program Phase 1, step 2 (grant at first-invoice-paid).
66
- *
67
- * Called from the webhook only when the first_invoice_paid_at compare-and-
68
- * swap in the invoice.paid handler actually affected a row (genuinely the
69
- * first real paid invoice for this membership) -- that call passes no
70
- * `fromStatuses` override, so it only ever matches a 'signed_up' row.
71
- *
72
- * admin-referral-retry calls this SAME function with
73
- * `fromStatuses: ['grant_failed']` to retry a previously-failed grant --
74
- * see that function's own header comment for why it gates on the referred
75
- * membership's live status first, and why it does NOT reset the row to
76
- * 'signed_up' before calling this (that reset-then-call shape was tried and
77
- * reverted after a second-model review found it opened a stranded-row
78
- * window and a same-row race between two concurrent retries).
79
- *
80
- * Computes real credit amounts, grants a NEGATIVE Stripe Customer Balance
81
- * Transaction (a credit) on each of the two Stripe customers, and marks the
82
- * referral 'credited'.
83
- *
84
- * Entirely wrapped in try/catch and logs with the referral id on failure --
85
- * a Stripe failure here must never break invoice.paid processing for an
86
- * unrelated membership.
87
- *
88
- * IDEMPOTENT BY DESIGN -- this is also what makes it safe for
89
- * admin-referral-retry to call again on a grant_failed row: before each
90
- * Stripe call it checks whether this referral already has a txn id
91
- * persisted, and each Stripe call carries a fixed idempotency key derived
92
- * from the referral id, so a retry only attempts whichever side didn't
93
- * already complete. Never write a second, separate recovery path -- retry
94
- * by calling this function again.
42
+ * @deprecated SUPERSEDED -- no-op. Crediting is owned by gc-io's
43
+ * referral-qualify-daily job (30 days after signup). Never touches Stripe or
44
+ * the database; signature kept for published-package compatibility.
95
45
  */
96
- export async function maybeGrantReferralCredit(supabase, stripe, referredMembershipId, fromStatuses = ['signed_up']) {
97
- let referralId = null;
98
- // Guard used by every recordReferralFailure call below -- always the
99
- // row's REAL current status as read from the DB just now, never an
100
- // assumption, so the optimistic-concurrency guard inside
101
- // recordReferralFailure actually protects against a concurrent winner.
102
- let currentStatus = 'signed_up';
103
- try {
104
- const { data: rawReferral, error: refErr } = await supabase
105
- .from('referrals')
106
- .select('id,status,referring_membership_id,referred_membership_id,referred_plan_price_cents,is_private_office,' +
107
- 'stripe_balance_txn_id_referrer,stripe_balance_txn_id_referred')
108
- .eq('referred_membership_id', referredMembershipId)
109
- .in('status', fromStatuses)
110
- .maybeSingle();
111
- if (refErr) {
112
- console.error('[referralGrant] referral lookup failed', {
113
- membership_id: referredMembershipId, message: refErr.message,
114
- });
115
- return;
116
- }
117
- if (!rawReferral)
118
- return; // this membership has no referral in a retryable state -- normal case
119
- const typedReferral = rawReferral;
120
- referralId = typedReferral.id;
121
- currentStatus = typedReferral.status;
122
- const { referrerCents, referredCents } = computeReferralCredits(typedReferral.referred_plan_price_cents ?? 0, typedReferral.is_private_office === true);
123
- const { data: parties, error: partiesErr } = await supabase
124
- .from('memberships')
125
- .select('id,stripe_customer_id')
126
- .in('id', [typedReferral.referring_membership_id, typedReferral.referred_membership_id]);
127
- if (partiesErr || !parties) {
128
- console.error('[referralGrant] referral credit membership lookup failed', {
129
- referral_id: typedReferral.id, message: partiesErr?.message ?? 'no rows',
130
- });
131
- await recordReferralFailure(supabase, typedReferral.id, currentStatus, 'grant_failed', partiesErr ?? new Error('membership lookup returned no rows'));
132
- return;
133
- }
134
- const referringCustomerId = parties.find((m) => m.id === typedReferral.referring_membership_id)?.stripe_customer_id ?? null;
135
- const referredCustomerId = parties.find((m) => m.id === typedReferral.referred_membership_id)?.stripe_customer_id ?? null;
136
- if (!referringCustomerId || !referredCustomerId) {
137
- console.error('[referralGrant] referral credit missing stripe_customer_id', { referral_id: typedReferral.id });
138
- await recordReferralFailure(supabase, typedReferral.id, currentStatus, 'grant_failed', new Error('missing stripe_customer_id on one or both parties'));
139
- return;
140
- }
141
- // Each call carries a deterministic idempotency key derived from the
142
- // referral row's own id -- a webhook redelivery, or our own retry after
143
- // a transient failure below, can never double-credit either party even
144
- // if our own DB state is momentarily inconsistent; Stripe itself
145
- // refuses to apply the same key twice.
146
- //
147
- // Round-3 review foot-gun: idempotency keys expire after 24h (Stripe),
148
- // but a `grant_failed` row can be manually flipped back for retry well
149
- // after that -- at which point a stale key would no longer protect
150
- // against a double charge. The real guard is checking whether this
151
- // referral ALREADY has a txn id persisted (from a prior partial
152
- // attempt) and skipping straight past re-charging Stripe for that side
153
- // if so -- which is exactly why a failure to PERSIST that txn id after
154
- // a successful Stripe call (the `partialUpdErr`/`partialUpdErr2` blocks
155
- // below) must be treated as fatal, not logged-and-ignored: if the id
156
- // never lands in the DB, a later retry past the 24h window has no way
157
- // to know the money already moved, and will move it again.
158
- let referrerTxnId = typedReferral.stripe_balance_txn_id_referrer ?? null;
159
- if (!referrerTxnId) {
160
- try {
161
- // A NEGATIVE amount on a Customer Balance Transaction decreases what
162
- // the customer owes -- i.e. grants them a credit against their next
163
- // invoice. POST /v1/customers/{customer}/balance_transactions.
164
- const referrerTxn = await stripe.customers.createBalanceTransaction(referringCustomerId, {
165
- amount: -referrerCents,
166
- currency: 'usd',
167
- description: `Referral credit: friend joined via your referral link (referral ${typedReferral.id})`,
168
- }, { idempotencyKey: `ref-${typedReferral.id}-referrer-grant` });
169
- referrerTxnId = referrerTxn.id;
170
- }
171
- catch (e) {
172
- console.error('[referralGrant] referral referrer balance transaction creation failed', {
173
- referral_id: typedReferral.id, message: e instanceof Error ? e.message : String(e),
174
- });
175
- await recordReferralFailure(supabase, typedReferral.id, currentStatus, 'grant_failed', e);
176
- return;
177
- }
178
- // Persist immediately -- if the referred-side call below throws, this
179
- // row already shows real money moved once, with the txn id needed to
180
- // reconcile or manually complete the pair. A failure to persist THIS
181
- // txn id is fatal (see the 24h-idempotency-key comment above): the
182
- // Stripe transaction already exists for real, so silently continuing
183
- // would leave a retry blind to that fact.
184
- const { error: partialUpdErr } = await supabase
185
- .from('referrals')
186
- .update({ stripe_balance_txn_id_referrer: referrerTxnId, referrer_credit_cents: referrerCents })
187
- .eq('id', typedReferral.id);
188
- if (partialUpdErr) {
189
- console.error('[referralGrant] referral partial grant persist failed -- REFERRER STRIPE CREDIT ALREADY GRANTED', {
190
- referral_id: typedReferral.id, referrer_txn_id: referrerTxnId, message: partialUpdErr.message,
191
- });
192
- await recordReferralFailure(supabase, typedReferral.id, currentStatus, 'grant_failed', new Error(`REFERRER CREDIT GRANTED (txn ${referrerTxnId}) BUT TXN ID NOT PERSISTED (${partialUpdErr.message}) -- reconcile in Stripe before retrying; a retry past 24h without this id would charge again`));
193
- return;
194
- }
195
- }
196
- let referredTxnId = typedReferral.stripe_balance_txn_id_referred ?? null;
197
- if (!referredTxnId) {
198
- try {
199
- const referredTxn = await stripe.customers.createBalanceTransaction(referredCustomerId, {
200
- amount: -referredCents,
201
- currency: 'usd',
202
- description: `Referral credit: welcome credit for signing up with a referral code (referral ${typedReferral.id})`,
203
- }, { idempotencyKey: `ref-${typedReferral.id}-referred-grant` });
204
- referredTxnId = referredTxn.id;
205
- }
206
- catch (e) {
207
- console.error('[referralGrant] referral referred balance transaction creation failed -- referrer side already credited above', {
208
- referral_id: typedReferral.id, referrer_txn_id: referrerTxnId, message: e instanceof Error ? e.message : String(e),
209
- });
210
- await recordReferralFailure(supabase, typedReferral.id, currentStatus, 'grant_failed', e);
211
- return;
212
- }
213
- // Same reasoning as the referrer side above -- a failed persist here
214
- // means a real Stripe credit exists with no durable record of its id.
215
- const { error: partialUpdErr2 } = await supabase
216
- .from('referrals')
217
- .update({ stripe_balance_txn_id_referred: referredTxnId, referred_credit_cents: referredCents })
218
- .eq('id', typedReferral.id);
219
- if (partialUpdErr2) {
220
- console.error('[referralGrant] referral partial grant persist (referred side) failed -- REFERRED STRIPE CREDIT ALREADY GRANTED', {
221
- referral_id: typedReferral.id, referred_txn_id: referredTxnId, message: partialUpdErr2.message,
222
- });
223
- await recordReferralFailure(supabase, typedReferral.id, currentStatus, 'grant_failed', new Error(`REFERRED CREDIT GRANTED (txn ${referredTxnId}) BUT TXN ID NOT PERSISTED (${partialUpdErr2.message}) -- reconcile in Stripe before retrying; a retry past 24h without this id would charge again`));
224
- return;
225
- }
226
- }
227
- // referrer_credit_cents/referred_credit_cents are NOT set here -- each
228
- // was already persisted, atomically with its own txn id, above (round-4
229
- // review finding) -- so the amount recorded always matches what that
230
- // specific Stripe transaction actually charged, even across a retry
231
- // where the formula or the referral's price_cents might have changed.
232
- //
233
- // Guarded on `currentStatus` (the row's real status as read at the top
234
- // of this call), not a hardcoded 'signed_up' -- a retry from
235
- // grant_failed must flip FROM grant_failed, not from a status the row
236
- // was never actually in.
237
- const { error: creditUpdErr } = await supabase
238
- .from('referrals')
239
- .update({
240
- status: 'credited',
241
- credited_at: new Date().toISOString(),
242
- clawback_eligible_until: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(),
243
- })
244
- .eq('id', typedReferral.id)
245
- .eq('status', currentStatus);
246
- if (creditUpdErr) {
247
- console.error('[referralGrant] referral row update after crediting failed -- BOTH stripe transactions already succeeded, only this status flip failed', {
248
- referral_id: typedReferral.id, referrer_txn_id: referrerTxnId, referred_txn_id: referredTxnId,
249
- message: creditUpdErr.message,
250
- });
251
- await logOps(supabase, 'referral_credited_status_flip_failed', { referral_id: typedReferral.id, referrer_txn_id: referrerTxnId, referred_txn_id: referredTxnId, message: creditUpdErr.message }, { severity: 'error' }).catch(() => { });
252
- // Deliberately NOT recordReferralFailure here -- both Stripe
253
- // transactions already succeeded, so 'grant_failed' would misleadingly
254
- // imply the grant itself failed. The row stays at `currentStatus` with
255
- // both txn ids already persisted above, so a later retry of this
256
- // function is now SAFE: it will skip both createBalanceTransaction
257
- // calls (already have referrerTxnId/referredTxnId) and just
258
- // re-attempt this status flip.
259
- }
260
- }
261
- catch (e) {
262
- console.error('[referralGrant] maybeGrantReferralCredit failed', {
263
- membership_id: referredMembershipId, message: e instanceof Error ? e.message : String(e),
264
- });
265
- if (referralId)
266
- await recordReferralFailure(supabase, referralId, currentStatus, 'grant_failed', e);
267
- }
46
+ export async function maybeGrantReferralCredit(_supabase, _stripe, referredMembershipId, _fromStatuses = ['signed_up']) {
47
+ console.warn('[referralGrant] maybeGrantReferralCredit is superseded and does nothing: referral credits are paid by gc-io referral-qualify-daily 30 days after signup', { membership_id: referredMembershipId });
268
48
  }
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@simplelayer/graniteer-core",
3
- "version": "0.3.18",
3
+ "version": "0.3.19-referral.1",
4
4
  "description": "Shared platform core for Graniteer",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
7
7
  "scripts": {
8
- "test": "deno test --config deno.test.json --no-check --node-modules-dir=auto --allow-env --allow-net --allow-read src",
8
+ "test": "deno test --no-check --node-modules-dir=auto --allow-env --allow-net --allow-read src",
9
9
  "build": "node scripts/build.mjs",
10
10
  "verify:dist": "node scripts/verify-dist.mjs",
11
11
  "prepack": "npm run build && npm run verify:dist",
@@ -157,26 +157,6 @@
157
157
  "types": "./dist/email-templates/signup.d.ts",
158
158
  "default": "./dist/email-templates/signup.js"
159
159
  },
160
- "./bookingSource": {
161
- "types": "./dist/bookingSource.d.ts",
162
- "default": "./dist/bookingSource.js"
163
- },
164
- "./businessHours": {
165
- "types": "./dist/businessHours.d.ts",
166
- "default": "./dist/businessHours.js"
167
- },
168
- "./gcalBookingEvents": {
169
- "types": "./dist/gcalBookingEvents.d.ts",
170
- "default": "./dist/gcalBookingEvents.js"
171
- },
172
- "./connectBookingCharge": {
173
- "types": "./dist/connectBookingCharge.d.ts",
174
- "default": "./dist/connectBookingCharge.js"
175
- },
176
- "./stripeConnectEvents": {
177
- "types": "./dist/stripeConnectEvents.d.ts",
178
- "default": "./dist/stripeConnectEvents.js"
179
- },
180
160
  "./gcalSync": {
181
161
  "types": "./dist/gcalSync.d.ts",
182
162
  "default": "./dist/gcalSync.js"
@@ -417,10 +397,6 @@
417
397
  "types": "./dist/functions/boldsign-sender-identity.d.ts",
418
398
  "default": "./dist/functions/boldsign-sender-identity.js"
419
399
  },
420
- "./functions/booking-access-revoke-backstop": {
421
- "types": "./dist/functions/booking-access-revoke-backstop.d.ts",
422
- "default": "./dist/functions/booking-access-revoke-backstop.js"
423
- },
424
400
  "./functions/booking-availability": {
425
401
  "types": "./dist/functions/booking-availability.d.ts",
426
402
  "default": "./dist/functions/booking-availability.js"
@@ -1,2 +0,0 @@
1
- export declare const MAX_BOOKING_SOURCE_LENGTH = 40;
2
- export declare function sanitizeBookingSource(raw: unknown): string | null;
@@ -1,11 +0,0 @@
1
- export const MAX_BOOKING_SOURCE_LENGTH = 40;
2
- export function sanitizeBookingSource(raw) {
3
- if (typeof raw !== 'string')
4
- return null;
5
- const v = raw.trim().toLowerCase();
6
- if (v.length === 0 || v.length > MAX_BOOKING_SOURCE_LENGTH)
7
- return null;
8
- if (!/^[a-z0-9_-]+$/.test(v))
9
- return null;
10
- return v;
11
- }
@@ -1,11 +0,0 @@
1
- export declare const DEFAULT_MIN_NOTICE_MS: number;
2
- export interface NoticeConfig {
3
- minNoticeBusinessHours?: number | null;
4
- holidays?: string[] | null;
5
- }
6
- export declare function addBusinessHours(fromUtc: Date, hours: number, holidays?: readonly string[]): Date;
7
- export declare function hasBusinessHoursNotice(cfg?: NoticeConfig | null): cfg is NoticeConfig & {
8
- minNoticeBusinessHours: number;
9
- };
10
- export declare function earliestBookingStartMs(nowMs: number, cfg?: NoticeConfig | null): number;
11
- export declare function minNoticeErrorMessage(nowMs: number, cfg?: NoticeConfig | null): string;
@@ -1,55 +0,0 @@
1
- import { laMidnightUtc } from './gcalSync.js';
2
- import { addDaysStr, pacificDateStr } from './pacificDate.js';
3
- export const DEFAULT_MIN_NOTICE_MS = 15 * 60 * 1000;
4
- const HOUR_MS = 60 * 60 * 1000;
5
- const MAX_DAYS_WALKED = 3700;
6
- function isBusinessDay(dateStr, holidays) {
7
- if (holidays.has(dateStr))
8
- return false;
9
- const [y, m, d] = dateStr.split('-').map(Number);
10
- const wd = new Date(Date.UTC(y, m - 1, d, 12)).getUTCDay();
11
- return wd >= 1 && wd <= 5;
12
- }
13
- export function addBusinessHours(fromUtc, hours, holidays = []) {
14
- if (!Number.isFinite(hours) || hours <= 0)
15
- return new Date(fromUtc.getTime());
16
- const holidaySet = new Set(holidays);
17
- let remaining = hours * HOUR_MS;
18
- let cursor = fromUtc.getTime();
19
- let day = pacificDateStr(new Date(cursor));
20
- for (let i = 0; i < MAX_DAYS_WALKED; i++) {
21
- const nextDay = addDaysStr(day, 1);
22
- const nextMidnight = laMidnightUtc(nextDay).getTime();
23
- if (isBusinessDay(day, holidaySet)) {
24
- const available = nextMidnight - cursor;
25
- if (remaining <= available)
26
- return new Date(cursor + remaining);
27
- remaining -= available;
28
- }
29
- cursor = nextMidnight;
30
- day = nextDay;
31
- }
32
- return new Date(cursor + remaining);
33
- }
34
- export function hasBusinessHoursNotice(cfg) {
35
- return typeof cfg?.minNoticeBusinessHours === 'number' &&
36
- Number.isFinite(cfg.minNoticeBusinessHours) && cfg.minNoticeBusinessHours > 0;
37
- }
38
- export function earliestBookingStartMs(nowMs, cfg) {
39
- const floor = nowMs + DEFAULT_MIN_NOTICE_MS;
40
- if (!hasBusinessHoursNotice(cfg))
41
- return floor;
42
- const bh = addBusinessHours(new Date(nowMs), cfg.minNoticeBusinessHours, cfg.holidays ?? []).getTime();
43
- return Math.max(floor, bh);
44
- }
45
- export function minNoticeErrorMessage(nowMs, cfg) {
46
- if (!hasBusinessHoursNotice(cfg)) {
47
- return 'Bookings need at least 15 minutes notice — please choose a later start time.';
48
- }
49
- const earliest = new Intl.DateTimeFormat('en-US', {
50
- timeZone: 'America/Los_Angeles',
51
- weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit',
52
- }).format(new Date(earliestBookingStartMs(nowMs, cfg)));
53
- return `Bookings need at least ${cfg.minNoticeBusinessHours} business hours notice ` +
54
- `(Monday–Friday, excluding holidays). The earliest available start is ${earliest} Pacific time.`;
55
- }
@@ -1,49 +0,0 @@
1
- import type Stripe from 'stripe';
2
- export interface ConnectBookingOperator {
3
- stripeConnectedAccountId?: string | null;
4
- stripeApplicationFeePercent?: number | null;
5
- }
6
- export declare const CONNECTED_ACCOUNT_ID_RE: RegExp;
7
- export type ConnectConfigError = 'connect_account_invalid' | 'connect_fee_invalid' | 'connect_charge_invalid' | 'connect_fee_exceeds_charge';
8
- export type ConnectedAccountResolution = {
9
- ok: true;
10
- accountId: string | null;
11
- } | {
12
- ok: false;
13
- error: 'connect_account_invalid';
14
- };
15
- export type BookingChargePlan = {
16
- ok: true;
17
- connected: false;
18
- } | {
19
- ok: true;
20
- connected: true;
21
- accountId: string;
22
- applicationFeeCents: number;
23
- } | {
24
- ok: false;
25
- error: ConnectConfigError;
26
- };
27
- export declare function isValidConnectedAccountId(v: unknown): v is string;
28
- export interface ConnectTenantEnv {
29
- connectTenant: boolean;
30
- }
31
- export declare function defaultConnectTenantEnv(): ConnectTenantEnv;
32
- export declare function resolveConnectedAccount(operator: ConnectBookingOperator | null | undefined, env?: ConnectTenantEnv): ConnectedAccountResolution;
33
- export declare function planBookingCharge(operator: ConnectBookingOperator | null | undefined, chargeCents: number, env?: ConnectTenantEnv): BookingChargePlan;
34
- export declare function applyConnectToSessionParams(params: Stripe.Checkout.SessionCreateParams, plan: BookingChargePlan): Stripe.Checkout.SessionCreateParams;
35
- export declare function stripeAccountRequestOptions(accountId: string | null | undefined): {
36
- stripeAccount: string;
37
- } | undefined;
38
- type SessionCreator = {
39
- checkout: {
40
- sessions: {
41
- create: (params: Stripe.Checkout.SessionCreateParams, options?: {
42
- stripeAccount: string;
43
- }) => Promise<Stripe.Checkout.Session>;
44
- };
45
- };
46
- };
47
- export declare function createBookingCheckoutSession(stripe: SessionCreator, params: Stripe.Checkout.SessionCreateParams, plan: BookingChargePlan): Promise<Stripe.Checkout.Session>;
48
- export declare const CONNECT_MISCONFIGURED_MESSAGE = "Payments are misconfigured for this location (Stripe connected account or application fee). No charge was attempted.";
49
- export {};
@@ -1,68 +0,0 @@
1
- // Stripe Connect DIRECT charges for room bookings. Opt-in per operator: with no
2
- // `stripeConnectedAccountId` (undefined/null) every helper here is a no-op and
3
- // the caller's Stripe request is byte-identical to the pre-Connect one.
4
- import { computeApplicationFeeCents } from './checkoutSessionParams.js';
5
- export const CONNECTED_ACCOUNT_ID_RE = /^acct_[A-Za-z0-9]+$/;
6
- export function isValidConnectedAccountId(v) {
7
- return typeof v === 'string' && CONNECTED_ACCOUNT_ID_RE.test(v);
8
- }
9
- // A project that has STRIPE_CONNECT_WEBHOOK_SECRET set is a Connect tenant:
10
- // an omitted account id there is a wiring bug and must never fall back to the
11
- // platform account. GC never sets that secret, so its behavior is unchanged.
12
- export function defaultConnectTenantEnv() {
13
- return { connectTenant: !!Deno.env.get('STRIPE_CONNECT_WEBHOOK_SECRET') };
14
- }
15
- export function resolveConnectedAccount(operator, env = defaultConnectTenantEnv()) {
16
- const raw = operator?.stripeConnectedAccountId;
17
- if (raw === undefined || raw === null) {
18
- return env.connectTenant ? { ok: false, error: 'connect_account_invalid' } : { ok: true, accountId: null };
19
- }
20
- if (!isValidConnectedAccountId(raw))
21
- return { ok: false, error: 'connect_account_invalid' };
22
- return { ok: true, accountId: raw };
23
- }
24
- export function planBookingCharge(operator, chargeCents, env = defaultConnectTenantEnv()) {
25
- const account = resolveConnectedAccount(operator, env);
26
- if ('error' in account)
27
- return { ok: false, error: account.error };
28
- if (account.accountId === null)
29
- return { ok: true, connected: false };
30
- const pct = operator?.stripeApplicationFeePercent;
31
- const hasFee = !(pct === undefined || pct === null || pct === 0);
32
- // Exclusive upper bound: a 100% fee would leave the connected account paying
33
- // Stripe's processing fee on every booking.
34
- if (hasFee && (typeof pct !== 'number' || !Number.isFinite(pct) || pct <= 0 || pct >= 100)) {
35
- return { ok: false, error: 'connect_fee_invalid' };
36
- }
37
- if (!Number.isSafeInteger(chargeCents) || chargeCents <= 0) {
38
- return { ok: false, error: 'connect_charge_invalid' };
39
- }
40
- const fee = hasFee ? computeApplicationFeeCents(chargeCents, pct) : 0;
41
- if (!Number.isSafeInteger(fee) || fee < 0 || fee > chargeCents) {
42
- return { ok: false, error: 'connect_fee_exceeds_charge' };
43
- }
44
- return { ok: true, connected: true, accountId: account.accountId, applicationFeeCents: fee };
45
- }
46
- export function applyConnectToSessionParams(params, plan) {
47
- if (!plan.ok || !plan.connected || plan.applicationFeeCents <= 0)
48
- return params;
49
- return {
50
- ...params,
51
- payment_intent_data: {
52
- ...(params.payment_intent_data ?? {}),
53
- application_fee_amount: plan.applicationFeeCents,
54
- },
55
- };
56
- }
57
- export function stripeAccountRequestOptions(accountId) {
58
- return accountId ? { stripeAccount: accountId } : undefined;
59
- }
60
- export function createBookingCheckoutSession(stripe, params, plan) {
61
- if ('error' in plan) {
62
- return Promise.reject(new Error(`booking checkout refused: ${plan.error}`));
63
- }
64
- if (!plan.connected)
65
- return stripe.checkout.sessions.create(params);
66
- return stripe.checkout.sessions.create(applyConnectToSessionParams(params, plan), { stripeAccount: plan.accountId });
67
- }
68
- export const CONNECT_MISCONFIGURED_MESSAGE = 'Payments are misconfigured for this location (Stripe connected account or application fee). No charge was attempted.';
@@ -1,11 +0,0 @@
1
- /**
2
- * Bookings whose organizer grants the backstop may revoke via terminal booking.status.
3
- * Refund/dispute paths keep status `paid`; those bookings are selected via access_revoke_required_at.
4
- */
5
- export declare const BACKSTOP_BOOKING_STATUSES: readonly ["cancelled_credited", "cancelled_forfeited", "cancelled_refunded"];
6
- export declare function bookingStatusRequiresBackstopRevoke(status: string): boolean;
7
- export declare function bookingRowRequiresBackstopRevoke(booking: {
8
- status?: string;
9
- access_revoke_required_at?: string | null;
10
- }): boolean;
11
- export declare function handle(req: Request): Promise<Response>;
@@ -1,121 +0,0 @@
1
- // SCHEDULED backstop (C6 code-side): pg_cron → HTTP POST when wired. Not scheduled in-repo.
2
- //
3
- // gc-connect wiring (out of this repo):
4
- // - Set verify_jwt=false on this function ONLY together with the constant-time secret
5
- // check below (never an open POST).
6
- // - Store BOOKING_GRANT_REVOKE_BACKSTOP_SECRET in Vault; inject into the edge runtime.
7
- // Do not embed the secret in cron SQL text — reference the Vault secret from the job config.
8
- //
9
- // pg_cron jobs typically POST with an empty body (no next_cursor). Selection orders by
10
- // revoke_backstop_last_attempt_at (never-attempted first) so stuck grants do not starve the queue.
11
- import { createClient } from '@supabase/supabase-js';
12
- import { logOps } from '../ops.js';
13
- import { isBookingGrantRevokeEnabled, revokeBookingOrganizerAccessGrants } from './booking-access-revoke.js';
14
- const REVOCABLE_STATUSES = ['active', 'pending', 'reconciling', 'revoke_failed'];
15
- const MAX_GRANTS_PER_TICK = 5;
16
- /**
17
- * Bookings whose organizer grants the backstop may revoke via terminal booking.status.
18
- * Refund/dispute paths keep status `paid`; those bookings are selected via access_revoke_required_at.
19
- */
20
- export const BACKSTOP_BOOKING_STATUSES = [
21
- 'cancelled_credited',
22
- 'cancelled_forfeited',
23
- 'cancelled_refunded',
24
- ];
25
- export function bookingStatusRequiresBackstopRevoke(status) {
26
- return BACKSTOP_BOOKING_STATUSES.includes(status);
27
- }
28
- export function bookingRowRequiresBackstopRevoke(booking) {
29
- if (booking.access_revoke_required_at)
30
- return true;
31
- return bookingStatusRequiresBackstopRevoke(String(booking.status ?? ''));
32
- }
33
- function safeEqual(a, b) {
34
- const enc = new TextEncoder();
35
- const ab = enc.encode(a), bb = enc.encode(b);
36
- if (ab.length !== bb.length)
37
- return false;
38
- let diff = 0;
39
- for (let i = 0; i < ab.length; i++)
40
- diff |= ab[i] ^ bb[i];
41
- return diff === 0;
42
- }
43
- function envSecret(name) {
44
- const v = Deno.env.get(name);
45
- return v && v.length > 0 ? v : null;
46
- }
47
- function bookingFromJoin(row) {
48
- const b = row.bookings;
49
- if (Array.isArray(b))
50
- return b[0] ?? { status: '' };
51
- return b ?? { status: '' };
52
- }
53
- export async function handle(req) {
54
- if (req.method !== 'POST')
55
- return new Response('Method not allowed', { status: 405 });
56
- const provided = req.headers.get('x-booking-access-revoke-backstop-secret');
57
- const expected = envSecret('BOOKING_GRANT_REVOKE_BACKSTOP_SECRET');
58
- if (!provided || !expected || !safeEqual(provided, expected)) {
59
- return new Response('Unauthorized', { status: 401 });
60
- }
61
- if (!isBookingGrantRevokeEnabled()) {
62
- return new Response(JSON.stringify({ ok: true, skipped: 'revoke_disabled' }), {
63
- status: 200,
64
- headers: { 'Content-Type': 'application/json' },
65
- });
66
- }
67
- const supabase = createClient(Deno.env.get('SUPABASE_URL'), Deno.env.get('SUPABASE_SERVICE_ROLE_KEY'), { auth: { persistSession: false, autoRefreshToken: false } });
68
- const terminalStatuses = BACKSTOP_BOOKING_STATUSES.join(',');
69
- const { data: grantRows, error: grantErr } = await supabase
70
- .from('booking_access_grants')
71
- .select('id, booking_id, revoke_backstop_last_attempt_at, bookings!inner(status, access_revoke_required_at)')
72
- .in('status', [...REVOCABLE_STATUSES])
73
- .or(`status.in.(${terminalStatuses}),access_revoke_required_at.not.is.null`, { foreignTable: 'bookings' })
74
- .order('revoke_backstop_last_attempt_at', { ascending: true, nullsFirst: true })
75
- .order('id', { ascending: true })
76
- .limit(MAX_GRANTS_PER_TICK);
77
- if (grantErr) {
78
- await logOps(supabase, 'booking_access_revoke_backstop_list_failed', {
79
- error_code: grantErr.code ?? 'unknown',
80
- }, { severity: 'error' });
81
- return new Response(JSON.stringify({ ok: false }), { status: 500 });
82
- }
83
- const candidates = (grantRows ?? []);
84
- let processed = 0;
85
- for (const row of candidates) {
86
- if (!row.booking_id || !row.id)
87
- continue;
88
- const booking = bookingFromJoin(row);
89
- if (!bookingRowRequiresBackstopRevoke(booking))
90
- continue;
91
- const attemptAt = new Date().toISOString();
92
- const { error: attemptErr } = await supabase
93
- .from('booking_access_grants')
94
- .update({ revoke_backstop_last_attempt_at: attemptAt })
95
- .eq('id', row.id);
96
- if (attemptErr) {
97
- await logOps(supabase, 'booking_access_revoke_backstop_attempt_stamp_failed', {
98
- grant_id: row.id,
99
- error_code: attemptErr.code ?? 'unknown',
100
- }, { severity: 'error', bookingId: row.booking_id });
101
- }
102
- processed += 1;
103
- try {
104
- await revokeBookingOrganizerAccessGrants(supabase, {
105
- bookingId: row.booking_id,
106
- actingUserId: 'system:booking-access-revoke-backstop',
107
- reason: 'scheduled_backstop',
108
- });
109
- }
110
- catch (e) {
111
- await logOps(supabase, 'booking_access_revoke_backstop_revoke_failed', {
112
- grant_id: row.id,
113
- error_name: e instanceof Error ? e.name : 'Error',
114
- }, { severity: 'error', bookingId: row.booking_id });
115
- }
116
- }
117
- return new Response(JSON.stringify({ ok: true, processed }), {
118
- status: 200,
119
- headers: { 'Content-Type': 'application/json' },
120
- });
121
- }