@simplelayer/graniteer-core 0.1.2 → 0.2.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 (130) hide show
  1. package/index.js +2 -2
  2. package/package.json +73 -2
  3. package/src/agreementCheckout.ts +250 -0
  4. package/src/agreementPortalEmail.ts +128 -0
  5. package/src/billingPortalLinkEmail.ts +117 -0
  6. package/src/bookingAgreementEmail.ts +149 -0
  7. package/src/bookingEffects.ts +388 -0
  8. package/src/busClient.ts +268 -0
  9. package/src/busSignature.ts +71 -0
  10. package/src/checkoutCoupon.test.ts +675 -0
  11. package/src/checkoutCoupon.ts +455 -0
  12. package/src/commonsDeposit.ts +298 -0
  13. package/src/commonsDepositWebhook.ts +237 -0
  14. package/src/dayPassConfirmation.ts +230 -0
  15. package/src/dunningEmails.test.ts +263 -0
  16. package/src/dunningEmails.ts +203 -0
  17. package/src/email-templates/brand.ts +93 -0
  18. package/src/email-templates/magic-link.tsx +59 -0
  19. package/src/email-templates/recovery.tsx +59 -0
  20. package/src/email-templates/signup.tsx +67 -0
  21. package/src/functions/admin-cancel-membership.ts +311 -311
  22. package/src/functions/admin-change-membership-plan.ts +312 -308
  23. package/src/functions/admin-charge-guest-print.ts +229 -229
  24. package/src/functions/admin-correct-booking.ts +333 -333
  25. package/src/functions/admin-create-booking.ts +460 -0
  26. package/src/functions/admin-create-commons-event.ts +244 -244
  27. package/src/functions/admin-debug-boldsign-doc.ts +93 -93
  28. package/src/functions/admin-door-write.ts +272 -272
  29. package/src/functions/admin-issue-day-pass.ts +231 -0
  30. package/src/functions/admin-mark-booking-paid.ts +203 -203
  31. package/src/functions/admin-mint-billing-portal-link.ts +168 -0
  32. package/src/functions/admin-mint-portal-link.ts +62 -0
  33. package/src/functions/admin-photo-upload.ts +128 -128
  34. package/src/functions/admin-remove-team-member.ts +150 -150
  35. package/src/functions/admin-request-trial.ts +366 -0
  36. package/src/functions/admin-resend-commons-deposit-link.ts +323 -0
  37. package/src/functions/admin-reset-mfa.ts +138 -138
  38. package/src/functions/admin-retry-invoice-payment.test.ts +567 -0
  39. package/src/functions/admin-retry-invoice-payment.ts +333 -0
  40. package/src/functions/admin-reverse-coupon-redemption.ts +98 -98
  41. package/src/functions/admin-revoke-agreement.ts +467 -0
  42. package/src/functions/admin-send-commons-agreement.ts +214 -214
  43. package/src/functions/admin-set-credit-amount.ts +123 -123
  44. package/src/functions/admin-skip-commons-contract.ts +165 -165
  45. package/src/functions/admin-undo-membership-cancel.ts +144 -144
  46. package/src/functions/admin-wall-photo-write.ts +141 -141
  47. package/src/functions/auth-email-hook.ts +259 -0
  48. package/src/functions/boldsign-sender-identity.ts +114 -114
  49. package/src/functions/booking-availability.ts +419 -419
  50. package/src/functions/booking-member-preview.ts +136 -136
  51. package/src/functions/booking-status.ts +149 -0
  52. package/src/functions/conductor.ts +505 -0
  53. package/src/functions/create-agreement.ts +537 -0
  54. package/src/functions/create-booking.ts +648 -0
  55. package/src/functions/create-day-pass-checkout.ts +218 -0
  56. package/src/functions/create-portal-session.ts +142 -0
  57. package/src/functions/create-subscription-checkout.test.ts +222 -0
  58. package/src/functions/create-subscription-checkout.ts +440 -0
  59. package/src/functions/day-pass-status.ts +89 -89
  60. package/src/functions/diag-webpush-test.ts +45 -45
  61. package/src/functions/event-access-admin.ts +277 -0
  62. package/src/functions/event-access-store.ts +334 -309
  63. package/src/functions/ezeep-print-webhook.ts +213 -213
  64. package/src/functions/ezeep-usage-reconcile.ts +299 -299
  65. package/src/functions/fetch-avatar-original.ts +457 -0
  66. package/src/functions/get-provider-sign-link.ts +155 -0
  67. package/src/functions/get-signing-link.ts +211 -211
  68. package/src/functions/guest-print-setup-confirm.ts +128 -128
  69. package/src/functions/guest-print-submit.ts +149 -149
  70. package/src/functions/luma-webhook.ts +165 -165
  71. package/src/functions/manage-booking.ts +472 -0
  72. package/src/functions/mcp.ts +67 -0
  73. package/src/functions/member-door-action.test.ts +1248 -0
  74. package/src/functions/member-door-action.ts +863 -0
  75. package/src/functions/member-unifi-mapping.test.ts +516 -0
  76. package/src/functions/member-unifi-mapping.ts +206 -0
  77. package/src/functions/membership-door-sync.ts +956 -0
  78. package/src/functions/migration-collision-alert.copy.ts +232 -232
  79. package/src/functions/migration-collision-alert.test.ts +349 -349
  80. package/src/functions/migration-collision-alert.ts +232 -232
  81. package/src/functions/office-assignment-end.ts +146 -146
  82. package/src/functions/portal-booking-access.ts +217 -95
  83. package/src/functions/portal-list-invoices.ts +99 -99
  84. package/src/functions/portal-request-login.ts +192 -0
  85. package/src/functions/portal-resend-invite.ts +248 -0
  86. package/src/functions/portal-submit-event.ts +168 -0
  87. package/src/functions/print-billing-recover.ts +97 -97
  88. package/src/functions/print-billing-run.ts +183 -183
  89. package/src/functions/public-facts.ts +168 -168
  90. package/src/functions/push-send.ts +348 -0
  91. package/src/functions/push-test.ts +234 -0
  92. package/src/functions/request-portal-link.ts +211 -0
  93. package/src/functions/reschedule-booking.ts +649 -0
  94. package/src/functions/review-ratings.ts +113 -0
  95. package/src/functions/space-availability-range.acceptance.test.ts +161 -161
  96. package/src/functions/space-availability-range.ts +142 -142
  97. package/src/functions/stripe-db-reconcile.ts +319 -0
  98. package/src/functions/stripe-webhook.moved-regression.test.ts +78 -0
  99. package/src/functions/stripe-webhook.ts +2595 -0
  100. package/src/functions/sync-gcal-blackouts.ts +298 -298
  101. package/src/functions/timetable-event-register.ts +162 -162
  102. package/src/functions/timetable-event-status.ts +90 -90
  103. package/src/functions/timetable-spaces.ts +219 -219
  104. package/src/functions/touch-pass-reconciler.ts +689 -689
  105. package/src/functions/touch-pass-signup.ts +478 -0
  106. package/src/functions/upload-booking-display-image.ts +179 -0
  107. package/src/functions/virtual-onboarding-purge.ts +134 -134
  108. package/src/functions/virtual-onboarding-submit.ts +315 -315
  109. package/src/functions/voice-booking.ts +453 -0
  110. package/src/functions/voice-day-pass.ts +346 -0
  111. package/src/functions/voice-inquiry.test.ts +301 -301
  112. package/src/functions/voice-inquiry.ts +198 -198
  113. package/src/functions/voice-membership-signup.ts +355 -0
  114. package/src/functions/voice-tour-availability.ts +204 -204
  115. package/src/functions/voice-tour-booking.ts +429 -0
  116. package/src/ghlEventInquiry.ts +143 -0
  117. package/src/mailArrivalEmail.ts +121 -0
  118. package/src/manageToken.ts +363 -0
  119. package/src/membershipBusClient.ts +537 -0
  120. package/src/membershipWelcome.ts +683 -0
  121. package/src/migrationCheckout.ts +366 -0
  122. package/src/pacificDate.ts +54 -0
  123. package/src/paymentLinkEmail.ts +123 -0
  124. package/src/signedUnpaidReminderEmail.test.ts +246 -0
  125. package/src/signedUnpaidReminderEmail.ts +132 -0
  126. package/src/stripeCoworkingPortal.ts +91 -0
  127. package/src/supabaseTestFakes.ts +131 -131
  128. package/src/supportTicketEmail.ts +119 -0
  129. package/src/unifiAccessPolicies.ts +228 -0
  130. package/src/unifiGroups.ts +129 -0
