@simplelayer/graniteer-core 0.1.2 → 0.2.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 (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 +309 -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 +95 -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,648 @@
1
+ import { corsHeaders } from 'npm:@supabase/supabase-js@2/cors';
2
+ import { createClient } from 'npm:@supabase/supabase-js@2';
3
+ import Stripe from 'npm:stripe@17.5.0';
4
+ import { z } from 'npm:zod@3.23.8';
5
+ import { clientIp, checkRateLimit } from 'npm:@simplelayer/graniteer-core/rateLimit';
6
+ import { logOps } from 'npm:@simplelayer/graniteer-core/ops';
7
+ import { reclaimStaleHoldsExceptCompletedTier3 } from 'npm:@simplelayer/graniteer-core/bookingHoldReclaim';
8
+ import { validateAndPriceForRoom, formatHumanTime } from 'npm:@simplelayer/graniteer-core/pricing';
9
+ import { resolveMembershipContext } from 'npm:@simplelayer/graniteer-core/membership';
10
+ import {
11
+ resolveContractTier,
12
+ loadTier1Terms,
13
+ insertTier1Agreement,
14
+ signerIpFrom,
15
+ signerUserAgentFrom,
16
+ type Tier1Terms,
17
+ } from 'npm:@simplelayer/graniteer-core/tier1Agreement';
18
+ import {
19
+ checkPolicyAcceptance,
20
+ insertPolicyAcknowledgment,
21
+ POLICY_NOT_ACCEPTED_ERROR,
22
+ } from 'npm:@simplelayer/graniteer-core/policyAcknowledgment';
23
+ import { createEventInquiryLead } from 'npm:@simplelayer/graniteer-core/ghlEventInquiry';
24
+
25
+ const Contact = z.object({
26
+ name: z.string().min(1).max(200),
27
+ email: z.string().email(),
28
+ phone: z.string().max(40).optional(),
29
+ });
30
+ const Body = z.object({
31
+ room_id: z.string().uuid(),
32
+ start: z.string().datetime().optional(),
33
+ end: z.string().datetime().optional(),
34
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
35
+ day_mode: z.enum(['full', 'half_am', 'half_pm']).optional(),
36
+ contact: Contact,
37
+ policy_accepted: z.literal(true),
38
+ coupon_code: z.string().trim().min(1).max(64).optional(),
39
+ agreement: z.object({
40
+ terms_version: z.string().min(1).max(32),
41
+ method: z.enum(['click_through', 'phone_verbal']).optional(),
42
+ }).optional(),
43
+ agreementAccepted: z.boolean().optional(),
44
+ avRequest: z.boolean().optional(),
45
+ avRequestNotes: z.string().max(1000).optional(),
46
+ });
47
+
48
+ // Stripe rejects charges under $0.50. When credit + coupon leave a sub-minimum
49
+ // remainder we treat the booking as fully covered rather than failing checkout.
50
+ const STRIPE_MIN_CHARGE_CENTS = 50;
51
+
52
+ // Loose row shape covering just the fields create-booking's side effects
53
+ // actually read - matches gc-connect's local _shared/bookingEffects.ts
54
+ // BookingRow, which stays in gc-connect (not moved this phase).
55
+ interface EffectsBookingRow {
56
+ id: string;
57
+ contact_name: string | null;
58
+ contact_email: string;
59
+ contact_phone: string | null;
60
+ during: string;
61
+ charged_amount_cents?: number | null;
62
+ list_amount_cents?: number | null;
63
+ google_event_id?: string | null;
64
+ ghl_contact_id?: string | null;
65
+ rooms: {
66
+ id?: string;
67
+ name: string;
68
+ address?: string | null;
69
+ google_calendar_id?: string | null;
70
+ slug: string | null;
71
+ usage_instructions?: string | null;
72
+ } | null;
73
+ }
74
+
75
+ // The gc-connect wrapper imports these from its own local _shared/bookingEffects.ts
76
+ // and _shared/busClient.ts (FTW-middleware-specific integrations, out of scope
77
+ // for this phase) and passes them through unchanged.
78
+ export interface CreateBookingDeps {
79
+ notifyGhl: (admin: unknown, row: EffectsBookingRow, doorAccess: unknown) => Promise<void>;
80
+ createCalendarEvent: (admin: unknown, row: EffectsBookingRow) => Promise<void>;
81
+ parseTstzRange: (range: string) => { startISO: string; endISO: string } | null;
82
+ busProvision: (
83
+ input: {
84
+ bookingId: string;
85
+ roomKey: string;
86
+ startUtc: string;
87
+ endUtc: string;
88
+ customer: { name?: string; email: string; phone?: string };
89
+ },
90
+ supabase: unknown,
91
+ ) => Promise<Record<string, unknown> | null>;
92
+ extractDoorAccess: (busResp: Record<string, unknown> | null) => unknown;
93
+ }
94
+
95
+ export async function handle(req: Request, operator: { domain: string; actorEmail: string }, deps: CreateBookingDeps): Promise<Response> {
96
+ if (req.method === 'OPTIONS') return new Response('ok', { headers: corsHeaders });
97
+
98
+ try {
99
+ const raw = await req.json().catch(() => ({}));
100
+ const parsed = Body.safeParse(raw);
101
+ if (!parsed.success) {
102
+ return new Response(JSON.stringify({ error: parsed.error.flatten() }), {
103
+ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
104
+ });
105
+ }
106
+ const { room_id, contact } = parsed.data;
107
+ const nowMs = Date.now();
108
+
109
+ const supabase = createClient(
110
+ Deno.env.get('SUPABASE_URL')!,
111
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')!,
112
+ );
113
+
114
+ const ip = clientIp(req);
115
+ const emailKey = contact.email.toLowerCase();
116
+ const [ipOk, emailOk] = await Promise.all([
117
+ checkRateLimit(supabase, 'create-booking', ip, 10, 600),
118
+ checkRateLimit(supabase, 'create-booking-email', emailKey, 5, 600),
119
+ ]);
120
+ if (!ipOk || !emailOk) {
121
+ return new Response(
122
+ JSON.stringify({ error: 'Too many booking attempts — please wait a few minutes and try again.' }),
123
+ { status: 429, headers: { ...corsHeaders, 'Content-Type': 'application/json' } },
124
+ );
125
+ }
126
+
127
+ // Cap concurrent live pending holds per email (fail-open).
128
+ const { count: pendingHolds, error: holdErr } = await supabase
129
+ .from('bookings')
130
+ .select('id', { count: 'exact', head: true })
131
+ .eq('contact_email', emailKey)
132
+ .eq('status', 'pending')
133
+ .gt('hold_expires_at', new Date().toISOString());
134
+ if (holdErr) {
135
+ console.warn('[create-booking] pending-hold count failed', holdErr);
136
+ } else if ((pendingHolds ?? 0) >= 2) {
137
+ return new Response(
138
+ JSON.stringify({ error: 'You already have 2 pending booking holds. Please complete or wait for one to expire (holds release after 1 hour), then try again.' }),
139
+ { status: 429, headers: { ...corsHeaders, 'Content-Type': 'application/json' } },
140
+ );
141
+ }
142
+
143
+ const { data: room, error: rErr } = await supabase
144
+ .from('rooms')
145
+ .select('id,name,slug,hourly_cents,day_cents,half_day_cents,min_booking_minutes,booking_mode,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,checkout_agreement_text')
146
+ .eq('id', room_id)
147
+ .eq('active', true)
148
+ .maybeSingle();
149
+ if (rErr) throw rErr;
150
+ if (!room) {
151
+ return new Response(JSON.stringify({ error: 'Room not found' }), {
152
+ status: 404, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
153
+ });
154
+ }
155
+
156
+ // === Per-room checkout agreement gate ===
157
+ const policyCheck = checkPolicyAcceptance(
158
+ room as { checkout_agreement_text: string | null },
159
+ parsed.data.agreementAccepted,
160
+ );
161
+ if (!policyCheck.ok) {
162
+ return new Response(JSON.stringify({ error: POLICY_NOT_ACCEPTED_ERROR }), {
163
+ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
164
+ });
165
+ }
166
+
167
+ // Server-authoritative membership lookup — NEVER trust a client member flag.
168
+ const { isMember, membershipId } = await resolveMembershipContext(supabase, emailKey);
169
+
170
+ // === Commons Booking Contract gate (Tier 1 only in this phase) ===
171
+ const contractTier = await resolveContractTier(supabase, room_id);
172
+ if (contractTier === null) {
173
+ await logOps(supabase, 'room_not_contract_mapped',
174
+ { room_id, room_slug: room.slug }, { severity: 'error' });
175
+ return new Response(JSON.stringify({ error: 'room_not_contract_mapped' }), {
176
+ status: 409, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
177
+ });
178
+ }
179
+ let tier1Terms: Tier1Terms | null = null;
180
+ if (contractTier === 1) {
181
+ const declared = parsed.data.agreement?.terms_version ?? null;
182
+ if (!declared) {
183
+ return new Response(JSON.stringify({ error: 'agreement_required' }), {
184
+ status: 400, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
185
+ });
186
+ }
187
+ const loaded = await loadTier1Terms(supabase, declared);
188
+ if (!loaded.ok) {
189
+ if (loaded.error === 'terms_version_stale') {
190
+ return new Response(
191
+ JSON.stringify({ error: 'terms_version_stale', current_version: loaded.current_version }),
192
+ { status: 409, headers: { ...corsHeaders, 'Content-Type': 'application/json' } },
193
+ );
194
+ }
195
+ await logOps(supabase, 'booking_terms_unavailable',
196
+ { room_id, room_slug: room.slug }, { severity: 'error' });
197
+ return new Response(JSON.stringify({ error: 'terms_unavailable' }), {
198
+ status: 503, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
199
+ });
200
+ }
201
+ tier1Terms = loaded.terms;
202
+ }
203
+
204
+ const priced = await validateAndPriceForRoom(supabase, room, parsed.data, nowMs, { isMember, allowDynamic: true });
205
+ if (!priced.ok) {
206
+ return new Response(JSON.stringify({ error: priced.error }), {
207
+ status: priced.status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
208
+ });
209
+ }
210
+ const {
211
+ startUtc, endUtc, price_cents: P, rangeLiteral,
212
+ dynamic_discount_cents, dynamic_discount_rule_type, list_rule_type,
213
+ } = priced;
214
+ const net = P - dynamic_discount_cents;
215
+
216
+ // Reclaim stale holds overlapping the range so abandoned carts don't block it.
217
+ await reclaimStaleHoldsExceptCompletedTier3(supabase, room_id, rangeLiteral);
218
+
219
+ const usesBoldSignAgreement = contractTier === 2 || contractTier === 3;
220
+ const holdExpires = new Date(Date.now() + 60 * 60 * 1000).toISOString();
221
+ const effectiveHoldExpires = usesBoldSignAgreement
222
+ ? new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
223
+ : holdExpires;
224
+ const { data: inserted, error: iErr } = await supabase
225
+ .from('bookings')
226
+ .insert({
227
+ room_id,
228
+ during: rangeLiteral,
229
+ status: 'pending',
230
+ hold_expires_at: effectiveHoldExpires,
231
+ list_amount_cents: P,
232
+ dynamic_discount_cents,
233
+ dynamic_discount_rule_type,
234
+ list_rule_type,
235
+ contact_email: emailKey,
236
+ contact_name: contact.name,
237
+ contact_phone: contact.phone ?? 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
+ const code = (iErr as any).code;
246
+ if (code === '23P01') {
247
+ return new Response(
248
+ JSON.stringify({ error: 'That time was just booked — please choose another slot.' }),
249
+ { status: 409, headers: { ...corsHeaders, 'Content-Type': 'application/json' } },
250
+ );
251
+ }
252
+ throw iErr;
253
+ }
254
+ const booking_id = inserted.id;
255
+
256
+ // Record the Tier 1 click-through agreement IMMEDIATELY after the hold.
257
+ if (contractTier === 1 && tier1Terms) {
258
+ const { error: agErr } = await insertTier1Agreement(supabase, {
259
+ bookingId: booking_id,
260
+ roomSlug: room.slug ?? null,
261
+ terms: tier1Terms,
262
+ method: parsed.data.agreement?.method,
263
+ signerName: contact.name,
264
+ signerEmail: emailKey,
265
+ signerIp: signerIpFrom(req),
266
+ signerUserAgent: signerUserAgentFrom(req),
267
+ });
268
+ if (agErr) {
269
+ await supabase.from('bookings').delete().eq('id', booking_id);
270
+ await logOps(supabase, 'booking_agreement_capture_failed',
271
+ { message: agErr, room_id, tier: 1 }, { severity: 'error', bookingId: booking_id });
272
+ return new Response(JSON.stringify({ error: 'agreement_capture_failed' }), {
273
+ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
274
+ });
275
+ }
276
+ }
277
+
278
+ // Record the per-room checkout-agreement acknowledgment.
279
+ if (policyCheck.required && room.checkout_agreement_text) {
280
+ const { error: ackErr } = await insertPolicyAcknowledgment(supabase, {
281
+ bookingId: booking_id,
282
+ roomId: room_id,
283
+ agreementText: room.checkout_agreement_text as string,
284
+ acceptedEmail: emailKey,
285
+ acceptedIp: ip,
286
+ });
287
+ if (ackErr) {
288
+ await logOps(supabase, 'booking_policy_acknowledgment_insert_failed',
289
+ { message: ackErr, room_id }, { severity: 'error', bookingId: booking_id })
290
+ .catch(() => {});
291
+ }
292
+ }
293
+
294
+ // Commons A/V support request (v1, non-priced).
295
+ if (parsed.data.avRequest === true && room.slug === 'commons') {
296
+ try {
297
+ const GHL_API_KEY = Deno.env.get('GHL_API_KEY');
298
+ const GHL_LOCATION_ID = Deno.env.get('GHL_LOCATION_ID');
299
+ if (!GHL_API_KEY || !GHL_LOCATION_ID) {
300
+ throw new Error('GHL_API_KEY/GHL_LOCATION_ID not configured');
301
+ }
302
+ const result = await createEventInquiryLead(GHL_API_KEY, GHL_LOCATION_ID, {
303
+ name: contact.name,
304
+ email: emailKey,
305
+ phone: contact.phone,
306
+ eventType: 'Commons A/V Support',
307
+ preferredDate: formatHumanTime(startUtc, endUtc),
308
+ message: parsed.data.avRequestNotes?.trim() || '(no details provided)',
309
+ source: 'Booking checkout — Commons A/V request',
310
+ tags: ['A/V Request', operator.domain],
311
+ }, operator.domain);
312
+ if (!result.ok) throw new Error('createEventInquiryLead returned ok:false');
313
+ await logOps(supabase, 'commons_av_request_sent',
314
+ { contactId: result.contactId, opportunityId: result.opportunityId },
315
+ { severity: 'info', bookingId: booking_id });
316
+ } catch (e) {
317
+ await logOps(supabase, 'commons_av_request_failed',
318
+ { message: e instanceof Error ? e.message : String(e) },
319
+ { severity: 'warning', bookingId: booking_id });
320
+ }
321
+ }
322
+
323
+ // Tier 2/3: send the BoldSign agreement now.
324
+ if (usesBoldSignAgreement) {
325
+ const agreementVariant = contractTier === 3 ? 'day_rate' : undefined;
326
+ let sendOk = false;
327
+ let sendDetail = '';
328
+ try {
329
+ const res = await fetch(`${Deno.env.get('SUPABASE_URL')}/functions/v1/send-booking-agreement`, {
330
+ method: 'POST',
331
+ headers: {
332
+ 'Content-Type': 'application/json',
333
+ Authorization: `Bearer ${Deno.env.get('SUPABASE_SERVICE_ROLE_KEY')}`,
334
+ },
335
+ body: JSON.stringify({
336
+ booking_id,
337
+ ...(agreementVariant ? { agreement_variant: agreementVariant } : {}),
338
+ }),
339
+ });
340
+ sendDetail = (await res.text()).slice(0, 300);
341
+ sendOk = res.ok;
342
+ } catch (e) {
343
+ sendDetail = e instanceof Error ? e.message : String(e);
344
+ }
345
+ if (!sendOk) {
346
+ await logOps(supabase, 'booking_agreement_send_invoke_failed',
347
+ { message: sendDetail, room_id, tier: contractTier }, { severity: 'error', bookingId: booking_id },
348
+ ).catch(() => {});
349
+ return new Response(JSON.stringify({ error: 'agreement_send_failed', booking_id }), {
350
+ status: 502, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
351
+ });
352
+ }
353
+ }
354
+
355
+ // === Period-based monthly credit hold (Stage 3) ===
356
+ let credit_applied = 0;
357
+ const creditEligible = room.booking_mode !== 'quote' && contractTier !== 3;
358
+ if (membershipId && creditEligible) {
359
+ try {
360
+ const { data: period, error: perErr } = await supabase.rpc(
361
+ 'credit_get_or_create_period', { p_membership_id: membershipId },
362
+ );
363
+ if (perErr) throw perErr;
364
+ // deno-lint-ignore no-explicit-any
365
+ const pr = period as any;
366
+ const avail = Math.max(0,
367
+ (pr?.granted_cents ?? 0) - (pr?.consumed_cents ?? 0)
368
+ - (pr?.held_cents ?? 0) - (pr?.expired_cents ?? 0));
369
+ const want = Math.min(net, avail);
370
+ if (want > 0) {
371
+ const { error: holdErr2 } = await supabase.rpc('credit_hold', {
372
+ p_membership_id: membershipId,
373
+ p_booking_id: booking_id,
374
+ p_amount_cents: want,
375
+ p_idempotency_key: `hold:${booking_id}`,
376
+ });
377
+ if (holdErr2) throw holdErr2;
378
+ credit_applied = want;
379
+ }
380
+ } catch (e) {
381
+ console.warn('[create-booking] credit hold skipped', String(e));
382
+ credit_applied = 0;
383
+ }
384
+ }
385
+
386
+ // === Optional coupon ===
387
+ let discount_applied = 0;
388
+ let coupon_error: string | null = null;
389
+ const couponCode = parsed.data.coupon_code;
390
+ if (couponCode) {
391
+ const couponBase = Math.max(0, net - credit_applied);
392
+ try {
393
+ const { data: vres, error: vErr } = await supabase.rpc('coupon_validate', {
394
+ p_code: couponCode,
395
+ p_membership_id: membershipId,
396
+ p_scope_type: 'room',
397
+ p_scope_target_id: room_id,
398
+ p_base_amount_cents: couponBase,
399
+ });
400
+ if (vErr) throw vErr;
401
+ // deno-lint-ignore no-explicit-any
402
+ const v = (Array.isArray(vres) ? vres[0] : vres) as any;
403
+ if (v?.valid) {
404
+ const { data: red, error: rErr2 } = await supabase.rpc('coupon_redeem', {
405
+ p_coupon_id: v.coupon_id,
406
+ p_member_email: emailKey,
407
+ p_applied_to_type: 'booking',
408
+ p_applied_to_id: booking_id,
409
+ p_base_amount_cents: couponBase,
410
+ p_idempotency_key: `coupon:${booking_id}`,
411
+ });
412
+ if (rErr2) throw rErr2;
413
+ // deno-lint-ignore no-explicit-any
414
+ discount_applied = Math.max(0, ((red as any)?.amount_applied_cents ?? 0));
415
+ } else {
416
+ coupon_error = v?.reason ?? 'COUPON_NOT_APPLICABLE';
417
+ }
418
+ } catch (e) {
419
+ console.warn('[create-booking] coupon failed', String(e));
420
+ coupon_error = 'COUPON_NOT_APPLICABLE';
421
+ discount_applied = 0;
422
+ }
423
+ }
424
+
425
+ let charged = Math.max(0, net - credit_applied - discount_applied);
426
+ if (charged > 0 && charged < STRIPE_MIN_CHARGE_CENTS) {
427
+ discount_applied += charged;
428
+ charged = 0;
429
+ }
430
+
431
+ if (credit_applied > 0 || discount_applied > 0) {
432
+ await supabase
433
+ .from('bookings')
434
+ .update({
435
+ credit_applied_cents: credit_applied,
436
+ discount_applied_cents: discount_applied,
437
+ })
438
+ .eq('id', booking_id);
439
+ }
440
+
441
+ // 4A. Fully covered — no Stripe. Finalize now.
442
+ if (charged === 0) {
443
+ if (credit_applied > 0) {
444
+ const { error: consumeErr } = await supabase.rpc('credit_consume', {
445
+ p_booking_id: booking_id,
446
+ p_idempotency_key: `consume:${booking_id}`,
447
+ });
448
+ if (consumeErr) {
449
+ console.error('[create-booking] credit_consume failed', consumeErr);
450
+ await logOps(supabase, 'credit_consume_failed',
451
+ { message: consumeErr.message }, { severity: 'error', bookingId: booking_id });
452
+ }
453
+ }
454
+ if (discount_applied > 0) {
455
+ try {
456
+ const { data: redRow } = await supabase
457
+ .from('coupon_redemptions')
458
+ .select('id,status')
459
+ .eq('applied_to_type', 'booking')
460
+ .eq('applied_to_id', booking_id)
461
+ .maybeSingle();
462
+ if (redRow && redRow.status !== 'applied' && redRow.status !== 'reversed') {
463
+ await supabase.rpc('coupon_mark_applied', { p_redemption_id: redRow.id });
464
+ }
465
+ } catch (e) {
466
+ await logOps(supabase, 'coupon_mark_applied_failed',
467
+ { message: String(e) }, { severity: 'warning', bookingId: booking_id });
468
+ }
469
+ }
470
+
471
+ const { error: fullyCoveredUpdateErr } = await supabase
472
+ .from('bookings')
473
+ .update({ status: 'paid', charged_amount_cents: 0 })
474
+ .eq('id', booking_id);
475
+ if (fullyCoveredUpdateErr) {
476
+ console.error('[create-booking] fully-covered status update failed', fullyCoveredUpdateErr);
477
+ await logOps(supabase, 'booking_status_update_failed',
478
+ { message: fullyCoveredUpdateErr.message }, { severity: 'error', bookingId: booking_id });
479
+ }
480
+
481
+ // Post-paid side effects (best-effort; same shape as stripe-webhook).
482
+ try {
483
+ const { data: full } = await supabase
484
+ .from('bookings')
485
+ .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)')
486
+ .eq('id', booking_id)
487
+ .maybeSingle();
488
+ if (full) {
489
+ const eff = full as unknown as EffectsBookingRow;
490
+ let busResp: Record<string, unknown> | null = null;
491
+ try {
492
+ const range = deps.parseTstzRange(eff.during);
493
+ const slug = eff.rooms?.slug ?? null;
494
+ if (range && slug) {
495
+ busResp = await deps.busProvision({
496
+ bookingId: eff.id,
497
+ roomKey: slug,
498
+ startUtc: range.startISO,
499
+ endUtc: range.endISO,
500
+ customer: {
501
+ name: eff.contact_name ?? undefined,
502
+ email: eff.contact_email,
503
+ phone: eff.contact_phone ?? undefined,
504
+ },
505
+ }, supabase);
506
+ } else {
507
+ console.log('[create-booking] busProvision skipped (missing slug/range)', booking_id);
508
+ }
509
+ } catch { /* never break the caller */ }
510
+ try { await deps.notifyGhl(supabase, eff, deps.extractDoorAccess(busResp)); }
511
+ catch (e) {
512
+ await logOps(supabase, 'booking_side_effect_failed',
513
+ { step: 'notifyGhl', message: String(e) },
514
+ { severity: 'warning', bookingId: booking_id });
515
+ }
516
+ try { await deps.createCalendarEvent(supabase, eff); }
517
+ catch (e) {
518
+ await logOps(supabase, 'booking_side_effect_failed',
519
+ { step: 'createCalendarEvent', message: String(e) },
520
+ { severity: 'warning', bookingId: booking_id });
521
+ }
522
+ }
523
+ } catch (e) {
524
+ console.error('[create-booking] fully-covered side effects error', e);
525
+ }
526
+
527
+ return new Response(JSON.stringify({
528
+ fully_covered: true,
529
+ booking_id,
530
+ credit_applied_cents: credit_applied,
531
+ discount_applied_cents: discount_applied,
532
+ ...(coupon_error ? { coupon_error } : {}),
533
+ charged_amount_cents: 0,
534
+ }), {
535
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
536
+ });
537
+ }
538
+
539
+ // Abandon path helper: release the credit hold + reverse the coupon.
540
+ const abandonHoldAndCoupon = async (reason: string) => {
541
+ if (credit_applied > 0) {
542
+ const { error } = await supabase.rpc('credit_release', {
543
+ p_booking_id: booking_id,
544
+ p_reason: reason,
545
+ p_idempotency_key: `release:${booking_id}`,
546
+ });
547
+ if (error) {
548
+ await logOps(supabase, 'credit_release_failed',
549
+ { message: error.message }, { severity: 'error', bookingId: booking_id });
550
+ }
551
+ }
552
+ if (discount_applied > 0) {
553
+ try {
554
+ const { data: redRow } = await supabase
555
+ .from('coupon_redemptions')
556
+ .select('id,status')
557
+ .eq('applied_to_type', 'booking')
558
+ .eq('applied_to_id', booking_id)
559
+ .maybeSingle();
560
+ if (redRow && redRow.status !== 'reversed') {
561
+ await supabase.rpc('coupon_reverse', {
562
+ p_redemption_id: redRow.id,
563
+ p_reason: reason,
564
+ p_actor_email: operator.actorEmail,
565
+ });
566
+ }
567
+ } catch (e) {
568
+ await logOps(supabase, 'coupon_reverse_failed',
569
+ { message: String(e) }, { severity: 'warning', bookingId: booking_id });
570
+ }
571
+ }
572
+ };
573
+
574
+ // 4B. charged > 0 — Stripe checkout for the net amount. Credit stays HELD.
575
+ const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
576
+ if (!stripeKey) {
577
+ await abandonHoldAndCoupon('payments_not_configured');
578
+ await supabase.from('bookings').update({ status: 'expired' }).eq('id', booking_id);
579
+ return new Response(JSON.stringify({ error: 'Payments not configured (missing STRIPE_SECRET_KEY).' }), {
580
+ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
581
+ });
582
+ }
583
+ const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' as Stripe.LatestApiVersion });
584
+
585
+ const origin = req.headers.get('origin');
586
+ const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
587
+ const human = formatHumanTime(startUtc, endUtc);
588
+
589
+ try {
590
+ const session = await stripe.checkout.sessions.create({
591
+ mode: 'payment',
592
+ customer_email: contact.email,
593
+ line_items: [{
594
+ quantity: 1,
595
+ price_data: {
596
+ currency: 'usd',
597
+ unit_amount: charged,
598
+ product_data: { name: `${room.name} — ${human}` },
599
+ },
600
+ }],
601
+ metadata: { booking_id },
602
+ expires_at: Math.floor(Date.now() / 1000) + 60 * 60,
603
+ success_url: `${base}/booking/confirmation?session_id={CHECKOUT_SESSION_ID}`,
604
+ cancel_url: `${base}/meeting-rooms/${room.slug ?? ''}?canceled=1`,
605
+ // TODO: enable Stripe automatic tax once tax registrations are configured.
606
+ // automatic_tax: { enabled: true },
607
+ });
608
+
609
+ await supabase
610
+ .from('bookings')
611
+ .update({ stripe_session_id: session.id })
612
+ .eq('id', booking_id);
613
+
614
+ return new Response(JSON.stringify({
615
+ ...(usesBoldSignAgreement ? { agreement_pending: true } : { url: session.url }),
616
+ booking_id,
617
+ credit_applied_cents: credit_applied,
618
+ discount_applied_cents: discount_applied,
619
+ ...(coupon_error ? { coupon_error } : {}),
620
+ charged_amount_cents: charged,
621
+ }), {
622
+ headers: { ...corsHeaders, 'Content-Type': 'application/json' },
623
+ });
624
+ } catch (e) {
625
+ await abandonHoldAndCoupon('stripe_create_failed');
626
+ await supabase.from('bookings').update({ status: 'expired' }).eq('id', booking_id);
627
+ await logOps(supabase, 'create_booking_stripe_create_failed',
628
+ { message: String(e) }, { severity: 'error', bookingId: booking_id });
629
+ return new Response(JSON.stringify({ error: 'payment_start_failed' }), {
630
+ status: 502, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
631
+ });
632
+ }
633
+ } catch (e) {
634
+ console.error('create-booking error', e);
635
+ try {
636
+ const opsClient = createClient(
637
+ Deno.env.get('SUPABASE_URL') ?? '',
638
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '',
639
+ );
640
+ await logOps(opsClient, 'booking_error',
641
+ { message: e instanceof Error ? e.message : String(e) },
642
+ { severity: 'error' });
643
+ } catch { /* ignore */ }
644
+ return new Response(JSON.stringify({ error: "Something went wrong starting your payment. Please try again." }), {
645
+ status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
646
+ });
647
+ }
648
+ }