@simplelayer/graniteer-core 0.3.19 → 0.3.20

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 (40) hide show
  1. package/dist/bookingSource.d.ts +2 -0
  2. package/dist/bookingSource.js +11 -0
  3. package/dist/businessHours.d.ts +11 -0
  4. package/dist/businessHours.js +55 -0
  5. package/dist/connectBookingCharge.d.ts +49 -0
  6. package/dist/connectBookingCharge.js +68 -0
  7. package/dist/functions/admin-create-booking.d.ts +3 -0
  8. package/dist/functions/admin-create-booking.js +15 -2
  9. package/dist/functions/admin-mark-booking-paid.d.ts +6 -1
  10. package/dist/functions/admin-mark-booking-paid.js +27 -3
  11. package/dist/functions/booking-access-revoke-backstop.d.ts +11 -0
  12. package/dist/functions/booking-access-revoke-backstop.js +121 -0
  13. package/dist/functions/booking-access-revoke-door-state.d.ts +22 -0
  14. package/dist/functions/booking-access-revoke-door-state.js +61 -0
  15. package/dist/functions/booking-access-revoke.d.ts +35 -0
  16. package/dist/functions/booking-access-revoke.js +279 -0
  17. package/dist/functions/booking-availability.d.ts +2 -1
  18. package/dist/functions/booking-availability.js +14 -5
  19. package/dist/functions/create-booking.d.ts +5 -0
  20. package/dist/functions/create-booking.js +22 -4
  21. package/dist/functions/manage-booking.d.ts +6 -0
  22. package/dist/functions/manage-booking.js +36 -13
  23. package/dist/functions/reschedule-booking.d.ts +5 -0
  24. package/dist/functions/reschedule-booking.js +39 -2
  25. package/dist/functions/space-availability-range.d.ts +2 -1
  26. package/dist/functions/space-availability-range.js +8 -1
  27. package/dist/functions/stripe-webhook.d.ts +4 -0
  28. package/dist/functions/stripe-webhook.js +193 -2
  29. package/dist/functions/sync-gcal-blackouts.js +1 -1
  30. package/dist/gcalBookingEvents.d.ts +59 -0
  31. package/dist/gcalBookingEvents.js +182 -0
  32. package/dist/gcalSync.d.ts +1 -0
  33. package/dist/gcalSync.js +5 -0
  34. package/dist/pricing.d.ts +10 -2
  35. package/dist/pricing.js +14 -9
  36. package/dist/stripeConnectEvents.d.ts +11 -0
  37. package/dist/stripeConnectEvents.js +37 -0
  38. package/dist/tenant-config.d.ts +8 -0
  39. package/dist/tenant-config.js +24 -0
  40. package/package.json +26 -2
@@ -11,6 +11,8 @@ import { resolveIsMember } from '../membership.js';
11
11
  import { buildRescheduleCreditGrants } from '../rescheduleCredit.js';
12
12
  import { resolveContractTier, loadTier1Terms, insertTier1Agreement, signerIpFrom, signerUserAgentFrom, } from '../tier1Agreement.js';
13
13
  import { JWT } from 'google-auth-library';