@@ -0,0 +1,649 @@
1
+ import { createClient } from 'npm:@supabase/supabase-js@2';
2
+ import Stripe from 'npm:stripe@17.5.0';
3
+ import { z } from 'npm:zod@3.23.8';
4
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
5
+ import { verifyManageToken } from 'npm:@simplelayer/graniteer-core/manageToken';
6
+ import { resolvePortalSessionEmail } from 'npm:@simplelayer/graniteer-core/portalSession';
7
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
8
+ import { reclaimStaleHoldsExceptCompletedTier3 } from 'npm:@simplelayer/graniteer-core/bookingHoldReclaim';
9
+ import {
10
+ validateAndPriceForRoom,
11
+ formatHumanTime,
12
+ type RoomForPricing,
13
+ } from 'npm:@simplelayer/graniteer-core/pricing';
14
+ import { resolveIsMember } from 'npm:@simplelayer/graniteer-core/membership';
15
+ import { buildRescheduleCreditGrants } from 'npm:@simplelayer/graniteer-core/rescheduleCredit';
16
+ import {
17
+ resolveContractTier,
18
+ loadTier1Terms,
19
+ insertTier1Agreement,
20
+ signerIpFrom,
21
+ signerUserAgentFrom,
22
+ } from 'npm:@simplelayer/graniteer-core/tier1Agreement';
23
+ import { JWT } from 'npm:google-auth-library@9';
24
+
25
+ const corsHeaders = {
26
+ 'Access-Control-Allow-Origin': '*',
27
+ 'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
28
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
29
+ };
30
+
31
+ const STRIPE_MIN_CHARGE_CENTS = 50;
32
+
33
+ const Body = z.object({
34
+ token: z.string().min(1).optional(),
35
+ booking_id: z.string().uuid().optional(),
36
+ start: z.string().datetime().optional(),
37
+ end: z.string().datetime().optional(),
38
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
39
+ day_mode: z.enum(['full', 'half_am', 'half_pm']).optional(),
40
+ });
41
+
42
+ function json(status: number, body: unknown) {
43
+ return new Response(JSON.stringify(body), {
44
+ status,
45
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
46
+ });
47
+ }
48
+
49
+ // Best-effort delete of the ORIGINAL booking's Google Calendar event.
50
+ async function deleteCalendarEvent(calendarId: string | null, eventId: string | null) {
51
+ const clientEmail = Deno.env.get('GOOGLE_SA_CLIENT_EMAIL');
52
+ const rawKey = Deno.env.get('GOOGLE_SA_PRIVATE_KEY');
53
+ if (!clientEmail || !rawKey || !calendarId || !eventId) return;
54
+ try {
55
+ const privateKey = rawKey.replace(/\\n/g, '\n');
56
+ const jwt = new JWT({ email: clientEmail, key: privateKey, scopes: ['https://www.googleapis.com/auth/calendar.events'] });
57
+ const tok = await jwt.getAccessToken();
58
+ if (!tok?.token) return;
59
+ const url = `https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(calendarId)}/events/${encodeURIComponent(eventId)}`;
60
+ await fetch(url, { method: 'DELETE', headers: { Authorization: `Bearer ${tok.token}` } });
61
+ } catch (e) {
62
+ console.warn('[reschedule-booking] calendar delete failed', e);
63
+ }
64
+ }
65
+
66
+ // Loose row shape covering just the fields reschedule-booking's side effects
67
+ // actually read - matches gc-connect's local _shared/bookingEffects.ts
68
+ // BookingRow, which stays in gc-connect (not moved this phase).
69
+ interface EffectsBookingRow {
70
+ id: string;
71
+ contact_name: string | null;
72
+ contact_email: string;
73
+ contact_phone: string | null;
74
+ during: string;
75
+ charged_amount_cents?: number | null;
76
+ list_amount_cents?: number | null;
77
+ google_event_id?: string | null;
78
+ ghl_contact_id?: string | null;
79
+ rooms: {
80
+ id?: string;
81
+ name: string;
82
+ address?: string | null;
83
+ google_calendar_id?: string | null;
84
+ slug: string | null;
85
+ usage_instructions?: string | null;
86
+ } | null;
87
+ }
88
+
89
+ // The gc-connect wrapper imports these from its own local _shared/bookingEffects.ts
90
+ // and _shared/busClient.ts (FTW-middleware-specific integrations, out of scope
91
+ // for this phase) and passes them through unchanged.
92
+ export interface RescheduleBookingDeps {
93
+ notifyGhl: (admin: unknown, row: EffectsBookingRow, doorAccess: unknown) => Promise<void>;
94
+ createCalendarEvent: (admin: unknown, row: EffectsBookingRow) => Promise<void>;
95
+ parseTstzRange: (range: string) => { startISO: string; endISO: string } | null;
96
+ busProvision: (
97
+ input: {
98
+ bookingId: string;
99
+ roomKey: string;
100
+ startUtc: string;
101
+ endUtc: string;
102
+ customer: { name?: string; email: string; phone?: string };
103
+ },
104
+ admin: unknown,
105
+ ) => Promise<Record<string, unknown> | null>;
106
+ busCancel: (
107
+ input: { bookingId: string; roomKey: string; startUtc: string; endUtc: string },
108
+ admin: unknown,
109
+ ) => Promise<unknown>;
110
+ extractDoorAccess: (busResp: Record<string, unknown> | null) => unknown;
111
+ }
112
+
113
+ export async function handle(req: Request, operator: { domain: string; actorEmail: string }, deps: RescheduleBookingDeps): Promise<Response> {
114
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
115
+ if (req.method !== 'POST') return json(405, { error: 'method_not_allowed' });
116
+
117
+ const SUPABASE_URL = Deno.env.get('SUPABASE_URL')!;
118
+ const SERVICE_ROLE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!;
119
+ const secret = Deno.env.get('MANAGE_TOKEN_SECRET');
120
+ if (!secret) return json(500, { error: 'not_configured' });
121
+ const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
122
+ auth: { persistSession: false, autoRefreshToken: false },
123
+ });
124
+
125
+ // Rate-limit BEFORE any DB work (same pattern as manage-booking).
126
+ const ip = clientIp(req);
127
+ const ipOk = await checkRateLimit(admin, 'reschedule-booking-ip', ip, 30, 300);
128
+ if (!ipOk) return json(429, { error: 'rate_limited' });
129
+
130
+ const raw = await req.json().catch(() => ({}));
131
+ const parsed = Body.safeParse(raw);
132
+ if (!parsed.success) return json(400, { error: parsed.error.flatten() });
133
+ const { token } = parsed.data;
134
+
135
+ // Two accepted auth modes, resolving to the same (bookingId, authedEmail):
136
+ // 1. HMAC manage token (emailed link) — unchanged, still the default.
137
+ // 2. Member-portal session: Authorization: Bearer <jwt> + booking_id.
138
+ let bookingId = '';
139
+ let authedEmail = '';
140
+ if (token) {
141
+ const payload = await verifyManageToken(token, secret);
142
+ if (!payload) return json(401, { error: 'invalid_or_expired_token' });
143
+ bookingId = payload.bid;
144
+ authedEmail = payload.eml;
145
+ } else {
146
+ const sessionEmail = await resolvePortalSessionEmail(req, admin);
147
+ if (!sessionEmail || !parsed.data.booking_id) {
148
+ return json(401, { error: 'invalid_or_expired_token' });
149
+ }
150
+ bookingId = parsed.data.booking_id;
151
+ authedEmail = sessionEmail;
152
+ }
153
+
154
+ const bidOk = await checkRateLimit(admin, 'reschedule-booking-bid', bookingId, 30, 300);
155
+ if (!bidOk) return json(429, { error: 'rate_limited' });
156
+
157
+ // 1. Load ORIGINAL booking + room.
158
+ const { data: origRaw, error: oErr } = await admin
159
+ .from('bookings')
160
+ .select('id,status,contact_email,contact_name,contact_phone,ghl_contact_id,is_member,during,charged_amount_cents,credit_applied_cents,discount_applied_cents,list_amount_cents,dynamic_discount_cents,dynamic_discount_rule_type,google_event_id,rooms(id,name,slug,address,google_calendar_id,booking_mode,hourly_cents,day_cents,half_day_cents,min_booking_minutes,active,dynamic_pricing_eligible,half_day_am_start,half_day_am_end,half_day_pm_start,half_day_pm_end,half_day_days_of_week)')
161
+ .eq('id', bookingId)
162
+ .maybeSingle();
163
+ if (oErr) return json(500, { error: 'lookup_failed' });
164
+ if (!origRaw) return json(404, { error: 'not_found' });
165
+ // deno-lint-ignore no-explicit-any
166
+ const O: any = origRaw;
167
+ if ((O.contact_email ?? '').toLowerCase() !== authedEmail.toLowerCase()) {
168
+ return json(401, { error: 'invalid_or_expired_token' });
169
+ }
170
+
171
+ // 2. Must be paid.
172
+ if (O.status !== 'paid') {
173
+ return json(409, { error: 'already_changed', status: O.status });
174
+ }
175
+
176
+ // 3. >48h before start only.
177
+ const parsedRange = deps.parseTstzRange(O.during);
178
+ if (!parsedRange) return json(500, { error: 'bad_time_range' });
179
+ const origStartMs = new Date(parsedRange.startISO).getTime();
180
+ const nowMs = Date.now();
181
+ if ((origStartMs - nowMs) < 48 * 60 * 60 * 1000) {
182
+ return json(400, { error: 'too_late_to_reschedule' });
183
+ }
184
+
185
+ // 4. Validate + price NEW slot (same room, via shared pricing).
186
+ const room = O.rooms as RoomForPricing & { slug: string | null; address: string | null; google_calendar_id: string | null };
187
+ if (!room) return json(500, { error: 'room_missing' });
188
+ // Server-authoritative membership lookup — fresh, by the original booking's email.
189
+ const isMember = await resolveIsMember(admin, O.contact_email ?? '');
190
+ const priced = await validateAndPriceForRoom(admin, room, parsed.data, nowMs, {
191
+ isMember,
192
+ allowDynamic: true,
193
+ allowFreshDynamic: false,
194
+ carryForward: {
195
+ list_cents: O.list_amount_cents ?? 0,
196
+ discount_cents: O.dynamic_discount_cents ?? 0,
197
+ rule_type: (O.dynamic_discount_rule_type as string | null) ?? null,
198
+ },
199
+ });
200
+ if (!priced.ok) return json(priced.status, { error: priced.error });
201
+ const P = priced.price_cents;
202
+ const { startUtc, endUtc, rangeLiteral } = priced;
203
+ const dynamic_discount_cents = priced.dynamic_discount_cents;
204
+ const dynamic_discount_rule_type = priced.dynamic_discount_rule_type;
205
+ const list_rule_type = priced.list_rule_type;
206
+ const net = P - dynamic_discount_cents;
207
+
208
+ if ((O.dynamic_discount_cents ?? 0) > 0) {
209
+ await logOps(admin, 'reschedule_discount_carried_forward', {
210
+ original_booking_id: O.id,
211
+ original_list_cents: O.list_amount_cents ?? 0,
212
+ original_discount_cents: O.dynamic_discount_cents ?? 0,
213
+ new_list_cents: P,
214
+ applied_discount_cents: dynamic_discount_cents,
215
+ rule_type: dynamic_discount_rule_type,
216
+ }, { severity: 'info', bookingId: O.id }).catch(() => {});
217
+ }
218
+
219
+ // 5. Reserve NEW slot with a 1-hour pending hold.
220
+ await reclaimStaleHoldsExceptCompletedTier3(admin, room.id, rangeLiteral);
221
+
222
+ const holdExpires = new Date(Date.now() + 60 * 60 * 1000).toISOString();
223
+ const { data: newBk, error: iErr } = await admin
224
+ .from('bookings')
225
+ .insert({
226
+ room_id: room.id,
227
+ during: rangeLiteral,
228
+ status: 'pending',
229
+ hold_expires_at: holdExpires,
230
+ list_amount_cents: P,
231
+ dynamic_discount_cents,
232
+ dynamic_discount_rule_type,
233
+ list_rule_type,
234
+ contact_email: (O.contact_email ?? '').toLowerCase(),
235
+ contact_name: O.contact_name,
236
+ contact_phone: O.contact_phone ?? null,
237
+ ghl_contact_id: O.ghl_contact_id ?? null,
238
+ is_member: isMember,
239
+ policy_accepted_at: new Date().toISOString(),
240
+ })
241
+ .select('id')
242
+ .single();
243
+ if (iErr) {
244
+ // deno-lint-ignore no-explicit-any
245
+ if ((iErr as any).code === '23P01') return json(409, { error: 'slot_taken' });
246
+ console.error('[reschedule-booking] new booking insert failed', iErr);
247
+ return json(500, { error: 'reserve_failed' });
248
+ }
249
+ const NEW_ID = newBk.id;
250
+
251
+ // 6. Guarded cancel of ORIGINAL (paid → cancelled_credited).
252
+ const { data: cancelled, error: cErr } = await admin
253
+ .from('bookings')
254
+ .update({ status: 'cancelled_credited' })
255
+ .eq('id', O.id)
256
+ .eq('status', 'paid')
257
+ .select('id');
258
+ if (cErr || !cancelled || cancelled.length === 0) {
259
+ await admin.from('bookings').update({ status: 'expired' }).eq('id', NEW_ID);
260
+ return json(409, { error: 'already_changed' });
261
+ }
262
+
263
+ // Issue credit for the amount originally charged, split into up to TWO
264
+ // separate grants so a reschedule can never launder a short-lived credit
265
+ // into a longer-lived one (see _shared/rescheduleCredit.ts).
266
+ {
267
+ const defaultExp = new Date();
268
+ defaultExp.setUTCFullYear(defaultExp.getUTCFullYear() + 1);
269
+
270
+ const { grants, expiryLookupErrored, expiryLookupDetail, expirySource } =
271
+ await buildRescheduleCreditGrants(admin, {
272
+ bookingId: O.id,
273
+ contactEmail: O.contact_email ?? '',
274
+ ghlContactId: O.ghl_contact_id ?? null,
275
+ cashPortionCents: O.charged_amount_cents ?? 0,
276
+ creditPortionCents: O.credit_applied_cents ?? 0,
277
+ defaultExp,
278
+ });
279
+ if (expiryLookupErrored) {
280
+ await logOps(admin, 'reschedule_orig_credit_expiry_lookup_failed',
281
+ { message: expiryLookupDetail, source: expirySource, credit_applied_cents: O.credit_applied_cents ?? 0 },
282
+ { severity: 'error', bookingId: O.id }).catch(() => {});
283
+ }
284
+
285
+ if (grants.length > 0) {
286
+ const { error: creditErr } = await admin.from('credits').insert(grants);
287
+ if (creditErr) {
288
+ await admin.from('bookings').update({ status: 'paid' }).eq('id', O.id);
289
+ await admin.from('bookings').update({ status: 'expired' }).eq('id', NEW_ID);
290
+ await logOps(admin, 'reschedule_credit_insert_failed',
291
+ { message: creditErr.message },
292
+ { severity: 'error', bookingId: O.id });
293
+ return json(500, { error: 'credit_insert_failed' });
294
+ }
295
+ }
296
+ }
297
+
298
+ // Best-effort delete of ORIGINAL calendar event.
299
+ try {
300
+ await deleteCalendarEvent(room.google_calendar_id, O.google_event_id);
301
+ if (O.google_event_id) {
302
+ await admin.from('bookings').update({ google_event_id: null }).eq('id', O.id);
303
+ }
304
+ } catch (e) {
305
+ await logOps(admin, 'reschedule_calendar_delete_failed',
306
+ { message: String(e) },
307
+ { severity: 'warning', bookingId: O.id });
308
+ }
309
+
310
+ // Bus: cancel the ORIGINAL booking (post-commit; never break the caller).
311
+ try {
312
+ const origRange = deps.parseTstzRange(O.during);
313
+ const origSlug = room.slug ?? null;
314
+ if (origRange && origSlug) {
315
+ await deps.busCancel({
316
+ bookingId: O.id,
317
+ roomKey: origSlug,
318
+ startUtc: origRange.startISO,
319
+ endUtc: origRange.endISO,
320
+ }, admin);
321
+ } else {
322
+ console.log('[reschedule-booking] busCancel skipped (missing slug/range)', O.id);
323
+ }
324
+ } catch { /* never break the caller */ }
325
+
326
+ // 7. Compute available credit balance for this email.
327
+ const emailLower = (O.contact_email ?? '').toLowerCase();
328
+ const { data: availableRaw, error: avErr } = await admin
329
+ .from('credits')
330
+ .select('id,delta_cents,expires_at,contact_email')
331
+ .ilike('contact_email', emailLower)
332
+ .eq('entry_type', 'grant')
333
+ .is('redeemed_at', null)
334
+ .is('redeemed_booking_id', null);
335
+ if (avErr) {
336
+ console.error('[reschedule-booking] credits read failed', avErr);
337
+ return json(500, { error: 'credits_lookup_failed' });
338
+ }
339
+ const available = (availableRaw ?? []).filter(
340
+ (c) => (c.contact_email ?? '').toLowerCase() === emailLower,
341
+ );
342
+ const nowIso = new Date();
343
+ const usable = (available ?? []).filter((c) => !c.expires_at || new Date(c.expires_at) > nowIso);
344
+ const balance = usable.reduce((s, c) => s + (c.delta_cents ?? 0), 0);
345
+ const credit_applied = Math.min(net, balance);
346
+
347
+ // 7b. Coupon carry-forward (F3).
348
+ const coupon_base = Math.max(0, net - credit_applied);
349
+ let coupon_carried = 0;
350
+ let transferredRedemptionId: string | null = null;
351
+ const unwindCarriedCoupon = async (reason: string) => {
352
+ if (!transferredRedemptionId) return;
353
+ try {
354
+ await admin.rpc('coupon_reverse', {
355
+ p_redemption_id: transferredRedemptionId,
356
+ p_reason: reason,
357
+ p_actor_email: operator.actorEmail,
358
+ });
359
+ } catch { /* best effort */ }
360
+ };
361
+ {
362
+ const { data: redRow } = await admin
363
+ .from('coupon_redemptions')
364
+ .select('id,amount_applied_cents,status')
365
+ .eq('applied_to_type', 'booking')
366
+ .eq('applied_to_id', O.id)
367
+ .in('status', ['applied', 'reserved'])
368
+ .maybeSingle();
369
+ if (redRow) {
370
+ const orig_base = (O.charged_amount_cents ?? 0) + (O.discount_applied_cents ?? 0);
371
+ const amt = redRow.amount_applied_cents ?? 0;
372
+ const cap = orig_base > 0
373
+ ? Math.min(coupon_base, Math.round((coupon_base * amt) / orig_base))
374
+ : Math.min(coupon_base, amt);
375
+ try {
376
+ const { data: moved, error: mvErr } = await admin.rpc('coupon_transfer_redemption', {
377
+ p_redemption_id: redRow.id,
378
+ p_new_booking_id: NEW_ID,
379
+ p_max_amount_cents: Math.max(0, cap),
380
+ p_new_idempotency_key: `coupon:${NEW_ID}`,
381
+ });
382
+ if (mvErr) throw mvErr;
383
+ // deno-lint-ignore no-explicit-any
384
+ coupon_carried = ((moved as any)?.amount_applied_cents ?? 0) as number;
385
+ transferredRedemptionId = redRow.id;
386
+ await logOps(admin, 'reschedule_coupon_carried_forward', {
387
+ original_booking_id: O.id,
388
+ redemption_id: redRow.id,
389
+ original_amount_cents: amt,
390
+ carried_amount_cents: coupon_carried,
391
+ orig_base_cents: orig_base,
392
+ new_base_cents: coupon_base,
393
+ }, { severity: 'info', bookingId: NEW_ID }).catch(() => {});
394
+ } catch (e) {
395
+ coupon_carried = 0;
396
+ transferredRedemptionId = null;
397
+ try {
398
+ await admin.rpc('coupon_reverse', {
399
+ p_redemption_id: redRow.id,
400
+ p_reason: 'reschedule_carry_failed',
401
+ p_actor_email: operator.actorEmail,
402
+ });
403
+ } catch { /* logged below */ }
404
+ await logOps(admin, 'reschedule_coupon_carry_failed', {
405
+ original_booking_id: O.id,
406
+ redemption_id: redRow.id,
407
+ message: String(e),
408
+ }, { severity: 'error', bookingId: NEW_ID }).catch(() => {});
409
+ }
410
+ }
411
+ }
412
+
413
+ let charged = coupon_base - coupon_carried;
414
+ let stripe_floor = 0;
415
+ if (charged > 0 && charged < STRIPE_MIN_CHARGE_CENTS) { stripe_floor = charged; charged = 0; }
416
+ const discount_applied = coupon_carried + stripe_floor;
417
+ if (charged < 0) {
418
+ await logOps(admin, 'reschedule_negative_charge',
419
+ { P, net, dynamic_discount_cents, balance, credit_applied, coupon_carried },
420
+ { severity: 'error', bookingId: NEW_ID });
421
+ await unwindCarriedCoupon('reschedule_negative_charge');
422
+ return json(500, { error: 'internal_price_error' });
423
+ }
424
+
425
+ // 8. Set NEW.credit_applied_cents.
426
+ await admin
427
+ .from('bookings')
428
+ .update({ credit_applied_cents: credit_applied, discount_applied_cents: discount_applied })
429
+ .eq('id', NEW_ID);
430
+
431
+ // 9. RESERVE credits: soonest-expiring first, accumulate until >= credit_applied.
432
+ usable.sort((a, b) => {
433
+ const ae = a.expires_at ? new Date(a.expires_at).getTime() : Number.POSITIVE_INFINITY;
434
+ const be = b.expires_at ? new Date(b.expires_at).getTime() : Number.POSITIVE_INFINITY;
435
+ return ae - be;
436
+ });
437
+ const reservedIds: string[] = [];
438
+ let reserved_total = 0;
439
+ for (const c of usable) {
440
+ if (reserved_total >= credit_applied) break;
441
+ reservedIds.push(c.id);
442
+ reserved_total += c.delta_cents ?? 0;
443
+ }
444
+ if (reservedIds.length > 0) {
445
+ const { error: rErr } = await admin
446
+ .from('credits')
447
+ .update({ redeemed_booking_id: NEW_ID })
448
+ .in('id', reservedIds)
449
+ .is('redeemed_at', null)
450
+ .is('redeemed_booking_id', null);
451
+ if (rErr) {
452
+ console.error('[reschedule-booking] credit reservation failed', rErr);
453
+ await logOps(admin, 'reschedule_reserve_failed',
454
+ { message: rErr.message }, { severity: 'error', bookingId: NEW_ID });
455
+ await unwindCarriedCoupon('reschedule_reserve_credit_failed');
456
+ return json(500, { error: 'reserve_credit_failed' });
457
+ }
458
+ }
459
+
460
+ // 10A. Fully covered — no Stripe. Finalize now.
461
+ if (charged === 0) {
462
+ try {
463
+ const rTier = await resolveContractTier(admin, room.id);
464
+ if (rTier === null) {
465
+ await logOps(admin, 'room_not_contract_mapped',
466
+ { room_id: room.id, room_slug: room.slug, path: 'reschedule' },
467
+ { severity: 'error', bookingId: NEW_ID }).catch(() => {});
468
+ } else if (rTier === 1) {
469
+ const loaded = await loadTier1Terms(admin, null);
470
+ if (!loaded.ok) throw new Error(loaded.error);
471
+ const { error: agErr } = await insertTier1Agreement(admin, {
472
+ bookingId: NEW_ID,
473
+ roomSlug: room.slug ?? null,
474
+ terms: loaded.terms,
475
+ signerName: O.contact_name ?? null,
476
+ signerEmail: (O.contact_email ?? '').toLowerCase() || null,
477
+ signerIp: signerIpFrom(req),
478
+ signerUserAgent: signerUserAgentFrom(req),
479
+ });
480
+ if (agErr) throw new Error(agErr);
481
+ } else if (rTier === 2 || rTier === 3) {
482
+ const res = await fetch(`${Deno.env.get('SUPABASE_URL')}/functions/v1/send-booking-agreement`, {
483
+ method: 'POST',
484
+ headers: {
485
+ 'Content-Type': 'application/json',
486
+ Authorization: `Bearer ${Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')}`,
487
+ },
488
+ body: JSON.stringify({
489
+ booking_id: NEW_ID,
490
+ ...(rTier === 3 ? { agreement_variant: 'day_rate' } : {}),
491
+ }),
492
+ });
493
+ if (!res.ok) throw new Error(`send_booking_agreement_${res.status}: ${(await res.text()).slice(0, 200)}`);
494
+ }
495
+ } catch (e) {
496
+ await logOps(admin, 'booking_agreement_capture_failed',
497
+ { message: String(e), room_id: room.id, tier: 1, path: 'reschedule' },
498
+ { severity: 'error', bookingId: NEW_ID }).catch(() => {});
499
+ }
500
+
501
+ const { error: finErr } = await admin.rpc('credit_reservation_finalize', {
502
+ p_booking_id: NEW_ID,
503
+ p_applied_cents: credit_applied,
504
+ });
505
+ if (finErr) {
506
+ await logOps(admin, 'reschedule_reservation_finalize_failed',
507
+ { message: finErr.message, credit_applied, reserved_total },
508
+ { severity: 'error', bookingId: NEW_ID }).catch(() => {});
509
+ }
510
+ if (transferredRedemptionId) {
511
+ const { error: cmErr } = await admin.rpc('coupon_mark_applied', {
512
+ p_redemption_id: transferredRedemptionId,
513
+ });
514
+ if (cmErr) {
515
+ await logOps(admin, 'reschedule_coupon_mark_applied_failed',
516
+ { message: cmErr.message, redemption_id: transferredRedemptionId },
517
+ { severity: 'error', bookingId: NEW_ID }).catch(() => {});
518
+ }
519
+ }
520
+
521
+ await admin
522
+ .from('bookings')
523
+ .update({ status: 'paid', charged_amount_cents: 0 })
524
+ .eq('id', NEW_ID);
525
+
526
+ // Run booking effects on the NEW booking.
527
+ try {
528
+ const { data: full } = await admin
529
+ .from('bookings')
530
+ .select('id,contact_name,contact_email,contact_phone,during,charged_amount_cents,list_amount_cents,google_event_id,ghl_contact_id,rooms(id,name,address,google_calendar_id,slug,usage_instructions)')
531
+ .eq('id', NEW_ID)
532
+ .maybeSingle();
533
+ if (full) {
534
+ const eff = full as unknown as EffectsBookingRow;
535
+ let busResp: Record<string, unknown> | null = null;
536
+ try {
537
+ const range = deps.parseTstzRange(eff.during);
538
+ const slug = eff.rooms?.slug ?? null;
539
+ if (range && slug) {
540
+ busResp = await deps.busProvision({
541
+ bookingId: eff.id,
542
+ roomKey: slug,
543
+ startUtc: range.startISO,
544
+ endUtc: range.endISO,
545
+ customer: {
546
+ name: eff.contact_name ?? undefined,
547
+ email: eff.contact_email,
548
+ phone: eff.contact_phone ?? undefined,
549
+ },
550
+ }, admin);
551
+ } else {
552
+ console.log('[reschedule-booking] busProvision skipped (missing slug/range)', NEW_ID);
553
+ }
554
+ } catch { /* never break the caller */ }
555
+ try { await deps.notifyGhl(admin, eff, deps.extractDoorAccess(busResp)); }
556
+ catch (e) {
557
+ await logOps(admin, 'booking_side_effect_failed',
558
+ { step: 'notifyGhl', message: String(e) },
559
+ { severity: 'warning', bookingId: NEW_ID });
560
+ }
561
+ try { await deps.createCalendarEvent(admin, eff); }
562
+ catch (e) {
563
+ await logOps(admin, 'booking_side_effect_failed',
564
+ { step: 'createCalendarEvent', message: String(e) },
565
+ { severity: 'warning', bookingId: NEW_ID });
566
+ }
567
+ }
568
+ } catch (e) {
569
+ console.error('[reschedule-booking] side effects error', e);
570
+ }
571
+
572
+ return json(200, {
573
+ rescheduled: true,
574
+ fully_covered: true,
575
+ booking_id: NEW_ID,
576
+ credit_applied_cents: credit_applied,
577
+ charged_amount_cents: 0,
578
+ });
579
+ }
580
+
581
+ // 10B. charged > 0 — build Stripe checkout. Leave credits RESERVED.
582
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
583
+ if (!stripeKey) {
584
+ await admin.rpc('credit_reservation_release', {
585
+ p_booking_id: NEW_ID,
586
+ p_reason: 'reschedule_missing_stripe_key',
587
+ });
588
+ await unwindCarriedCoupon('reschedule_missing_stripe_key');
589
+ return json(500, { error: 'Payments not configured' });
590
+ }
591
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
592
+ const origin = req.headers.get('origin');
593
+ const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
594
+ const human = formatHumanTime(startUtc, endUtc);
595
+
596
+ try {
597
+ const session = await stripe.checkout.sessions.create({
598
+ mode: 'payment',
599
+ customer_email: O.contact_email,
600
+ line_items: [{
601
+ quantity: 1,
602
+ price_data: {
603
+ currency: 'usd',
604
+ unit_amount: charged,
605
+ product_data: { name: `${room.name} — ${human}` },
606
+ },
607
+ }],
608
+ metadata: { booking_id: NEW_ID, reschedule: '1' },
609
+ expires_at: Math.floor(Date.now() / 1000) + 60 * 60,
610
+ success_url: `${base}/booking/confirmation?session_id={CHECKOUT_SESSION_ID}`,
611
+ cancel_url: token
612
+ ? `${base}/manage-booking/?token=${encodeURIComponent(token)}`
613
+ : `${base}/portal/bookings`,
614
+ });
615
+
616
+ await admin
617
+ .from('bookings')
618
+ .update({ stripe_session_id: session.id })
619
+ .eq('id', NEW_ID);
620
+
621
+ return json(200, {
622
+ rescheduled: false,
623
+ url: session.url,
624
+ booking_id: NEW_ID,
625
+ credit_applied_cents: credit_applied,
626
+ charged_amount_cents: charged,
627
+ });
628
+ } catch (e) {
629
+ await admin.rpc('credit_reservation_release', {
630
+ p_booking_id: NEW_ID,
631
+ p_reason: 'reschedule_stripe_create_failed',
632
+ });
633
+ if (transferredRedemptionId) {
634
+ await admin.rpc('coupon_reverse', {
635
+ p_redemption_id: transferredRedemptionId,
636
+ p_reason: 'reschedule_stripe_create_failed',
637
+ p_actor_email: operator.actorEmail,
638
+ }).then(() => {}, () => {});
639
+ }
640
+ await admin
641
+ .from('bookings')
642
+ .update({ status: 'expired' })
643
+ .eq('id', NEW_ID);
644
+ await logOps(admin, 'reschedule_stripe_create_failed',
645
+ { message: String(e) },
646
+ { severity: 'error', bookingId: NEW_ID });
647
+ return json(502, { error: 'payment_start_failed' });
648
+ }
649
+ }