@simplelayer/graniteer-core 0.4.3 → 0.5.0-rc.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 (120) hide show
  1. package/LICENSE +4 -0
  2. package/dist/bookingAgreementEmail.d.ts +34 -3
  3. package/dist/bookingAgreementEmail.js +100 -1
  4. package/dist/bookingEffects.d.ts +3 -1
  5. package/dist/bookingEffects.js +4 -3
  6. package/dist/bookingSource.d.ts +2 -0
  7. package/dist/bookingSource.js +11 -0
  8. package/dist/businessHours.d.ts +11 -0
  9. package/dist/businessHours.js +55 -0
  10. package/dist/checkoutSessionParams.d.ts +33 -0
  11. package/dist/checkoutSessionParams.js +71 -0
  12. package/dist/commonsSignedUnpaidCancellation.d.ts +154 -0
  13. package/dist/commonsSignedUnpaidCancellation.js +650 -0
  14. package/dist/connectBookingCharge.d.ts +49 -0
  15. package/dist/connectBookingCharge.js +72 -0
  16. package/dist/entitlements.d.ts +1 -1
  17. package/dist/entitlements.js +6 -1
  18. package/dist/functions/admin-acknowledge-contract-violation.d.ts +1 -0
  19. package/dist/functions/admin-acknowledge-contract-violation.js +120 -0
  20. package/dist/functions/admin-cancel-membership.js +109 -13
  21. package/dist/functions/admin-change-membership-plan.js +74 -18
  22. package/dist/functions/admin-charge-guest-print.d.ts +3 -1
  23. package/dist/functions/admin-charge-guest-print.js +8 -1
  24. package/dist/functions/admin-create-booking.d.ts +8 -3
  25. package/dist/functions/admin-create-booking.js +15 -2
  26. package/dist/functions/admin-create-commons-event.d.ts +3 -1
  27. package/dist/functions/admin-create-commons-event.js +8 -1
  28. package/dist/functions/admin-door-write.d.ts +3 -1
  29. package/dist/functions/admin-door-write.js +8 -1
  30. package/dist/functions/admin-issue-day-pass.d.ts +1 -0
  31. package/dist/functions/admin-issue-day-pass.js +8 -1
  32. package/dist/functions/admin-mark-booking-paid.d.ts +6 -1
  33. package/dist/functions/admin-mark-booking-paid.js +27 -3
  34. package/dist/functions/admin-request-trial.js +22 -1
  35. package/dist/functions/auth-email-hook.js +42 -2
  36. package/dist/functions/booking-access-revoke-backstop.d.ts +11 -0
  37. package/dist/functions/booking-access-revoke-backstop.js +121 -0
  38. package/dist/functions/booking-access-revoke-door-state.d.ts +22 -0
  39. package/dist/functions/booking-access-revoke-door-state.js +61 -0
  40. package/dist/functions/booking-access-revoke.d.ts +35 -0
  41. package/dist/functions/booking-access-revoke.js +280 -0
  42. package/dist/functions/booking-availability.d.ts +2 -1
  43. package/dist/functions/booking-availability.js +14 -5
  44. package/dist/functions/conductor.js +39 -16
  45. package/dist/functions/create-booking.d.ts +10 -3
  46. package/dist/functions/create-booking.js +22 -4
  47. package/dist/functions/create-day-pass-checkout.d.ts +1 -0
  48. package/dist/functions/create-day-pass-checkout.js +6 -0
  49. package/dist/functions/create-subscription-checkout.js +7 -2
  50. package/dist/functions/event-access-admin.d.ts +1 -0
  51. package/dist/functions/event-access-admin.js +23 -1
  52. package/dist/functions/event-access-store.js +18 -0
  53. package/dist/functions/guest-print-setup-confirm.d.ts +3 -1
  54. package/dist/functions/guest-print-setup-confirm.js +8 -1
  55. package/dist/functions/guest-print-submit.d.ts +3 -1
  56. package/dist/functions/guest-print-submit.js +8 -1
  57. package/dist/functions/manage-booking.d.ts +24 -1
  58. package/dist/functions/manage-booking.js +151 -16
  59. package/dist/functions/mcp.d.ts +2 -2
  60. package/dist/functions/mcp.js +2 -2
  61. package/dist/functions/member-door-action.d.ts +3 -1
  62. package/dist/functions/member-door-action.js +9 -2
  63. package/dist/functions/membership-door-sync.d.ts +18 -0
  64. package/dist/functions/membership-door-sync.js +76 -6
  65. package/dist/functions/office-assignment-end.d.ts +3 -1
  66. package/dist/functions/office-assignment-end.js +8 -1
  67. package/dist/functions/portal-submit-event.d.ts +1 -0
  68. package/dist/functions/portal-submit-event.js +4 -0
  69. package/dist/functions/reschedule-booking.d.ts +11 -4
  70. package/dist/functions/reschedule-booking.js +39 -2
  71. package/dist/functions/review-ratings.js +1 -1
  72. package/dist/functions/space-availability-range.d.ts +2 -1
  73. package/dist/functions/space-availability-range.js +8 -1
  74. package/dist/functions/stripe-db-reconcile.js +8 -1
  75. package/dist/functions/stripe-webhook.d.ts +4 -0
  76. package/dist/functions/stripe-webhook.js +328 -17
  77. package/dist/functions/sync-gcal-blackouts.js +1 -1
  78. package/dist/functions/timetable-event-register.d.ts +3 -1
  79. package/dist/functions/timetable-event-register.js +8 -1
  80. package/dist/functions/touch-pass-signup.d.ts +3 -1
  81. package/dist/functions/touch-pass-signup.js +9 -2
  82. package/dist/functions/voice-booking.d.ts +1 -1
  83. package/dist/functions/voice-day-pass.d.ts +2 -1
  84. package/dist/functions/voice-day-pass.js +4 -0
  85. package/dist/functions/voice-inquiry.d.ts +3 -1
  86. package/dist/functions/voice-inquiry.js +9 -2
  87. package/dist/functions/voice-membership-signup.d.ts +2 -2
  88. package/dist/functions/voice-tour-booking.d.ts +1 -1
  89. package/dist/gcalBookingEvents.d.ts +59 -0
  90. package/dist/gcalBookingEvents.js +183 -0
  91. package/dist/gcalSync.d.ts +1 -0
  92. package/dist/gcalSync.js +5 -0
  93. package/dist/membershipSubscriptionItems.d.ts +87 -0
  94. package/dist/membershipSubscriptionItems.js +71 -0
  95. package/dist/membershipWelcome.d.ts +1 -1
  96. package/dist/ops.js +4 -3
  97. package/dist/outbox.d.ts +64 -0
  98. package/dist/outbox.js +70 -0
  99. package/dist/pricing.d.ts +10 -2
  100. package/dist/pricing.js +14 -9
  101. package/dist/referralCodeLookup.d.ts +13 -0
  102. package/dist/referralCodeLookup.js +17 -0
  103. package/dist/referralCredits.d.ts +5 -0
  104. package/dist/referralCredits.js +5 -0
  105. package/dist/referralGrant.d.ts +4 -31
  106. package/dist/referralGrant.js +14 -234
  107. package/dist/runtime/env.d.ts +7 -0
  108. package/dist/runtime/env.js +32 -0
  109. package/dist/runtime/fs.d.ts +5 -0
  110. package/dist/runtime/fs.js +16 -0
  111. package/dist/runtime/serve.d.ts +8 -0
  112. package/dist/runtime/serve.js +12 -0
  113. package/dist/stripeConnectEvents.d.ts +11 -0
  114. package/dist/stripeConnectEvents.js +37 -0
  115. package/dist/supabaseTestFakes.js +7 -1
  116. package/dist/tenant-config.d.ts +8 -0
  117. package/dist/tenant-config.js +25 -0
  118. package/dist/tenantManifest.d.ts +85 -0
  119. package/dist/tenantManifest.js +43 -0
  120. package/package.json +59 -3
