@simplelayer/graniteer-core 0.4.2 → 0.5.0-rc.0

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 +279 -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 +9 -1
  58. package/dist/functions/manage-booking.js +140 -6
  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 +182 -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/outbox.d.ts +64 -0
  97. package/dist/outbox.js +70 -0
  98. package/dist/pricing.d.ts +10 -2
  99. package/dist/pricing.js +14 -9
  100. package/dist/printBilling.js +47 -47
  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
@@ -6,8 +6,21 @@ import { isDepositOnly, parseTstzRange } from '../bookingEffects.js';
6
6
  import { extractDoorAccess } from '../busClient.js';
7
7
  import { logWelcomeSkipped, WELCOME_OK_STATUSES, } from '../membershipWelcome.js';
8
8
  import { sendDunningEmail } from '../dunningEmails.js';
9
- import { recordReferralFailure, maybeGrantReferralCredit } from '../referralGrant.js';
9
+ import { recordReferralFailure } from '../referralGrant.js';
10
+ import { escapeLikePattern, isValidReferralCode } from '../referralCodeLookup.js';
11
+ import { findBaseItem } from '../membershipSubscriptionItems.js';
12
+ import { cancelUnpaidSignedBooking, isSignedUnpaidCancelDue, isCommonsSignedUnpaidPolicyEligible, readCommonsSignedPaymentLinkDryRun } from '../commonsSignedUnpaidCancellation.js';
13
+ import { sendBookingCancelledUnpaidEmailOnce } from '../bookingAgreementEmail.js';
14
+ import { errorNameFromUnknown, revokeBookingOrganizerAccessGrants, shouldRevokeOrganizerGrantsOnStripeChargeRefunded, } from './booking-access-revoke.js';
15
+ import { isValidConnectedAccountId } from '../connectBookingCharge.js';
16
+ import { connectAcceptedOpsKind, gateConnectBookingEvent } from '../stripeConnectEvents.js';
10
17
  export function createStripeWebhookHandler(config) {
18
+ return buildStripeWebhookHandler(config, null);
19
+ }
20
+ export function createStripeConnectWebhookHandler(config) {
21
+ return buildStripeWebhookHandler(config, { accountId: config.stripeConnectedAccountId });
22
+ }
23
+ function buildStripeWebhookHandler(config, connect) {
11
24
  const { systemActorEmail, dayPassPortalRedirectUrl, teamSeatSlug, virtualOfficeSlug, siteConfig, busProvision, busCancel, notifyGhl, createCalendarEvent, handleCommonsDepositSession, sendVirtualOfficeWelcome, sendMembershipWelcome, sendPrivateOfficeWelcome, loadPrivateOfficeBilling, sendTeamSeatWelcome, maybeActivateAgreement, pacificMidnightUtc, maybeConvertTrialGrant, provisionDayPass, cancelDayPass, } = config;
12
25
  // No CORS — this is called by Stripe, not the browser.
13
26
  return async (req) => {
@@ -15,11 +28,16 @@ export function createStripeWebhookHandler(config) {
15
28
  return new Response('Method not allowed', { status: 405 });
16
29
  }
17
30
  const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
18
- const webhookSecret = Deno.env.get('STRIPE_WEBHOOK_SECRET');
31
+ const webhookSecret = connect
32
+ ? Deno.env.get('STRIPE_CONNECT_WEBHOOK_SECRET')
33
+ : Deno.env.get('STRIPE_WEBHOOK_SECRET');
19
34
  if (!stripeKey || !webhookSecret) {
20
35
  return new Response('Webhook not configured', { status: 500 });
21
36
  }
22
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
37
+ if (connect && !isValidConnectedAccountId(connect.accountId)) {
38
+ return new Response('Connect webhook not configured', { status: 500 });
39
+ }
40
+ let stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
23
41
  const signature = req.headers.get('stripe-signature');
24
42
  if (!signature)
25
43
  return new Response('Missing signature', { status: 400 });
@@ -33,6 +51,30 @@ export function createStripeWebhookHandler(config) {
33
51
  return new Response('Invalid signature', { status: 400 });
34
52
  }
35
53
  const supabase = createClient(Deno.env.get('SUPABASE_URL'), Deno.env.get('SUPABASE_SERVICE_ROLE_KEY'));
54
+ if (connect) {
55
+ const connectAccountId = connect.accountId;
56
+ const gate = gateConnectBookingEvent(event, connectAccountId);
57
+ const ignoredReason = 'reason' in gate ? gate.reason : null;
58
+ await logOps(supabase, ignoredReason ? 'stripe_connect_event_ignored' : connectAcceptedOpsKind(event.type), {
59
+ event_id: event.id,
60
+ event_type: event.type,
61
+ connected_account_id: event.account ?? null,
62
+ ...(ignoredReason ? { reason: ignoredReason } : {}),
63
+ }, {
64
+ severity: ignoredReason
65
+ ? (ignoredReason === 'account_mismatch' ? 'warning' : 'info')
66
+ : (event.type.startsWith('charge.') ? 'warning' : 'info'),
67
+ }).catch(() => { });
68
+ if (ignoredReason) {
69
+ return new Response(JSON.stringify({ received: true, connect_event: true, ignored: ignoredReason }), {
70
+ headers: { 'Content-Type': 'application/json' }, status: 200,
71
+ });
72
+ }
73
+ stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia', stripeAccount: connectAccountId });
74
+ // Account already verified above; clear it so the platform-only guard below lets this event reach the shared booking logic.
75
+ // Namespace the id so a platform-endpoint ledger row for the same evt_ can never swallow this delivery as a duplicate.
76
+ event = { ...event, id: `connect:${event.id}`, account: undefined };
77
+ }
36
78
  // Idempotency ledger — dedupe Stripe redeliveries.
37
79
  {
38
80
  const { error: ledgerErr } = await supabase
@@ -59,6 +101,107 @@ export function createStripeWebhookHandler(config) {
59
101
  .from('bookings').select('id,status').eq('stripe_session_id', session.id).maybeSingle();
60
102
  return data;
61
103
  }
104
+ let bookingLookupErrored = false;
105
+ async function findBookingIdByPaymentIntent(paymentIntentId) {
106
+ bookingLookupErrored = false;
107
+ const { data: rows, error } = await supabase
108
+ .from('bookings')
109
+ .select('id')
110
+ .eq('stripe_payment_intent', paymentIntentId)
111
+ .limit(2);
112
+ if (error) {
113
+ const code = error.code;
114
+ await logOps(supabase, 'booking_access_revoke_booking_lookup_failed', {
115
+ payment_intent_id: paymentIntentId,
116
+ ...(typeof code === 'string' ? { error_code: code } : {}),
117
+ }, { severity: 'error', bookingId: null });
118
+ bookingLookupErrored = true;
119
+ return null;
120
+ }
121
+ const list = (rows ?? []);
122
+ if (list.length > 1) {
123
+ await logOps(supabase, 'booking_access_revoke_booking_lookup_duplicate_pi', {
124
+ payment_intent_id: paymentIntentId,
125
+ match_count: list.length,
126
+ }, { severity: 'error', bookingId: null });
127
+ return null;
128
+ }
129
+ return list[0]?.id ?? null;
130
+ }
131
+ async function releaseStripeEventLedgerForRetry(eventId) {
132
+ const { error } = await supabase.from('stripe_events').delete().eq('event_id', eventId);
133
+ if (error) {
134
+ const code = error.code;
135
+ await logOps(supabase, 'stripe_events_ledger_release_failed', {
136
+ ...(typeof code === 'string' ? { error_code: code } : {}),
137
+ }, { severity: 'error' });
138
+ }
139
+ }
140
+ function webhookResponseMarkerFailedForRetry() {
141
+ return new Response(JSON.stringify({ error: 'booking_access_revoke_marker_failed' }), {
142
+ status: 500,
143
+ headers: { 'Content-Type': 'application/json' },
144
+ });
145
+ }
146
+ async function maybeRevokeBookingAccessForCharge(charge, reason) {
147
+ const piId = typeof charge.payment_intent === 'string'
148
+ ? charge.payment_intent
149
+ : charge.payment_intent?.id ?? null;
150
+ if (!piId)
151
+ return 'skipped';
152
+ let bookingId = null;
153
+ let markerFailed = false;
154
+ try {
155
+ bookingId = await findBookingIdByPaymentIntent(piId);
156
+ if (!bookingId) {
157
+ // Connect: the marker is the only thing blocking self-service credit,
158
+ // so a lookup DB error must be retried by Stripe, not silently acked.
159
+ return connect && bookingLookupErrored ? 'marker_failed' : 'skipped';
160
+ }
161
+ if (connect) {
162
+ // Connect (direct-charge) bookings are refunded outside the app, so
163
+ // nothing cancels the booking: status stays 'paid', the slot stays
164
+ // blocked and door access stays live. Page staff to cancel in admin.
165
+ await logOps(supabase, 'connect_booking_refund_needs_cancel', {
166
+ charge_id: charge.id,
167
+ event_type: event.type,
168
+ reason,
169
+ }, { severity: 'error', bookingId }).catch(() => { });
170
+ }
171
+ const markerAt = new Date().toISOString();
172
+ const { error: markerErr } = await supabase
173
+ .from('bookings')
174
+ .update({ access_revoke_required_at: markerAt })
175
+ .eq('id', bookingId);
176
+ const runInlineRevoke = async () => {
177
+ await revokeBookingOrganizerAccessGrants(supabase, {
178
+ bookingId,
179
+ actingUserId: `system:${systemActorEmail}`,
180
+ reason,
181
+ });
182
+ };
183
+ if (markerErr) {
184
+ markerFailed = true;
185
+ const code = markerErr.code;
186
+ await logOps(supabase, 'booking_access_revoke_marker_failed', {
187
+ ...(typeof code === 'string' ? { error_code: code } : {}),
188
+ }, { severity: 'error', bookingId });
189
+ await runInlineRevoke();
190
+ return 'marker_failed';
191
+ }
192
+ await runInlineRevoke();
193
+ return 'ok';
194
+ }
195
+ catch (e) {
196
+ await logOps(supabase, 'booking_access_revoke_step_failed', {
197
+ reason,
198
+ error_name: errorNameFromUnknown(e),
199
+ }, { severity: 'error', bookingId });
200
+ if (markerFailed)
201
+ return 'marker_failed';
202
+ return 'skipped';
203
+ }
204
+ }
62
205
  // --- Internal coupon helpers (self-serve membership / day-pass checkout) ---
63
206
  // create-subscription-checkout and create-day-pass-checkout reserve a
64
207
  // coupon_redemptions row at session-creation time and stamp its id onto the
@@ -287,7 +430,14 @@ export function createStripeWebhookHandler(config) {
287
430
  const top = anySub.current_period_end;
288
431
  if (typeof top === 'number')
289
432
  return new Date(top * 1000).toISOString();
290
- // Recent Stripe API versions expose the billing period on the subscription item.
433
+ // Recent Stripe API versions expose the billing period on the subscription
434
+ // item instead. Prefer the base (non-addon) item; fall back to the old
435
+ // items.data[0] behavior when findBaseItem can't resolve exactly one
436
+ // (e.g. an addon-only or unexpectedly-shaped subscription) so this never
437
+ // regresses for a shape it used to handle.
438
+ const baseItemCpe = findBaseItem(anySub)?.current_period_end;
439
+ if (typeof baseItemCpe === 'number')
440
+ return new Date(baseItemCpe * 1000).toISOString();
291
441
  const itemCpe = anySub.items?.data?.[0]?.current_period_end;
292
442
  if (typeof itemCpe === 'number')
293
443
  return new Date(itemCpe * 1000).toISOString();
@@ -441,10 +591,16 @@ export function createStripeWebhookHandler(config) {
441
591
  const refCode = sub.metadata?.referral_code;
442
592
  if (!refCode)
443
593
  return; // no referral on this signup -- normal case
594
+ // Allowlist BEFORE any query: a code outside [A-Za-z0-9]{1,32} (e.g. a
595
+ // '*' wildcard) is treated exactly like no referral code at all.
596
+ if (!isValidReferralCode(refCode))
597
+ return;
444
598
  const { data: referrer, error: referrerErr } = await supabase
445
599
  .from('memberships')
446
600
  .select('id')
447
- .eq('referral_code', refCode)
601
+ .ilike('referral_code', escapeLikePattern(refCode))
602
+ .order('id', { ascending: true })
603
+ .limit(1)
448
604
  .maybeSingle();
449
605
  if (referrerErr || !referrer)
450
606
  return; // unresolvable code -- silently skip, never block signup
@@ -1650,7 +1806,32 @@ export function createStripeWebhookHandler(config) {
1650
1806
  // else-if branch further down -- which handles the actual
1651
1807
  // cancelled_* case -- can reuse it without recomputing.
1652
1808
  const bkIsCancelled = bkStatus.startsWith('cancelled_');
1809
+ // Connect-only: non-Connect (GC) completions keep the legacy behavior.
1810
+ const sessionIsPaid = !connect ||
1811
+ session.payment_status === 'paid' || session.payment_status === 'no_payment_required';
1653
1812
  if (booking &&
1813
+ !sessionIsPaid &&
1814
+ bkStatus !== 'paid' &&
1815
+ bkStatus !== 'deposit_paid' &&
1816
+ !bkIsCancelled) {
1817
+ // Delayed-notification payment methods complete the session with
1818
+ // payment_status 'unpaid'; no money has moved, so the booking must
1819
+ // stay pending. Never silent (project invariant).
1820
+ const unpaid = await logOps(supabase, 'booking_session_completed_unpaid', {
1821
+ session_id: session.id,
1822
+ payment_status: session.payment_status ?? null,
1823
+ booking_status: bkStatus,
1824
+ amount_total: session.amount_total ?? null,
1825
+ }, {
1826
+ severity: 'warning',
1827
+ bookingId: booking.id,
1828
+ dedupeKey: `booking_session_completed_unpaid:${booking.id}:${session.id}`,
1829
+ });
1830
+ if (!unpaid.ok) {
1831
+ console.error('[stripe-webhook] unpaid-completion alarm failed to persist', { bookingId: booking.id, sessionId: session.id, error: unpaid.error });
1832
+ }
1833
+ }
1834
+ else if (booking &&
1654
1835
  bkStatus !== 'paid' &&
1655
1836
  bkStatus !== 'deposit_paid' &&
1656
1837
  !bkIsCancelled) {
@@ -1909,6 +2090,14 @@ export function createStripeWebhookHandler(config) {
1909
2090
  console.error('[stripe-webhook] charge.refunded referral clawback step failed', e instanceof Error ? e.message : String(e));
1910
2091
  }
1911
2092
  }
2093
+ // O3(b): organizer grant revoke on refund — gated by CS-GM partial-refund policy.
2094
+ if (shouldRevokeOrganizerGrantsOnStripeChargeRefunded(charge)) {
2095
+ const markerOutcome = await maybeRevokeBookingAccessForCharge(charge, 'charge_refunded');
2096
+ if (markerOutcome === 'marker_failed') {
2097
+ await releaseStripeEventLedgerForRetry(event.id);
2098
+ return webhookResponseMarkerFailedForRetry();
2099
+ }
2100
+ }
1912
2101
  break;
1913
2102
  }
1914
2103
  case 'charge.dispute.created': {
@@ -1918,6 +2107,38 @@ export function createStripeWebhookHandler(config) {
1918
2107
  // charge.dispute.closed below, gated on status === 'lost'.
1919
2108
  const dispute = event.data.object;
1920
2109
  await logOps(supabase, 'referral_dispute_opened_no_action', { dispute_id: dispute.id, charge: typeof dispute.charge === 'string' ? dispute.charge : dispute.charge?.id ?? null }, { severity: 'warning' }).catch(() => { });
2110
+ // O3(b): chargeback opened — revoke organizer access immediately.
2111
+ let bookingIdForDisputeRevoke = null;
2112
+ try {
2113
+ const chargeId = typeof dispute.charge === 'string' ? dispute.charge : dispute.charge?.id ?? null;
2114
+ if (chargeId) {
2115
+ const charge = await stripe.charges.retrieve(chargeId);
2116
+ const piId = typeof charge.payment_intent === 'string'
2117
+ ? charge.payment_intent
2118
+ : charge.payment_intent?.id ?? null;
2119
+ if (piId) {
2120
+ bookingIdForDisputeRevoke = await findBookingIdByPaymentIntent(piId);
2121
+ }
2122
+ const markerOutcome = await maybeRevokeBookingAccessForCharge(charge, 'charge_dispute_created');
2123
+ if (markerOutcome === 'marker_failed') {
2124
+ await releaseStripeEventLedgerForRetry(event.id);
2125
+ return webhookResponseMarkerFailedForRetry();
2126
+ }
2127
+ }
2128
+ }
2129
+ catch (e) {
2130
+ const permanentStripeError = e?.type === 'StripeInvalidRequestError' && !isRetryableStripeError(e);
2131
+ await logOps(supabase, 'booking_access_revoke_step_failed', {
2132
+ reason: 'charge_dispute_created',
2133
+ error_name: errorNameFromUnknown(e),
2134
+ permanent_stripe_error: permanentStripeError,
2135
+ }, { severity: 'error', bookingId: bookingIdForDisputeRevoke });
2136
+ if (connect && !permanentStripeError) {
2137
+ // Marker is the only thing blocking self-service credit on Connect; let Stripe retry.
2138
+ await releaseStripeEventLedgerForRetry(event.id);
2139
+ return webhookResponseMarkerFailedForRetry();
2140
+ }
2141
+ }
1921
2142
  break;
1922
2143
  }
1923
2144
  case 'charge.dispute.closed': {
@@ -1982,6 +2203,101 @@ export function createStripeWebhookHandler(config) {
1982
2203
  // reschedule's new booking to 'expired' (~15-20 min) BEFORE Stripe's own
1983
2204
  // session expiry fires, so gating on 'pending' alone skipped the unwind.
1984
2205
  if (booking && (booking.status === 'pending' || booking.status === 'expired')) {
2206
+ // Commons lost-booking fix: a stale Checkout Session must not
2207
+ // release a tier-3 booking whose BoldSign agreement is already
2208
+ // `completed` unless the self-serve signed-unpaid policy says
2209
+ // cancel (48h after agreement SENT). Staff-sent deposit agreements
2210
+ // are never policy-eligible and stay protected here.
2211
+ let lookupFailed = false;
2212
+ let completedTier3Agreement = false;
2213
+ let tier3AgreementSentAt = null;
2214
+ let agreementCtx = null;
2215
+ try {
2216
+ const { data: agreementRow, error: agreementErr } = await supabase
2217
+ .from('booking_agreements')
2218
+ .select('status,created_at,sent_by_user_id,sent_by_email')
2219
+ .eq('booking_id', booking.id)
2220
+ .eq('tier', 3)
2221
+ .order('created_at', { ascending: false })
2222
+ .limit(1)
2223
+ .maybeSingle();
2224
+ if (agreementErr)
2225
+ throw agreementErr;
2226
+ const row = agreementRow;
2227
+ completedTier3Agreement = row?.status === 'completed';
2228
+ tier3AgreementSentAt = row?.created_at ?? null;
2229
+ agreementCtx = row
2230
+ ? { sent_by_user_id: row.sent_by_user_id, sent_by_email: row.sent_by_email }
2231
+ : null;
2232
+ }
2233
+ catch (e) {
2234
+ console.error('[stripe-webhook] checkout-expired tier-3 agreement lookup failed', e);
2235
+ lookupFailed = true;
2236
+ }
2237
+ const policyEligible = isCommonsSignedUnpaidPolicyEligible(tier3AgreementSentAt, agreementCtx);
2238
+ const signedUnpaidCancelDue = completedTier3Agreement && policyEligible &&
2239
+ isSignedUnpaidCancelDue(tier3AgreementSentAt, Date.now());
2240
+ const completedTier3StillProtected = completedTier3Agreement &&
2241
+ (!policyEligible || !signedUnpaidCancelDue);
2242
+ if (lookupFailed) {
2243
+ const alarm = await logOps(supabase, 'checkout_expired_lookup_failed', {
2244
+ event_type: event.type,
2245
+ }, {
2246
+ severity: 'error',
2247
+ bookingId: booking.id,
2248
+ dedupeKey: `checkout_expired_lookup_failed:${booking.id}:${event.id}`,
2249
+ });
2250
+ if (!alarm.ok) {
2251
+ console.error('[stripe-webhook] checkout_expired_lookup_failed ops_event failed to persist', alarm.error);
2252
+ }
2253
+ break;
2254
+ }
2255
+ if (completedTier3StillProtected) {
2256
+ const alarm = await logOps(supabase, 'checkout_expired_hold_live', {
2257
+ event_type: event.type,
2258
+ completed_tier3_agreement: true,
2259
+ }, {
2260
+ severity: 'warning',
2261
+ bookingId: booking.id,
2262
+ dedupeKey: `checkout_expired_hold_live:${booking.id}:${event.id}`,
2263
+ });
2264
+ if (!alarm.ok) {
2265
+ console.error('[stripe-webhook] checkout_expired_hold_live ops_event failed to persist', alarm.error);
2266
+ }
2267
+ break;
2268
+ }
2269
+ if (signedUnpaidCancelDue) {
2270
+ const dryRun = readCommonsSignedPaymentLinkDryRun();
2271
+ const result = await cancelUnpaidSignedBooking({ bookingId: booking.id, dryRun }, { supabase, stripe, busCancel, systemActorEmail });
2272
+ if (!result.ok) {
2273
+ console.error('[stripe-webhook] cancelUnpaidSignedBooking check failed', result.reason);
2274
+ await logOps(supabase, 'checkout_expired_lookup_failed', { event_type: event.type, reason: result.reason }, { severity: 'error', bookingId: booking.id,
2275
+ dedupeKey: `checkout_expired_lookup_failed:${booking.id}:${event.id}` }).catch(() => { });
2276
+ }
2277
+ else if (result.action === 'cancelled' && !result.dryRun && result.contactEmail?.trim()) {
2278
+ try {
2279
+ await sendBookingCancelledUnpaidEmailOnce(supabase, {
2280
+ bookingId: booking.id,
2281
+ email: result.contactEmail.trim(),
2282
+ name: result.contactName,
2283
+ roomName: null,
2284
+ bookingDuring: result.bookingDuring,
2285
+ }, {
2286
+ name: siteConfig.operatorName,
2287
+ shortName: siteConfig.operatorShortName,
2288
+ supportEmail: siteConfig.supportEmail,
2289
+ });
2290
+ }
2291
+ catch (e) {
2292
+ console.error('[stripe-webhook] sendBookingCancelledUnpaidEmailOnce threw', e);
2293
+ await logOps(supabase, 'booking_side_effect_failed', { step: 'sendBookingCancelledUnpaidEmailOnce', message: String(e) }, { severity: 'warning', bookingId: booking.id }).catch(() => { });
2294
+ }
2295
+ }
2296
+ else if (result.action !== 'cancelled') {
2297
+ console.log('[stripe-webhook] cancelUnpaidSignedBooking no-op', result.action, result.reason);
2298
+ }
2299
+ break;
2300
+ }
1985
2301
  if (booking.status === 'pending') {
1986
2302
  await supabase.from('bookings').update({ status: 'expired' }).eq('id', booking.id);
1987
2303
  }
@@ -2025,6 +2341,11 @@ export function createStripeWebhookHandler(config) {
2025
2341
  console.error('[stripe-webhook] coupon_reverse failed', e);
2026
2342
  await logOps(supabase, 'coupon_reverse_failed', { message: String(e) }, { severity: 'warning', bookingId: booking.id });
2027
2343
  }
2344
+ // Reached only when signedUnpaidCancelDue is false (handled
2345
+ // above, via cancelUnpaidSignedBooking, if true) -- this is
2346
+ // always the GENERIC release (hold genuinely passed, no
2347
+ // tier-3-agreement protection at all), never the signed-unpaid
2348
+ // Commons case.
2028
2349
  await logOps(supabase, 'payment_failed', { event_type: event.type }, { severity: 'warning', bookingId: booking.id });
2029
2350
  try {
2030
2351
  const { data: cancelInfo } = await supabase
@@ -2229,18 +2550,8 @@ export function createStripeWebhookHandler(config) {
2229
2550
  .select('id');
2230
2551
  if (fipErr)
2231
2552
  console.warn('[stripe-webhook] first_invoice_paid_at write failed', fipErr);
2232
- // Round-3 review finding: isGenuineInvoicePayment is an OR that
2233
- // only blocks a $0 invoice when billing_reason ===
2234
- // 'subscription_create' -- every other billing_reason
2235
- // (subscription_cycle after a 100%-off code, a $0 invoice
2236
- // covered entirely by account balance, etc.) bypasses the
2237
- // amount check entirely. Gate the referral grant itself on a
2238
- // genuinely nonzero amount_paid, separately from
2239
- // first_invoice_paid_at (which has other consumers and should
2240
- // keep its existing, broader semantics).
2241
- if (!fipErr && fipRows && fipRows.length > 0 && (inv.amount_paid ?? 0) > 0) {
2242
- await maybeGrantReferralCredit(supabase, stripe, fipRows[0].id);
2243
- }
2553
+ // Referral crediting is NOT done here any more: gc-io's
2554
+ // referral-qualify-daily job pays it 30 days after signup.
2244
2555
  }
2245
2556
  }
2246
2557
  break;
@@ -173,7 +173,7 @@ export async function handle(req) {
173
173
  const keepIds = new Set();
174
174
  for (const ev of events) {
175
175
  if (shouldSkipEvent(ev, selfIds)) {
176
- if (ev.id && (selfIds.has(ev.id) || ev.extendedProperties?.private?.gc_source === 'gc-connect')) {
176
+ if (ev.id && (selfIds.has(ev.id) || ev.extendedProperties?.private?.gc_source === 'gc-connect' || ev.extendedProperties?.private?.cs_booking_id)) {
177
177
  skippedSelf++;
178
178
  }
179
179
  continue;
@@ -1 +1,3 @@
1
- export declare function handle(req: Request): Promise<Response>;
1
+ export declare function handle(req: Request, operator?: {
2
+ planId?: string | null;
3
+ }): Promise<Response>;
@@ -24,6 +24,7 @@ import { createClient } from '@supabase/supabase-js';
24
24
  import { resolvePortalSession } from '../portalSession.js';
25
25
  import { checkRateLimit } from '../rateLimit.js';
26
26
  import { logOps } from '../ops.js';
27
+ import { hasEntitlement } from '../entitlements.js';
27
28
  const corsHeaders = {
28
29
  'Access-Control-Allow-Origin': '*',
29
30
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -75,7 +76,10 @@ async function findOwnGuest(eventId, email, apiKey) {
75
76
  }
76
77
  return { guest: null };
77
78
  }
78
- export async function handle(req) {
79
+ export async function handle(req,
80
+ // D33 Phase E.1: planId is optional -- absent/unrecognized resolves to the
81
+ // full-featured legacy plan, so every existing caller is unaffected.
82
+ operator = {}) {
79
83
  if (req.method === 'OPTIONS')
80
84
  return new Response('ok', { headers: corsHeaders });
81
85
  if (req.method !== 'POST')
@@ -92,6 +96,9 @@ export async function handle(req) {
92
96
  const ok = await checkRateLimit(admin, 'timetable-event-register', session.email, 15, 600);
93
97
  if (!ok)
94
98
  return json(429, { error: 'rate_limited' });
99
+ if (!hasEntitlement(operator, 'events')) {
100
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'events' });
101
+ }
95
102
  const payload = await req.json().catch(() => ({}));
96
103
  const eventId = typeof payload?.event_id === 'string' ? payload.event_id.trim() : '';
97
104
  const action = payload?.action === 'cancel' ? 'cancel' : 'register';
@@ -1 +1,3 @@
1
- export declare function handle(req: Request): Promise<Response>;
1
+ export declare function handle(req: Request, operator?: {
2
+ planId?: string | null;
3
+ }): Promise<Response>;
@@ -44,6 +44,7 @@ import { z } from 'zod';
44
44
  import { clientIp, checkRateLimit } from '../rateLimit.js';
45
45
  import { resolvePortalSession } from '../portalSession.js';
46
46
  import { logOps } from '../ops.js';
47
+ import { hasEntitlement } from '../entitlements.js';
47
48
  const corsHeaders = {
48
49
  'Access-Control-Allow-Origin': '*',
49
50
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -65,7 +66,10 @@ const TOUCH_PASS_AMOUNT_CENTS = 500; // $5.00 flat -- see plan v7 §2 step 4
65
66
  const Body = z.object({
66
67
  membership_id: z.string().uuid(),
67
68
  });
68
- export async function handle(req) {
69
+ export async function handle(req,
70
+ // D33 Phase E.1: planId is optional -- absent/unrecognized resolves to the
71
+ // full-featured legacy plan, so every existing caller is unaffected.
72
+ operator = {}) {
69
73
  if (req.method === 'OPTIONS')
70
74
  return new Response('ok', { headers: corsHeaders });
71
75
  if (req.method !== 'POST')
@@ -107,6 +111,9 @@ export async function handle(req) {
107
111
  if (!allowlist.has(session.id)) {
108
112
  return json(503, { ok: false, error: 'not_configured' });
109
113
  }
114
+ if (!hasEntitlement(operator, 'access_control')) {
115
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'access_control' });
116
+ }
110
117
  // ---- Body ----------------------------------------------------------------
111
118
  const raw = await req.json().catch(() => ({}));
112
119
  const parsed = Body.safeParse(raw);
@@ -121,7 +128,7 @@ export async function handle(req) {
121
128
  if (buckets.some((ok) => !ok))
122
129
  return json(429, { ok: false, error: 'rate_limited' });
123
130
  // ===========================================================================
124
- // §2 step 1 -- claim-lock the row, keyed on gc-io's own RLS resolution order.
131
+ // §2 step 1 -- claim-lock the row, keyed on this platform's own RLS resolution order.
125
132
  // ===========================================================================
126
133
  // Uses the touch_pass_claim_pending() SQL function (SECURITY DEFINER,
127
134
  // EXECUTE revoked from anon/authenticated, granted only to service_role --
@@ -1,6 +1,6 @@
1
1
  /** Tenant-owned inputs to this function. */
2
2
  export type VoiceBookingConfig = {
3
- /** Spoken/texted business name, e.g. "Granite City Workspaces". */
3
+ /** Spoken/texted business name, e.g. "Acme Coworking". */
4
4
  businessName: string;
5
5
  /** Spoken/texted support phone number, e.g. "(916) 836-0808". */
6
6
  supportPhoneDisplay: string;
@@ -7,9 +7,10 @@ export type VoiceDayPassConfig = {
7
7
  * caller-supplied.
8
8
  */
9
9
  dayPassPlanSlug: string;
10
- /** Spoken/texted business name, e.g. "Granite City Workspaces". */
10
+ /** Spoken/texted business name, e.g. "Acme Coworking". */
11
11
  businessName: string;
12
12
  /** Spoken/texted support phone number, e.g. "(916) 836-0808". */
13
13
  supportPhoneDisplay: string;
14
+ planId?: string | null;
14
15
  };
15
16
  export declare function handle(req: Request, config: VoiceDayPassConfig): Promise<Response>;
@@ -11,6 +11,7 @@ import { createClient } from '@supabase/supabase-js';
11
11
  import { z } from 'zod';
12
12
  import { logOps } from '../ops.js';
13
13
  import { verifyRetellSignature } from '../retellSignature.js';
14
+ import { hasEntitlement } from '../entitlements.js';
14
15
  const Body = z.object({
15
16
  contact_name: z.string().min(1).max(200),
16
17
  contact_email: z.string().email(),
@@ -183,6 +184,9 @@ export async function handle(req, config) {
183
184
  if (!parsed.success)
184
185
  return json(400, { ok: false, error: 'invalid_request' });
185
186
  const { contact_name, contact_email, contact_phone, visit_date, arrival_time, idempotency_key, } = parsed.data;
187
+ if (!hasEntitlement(config, 'day_pass')) {
188
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'day_pass' });
189
+ }
186
190
  const supabaseUrl = Deno.env.get('SUPABASE_URL');
187
191
  const serviceKey = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY');
188
192
  const supabase = createClient(supabaseUrl, serviceKey);
@@ -1 +1,3 @@
1
- export declare function handleVoiceInquiry(req: Request): Promise<Response>;
1
+ export declare function handleVoiceInquiry(req: Request, operator?: {
2
+ planId?: string | null;
3
+ }): Promise<Response>;
@@ -18,6 +18,7 @@ import { clientIp, checkRateLimit } from '../rateLimit.js';
18
18
  import { verifyRetellSignature } from '../retellSignature.js';
19
19
  import { logOps } from '../ops.js';
20
20
  import { syncVoiceInquiryToGhl } from '../ghlVoiceInquiry.js';
21
+ import { hasEntitlement } from '../entitlements.js';
21
22
  const Body = z.object({
22
23
  caller_name: z.string().min(1).max(200), // agent sends "unknown" literal if caller never gave one
23
24
  callback_number: z.string().min(1).max(40),
@@ -57,7 +58,10 @@ function normalizePhone(value) {
57
58
  return `+1${digits}`;
58
59
  return `${plus}${digits}`;
59
60
  }
60
- export async function handleVoiceInquiry(req) {
61
+ export async function handleVoiceInquiry(req,
62
+ // D33 Phase E.1: planId is optional -- absent/unrecognized resolves to the
63
+ // full-featured legacy plan, so every existing caller is unaffected.
64
+ operator = {}) {
61
65
  if (req.method === 'OPTIONS')
62
66
  return new Response('ok', { headers: corsHeaders });
63
67
  // Raw text first: the signature is over the exact bytes sent.
@@ -76,6 +80,9 @@ export async function handleVoiceInquiry(req) {
76
80
  if (!parsed.success)
77
81
  return json(400, { ok: false, error: 'invalid_request' });
78
82
  const { caller_name, callback_number, request_type, reason, preferred_time, call_id, caller_id_number, } = parsed.data;
83
+ if (!hasEntitlement(operator, 'voice_ai')) {
84
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'voice_ai' });
85
+ }
79
86
  const supabase = createClient(Deno.env.get('SUPABASE_URL'), Deno.env.get('SUPABASE_SERVICE_ROLE_KEY'));
80
87
  try {
81
88
  const ipOk = await checkRateLimit(supabase, 'voice-inquiry-ip', clientIp(req), 10, 600);
@@ -153,4 +160,4 @@ export async function handleVoiceInquiry(req) {
153
160
  // real listener — as the deployed edge function entrypoint this module is
154
161
  // always the main module, so the guard is a no-op in production.
155
162
  if (import.meta.main)
156
- Deno.serve(handleVoiceInquiry);
163
+ Deno.serve((req) => handleVoiceInquiry(req));
@@ -4,10 +4,10 @@ export type VoiceMembershipSignupConfig = {
4
4
  * Plan slugs sellable over this phone flow. Everything else in the
5
5
  * operator's catalog (virtual office, private offices, ...) needs a
6
6
  * product decision before it can be sold this way — see the caller's own
7
- * comment for the reasoning behind Granite City's exclusions.
7
+ * comment for the reasoning behind the current tenant's exclusions.
8
8
  */
9
9
  sellablePlanSlugs: readonly string[];
10
- /** Spoken/texted business name, e.g. "Granite City Workspaces". */
10
+ /** Spoken/texted business name, e.g. "Acme Coworking". */
11
11
  businessName: string;
12
12
  /** Spoken/texted support phone number, e.g. "(916) 836-0808". */
13
13
  supportPhoneDisplay: string;
@@ -13,7 +13,7 @@ export type VoiceTourBookingConfig = {
13
13
  * only a longer/shorter config array.
14
14
  */
15
15
  calendars: readonly TourCalendarConfig[];
16
- /** Spoken/texted business name, e.g. "Granite City Workspaces". */
16
+ /** Spoken/texted business name, e.g. "Acme Coworking". */
17
17
  businessName: string;
18
18
  /** Spoken/texted support phone number, e.g. "(916) 836-0808". */
19
19
  supportPhoneDisplay: string;