14
+ import { writebackBookingCancelled, writebackBookingCreated } from '../gcalBookingEvents.js';
15
+ import { createBookingCheckoutSession, planBookingCharge } from '../connectBookingCharge.js';
14
16
  const corsHeaders = {
15
17
  'Access-Control-Allow-Origin': '*',
16
18
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -134,6 +136,7 @@ export async function handle(req, operator, deps) {
134
136
  isMember,
135
137
  allowDynamic: true,
136
138
  allowFreshDynamic: false,
139
+ notice: operator,
137
140
  carryForward: {
138
141
  list_cents: O.list_amount_cents ?? 0,
139
142
  discount_cents: O.dynamic_discount_cents ?? 0,
@@ -189,15 +192,36 @@ export async function handle(req, operator, deps) {
189
192
  return json(500, { error: 'reserve_failed' });
190
193
  }
191
194
  const NEW_ID = newBk.id;
195
+ // Validate Connect account/fee config BEFORE the original booking is
196
+ // cancelled and credited: a bad config must not destroy a confirmed booking.
197
+ // Nothing is reserved yet (credits/coupon come later), so only the new row
198
+ // needs cleanup.
199
+ const connectPreflight = planBookingCharge(operator, 1);
200
+ if ('error' in connectPreflight) {
201
+ await admin.from('bookings').update({ status: 'expired' }).eq('id', NEW_ID);
202
+ await logOps(admin, 'booking_connect_config_invalid', { error: connectPreflight.error, path: 'reschedule-booking', stage: 'preflight' }, { severity: 'error', bookingId: O.id });
203
+ return json(500, { error: 'payments_misconfigured' });
204
+ }
192
205
  // 6. Guarded cancel of ORIGINAL (paid → cancelled_credited).
193
206
  const { data: cancelled, error: cErr } = await admin
194
207
  .from('bookings')
195
208
  .update({ status: 'cancelled_credited' })
196
209
  .eq('id', O.id)
197
210
  .eq('status', 'paid')
211
+ .is('access_revoke_required_at', null)
198
212
  .select('id');
199
213
  if (cErr || !cancelled || cancelled.length === 0) {
200
214
  await admin.from('bookings').update({ status: 'expired' }).eq('id', NEW_ID);
215
+ if (!cErr) {
216
+ const { data: flagRow } = await admin
217
+ .from('bookings')
218
+ .select('status,access_revoke_required_at')
219
+ .eq('id', O.id)
220
+ .maybeSingle();
221
+ if (flagRow && flagRow.status === 'paid' && flagRow.access_revoke_required_at) {
222
+ return json(409, { error: 'booking_flagged_contact_support' });
223
+ }
224
+ }
201
225
  return json(409, { error: 'already_changed' });
202
226
  }
203
227
  // Issue credit for the amount originally charged, split into up to TWO
@@ -227,6 +251,8 @@ export async function handle(req, operator, deps) {
227
251
  }
228
252
  }
229
253
  }
254
+ // Opt-in, fail-soft: remove the original booking's write-back event.
255
+ await writebackBookingCancelled(operator, room.google_calendar_id, O.id);
230
256
  // Best-effort delete of ORIGINAL calendar event.
231
257
  try {
232
258
  await deleteCalendarEvent(room.google_calendar_id, O.google_event_id);
@@ -491,6 +517,7 @@ export async function handle(req, operator, deps) {
491
517
  catch (e) {
492
518
  await logOps(admin, 'booking_side_effect_failed', { step: 'createCalendarEvent', message: String(e) }, { severity: 'warning', bookingId: NEW_ID });
493
519
  }
520
+ await writebackBookingCreated(operator, eff);
494
521
  }
495
522
  }
496
523
  catch (e) {
@@ -514,12 +541,22 @@ export async function handle(req, operator, deps) {
514
541
  await unwindCarriedCoupon('reschedule_missing_stripe_key');
515
542
  return json(500, { error: 'Payments not configured' });
516
543
  }
544
+ const chargePlan = planBookingCharge(operator, charged);
545
+ if ('error' in chargePlan) {
546
+ await admin.rpc('credit_reservation_release', {
547
+ p_booking_id: NEW_ID,
548
+ p_reason: 'reschedule_payments_misconfigured',
549
+ });
550
+ await unwindCarriedCoupon('reschedule_payments_misconfigured');
551
+ await logOps(admin, 'booking_connect_config_invalid', { error: chargePlan.error, path: 'reschedule-booking' }, { severity: 'error', bookingId: NEW_ID });
552
+ return json(500, { error: 'payments_misconfigured' });
553
+ }
517
554
  const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
518
555
  const origin = req.headers.get('origin');
519
556
  const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
520
557
  const human = formatHumanTime(startUtc, endUtc);
521
558
  try {
522
- const session = await stripe.checkout.sessions.create({
559
+ const session = await createBookingCheckoutSession(stripe, {
523
560
  mode: 'payment',
524
561
  customer_email: O.contact_email,
525
562
  line_items: [{
@@ -536,7 +573,7 @@ export async function handle(req, operator, deps) {
536
573
  cancel_url: token
537
574
  ? `${base}/manage-booking/?token=${encodeURIComponent(token)}`
538
575
  : `${base}/portal/bookings`,
539
- });
576
+ }, chargePlan);
540
577
  await admin
541
578
  .from('bookings')
542
579
  .update({ stripe_session_id: session.id })
@@ -1 +1,2 @@
1
- export declare function handle(req: Request): Promise<Response>;
1
+ import type { NoticeConfig } from '../businessHours.js';
2
+ export declare function handle(req: Request, operator?: NoticeConfig | null): Promise<Response>;
@@ -28,13 +28,14 @@ import { z } from 'zod';
28
28
  import { getBusyRangesDetailed, laWallToUtc } from '../availability.js';
29
29
  import { clientIp, checkRateLimit } from '../rateLimit.js';
30
30
  import { dateRange, nextDateStr, statusForDay } from './dayStatus.js';
31
+ import { earliestBookingStartMs, hasBusinessHoursNotice } from '../businessHours.js';
31
32
  const MAX_RANGE_DAYS = 31;
32
33
  const Body = z.object({
33
34
  start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
34
35
  end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
35
36
  room_ids: z.array(z.string().uuid()).optional(),
36
37
  });
37
- export async function handle(req) {
38
+ export async function handle(req, operator) {
38
39
  if (req.method === 'OPTIONS')
39
40
  return new Response('ok', { headers: corsHeaders });
40
41
  try {
@@ -79,12 +80,18 @@ export async function handle(req) {
79
80
  throw roomsErr;
80
81
  const rooms = (roomsData ?? []);
81
82
  const dates = dateRange(start_date, end_date);
83
+ const noticeFloorMs = hasBusinessHoursNotice(operator) ? earliestBookingStartMs(Date.now(), operator) : null;
82
84
  const results = await Promise.all(rooms.map(async (room) => {
83
85
  const days = await Promise.all(dates.map(async (dateStr) => {
84
86
  const windowStart = laWallToUtc(dateStr, 0, 0).getTime();
85
87
  const windowEnd = laWallToUtc(nextDateStr(dateStr), 0, 0).getTime();
86
88
  const rangeLiteral = `[${new Date(windowStart).toISOString()},${new Date(windowEnd).toISOString()})`;
87
89
  const { busy, unparsed } = await getBusyRangesDetailed(supabase, room.id, rangeLiteral);
90
+ // Opt-in notice window: treat everything before the earliest bookable
91
+ // start as busy so the public calendar never advertises it as open.
92
+ if (noticeFloorMs !== null && noticeFloorMs > windowStart) {
93
+ busy.push([windowStart, Math.min(noticeFloorMs, windowEnd)]);
94
+ }
88
95
  return {
89
96
  date: dateStr,
90
97
  status: statusForDay(room.booking_mode, busy, unparsed, windowStart, windowEnd),
@@ -43,4 +43,8 @@ export interface StripeWebhookConfig {
43
43
  }>;
44
44
  }
45
45
  export declare function createStripeWebhookHandler(config: StripeWebhookConfig): (req: Request) => Promise<Response>;
46
+ export interface StripeConnectWebhookOperator {
47
+ stripeConnectedAccountId: string | null | undefined;
48
+ }
49
+ export declare function createStripeConnectWebhookHandler(config: StripeWebhookConfig & StripeConnectWebhookOperator): (req: Request) => Promise<Response>;
46
50
  export {};
@@ -10,7 +10,16 @@ import { recordReferralFailure, maybeGrantReferralCredit } from '../referralGran
10
10
  import { findBaseItem } from '../membershipSubscriptionItems.js';
11
11
  import { cancelUnpaidSignedBooking, isSignedUnpaidCancelDue, isCommonsSignedUnpaidPolicyEligible, readCommonsSignedPaymentLinkDryRun } from '../commonsSignedUnpaidCancellation.js';
12
12
  import { sendBookingCancelledUnpaidEmailOnce } from '../bookingAgreementEmail.js';
13
+ import { errorNameFromUnknown, revokeBookingOrganizerAccessGrants, shouldRevokeOrganizerGrantsOnStripeChargeRefunded, } from './booking-access-revoke.js';
14
+ import { isValidConnectedAccountId } from '../connectBookingCharge.js';
15
+ import { connectAcceptedOpsKind, gateConnectBookingEvent } from '../stripeConnectEvents.js';
13
16
  export function createStripeWebhookHandler(config) {
17
+ return buildStripeWebhookHandler(config, null);
18
+ }
19
+ export function createStripeConnectWebhookHandler(config) {
20
+ return buildStripeWebhookHandler(config, { accountId: config.stripeConnectedAccountId });
21
+ }
22
+ function buildStripeWebhookHandler(config, connect) {
14
23
  const { systemActorEmail, dayPassPortalRedirectUrl, teamSeatSlug, virtualOfficeSlug, siteConfig, busProvision, busCancel, notifyGhl, createCalendarEvent, handleCommonsDepositSession, sendVirtualOfficeWelcome, sendMembershipWelcome, sendPrivateOfficeWelcome, loadPrivateOfficeBilling, sendTeamSeatWelcome, maybeActivateAgreement, pacificMidnightUtc, maybeConvertTrialGrant, provisionDayPass, cancelDayPass, } = config;
15
24
  // No CORS — this is called by Stripe, not the browser.
16
25
  return async (req) => {
@@ -18,11 +27,16 @@ export function createStripeWebhookHandler(config) {
18
27
  return new Response('Method not allowed', { status: 405 });
19
28
  }
20
29
  const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
21
- const webhookSecret = Deno.env.get('STRIPE_WEBHOOK_SECRET');
30
+ const webhookSecret = connect
31
+ ? Deno.env.get('STRIPE_CONNECT_WEBHOOK_SECRET')
32
+ : Deno.env.get('STRIPE_WEBHOOK_SECRET');
22
33
  if (!stripeKey || !webhookSecret) {
23
34
  return new Response('Webhook not configured', { status: 500 });
24
35
  }
25
- const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
36
+ if (connect && !isValidConnectedAccountId(connect.accountId)) {
37
+ return new Response('Connect webhook not configured', { status: 500 });
38
+ }
39
+ let stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
26
40
  const signature = req.headers.get('stripe-signature');
27
41
  if (!signature)
28
42
  return new Response('Missing signature', { status: 400 });
@@ -36,6 +50,30 @@ export function createStripeWebhookHandler(config) {
36
50
  return new Response('Invalid signature', { status: 400 });
37
51
  }
38
52
  const supabase = createClient(Deno.env.get('SUPABASE_URL'), Deno.env.get('SUPABASE_SERVICE_ROLE_KEY'));
53
+ if (connect) {
54
+ const connectAccountId = connect.accountId;
55
+ const gate = gateConnectBookingEvent(event, connectAccountId);
56
+ const ignoredReason = 'reason' in gate ? gate.reason : null;
57
+ await logOps(supabase, ignoredReason ? 'stripe_connect_event_ignored' : connectAcceptedOpsKind(event.type), {
58
+ event_id: event.id,
59
+ event_type: event.type,
60
+ connected_account_id: event.account ?? null,
61
+ ...(ignoredReason ? { reason: ignoredReason } : {}),
62
+ }, {
63
+ severity: ignoredReason
64
+ ? (ignoredReason === 'account_mismatch' ? 'warning' : 'info')
65
+ : (event.type.startsWith('charge.') ? 'warning' : 'info'),
66
+ }).catch(() => { });
67
+ if (ignoredReason) {
68
+ return new Response(JSON.stringify({ received: true, connect_event: true, ignored: ignoredReason }), {
69
+ headers: { 'Content-Type': 'application/json' }, status: 200,
70
+ });
71
+ }
72
+ stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia', stripeAccount: connectAccountId });
73
+ // Account already verified above; clear it so the platform-only guard below lets this event reach the shared booking logic.
74
+ // Namespace the id so a platform-endpoint ledger row for the same evt_ can never swallow this delivery as a duplicate.
75
+ event = { ...event, id: `connect:${event.id}`, account: undefined };
76
+ }
39
77
  // Idempotency ledger — dedupe Stripe redeliveries.
40
78
  {
41
79
  const { error: ledgerErr } = await supabase
@@ -62,6 +100,101 @@ export function createStripeWebhookHandler(config) {
62
100
  .from('bookings').select('id,status').eq('stripe_session_id', session.id).maybeSingle();
63
101
  return data;
64
102
  }
103
+ async function findBookingIdByPaymentIntent(paymentIntentId) {
104
+ const { data: rows, error } = await supabase
105
+ .from('bookings')
106
+ .select('id')
107
+ .eq('stripe_payment_intent', paymentIntentId)
108
+ .limit(2);
109
+ if (error) {
110
+ const code = error.code;
111
+ await logOps(supabase, 'booking_access_revoke_booking_lookup_failed', {
112
+ payment_intent_id: paymentIntentId,
113
+ ...(typeof code === 'string' ? { error_code: code } : {}),
114
+ }, { severity: 'error', bookingId: null });
115
+ return null;
116
+ }
117
+ const list = (rows ?? []);
118
+ if (list.length > 1) {
119
+ await logOps(supabase, 'booking_access_revoke_booking_lookup_duplicate_pi', {
120
+ payment_intent_id: paymentIntentId,
121
+ match_count: list.length,
122
+ }, { severity: 'error', bookingId: null });
123
+ return null;
124
+ }
125
+ return list[0]?.id ?? null;
126
+ }
127
+ async function releaseStripeEventLedgerForRetry(eventId) {
128
+ const { error } = await supabase.from('stripe_events').delete().eq('event_id', eventId);
129
+ if (error) {
130
+ const code = error.code;
131
+ await logOps(supabase, 'stripe_events_ledger_release_failed', {
132
+ ...(typeof code === 'string' ? { error_code: code } : {}),
133
+ }, { severity: 'error' });
134
+ }
135
+ }
136
+ function webhookResponseMarkerFailedForRetry() {
137
+ return new Response(JSON.stringify({ error: 'booking_access_revoke_marker_failed' }), {
138
+ status: 500,
139
+ headers: { 'Content-Type': 'application/json' },
140
+ });
141
+ }
142
+ async function maybeRevokeBookingAccessForCharge(charge, reason) {
143
+ const piId = typeof charge.payment_intent === 'string'
144
+ ? charge.payment_intent
145
+ : charge.payment_intent?.id ?? null;
146
+ if (!piId)
147
+ return 'skipped';
148
+ let bookingId = null;
149
+ let markerFailed = false;
150
+ try {
151
+ bookingId = await findBookingIdByPaymentIntent(piId);
152
+ if (!bookingId)
153
+ return 'skipped';
154
+ if (connect) {
155
+ // Connect (direct-charge) bookings are refunded outside the app, so
156
+ // nothing cancels the booking: status stays 'paid', the slot stays
157
+ // blocked and door access stays live. Page staff to cancel in admin.
158
+ await logOps(supabase, 'connect_booking_refund_needs_cancel', {
159
+ charge_id: charge.id,
160
+ event_type: event.type,
161
+ reason,
162
+ }, { severity: 'error', bookingId }).catch(() => { });
163
+ }
164
+ const markerAt = new Date().toISOString();
165
+ const { error: markerErr } = await supabase
166
+ .from('bookings')
167
+ .update({ access_revoke_required_at: markerAt })
168
+ .eq('id', bookingId);
169
+ const runInlineRevoke = async () => {
170
+ await revokeBookingOrganizerAccessGrants(supabase, {
171
+ bookingId,
172
+ actingUserId: `system:${systemActorEmail}`,
173
+ reason,
174
+ });
175
+ };
176
+ if (markerErr) {
177
+ markerFailed = true;
178
+ const code = markerErr.code;
179
+ await logOps(supabase, 'booking_access_revoke_marker_failed', {
180
+ ...(typeof code === 'string' ? { error_code: code } : {}),
181
+ }, { severity: 'error', bookingId });
182
+ await runInlineRevoke();
183
+ return 'marker_failed';
184
+ }
185
+ await runInlineRevoke();
186
+ return 'ok';
187
+ }
188
+ catch (e) {
189
+ await logOps(supabase, 'booking_access_revoke_step_failed', {
190
+ reason,
191
+ error_name: errorNameFromUnknown(e),
192
+ }, { severity: 'error', bookingId });
193
+ if (markerFailed)
194
+ return 'marker_failed';
195
+ return 'skipped';
196
+ }
197
+ }
65
198
  // --- Internal coupon helpers (self-serve membership / day-pass checkout) ---
66
199
  // create-subscription-checkout and create-day-pass-checkout reserve a
67
200
  // coupon_redemptions row at session-creation time and stamp its id onto the
@@ -1660,7 +1793,32 @@ export function createStripeWebhookHandler(config) {
1660
1793
  // else-if branch further down -- which handles the actual
1661
1794
  // cancelled_* case -- can reuse it without recomputing.
1662
1795
  const bkIsCancelled = bkStatus.startsWith('cancelled_');
1796
+ // Connect-only: non-Connect (GC) completions keep the legacy behavior.
1797
+ const sessionIsPaid = !connect ||
1798
+ session.payment_status === 'paid' || session.payment_status === 'no_payment_required';
1663
1799
  if (booking &&
1800
+ !sessionIsPaid &&
1801
+ bkStatus !== 'paid' &&
1802
+ bkStatus !== 'deposit_paid' &&
1803
+ !bkIsCancelled) {
1804
+ // Delayed-notification payment methods complete the session with
1805
+ // payment_status 'unpaid'; no money has moved, so the booking must
1806
+ // stay pending. Never silent (project invariant).
1807
+ const unpaid = await logOps(supabase, 'booking_session_completed_unpaid', {
1808
+ session_id: session.id,
1809
+ payment_status: session.payment_status ?? null,
1810
+ booking_status: bkStatus,
1811
+ amount_total: session.amount_total ?? null,
1812
+ }, {
1813
+ severity: 'warning',
1814
+ bookingId: booking.id,
1815
+ dedupeKey: `booking_session_completed_unpaid:${booking.id}:${session.id}`,
1816
+ });
1817
+ if (!unpaid.ok) {
1818
+ console.error('[stripe-webhook] unpaid-completion alarm failed to persist', { bookingId: booking.id, sessionId: session.id, error: unpaid.error });
1819
+ }
1820
+ }
1821
+ else if (booking &&
1664
1822
  bkStatus !== 'paid' &&
1665
1823
  bkStatus !== 'deposit_paid' &&
1666
1824
  !bkIsCancelled) {
@@ -1919,6 +2077,14 @@ export function createStripeWebhookHandler(config) {
1919
2077
  console.error('[stripe-webhook] charge.refunded referral clawback step failed', e instanceof Error ? e.message : String(e));
1920
2078
  }
1921
2079
  }
2080
+ // O3(b): organizer grant revoke on refund — gated by CS-GM partial-refund policy.
2081
+ if (shouldRevokeOrganizerGrantsOnStripeChargeRefunded(charge)) {
2082
+ const markerOutcome = await maybeRevokeBookingAccessForCharge(charge, 'charge_refunded');
2083
+ if (markerOutcome === 'marker_failed') {
2084
+ await releaseStripeEventLedgerForRetry(event.id);
2085
+ return webhookResponseMarkerFailedForRetry();
2086
+ }
2087
+ }
1922
2088
  break;
1923
2089
  }
1924
2090
  case 'charge.dispute.created': {
@@ -1928,6 +2094,31 @@ export function createStripeWebhookHandler(config) {
1928
2094
  // charge.dispute.closed below, gated on status === 'lost'.
1929
2095
  const dispute = event.data.object;
1930
2096
  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(() => { });
2097
+ // O3(b): chargeback opened — revoke organizer access immediately.
2098
+ let bookingIdForDisputeRevoke = null;
2099
+ try {
2100
+ const chargeId = typeof dispute.charge === 'string' ? dispute.charge : dispute.charge?.id ?? null;
2101
+ if (chargeId) {
2102
+ const charge = await stripe.charges.retrieve(chargeId);
2103
+ const piId = typeof charge.payment_intent === 'string'
2104
+ ? charge.payment_intent
2105
+ : charge.payment_intent?.id ?? null;
2106
+ if (piId) {
2107
+ bookingIdForDisputeRevoke = await findBookingIdByPaymentIntent(piId);
2108
+ }
2109
+ const markerOutcome = await maybeRevokeBookingAccessForCharge(charge, 'charge_dispute_created');
2110
+ if (markerOutcome === 'marker_failed') {
2111
+ await releaseStripeEventLedgerForRetry(event.id);
2112
+ return webhookResponseMarkerFailedForRetry();
2113
+ }
2114
+ }
2115
+ }
2116
+ catch (e) {
2117
+ await logOps(supabase, 'booking_access_revoke_step_failed', {
2118
+ reason: 'charge_dispute_created',
2119
+ error_name: errorNameFromUnknown(e),
2120
+ }, { severity: 'error', bookingId: bookingIdForDisputeRevoke });
2121
+ }
1931
2122
  break;
1932
2123
  }
1933
2124
  case 'charge.dispute.closed': {
@@ -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;
@@ -0,0 +1,59 @@
1
+ export interface BookingEventInput {
2
+ calendarId: string;
3
+ bookingId: string;
4
+ startIso: string;
5
+ endIso: string;
6
+ summary: string;
7
+ description?: string;
8
+ location?: string;
9
+ }
10
+ export interface GcalWritebackDeps {
11
+ fetch?: typeof fetch;
12
+ getAccessToken?: () => Promise<string | null>;
13
+ }
14
+ export type WritebackResult = {
15
+ ok: true;
16
+ eventId: string;
17
+ action: 'created' | 'updated' | 'deleted' | 'already_absent';
18
+ } | {
19
+ ok: false;
20
+ reason: 'no_credentials' | 'no_calendar' | 'http_error' | 'exception';
21
+ status?: number;
22
+ detail?: string;
23
+ };
24
+ export declare function eventIdForBooking(bookingId: string): string;
25
+ export declare function createBookingEvent(input: BookingEventInput, deps?: GcalWritebackDeps): Promise<WritebackResult>;
26
+ export declare function updateBookingEvent(input: BookingEventInput, deps?: GcalWritebackDeps): Promise<WritebackResult>;
27
+ export declare function deleteBookingEvent(calendarId: string | null | undefined, bookingId: string, deps?: GcalWritebackDeps): Promise<WritebackResult>;
28
+ export interface WritebackOperator {
29
+ googleCalendarWriteback?: boolean | null;
30
+ }
31
+ export declare function isGcalWritebackEnabled(operator: WritebackOperator | null | undefined): boolean;
32
+ export interface WritebackBookingRow {
33
+ id: string;
34
+ contact_name?: string | null;
35
+ contact_email?: string | null;
36
+ contact_phone?: string | null;
37
+ during: string;
38
+ rooms?: {
39
+ name?: string | null;
40
+ address?: string | null;
41
+ google_calendar_id?: string | null;
42
+ } | null;
43
+ }
44
+ export declare function bookingRowToEventInput(row: WritebackBookingRow): BookingEventInput | null;
45
+ type LogFn = (msg: string, detail: unknown) => void;
46
+ /**
47
+ * Fail-soft create for a paid booking row. Never throws; returns null when the
48
+ * operator flag is off (the default), so callers can invoke it unconditionally.
49
+ */
50
+ export declare function writebackBookingCreated(operator: WritebackOperator | null | undefined, row: WritebackBookingRow, deps?: GcalWritebackDeps, log?: LogFn): Promise<WritebackResult | null>;
51
+ export declare function writebackBookingCancelled(operator: WritebackOperator | null | undefined, calendarId: string | null | undefined, bookingId: string, deps?: GcalWritebackDeps, log?: LogFn): Promise<WritebackResult | null>;
52
+ /**
53
+ * Adapter matching the `createCalendarEvent` dep shape used by create-booking,
54
+ * admin-create-booking, reschedule-booking and stripe-webhook. A tenant wrapper
55
+ * without door hardware can pass this as that dep; it is the only way to cover
56
+ * stripe-webhook's paid path without editing the webhook.
57
+ */
58
+ export declare function makeWritebackCreateCalendarEvent(operator: WritebackOperator, deps?: GcalWritebackDeps): (admin: unknown, row: WritebackBookingRow) => Promise<void>;
59
+ export {};
@@ -0,0 +1,182 @@
1
+ import { JWT } from 'google-auth-library';
2
+ import { parsePgRange } from './availability.js';
3
+ import { CS_BOOKING_ID_KEY } from './gcalSync.js';
4
+ const EVENTS_SCOPE = 'https://www.googleapis.com/auth/calendar.events';
5
+ const CAL_BASE = 'https://www.googleapis.com/calendar/v3/calendars';
6
+ const TZ = 'America/Los_Angeles';
7
+ // Deterministic id (Google allows client ids of [a-v0-9], 5-1024 chars; a UUID's
8
+ // hex digits qualify) so create is idempotent and update/delete need no stored id.
9
+ export function eventIdForBooking(bookingId) {
10
+ return `csb${bookingId.replace(/-/g, '').toLowerCase()}`;
11
+ }
12
+ async function defaultGetAccessToken() {
13
+ const clientEmail = Deno.env.get('GOOGLE_SA_CLIENT_EMAIL');
14
+ const rawKey = Deno.env.get('GOOGLE_SA_PRIVATE_KEY');
15
+ if (!clientEmail || !rawKey)
16
+ return null;
17
+ const jwt = new JWT({ email: clientEmail, key: rawKey.replace(/\\n/g, '\n'), scopes: [EVENTS_SCOPE] });
18
+ const tok = await jwt.getAccessToken();
19
+ return tok?.token ?? null;
20
+ }
21
+ function eventBody(input, includeId) {
22
+ return {
23
+ ...(includeId ? { id: eventIdForBooking(input.bookingId) } : {}),
24
+ summary: input.summary,
25
+ description: input.description,
26
+ location: input.location,
27
+ start: { dateTime: input.startIso, timeZone: TZ },
28
+ end: { dateTime: input.endIso, timeZone: TZ },
29
+ transparency: 'opaque',
30
+ extendedProperties: { private: { [CS_BOOKING_ID_KEY]: input.bookingId } },
31
+ };
32
+ }
33
+ async function call(method, calendarId, eventId, body, deps) {
34
+ const token = await (deps.getAccessToken ?? defaultGetAccessToken)();
35
+ if (!token)
36
+ return { noToken: true, status: 0 };
37
+ const url = `${CAL_BASE}/${encodeURIComponent(calendarId)}/events${eventId ? `/${encodeURIComponent(eventId)}` : ''}`;
38
+ const res = await (deps.fetch ?? fetch)(url, {
39
+ method,
40
+ headers: {
41
+ Authorization: `Bearer ${token}`,
42
+ ...(body ? { 'Content-Type': 'application/json' } : {}),
43
+ },
44
+ body: body ? JSON.stringify(body) : undefined,
45
+ signal: AbortSignal.timeout(15000),
46
+ });
47
+ return { noToken: false, status: res.status };
48
+ }
49
+ const isOk = (s) => s >= 200 && s < 300;
50
+ const noCreds = { ok: false, reason: 'no_credentials' };
51
+ const httpFail = (status) => ({ ok: false, reason: 'http_error', status });
52
+ export async function createBookingEvent(input, deps = {}) {
53
+ if (!input.calendarId)
54
+ return { ok: false, reason: 'no_calendar' };
55
+ try {
56
+ const eventId = eventIdForBooking(input.bookingId);
57
+ const r = await call('POST', input.calendarId, null, eventBody(input, true), deps);
58
+ if (r.noToken)
59
+ return noCreds;
60
+ if (isOk(r.status))
61
+ return { ok: true, eventId, action: 'created' };
62
+ // Deterministic id already exists (retry / duplicate delivery): converge via update.
63
+ if (r.status === 409)
64
+ return await updateBookingEvent(input, deps);
65
+ return httpFail(r.status);
66
+ }
67
+ catch (e) {
68
+ return { ok: false, reason: 'exception', detail: String(e) };
69
+ }
70
+ }
71
+ export async function updateBookingEvent(input, deps = {}) {
72
+ if (!input.calendarId)
73
+ return { ok: false, reason: 'no_calendar' };
74
+ try {
75
+ const eventId = eventIdForBooking(input.bookingId);
76
+ const r = await call('PATCH', input.calendarId, eventId, eventBody(input, false), deps);
77
+ if (r.noToken)
78
+ return noCreds;
79
+ if (isOk(r.status))
80
+ return { ok: true, eventId, action: 'updated' };
81
+ if (r.status === 404) {
82
+ const c = await call('POST', input.calendarId, null, eventBody(input, true), deps);
83
+ if (c.noToken)
84
+ return noCreds;
85
+ return isOk(c.status) ? { ok: true, eventId, action: 'created' } : httpFail(c.status);
86
+ }
87
+ return httpFail(r.status);
88
+ }
89
+ catch (e) {
90
+ return { ok: false, reason: 'exception', detail: String(e) };
91
+ }
92
+ }
93
+ export async function deleteBookingEvent(calendarId, bookingId, deps = {}) {
94
+ if (!calendarId)
95
+ return { ok: false, reason: 'no_calendar' };
96
+ try {
97
+ const eventId = eventIdForBooking(bookingId);
98
+ const r = await call('DELETE', calendarId, eventId, null, deps);
99
+ if (r.noToken)
100
+ return noCreds;
101
+ if (isOk(r.status))
102
+ return { ok: true, eventId, action: 'deleted' };
103
+ if (r.status === 404 || r.status === 410)
104
+ return { ok: true, eventId, action: 'already_absent' };
105
+ return httpFail(r.status);
106
+ }
107
+ catch (e) {
108
+ return { ok: false, reason: 'exception', detail: String(e) };
109
+ }
110
+ }
111
+ export function isGcalWritebackEnabled(operator) {
112
+ return operator?.googleCalendarWriteback === true;
113
+ }
114
+ export function bookingRowToEventInput(row) {
115
+ const calendarId = row.rooms?.google_calendar_id;
116
+ const range = parsePgRange(row.during);
117
+ if (!calendarId || !range)
118
+ return null;
119
+ const who = row.contact_name || row.contact_email || 'Guest';
120
+ const lines = [
121
+ row.contact_name ? `Name: ${row.contact_name}` : null,
122
+ row.contact_email ? `Email: ${row.contact_email}` : null,
123
+ row.contact_phone ? `Phone: ${row.contact_phone}` : null,
124
+ `Booking: ${row.id}`,
125
+ ].filter(Boolean);
126
+ return {
127
+ calendarId,
128
+ bookingId: row.id,
129
+ startIso: new Date(range[0]).toISOString(),
130
+ endIso: new Date(range[1]).toISOString(),
131
+ summary: `${row.rooms?.name ?? 'Booking'} — ${who}`,
132
+ description: lines.join('\n'),
133
+ location: row.rooms?.address ?? undefined,
134
+ };
135
+ }
136
+ const defaultLog = (m, d) => console.warn(m, d);
137
+ /**
138
+ * Fail-soft create for a paid booking row. Never throws; returns null when the
139
+ * operator flag is off (the default), so callers can invoke it unconditionally.
140
+ */
141
+ export async function writebackBookingCreated(operator, row, deps = {}, log = defaultLog) {
142
+ if (!isGcalWritebackEnabled(operator))
143
+ return null;
144
+ try {
145
+ const input = bookingRowToEventInput(row);
146
+ if (!input)
147
+ return { ok: false, reason: 'no_calendar' };
148
+ const res = await createBookingEvent(input, deps);
149
+ if (!res.ok)
150
+ log('[gcalBookingEvents] create failed', { bookingId: row.id, ...res });
151
+ return res;
152
+ }
153
+ catch (e) {
154
+ log('[gcalBookingEvents] create threw', { bookingId: row.id, error: String(e) });
155
+ return { ok: false, reason: 'exception', detail: String(e) };
156
+ }
157
+ }
158
+ export async function writebackBookingCancelled(operator, calendarId, bookingId, deps = {}, log = defaultLog) {
159
+ if (!isGcalWritebackEnabled(operator))
160
+ return null;
161
+ try {
162
+ const res = await deleteBookingEvent(calendarId, bookingId, deps);
163
+ if (!res.ok)
164
+ log('[gcalBookingEvents] delete failed', { bookingId, ...res });
165
+ return res;
166
+ }
167
+ catch (e) {
168
+ log('[gcalBookingEvents] delete threw', { bookingId, error: String(e) });
169
+ return { ok: false, reason: 'exception', detail: String(e) };
170
+ }
171
+ }
172
+ /**
173
+ * Adapter matching the `createCalendarEvent` dep shape used by create-booking,
174
+ * admin-create-booking, reschedule-booking and stripe-webhook. A tenant wrapper
175
+ * without door hardware can pass this as that dep; it is the only way to cover
176
+ * stripe-webhook's paid path without editing the webhook.
177
+ */
178
+ export function makeWritebackCreateCalendarEvent(operator, deps = {}) {
179
+ return async (_admin, row) => {
180
+ await writebackBookingCreated(operator, row, deps);
181
+ };
182
+ }
@@ -5,6 +5,7 @@ export declare function allDayToUtcRange(startDate: string, endDate: string): {
5
5
  endIso: string;
6
6
  };
7
7
  export declare function laMidnightUtc(dateStr: string): Date;
8
+ export declare const CS_BOOKING_ID_KEY = "cs_booking_id";
8
9
  export interface GcalEventStartEnd {
9
10
  dateTime?: string;
10
11
  date?: string;