package/dist/pricing.js CHANGED
@@ -6,11 +6,16 @@
6
6
  // rangeLiteral } describing a fully-validated booking window.
7
7
  import { getBusyRangesDetailed } from './availability.js';
8
8
  import { logOps } from './ops.js';
9
+ import { DEFAULT_MIN_NOTICE_MS, earliestBookingStartMs, minNoticeErrorMessage } from './businessHours.js';
9
10
  // Minimum lead time required between "now" and a booking's start time.
10
11
  // Mirrors the same purpose as GHL's `allowBookingAfter` setting on the tour
11
12
  // calendars, but for meeting rooms — previously there was no floor at all
12
13
  // beyond "not literally in the past" (see 2026-08-25 same-day-tour review).
13
- const MIN_BOOKING_NOTICE_MS = 15 * 60 * 1000;
14
+ const MIN_BOOKING_NOTICE_MS = DEFAULT_MIN_NOTICE_MS;
15
+ // Earliest allowed start. Unset notice config => exactly now + 15 minutes.
16
+ function noticeFloorMs(nowMs, notice) {
17
+ return notice ? earliestBookingStartMs(nowMs, notice) : nowMs + MIN_BOOKING_NOTICE_MS;
18
+ }
14
19
  function laOffsetHours(atUtc) {
15
20
  const parts = new Intl.DateTimeFormat('en-US', {
16
21
  timeZone: 'America/Los_Angeles',
@@ -126,7 +131,7 @@ export function resolveHalfDayWindow(room, dayMode, wd, dateStr, openUtc, closeU
126
131
  endUtc: laWallToUtc(y, mo, d, Math.floor(endMin / 60), endMin % 60),
127
132
  };
128
133
  }
129
- export async function validateAndPriceDayBlock(supabase, room, input, nowMs) {
134
+ export async function validateAndPriceDayBlock(supabase, room, input, nowMs, notice) {
130
135
  const { date, day_mode } = input;
131
136
  if (!date || !day_mode)
132
137
  return { ok: false, status: 400, error: 'date and day_mode are required for this room' };
@@ -165,8 +170,8 @@ export async function validateAndPriceDayBlock(supabase, room, input, nowMs) {
165
170
  endUtc = win.endUtc;
166
171
  price_cents = room.half_day_cents;
167
172
  }
168
- if (startUtc.getTime() < nowMs + MIN_BOOKING_NOTICE_MS) {
169
- return { ok: false, status: 400, error: 'Bookings need at least 15 minutes notice — please choose a later start time.' };
173
+ if (startUtc.getTime() < noticeFloorMs(nowMs, notice)) {
174
+ return { ok: false, status: 400, error: minNoticeErrorMessage(nowMs, notice) };
170
175
  }
171
176
  if (price_cents <= 0)
172
177
  return { ok: false, status: 400, error: 'invalid price' };
@@ -179,7 +184,7 @@ export async function validateAndPriceDayBlock(supabase, room, input, nowMs) {
179
184
  list_rule_type: null,
180
185
  };
181
186
  }
182
- export async function validateAndPriceHourly(supabase, room, input, nowMs) {
187
+ export async function validateAndPriceHourly(supabase, room, input, nowMs, notice) {
183
188
  const { start, end } = input;
184
189
  if (!start || !end)
185
190
  return { ok: false, status: 400, error: 'start and end are required' };
@@ -190,8 +195,8 @@ export async function validateAndPriceHourly(supabase, room, input, nowMs) {
190
195
  }
191
196
  if (!(startUtc < endUtc))
192
197
  return { ok: false, status: 400, error: 'end must be after start' };
193
- if (startUtc.getTime() < nowMs + MIN_BOOKING_NOTICE_MS) {
194
- return { ok: false, status: 400, error: 'Bookings need at least 15 minutes notice — please choose a later start time.' };
198
+ if (startUtc.getTime() < noticeFloorMs(nowMs, notice)) {
199
+ return { ok: false, status: 400, error: minNoticeErrorMessage(nowMs, notice) };
195
200
  }
196
201
  if (startUtc.getUTCSeconds() !== 0 || startUtc.getUTCMilliseconds() !== 0 ||
197
202
  endUtc.getUTCSeconds() !== 0 || endUtc.getUTCMilliseconds() !== 0 ||
@@ -699,8 +704,8 @@ export async function validateAndPriceForRoom(supabase, room, input, nowMs, opts
699
704
  }
700
705
  const isDayBlock = room.booking_mode === 'day_block';
701
706
  const price = () => (isDayBlock
702
- ? validateAndPriceDayBlock(supabase, room, { date: input.date, day_mode: input.day_mode }, nowMs)
703
- : validateAndPriceHourly(supabase, room, { start: input.start, end: input.end }, nowMs));
707
+ ? validateAndPriceDayBlock(supabase, room, { date: input.date, day_mode: input.day_mode }, nowMs, opts.notice)
708
+ : validateAndPriceHourly(supabase, room, { start: input.start, end: input.end }, nowMs, opts.notice));
704
709
  const baseRaw = await price();
705
710
  if (!baseRaw.ok)
706
711
  return baseRaw;
@@ -0,0 +1,13 @@
1
+ export declare function escapeLikePattern(input: string): string;
2
+ /**
3
+ * Allowlist for referral codes (issued codes are 8-char uppercase alphanumeric;
4
+ * the 1..32 range matches the zod bound on the checkout input and tolerates
5
+ * lowercase typos, which ilike matches case-insensitively).
6
+ *
7
+ * Why an allowlist and not just escapeLikePattern: PostgREST treats '*' in an
8
+ * ilike value as a wildcard alias for '%', and escapeLikePattern does not
9
+ * escape it, so '*' would match the first membership's code. Anything outside
10
+ * [A-Za-z0-9] is treated by callers as "no referral code supplied" and the
11
+ * lookup is skipped entirely. escapeLikePattern is kept as defense in depth.
12
+ */
13
+ export declare function isValidReferralCode(input: unknown): input is string;
@@ -0,0 +1,17 @@
1
+ export function escapeLikePattern(input) {
2
+ return input.replace(/[\\%_]/g, (ch) => '\\' + ch);
3
+ }
4
+ /**
5
+ * Allowlist for referral codes (issued codes are 8-char uppercase alphanumeric;
6
+ * the 1..32 range matches the zod bound on the checkout input and tolerates
7
+ * lowercase typos, which ilike matches case-insensitively).
8
+ *
9
+ * Why an allowlist and not just escapeLikePattern: PostgREST treats '*' in an
10
+ * ilike value as a wildcard alias for '%', and escapeLikePattern does not
11
+ * escape it, so '*' would match the first membership's code. Anything outside
12
+ * [A-Za-z0-9] is treated by callers as "no referral code supplied" and the
13
+ * lookup is skipped entirely. escapeLikePattern is kept as defense in depth.
14
+ */
15
+ export function isValidReferralCode(input) {
16
+ return typeof input === 'string' && /^[A-Za-z0-9]{1,32}$/.test(input);
17
+ }
@@ -2,4 +2,9 @@ export interface ReferralCredits {
2
2
  referrerCents: number;
3
3
  referredCents: number;
4
4
  }
5
+ /**
6
+ * @deprecated gc-io's referralQualify owns the referral credit formula now
7
+ * (50% of the referred member's first-month price, floored). Retained
8
+ * unchanged for published-package compatibility.
9
+ */
5
10
  export declare function computeReferralCredits(planPriceCents: number, isPrivateOffice: boolean): ReferralCredits;
@@ -13,6 +13,11 @@
13
13
  // price + a private-office flag into two credit amounts.
14
14
  const PRIVATE_OFFICE_REFERRER_CENTS = 30000; // flat $300
15
15
  const MIN_CREDIT_CENTS = 2500; // $25 floor on both sides
16
+ /**
17
+ * @deprecated gc-io's referralQualify owns the referral credit formula now
18
+ * (50% of the referred member's first-month price, floored). Retained
19
+ * unchanged for published-package compatibility.
20
+ */
16
21
  export function computeReferralCredits(planPriceCents, isPrivateOffice) {
17
22
  const referrerCents = isPrivateOffice
18
23
  ? PRIVATE_OFFICE_REFERRER_CENTS
@@ -14,36 +14,9 @@ type SupabaseLike = SupabaseClient<any, 'public', any>;
14
14
  */
15
15
  export declare function recordReferralFailure(supabase: SupabaseLike, referralId: string, fromStatus: 'signed_up' | 'grant_failed' | 'credited', toStatus: 'grant_failed' | 'clawback_failed', error: unknown): Promise<void>;
16
16
  /**
17
- * Referral program Phase 1, step 2 (grant at first-invoice-paid).
18
- *
19
- * Called from the webhook only when the first_invoice_paid_at compare-and-
20
- * swap in the invoice.paid handler actually affected a row (genuinely the
21
- * first real paid invoice for this membership) -- that call passes no
22
- * `fromStatuses` override, so it only ever matches a 'signed_up' row.
23
- *
24
- * admin-referral-retry calls this SAME function with
25
- * `fromStatuses: ['grant_failed']` to retry a previously-failed grant --
26
- * see that function's own header comment for why it gates on the referred
27
- * membership's live status first, and why it does NOT reset the row to
28
- * 'signed_up' before calling this (that reset-then-call shape was tried and
29
- * reverted after a second-model review found it opened a stranded-row
30
- * window and a same-row race between two concurrent retries).
31
- *
32
- * Computes real credit amounts, grants a NEGATIVE Stripe Customer Balance
33
- * Transaction (a credit) on each of the two Stripe customers, and marks the
34
- * referral 'credited'.
35
- *
36
- * Entirely wrapped in try/catch and logs with the referral id on failure --
37
- * a Stripe failure here must never break invoice.paid processing for an
38
- * unrelated membership.
39
- *
40
- * IDEMPOTENT BY DESIGN -- this is also what makes it safe for
41
- * admin-referral-retry to call again on a grant_failed row: before each
42
- * Stripe call it checks whether this referral already has a txn id
43
- * persisted, and each Stripe call carries a fixed idempotency key derived
44
- * from the referral id, so a retry only attempts whichever side didn't
45
- * already complete. Never write a second, separate recovery path -- retry
46
- * by calling this function again.
17
+ * @deprecated SUPERSEDED -- no-op. Crediting is owned by gc-io's
18
+ * referral-qualify-daily job (30 days after signup). Never touches Stripe or
19
+ * the database; signature kept for published-package compatibility.
47
20
  */
48
- export declare function maybeGrantReferralCredit(supabase: SupabaseLike, stripe: Stripe, referredMembershipId: string, fromStatuses?: readonly ('signed_up' | 'grant_failed')[]): Promise<void>;
21
+ export declare function maybeGrantReferralCredit(_supabase: SupabaseLike, _stripe: Stripe, referredMembershipId: string, _fromStatuses?: readonly ('signed_up' | 'grant_failed')[]): Promise<void>;
49
22
  export {};
@@ -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
  }
@@ -0,0 +1,7 @@
1
+ export interface EnvReader {
2
+ get(key: string): string | undefined;
3
+ }
4
+ export declare function setEnvReader(r: EnvReader | null): () => void;
5
+ export declare function hasEnvSource(): boolean;
6
+ export declare function getEnv(key: string): string | undefined;
7
+ export declare function requireEnv(key: string): string;
@@ -0,0 +1,32 @@
1
+ const defaultReader = {
2
+ get(key) {
3
+ const g = globalThis;
4
+ if (g.Deno?.env)
5
+ return g.Deno.env.get(key);
6
+ const procEnv = g.process?.env;
7
+ if (procEnv)
8
+ return procEnv[key];
9
+ return undefined;
10
+ },
11
+ };
12
+ let reader = null;
13
+ export function setEnvReader(r) {
14
+ const prev = reader;
15
+ reader = r;
16
+ return () => {
17
+ reader = prev;
18
+ };
19
+ }
20
+ export function hasEnvSource() {
21
+ const g = globalThis;
22
+ return !!g.Deno?.env || reader !== null || !!g.process?.env;
23
+ }
24
+ export function getEnv(key) {
25
+ return (reader ?? defaultReader).get(key);
26
+ }
27
+ export function requireEnv(key) {
28
+ const value = getEnv(key);
29
+ if (value === undefined)
30
+ throw new Error(`Missing required environment variable: ${key}`);
31
+ return value;
32
+ }
@@ -0,0 +1,5 @@
1
+ export interface TextFileReader {
2
+ (path: string): Promise<string>;
3
+ }
4
+ export declare function setTextFileReader(r: TextFileReader | null): void;
5
+ export declare function readText(path: string): Promise<string>;
@@ -0,0 +1,16 @@
1
+ let injected = null;
2
+ export function setTextFileReader(r) {
3
+ injected = r;
4
+ }
5
+ export async function readText(path) {
6
+ if (injected)
7
+ return injected(path);
8
+ const g = globalThis;
9
+ if (typeof g.Deno?.readTextFile === 'function')
10
+ return g.Deno.readTextFile(path);
11
+ if (g.process?.versions?.node) {
12
+ const fs = await import('node:fs/promises');
13
+ return fs.readFile(path, 'utf8');
14
+ }
15
+ throw new Error('readText: no filesystem available in this runtime; inject one with setTextFileReader');
16
+ }
@@ -0,0 +1,8 @@
1
+ export type FetchHandler = (req: Request, ...rest: any[]) => Response | Promise<Response>;
2
+ /**
3
+ * Starts Deno.serve(handler) when running under Deno; returns the handler.
4
+ * There is no import.meta.main gate here: a bare top-level serve(h) would start
5
+ * a listener whenever a test imports the module. Use it as
6
+ * `if (import.meta.main) serve(h)`.
7
+ */
8
+ export declare function serve<H extends FetchHandler>(handler: H): H;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Starts Deno.serve(handler) when running under Deno; returns the handler.
3
+ * There is no import.meta.main gate here: a bare top-level serve(h) would start
4
+ * a listener whenever a test imports the module. Use it as
5
+ * `if (import.meta.main) serve(h)`.
6
+ */
7
+ export function serve(handler) {
8
+ const deno = globalThis.Deno;
9
+ if (typeof deno?.serve === 'function')
10
+ deno.serve(handler);
11
+ return handler;
12
+ }
@@ -0,0 +1,11 @@
1
+ import type Stripe from 'stripe';
2
+ export declare const CONNECT_BOOKING_EVENT_TYPES: ReadonlySet<string>;
3
+ export type ConnectGateReason = 'not_connect_event' | 'account_mismatch' | 'event_type_not_handled' | 'not_a_booking_session';
4
+ export type ConnectGateResult = {
5
+ accept: true;
6
+ } | {
7
+ accept: false;
8
+ reason: ConnectGateReason;
9
+ };
10
+ export declare function gateConnectBookingEvent(event: Pick<Stripe.Event, 'type' | 'account' | 'data'>, operatorAccountId: string): ConnectGateResult;
11
+ export declare function connectAcceptedOpsKind(eventType: string): string;
@@ -0,0 +1,37 @@
1
+ // Gate for the Stripe Connect webhook endpoint (createStripeConnectWebhookHandler).
2
+ // Pure: decides whether a verified connected-account event may enter the shared
3
+ // booking logic in stripe-webhook.ts.
4
+ export const CONNECT_BOOKING_EVENT_TYPES = new Set([
5
+ 'checkout.session.completed',
6
+ 'checkout.session.expired',
7
+ 'checkout.session.async_payment_failed',
8
+ 'payment_intent.payment_failed',
9
+ 'charge.refunded',
10
+ 'charge.dispute.created',
11
+ 'charge.dispute.closed',
12
+ ]);
13
+ export function gateConnectBookingEvent(event, operatorAccountId) {
14
+ const acct = event.account;
15
+ if (typeof acct !== 'string' || acct.length === 0)
16
+ return { accept: false, reason: 'not_connect_event' };
17
+ if (acct !== operatorAccountId)
18
+ return { accept: false, reason: 'account_mismatch' };
19
+ if (!CONNECT_BOOKING_EVENT_TYPES.has(event.type))
20
+ return { accept: false, reason: 'event_type_not_handled' };
21
+ if (event.type.startsWith('checkout.session.')) {
22
+ const s = event.data?.object;
23
+ const md = (s?.metadata ?? {});
24
+ const bookingId = md.booking_id;
25
+ if (typeof bookingId !== 'string' || bookingId.length === 0 ||
26
+ md.checkout_type !== undefined || md.payment_type !== undefined ||
27
+ s?.mode === 'subscription') {
28
+ return { accept: false, reason: 'not_a_booking_session' };
29
+ }
30
+ }
31
+ return { accept: true };
32
+ }
33
+ export function connectAcceptedOpsKind(eventType) {
34
+ return eventType.startsWith('charge.')
35
+ ? 'stripe_connect_charge_refund_or_dispute'
36
+ : 'stripe_connect_event_accepted';
37
+ }
@@ -18,7 +18,13 @@ class FakeQuery {
18
18
  this.responder = responder;
19
19
  this.log = log;
20
20
  }
21
- select(columns) { this.rec.op = 'select'; this.rec.columns = columns; return this; }
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; }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Base origin of this tenant's membership/event-access middleware (the
3
+ * "ftw-middleware"-equivalent service that signs/serves door credentials,
4
+ * organizer links, and grant revokes). No trailing slash.
5
+ *
6
+ * Env var: EVENT_ACCESS_BUS_BASE
7
+ */
8
+ export declare function getEventAccessBusBase(): string;
@@ -0,0 +1,25 @@
1
+ // Centralized tenant-scoped configuration for the handful of values that
2
+ // historically were hardcoded to Granite City Workspaces' own infrastructure
3
+ // instead of being dependency-injected like the rest of the operator identity
4
+ // (GHL_LOCATION_ID, OPERATOR/siteConfig objects, Stripe keys, etc. -- see
5
+ // docs/resale/TENANT-AUDIT.md). Every constant here is backed by an env var,
6
+ // documented in .env.tenant.example at the repo root. When an env var is
7
+ // unset, the fallback is Granite City's current production value, so existing
8
+ // deployments keep working unchanged until their env is configured.
9
+ //
10
+ // Most tenant identity in this codebase is injected by the caller (the
11
+ // gc-connect-style wrapper that imports this package) rather than read from
12
+ // env here. This module exists only for the small number of call sites
13
+ // (manage-booking.ts, booking-access-revoke.ts) that don't already receive a
14
+ // busBase-shaped config object from their caller.
15
+ import { getEnv } from './runtime/env.js';
16
+ /**
17
+ * Base origin of this tenant's membership/event-access middleware (the
18
+ * "ftw-middleware"-equivalent service that signs/serves door credentials,
19
+ * organizer links, and grant revokes). No trailing slash.
20
+ *
21
+ * Env var: EVENT_ACCESS_BUS_BASE
22
+ */
23
+ export function getEventAccessBusBase() {
24
+ return getEnv('EVENT_ACCESS_BUS_BASE') ?? 'https://ftw.granitecity.io';
25
+ }