@simplelayer/graniteer-core 0.3.18 → 0.3.19

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 (41) hide show
  1. package/dist/functions/admin-create-booking.d.ts +0 -3
  2. package/dist/functions/admin-create-booking.js +2 -15
  3. package/dist/functions/admin-mark-booking-paid.d.ts +1 -6
  4. package/dist/functions/admin-mark-booking-paid.js +3 -27
  5. package/dist/functions/admin-request-trial.js +1 -1
  6. package/dist/functions/booking-availability.d.ts +1 -2
  7. package/dist/functions/booking-availability.js +5 -14
  8. package/dist/functions/create-booking.d.ts +0 -5
  9. package/dist/functions/create-booking.js +4 -22
  10. package/dist/functions/manage-booking.d.ts +0 -6
  11. package/dist/functions/manage-booking.js +12 -29
  12. package/dist/functions/reschedule-booking.d.ts +0 -5
  13. package/dist/functions/reschedule-booking.js +2 -28
  14. package/dist/functions/space-availability-range.d.ts +1 -2
  15. package/dist/functions/space-availability-range.js +1 -8
  16. package/dist/functions/stripe-webhook.d.ts +0 -4
  17. package/dist/functions/stripe-webhook.js +2 -168
  18. package/dist/functions/sync-gcal-blackouts.js +1 -1
  19. package/dist/gcalSync.d.ts +0 -1
  20. package/dist/gcalSync.js +0 -5
  21. package/dist/pricing.d.ts +2 -10
  22. package/dist/pricing.js +9 -14
  23. package/package.json +2 -26
  24. package/dist/bookingSource.d.ts +0 -2
  25. package/dist/bookingSource.js +0 -11
  26. package/dist/businessHours.d.ts +0 -11
  27. package/dist/businessHours.js +0 -55
  28. package/dist/connectBookingCharge.d.ts +0 -49
  29. package/dist/connectBookingCharge.js +0 -68
  30. package/dist/functions/booking-access-revoke-backstop.d.ts +0 -11
  31. package/dist/functions/booking-access-revoke-backstop.js +0 -121
  32. package/dist/functions/booking-access-revoke-door-state.d.ts +0 -22
  33. package/dist/functions/booking-access-revoke-door-state.js +0 -61
  34. package/dist/functions/booking-access-revoke.d.ts +0 -35
  35. package/dist/functions/booking-access-revoke.js +0 -279
  36. package/dist/gcalBookingEvents.d.ts +0 -59
  37. package/dist/gcalBookingEvents.js +0 -182
  38. package/dist/stripeConnectEvents.d.ts +0 -11
  39. package/dist/stripeConnectEvents.js +0 -37
  40. package/dist/tenant-config.d.ts +0 -8
  41. package/dist/tenant-config.js +0 -24
@@ -41,8 +41,5 @@ export interface AdminCreateBookingDeps {
41
41
  }
42
42
  export declare function handle(req: Request, operator: {
43
43
  domain: string;
44
- googleCalendarWriteback?: boolean | null;
45
- stripeConnectedAccountId?: string | null;
46
- stripeApplicationFeePercent?: number | null;
47
44
  }, deps: AdminCreateBookingDeps): Promise<Response>;
48
45
  export {};
@@ -19,9 +19,7 @@ import { logOps } from '../ops.js';
19
19
  import { reclaimStaleHoldsExceptCompletedTier3 } from '../bookingHoldReclaim.js';
20
20
  import { validateAndPriceForRoom, formatHumanTime, } from '../pricing.js';
21
21
  import { resolveIsMember, computeEntitlement } from '../membership.js';
22
- import { writebackBookingCreated } from '../gcalBookingEvents.js';
23
22
  import { buildAdminCheckoutSessionParams, consumeMemberCredit, holdMemberCredit, loadMembershipById, releaseMemberCredit, resolveRoomContractTier, splitCharge, } from '../adminBookingCredit.js';
24
- import { createBookingCheckoutSession, planBookingCharge } from '../connectBookingCharge.js';
25
23
  const corsHeaders = {
26
24
  'Access-Control-Allow-Origin': '*',
27
25
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -308,7 +306,6 @@ export async function handle(req, operator, deps) {
308
306
  catch (e) {
309
307
  console.warn('[admin-create-booking] gcal failed', e);
310
308
  }
311
- await writebackBookingCreated(operator, eff);
312
309
  };
313
310
  // Finalizes a booking that needs no Stripe payment: consume the held credit,
314
311
  // flip the row to paid, then run the paid side effects.
@@ -402,21 +399,11 @@ export async function handle(req, operator, deps) {
402
399
  await admin.from('bookings').update({ status: 'expired' }).eq('id', booking_id);
403
400
  return json(500, { ok: false, error: 'stripe_not_configured' });
404
401
  }
405
- const chargePlan = planBookingCharge(operator, charged);
406
- if ('error' in chargePlan) {
407
- await releaseHeldCredit('payments_misconfigured');
408
- await admin.from('bookings').update({ status: 'expired' }).eq('id', booking_id);
409
- try {
410
- await logOps(admin, 'booking_connect_config_invalid', { error: chargePlan.error, path: 'admin-create-booking', booking_id, actor: callerEmail }, { severity: 'error', bookingId: booking_id });
411
- }
412
- catch { /* ignore */ }
413
- return json(500, { ok: false, error: 'payments_misconfigured' });
414
- }
415
402
  const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
416
403
  const origin = req.headers.get('origin');
417
404
  const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
418
405
  try {
419
- const session = await createBookingCheckoutSession(stripe, buildAdminCheckoutSessionParams({
406
+ const session = await stripe.checkout.sessions.create(buildAdminCheckoutSessionParams({
420
407
  roomName: room.name,
421
408
  roomSlug: room.slug ?? null,
422
409
  human,
@@ -424,7 +411,7 @@ export async function handle(req, operator, deps) {
424
411
  bookingId: booking_id,
425
412
  amountCents: charged,
426
413
  base,
427
- }), chargePlan);
414
+ }));
428
415
  await admin.from('bookings').update({ stripe_session_id: session.id }).eq('id', booking_id);
429
416
  try {
430
417
  await logOps(admin, 'admin_payment_link_created', { booking_id, room: room.name, actor: callerEmail, amount_cents: net,
@@ -1,6 +1 @@
1
- export declare function handle(req: Request, operator?: {
2
- stripeConnectedAccountId?: string | null;
3
- }): Promise<Response>;
4
- export declare function createAdminMarkBookingPaidHandler(operator: {
5
- stripeConnectedAccountId?: string | null;
6
- }): (req: Request) => Promise<Response>;
1
+ export declare function handle(req: Request): Promise<Response>;
@@ -12,7 +12,6 @@ import { jwtVerify, createRemoteJWKSet } from 'jose';
12
12
  import Stripe from 'stripe';
13
13
  import { clientIp, checkRateLimit } from '../rateLimit.js';
14
14
  import { logOps } from '../ops.js';
15
- import { resolveConnectedAccount } from '../connectBookingCharge.js';
16
15
  const corsHeaders = {
17
16
  'Access-Control-Allow-Origin': '*',
18
17
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -57,7 +56,7 @@ const Body = z.object({
57
56
  // value added later (e.g. a dispute/chargeback state) should default to
58
57
  // NOT payable until someone explicitly decides otherwise.
59
58
  const PAYABLE_STATUSES = new Set(['pending', 'deposit_paid']);
60
- export async function handle(req, operator) {
59
+ export async function handle(req) {
61
60
  if (req.method === 'OPTIONS')
62
61
  return new Response('ok', { headers: corsHeaders });
63
62
  if (req.method !== 'POST')
@@ -142,28 +141,11 @@ export async function handle(req, operator) {
142
141
  if (!stripeKey) {
143
142
  return fail(500, 'stripe_not_configured', 'STRIPE_SECRET_KEY is not set; cannot safely void the outstanding deposit link.');
144
143
  }
145
- const connectAccount = resolveConnectedAccount(operator);
146
- if ('error' in connectAccount) {
147
- return fail(500, 'stripe_connect_misconfigured', 'The Stripe connected account for this location is misconfigured; cannot safely void the outstanding payment link.');
148
- }
149
144
  try {
150
145
  const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
151
- const connectedAccountId = connectAccount.accountId;
152
- const session = connectedAccountId
153
- ? await stripe.checkout.sessions.retrieve(String(booking.stripe_session_id), {}, { stripeAccount: connectedAccountId })
154
- : await stripe.checkout.sessions.retrieve(String(booking.stripe_session_id));
155
- if (session.status === 'complete') {
156
- // The customer already paid online (the webhook may not have landed yet).
157
- // Marking it paid offline too would double-charge them silently.
158
- return fail(409, 'already_paid_online', 'The customer already completed payment online for this booking; do not mark it paid manually. Wait for the payment to be recorded, or check the Stripe dashboard.');
159
- }
146
+ const session = await stripe.checkout.sessions.retrieve(String(booking.stripe_session_id));
160
147
  if (session.status === 'open') {
161
- if (connectedAccountId) {
162
- await stripe.checkout.sessions.expire(String(booking.stripe_session_id), {}, { stripeAccount: connectedAccountId });
163
- }
164
- else {
165
- await stripe.checkout.sessions.expire(String(booking.stripe_session_id));
166
- }
148
+ await stripe.checkout.sessions.expire(String(booking.stripe_session_id));
167
149
  }
168
150
  }
169
151
  catch (e) {
@@ -218,9 +200,3 @@ export async function handle(req, operator) {
218
200
  }, { severity: 'warning', bookingId: booking_id }).catch(() => { });
219
201
  return json(200, { ok: true, booking_id, status: 'paid', charged_amount_cents: netCents });
220
202
  }
221
- // Binds the operator so a Connect tenant never relies on a positional second
222
- // argument (Deno.serve passes its ServeHandlerInfo there). Extra args from the
223
- // runtime are ignored.
224
- export function createAdminMarkBookingPaidHandler(operator) {
225
- return (req) => handle(req, operator);
226
- }
@@ -10,7 +10,7 @@ const corsHeaders = {
10
10
  };
11
11
  const LA_TZ = 'America/Los_Angeles';
12
12
  const TRIAL_DAYS = 7;
13
- const TIMEOUT_MS = 20_000;
13
+ const TIMEOUT_MS = 45_000;
14
14
  const JWKS_URL_SUFFIX = '/auth/v1/.well-known/jwks.json';
15
15
  let jwksCache = null;
16
16
  function getJwks(supabaseUrl) {
@@ -1,2 +1 @@
1
- import type { NoticeConfig } from '../businessHours.js';
2
- export declare function handle(req: Request, operator?: NoticeConfig | null): Promise<Response>;
1
+ export declare function handle(req: Request): Promise<Response>;
@@ -4,7 +4,6 @@ import { z } from 'zod';
4
4
  import { getBusinessHoursRow, getBusyRanges, laWallToUtc, laWeekday, } from '../availability.js';
5
5
  import { listFlatBlockOffers, makeDynamicPctResolver, makeListAdjustmentResolver, resolveHalfDayWindow, } from '../pricing.js';
6
6
  import { clientIp, checkRateLimit } from '../rateLimit.js';
7
- import { earliestBookingStartMs, hasBusinessHoursNotice } from '../businessHours.js';
8
7
  // Spells out a whole-dollar amount as words for TTS safety. Retell's TTS has
9
8
  // been observed mispronouncing digit-form 2-3 digit dollar amounts (e.g.
10
9
  // "$215" rendered as "two dollars and fifteen cents") — confirmed via audio
@@ -57,7 +56,7 @@ const AvailabilityBody = z.object({
57
56
  });
58
57
  const ListBody = z.object({ action: z.literal('list') });
59
58
  const Body = z.union([AvailabilityBody, ListBody]);
60
- export async function handle(req, operator) {
59
+ export async function handle(req) {
61
60
  if (req.method === 'OPTIONS')
62
61
  return new Response('ok', { headers: corsHeaders });
63
62
  try {
@@ -182,8 +181,6 @@ export async function handle(req, operator) {
182
181
  // truth for what a customer is actually charged, so a wrong preview here
183
182
  // can never change a charge.
184
183
  const nowMs = Date.now();
185
- // Only when the operator opts in; otherwise slot output is exactly as before.
186
- const noticeFloorMs = hasBusinessHoursNotice(operator) ? earliestBookingStartMs(nowMs, operator) : null;
187
184
  const pctFor = makeDynamicPctResolver(supabase, room, nowMs);
188
185
  // Same contract as `pctFor`, for the list-ADJUSTING rules: a preview of a
189
186
  // peak-hour premium so the picker can show the uplift before the customer
@@ -230,8 +227,7 @@ export async function handle(req, operator) {
230
227
  const rangeLiteral = `[${openUtc.toISOString()},${closeUtc.toISOString()})`;
231
228
  const busy = await getBusyRanges(supabase, room_id, rangeLiteral);
232
229
  const overlaps = (s, e) => busy.some(([bs, be]) => s < be && e > bs);
233
- const fullFree = !overlaps(openUtc.getTime(), closeUtc.getTime()) &&
234
- (noticeFloorMs === null || openUtc.getTime() >= noticeFloorMs);
230
+ const fullFree = !overlaps(openUtc.getTime(), closeUtc.getTime());
235
231
  // Half-day windows come from the SAME resolver the charge path uses
236
232
  // (validateAndPriceDayBlock -> resolveHalfDayWindow), reading this
237
233
  // room's own override columns off the select('*') row above. A room
@@ -240,10 +236,8 @@ export async function handle(req, operator) {
240
236
  // never an error for the whole request. Full-day is untouched by it.
241
237
  const amWin = resolveHalfDayWindow(room, 'half_am', wd, dStr, openUtc, closeUtc);
242
238
  const pmWin = resolveHalfDayWindow(room, 'half_pm', wd, dStr, openUtc, closeUtc);
243
- const amFree = amWin.ok && !overlaps(amWin.startUtc.getTime(), amWin.endUtc.getTime()) &&
244
- (noticeFloorMs === null || amWin.startUtc.getTime() >= noticeFloorMs);
245
- const pmFree = pmWin.ok && !overlaps(pmWin.startUtc.getTime(), pmWin.endUtc.getTime()) &&
246
- (noticeFloorMs === null || pmWin.startUtc.getTime() >= noticeFloorMs);
239
+ const amFree = amWin.ok && !overlaps(amWin.startUtc.getTime(), amWin.endUtc.getTime());
240
+ const pmFree = pmWin.ok && !overlaps(pmWin.startUtc.getTime(), pmWin.endUtc.getTime());
247
241
  // One pct per day (not per block) — a deliberate simplification for
248
242
  // this preview; see makeDynamicPctResolver. Occupancy for this day is
249
243
  // resolved once here, not once per block. isFullDayPrice=true: this
@@ -305,8 +299,7 @@ export async function handle(req, operator) {
305
299
  for (let t = openUtc.getTime(); t + SLOT_MS <= closeUtc.getTime(); t += SLOT_MS) {
306
300
  const s = t;
307
301
  const e = t + SLOT_MS;
308
- const available = !busy.some(([bs, be]) => s < be && e > bs) &&
309
- (noticeFloorMs === null || s >= noticeFloorMs);
302
+ const available = !busy.some(([bs, be]) => s < be && e > bs);
310
303
  // Occupancy (if any occupancy rule is in play) is resolved once for
311
304
  // this whole business day via `rangeLiteral`, not once per slot. This
312
305
  // is the ordinary per-slot preview (isFullDayPrice=false) — it never
@@ -343,8 +336,6 @@ export async function handle(req, operator) {
343
336
  return false;
344
337
  if (bs < openUtc.getTime() || be > closeUtc.getTime())
345
338
  return false;
346
- if (noticeFloorMs !== null && bs < noticeFloorMs)
347
- return false;
348
339
  return !busy.some(([xs, xe]) => bs < xe && be > xs);
349
340
  });
350
341
  // Display-only preview of what pct would apply if the customer's final
@@ -42,10 +42,5 @@ export interface CreateBookingDeps {
42
42
  export declare function handle(req: Request, operator: {
43
43
  domain: string;
44
44
  actorEmail: string;
45
- minNoticeBusinessHours?: number | null;
46
- holidays?: string[] | null;
47
- googleCalendarWriteback?: boolean | null;
48
- stripeConnectedAccountId?: string | null;
49
- stripeApplicationFeePercent?: number | null;
50
45
  }, deps: CreateBookingDeps): Promise<Response>;
51
46
  export {};
@@ -10,10 +10,6 @@ import { resolveMembershipContext } from '../membership.js';
10
10
  import { resolveContractTier, loadTier1Terms, insertTier1Agreement, signerIpFrom, signerUserAgentFrom, } from '../tier1Agreement.js';
11
11
  import { checkPolicyAcceptance, insertPolicyAcknowledgment, POLICY_NOT_ACCEPTED_ERROR, } from '../policyAcknowledgment.js';
12
12
  import { createEventInquiryLead } from '../ghlEventInquiry.js';
13
- import { clampCheckoutExpiresAtSeconds } from '../checkoutSessionParams.js';
14
- import { sanitizeBookingSource } from '../bookingSource.js';
15
- import { writebackBookingCreated } from '../gcalBookingEvents.js';
16
- import { CONNECT_MISCONFIGURED_MESSAGE, createBookingCheckoutSession, planBookingCharge } from '../connectBookingCharge.js';
17
13
  const Contact = z.object({
18
14
  name: z.string().min(1).max(200),
19
15
  email: z.string().email(),
@@ -35,7 +31,6 @@ const Body = z.object({
35
31
  agreementAccepted: z.boolean().optional(),
36
32
  avRequest: z.boolean().optional(),
37
33
  avRequestNotes: z.string().max(1000).optional(),
38
- source: z.unknown().optional(),
39
34
  });
40
35
  // Stripe rejects charges under $0.50. When credit + coupon leave a sub-minimum
41
36
  // remainder we treat the booking as fully covered rather than failing checkout.
@@ -126,7 +121,7 @@ export async function handle(req, operator, deps) {
126
121
  }
127
122
  tier1Terms = loaded.terms;
128
123
  }
129
- const priced = await validateAndPriceForRoom(supabase, room, parsed.data, nowMs, { isMember, allowDynamic: true, notice: operator });
124
+ const priced = await validateAndPriceForRoom(supabase, room, parsed.data, nowMs, { isMember, allowDynamic: true });
130
125
  if (!priced.ok) {
131
126
  return new Response(JSON.stringify({ error: priced.error }), {
132
127
  status: priced.status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
@@ -137,7 +132,6 @@ export async function handle(req, operator, deps) {
137
132
  // Reclaim stale holds overlapping the range so abandoned carts don't block it.
138
133
  await reclaimStaleHoldsExceptCompletedTier3(supabase, room_id, rangeLiteral);
139
134
  const usesBoldSignAgreement = contractTier === 2 || contractTier === 3;
140
- const bookingSource = sanitizeBookingSource(parsed.data.source);
141
135
  const holdExpires = new Date(Date.now() + 60 * 60 * 1000).toISOString();
142
136
  const effectiveHoldExpires = usesBoldSignAgreement
143
137
  ? new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
@@ -158,8 +152,6 @@ export async function handle(req, operator, deps) {
158
152
  contact_phone: contact.phone ?? null,
159
153
  is_member: isMember,
160
154
  policy_accepted_at: new Date().toISOString(),
161
- // Only sent when present so an unmigrated database (no `source` column) keeps working.
162
- ...(bookingSource ? { source: bookingSource } : {}),
163
155
  })
164
156
  .select('id')
165
157
  .single();
@@ -427,7 +419,6 @@ export async function handle(req, operator, deps) {
427
419
  catch (e) {
428
420
  await logOps(supabase, 'booking_side_effect_failed', { step: 'createCalendarEvent', message: String(e) }, { severity: 'warning', bookingId: booking_id });
429
421
  }
430
- await writebackBookingCreated(operator, eff);
431
422
  }
432
423
  }
433
424
  catch (e) {
@@ -486,21 +477,12 @@ export async function handle(req, operator, deps) {
486
477
  status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
487
478
  });
488
479
  }
489
- const chargePlan = planBookingCharge(operator, charged);
490
- if ('error' in chargePlan) {
491
- await abandonHoldAndCoupon('payments_misconfigured');
492
- await supabase.from('bookings').update({ status: 'expired' }).eq('id', booking_id);
493
- await logOps(supabase, 'booking_connect_config_invalid', { error: chargePlan.error, path: 'create-booking' }, { severity: 'error', bookingId: booking_id });
494
- return new Response(JSON.stringify({ error: 'payments_misconfigured', message: CONNECT_MISCONFIGURED_MESSAGE }), {
495
- status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
496
- });
497
- }
498
480
  const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
499
481
  const origin = req.headers.get('origin');
500
482
  const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
501
483
  const human = formatHumanTime(startUtc, endUtc);
502
484
  try {
503
- const session = await createBookingCheckoutSession(stripe, {
485
+ const session = await stripe.checkout.sessions.create({
504
486
  mode: 'payment',
505
487
  customer_email: contact.email,
506
488
  line_items: [{
@@ -512,12 +494,12 @@ export async function handle(req, operator, deps) {
512
494
  },
513
495
  }],
514
496
  metadata: { booking_id },
515
- expires_at: clampCheckoutExpiresAtSeconds(Date.now(), effectiveHoldExpires),
497
+ expires_at: Math.floor(Date.now() / 1000) + 60 * 60,
516
498
  success_url: `${base}/booking/confirmation?session_id={CHECKOUT_SESSION_ID}`,
517
499
  cancel_url: `${base}/meeting-rooms/${room.slug ?? ''}?canceled=1`,
518
500
  // TODO: enable Stripe automatic tax once tax registrations are configured.
519
501
  // automatic_tax: { enabled: true },
520
- }, chargePlan);
502
+ });
521
503
  await supabase
522
504
  .from('bookings')
523
505
  .update({ stripe_session_id: session.id })
@@ -35,11 +35,6 @@ export interface ManageBookingDeps {
35
35
  }, admin: SupabaseLike) => Promise<unknown>;
36
36
  signBus: (verb: string, bookingId: string, roomKey: string, startUtc: string, endUtc: string, secret: string, ts: number) => Promise<string>;
37
37
  toBusUtc: (iso: string) => string;
38
- /** Override for this tenant's event-access middleware origin. Defaults to
39
- * tenant-config.ts's getEventAccessBusBase() (EVENT_ACCESS_BUS_BASE env
40
- * var) when omitted -- same opts-override pattern as
41
- * booking-access-revoke.ts's revokeBookingOrganizerAccessGrants. */
42
- busBase?: string;
43
38
  }
44
39
  declare function parseTstzRange(range: string): {
45
40
  startISO: string;
@@ -73,7 +68,6 @@ declare function bookingViewForCustomer(b: BookingRow, operator: {
73
68
  }>;
74
69
  export declare function handle(req: Request, operator: {
75
70
  operatorName: string;
76
- googleCalendarWriteback?: boolean | null;
77
71
  }, deps: ManageBookingDeps): Promise<Response>;
78
72
  export declare const _test: {
79
73
  bookingViewForCustomer: typeof bookingViewForCustomer;
@@ -1,6 +1,5 @@
1
1
  import { createClient } from '@supabase/supabase-js';
2
2
  import { JWT } from 'google-auth-library';
3
- import { writebackBookingCancelled } from '../gcalBookingEvents.js';
4
3
  import { clientIp, checkRateLimit } from '../rateLimit.js';
5
4
  import { verifyManageToken } from '../manageToken.js';
6
5
  import { resolvePortalSessionEmail } from '../portalSession.js';
@@ -8,8 +7,6 @@ import { logOps } from '../ops.js';
8
7
  import { deriveReservationWifiCode, isReservationWifiRoom } from '../reservationWifiCode.js';
9
8
  import { buildCancellationCreditGrants } from '../rescheduleCredit.js';
10
9
  import { sha256Hex, signBusMessage } from '../busSignature.js';
11
- import { getEventAccessBusBase } from '../tenant-config.js';
12
- import { revokeBookingOrganizerAccessGrants } from './booking-access-revoke.js';
13
10
  const corsHeaders = {
14
11
  'Access-Control-Allow-Origin': '*',
15
12
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -31,7 +28,8 @@ async function signOrganizerLinkE1(secret, verb, ts, bodyHashHex) {
31
28
  const msg = ['e1', verb, ts, bodyHashHex].join('\n');
32
29
  return signBusMessage(msg, secret);
33
30
  }
34
- async function mintOrganizerLinkUrl(admin, actingUserId, grantId, bookingId, busBase) {
31
+ const ORGANIZER_LINK_EXPECTED_ORIGIN = 'https://ftw.granitecity.io';
32
+ async function mintOrganizerLinkUrl(admin, actingUserId, grantId, bookingId) {
35
33
  // Every failure path logs a breadcrumb (severity 'warning', same as the
36
34
  // sibling credential branch's manage_credential_unauthorized) so a broken
37
35
  // contract is visible in ops_events/Slack, even though the customer-facing
@@ -50,7 +48,7 @@ async function mintOrganizerLinkUrl(admin, actingUserId, grantId, bookingId, bus
50
48
  const bodyHash = await sha256Hex(rawBody);
51
49
  const ts = String(Math.floor(Date.now() / 1000));
52
50
  const signature = await signOrganizerLinkE1(secret, 'organizer_link', ts, bodyHash);
53
- const res = await fetch(`${busBase}/admin/event-access/organizer-link`, {
51
+ const res = await fetch('https://ftw.granitecity.io/admin/event-access/organizer-link', {
54
52
  method: 'POST',
55
53
  headers: {
56
54
  'Content-Type': 'application/json',
@@ -67,23 +65,16 @@ async function mintOrganizerLinkUrl(admin, actingUserId, grantId, bookingId, bus
67
65
  return await fail('invalid_response');
68
66
  // The response isn't otherwise authenticated (no signature on the reply),
69
67
  // so a compromised/misconfigured middleware could hand back an
70
- // attacker-controlled URL. Reject anything not on the expected (this
71
- // tenant's own busBase) origin rather than trusting it blindly.
68
+ // attacker-controlled URL. Reject anything not on the expected origin
69
+ // rather than trusting it blindly.
72
70
  let origin;
73
- let expectedOrigin;
74
71
  try {
75
72
  origin = new URL(j.url).origin;
76
73
  }
77
74
  catch {
78
75
  origin = null;
79
76
  }
80
- try {
81
- expectedOrigin = new URL(busBase).origin;
82
- }
83
- catch {
84
- expectedOrigin = null;
85
- }
86
- if (!expectedOrigin || origin !== expectedOrigin)
77
+ if (origin !== ORGANIZER_LINK_EXPECTED_ORIGIN)
87
78
  return await fail('origin_mismatch', { origin });
88
79
  return j.url;
89
80
  }
@@ -212,7 +203,6 @@ export async function handle(req, operator, deps) {
212
203
  const admin = createClient(SUPABASE_URL, SERVICE_ROLE_KEY, {
213
204
  auth: { persistSession: false, autoRefreshToken: false },
214
205
  });
215
- const busBase = deps.busBase ?? getEventAccessBusBase();
216
206
  // Rate-limit BEFORE any DB work.
217
207
  const ip = clientIp(req);
218
208
  const [ipOk] = await Promise.all([
@@ -301,7 +291,11 @@ export async function handle(req, operator, deps) {
301
291
  const ts = Math.floor(Date.now() / 1000);
302
292
  const sig = await deps.signBus('credential', b.id, slug, startUtc, endUtc, busSecret, ts);
303
293
  const qs = new URLSearchParams({ source: 'gc-connect', booking_id: b.id });
304
- const res = await fetch(`${busBase}/bookings/credential?${qs.toString()}`, {
294
+ // FTW membership-bus base URL: same GC-hardcoded infra as
295
+ // _shared/busClient.ts's own BUS_BASE, tracked for the later "make the
296
+ // bus pluggable" phase of this project, not this identity-parameterization
297
+ // phase.
298
+ const res = await fetch(`https://ftw.granitecity.io/bookings/credential?${qs.toString()}`, {
305
299
  method: 'GET',
306
300
  headers: { 'X-GC-Signature': sig, 'X-GC-Timestamp': String(ts) },
307
301
  signal: AbortSignal.timeout(10000),
@@ -362,7 +356,7 @@ export async function handle(req, operator, deps) {
362
356
  const grantEndMs = grant.access_end ? new Date(grant.access_end).getTime() : NaN;
363
357
  const grantWithinWindow = !Number.isFinite(grantEndMs) || grantEndMs > Date.now();
364
358
  if (grant.id && grantWithinWindow) {
365
- organizerLinkUrl = await mintOrganizerLinkUrl(admin, `customer:${authedEmail}`, grant.id, b.id, busBase);
359
+ organizerLinkUrl = await mintOrganizerLinkUrl(admin, `customer:${authedEmail}`, grant.id, b.id);
366
360
  }
367
361
  return json(200, {
368
362
  unlock_pin: grant.unlock_pin ?? null,
@@ -469,8 +463,6 @@ export async function handle(req, operator, deps) {
469
463
  catch (e) {
470
464
  await logOps(admin, 'coupon_reverse_on_cancel_failed', { message: String(e) }, { severity: 'error', bookingId: b.id });
471
465
  }
472
- // Opt-in, fail-soft: remove the write-back event (deterministic id; no stored id needed).
473
- await writebackBookingCancelled(operator, b.rooms?.google_calendar_id, b.id);
474
466
  // Best-effort: delete Google Calendar event.
475
467
  try {
476
468
  const cal = await deleteCalendarEvent(b);
@@ -506,15 +498,6 @@ export async function handle(req, operator, deps) {
506
498
  }
507
499
  }
508
500
  catch { /* never break the response */ }
509
- // Best-effort: revoke organizer door grants (O3b). Must not block cancel.
510
- try {
511
- await revokeBookingOrganizerAccessGrants(admin, {
512
- bookingId: b.id,
513
- actingUserId: `customer:booking:${b.id}`,
514
- reason: 'booking_cancelled',
515
- });
516
- }
517
- catch { /* revokeBookingOrganizerAccessGrants never throws; belt-and-suspenders */ }
518
501
  const { data: fresh } = await admin
519
502
  .from('bookings')
520
503
  .select('id,status,contact_email,contact_name,contact_phone,ghl_contact_id,during,charged_amount_cents,list_amount_cents,dynamic_discount_cents,credit_applied_cents,google_event_id,rooms(id,name,address,google_calendar_id,booking_mode,hourly_cents,day_cents,half_day_cents,min_booking_minutes)')
@@ -48,10 +48,5 @@ export interface RescheduleBookingDeps {
48
48
  export declare function handle(req: Request, operator: {
49
49
  domain: string;
50
50
  actorEmail: string;
51
- minNoticeBusinessHours?: number | null;
52
- holidays?: string[] | null;
53
- googleCalendarWriteback?: boolean | null;
54
- stripeConnectedAccountId?: string | null;
55
- stripeApplicationFeePercent?: number | null;
56
51
  }, deps: RescheduleBookingDeps): Promise<Response>;
57
52
  export {};
@@ -11,8 +11,6 @@ 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';
16
14
  const corsHeaders = {
17
15
  'Access-Control-Allow-Origin': '*',
18
16
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -136,7 +134,6 @@ export async function handle(req, operator, deps) {
136
134
  isMember,
137
135
  allowDynamic: true,
138
136
  allowFreshDynamic: false,
139
- notice: operator,
140
137
  carryForward: {
141
138
  list_cents: O.list_amount_cents ?? 0,
142
139
  discount_cents: O.dynamic_discount_cents ?? 0,
@@ -192,16 +189,6 @@ export async function handle(req, operator, deps) {
192
189
  return json(500, { error: 'reserve_failed' });
193
190
  }
194
191
  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
- }
205
192
  // 6. Guarded cancel of ORIGINAL (paid → cancelled_credited).
206
193
  const { data: cancelled, error: cErr } = await admin
207
194
  .from('bookings')
@@ -240,8 +227,6 @@ export async function handle(req, operator, deps) {
240
227
  }
241
228
  }
242
229
  }
243
- // Opt-in, fail-soft: remove the original booking's write-back event.
244
- await writebackBookingCancelled(operator, room.google_calendar_id, O.id);
245
230
  // Best-effort delete of ORIGINAL calendar event.
246
231
  try {
247
232
  await deleteCalendarEvent(room.google_calendar_id, O.google_event_id);
@@ -506,7 +491,6 @@ export async function handle(req, operator, deps) {
506
491
  catch (e) {
507
492
  await logOps(admin, 'booking_side_effect_failed', { step: 'createCalendarEvent', message: String(e) }, { severity: 'warning', bookingId: NEW_ID });
508
493
  }
509
- await writebackBookingCreated(operator, eff);
510
494
  }
511
495
  }
512
496
  catch (e) {
@@ -530,22 +514,12 @@ export async function handle(req, operator, deps) {
530
514
  await unwindCarriedCoupon('reschedule_missing_stripe_key');
531
515
  return json(500, { error: 'Payments not configured' });
532
516
  }
533
- const chargePlan = planBookingCharge(operator, charged);
534
- if ('error' in chargePlan) {
535
- await admin.rpc('credit_reservation_release', {
536
- p_booking_id: NEW_ID,
537
- p_reason: 'reschedule_payments_misconfigured',
538
- });
539
- await unwindCarriedCoupon('reschedule_payments_misconfigured');
540
- await logOps(admin, 'booking_connect_config_invalid', { error: chargePlan.error, path: 'reschedule-booking' }, { severity: 'error', bookingId: NEW_ID });
541
- return json(500, { error: 'payments_misconfigured' });
542
- }
543
517
  const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
544
518
  const origin = req.headers.get('origin');
545
519
  const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
546
520
  const human = formatHumanTime(startUtc, endUtc);
547
521
  try {
548
- const session = await createBookingCheckoutSession(stripe, {
522
+ const session = await stripe.checkout.sessions.create({
549
523
  mode: 'payment',
550
524
  customer_email: O.contact_email,
551
525
  line_items: [{
@@ -562,7 +536,7 @@ export async function handle(req, operator, deps) {
562
536
  cancel_url: token
563
537
  ? `${base}/manage-booking/?token=${encodeURIComponent(token)}`
564
538
  : `${base}/portal/bookings`,
565
- }, chargePlan);
539
+ });
566
540
  await admin
567
541
  .from('bookings')
568
542
  .update({ stripe_session_id: session.id })
@@ -1,2 +1 @@
1
- import type { NoticeConfig } from '../businessHours.js';
2
- export declare function handle(req: Request, operator?: NoticeConfig | null): Promise<Response>;
1
+ export declare function handle(req: Request): Promise<Response>;
@@ -28,14 +28,13 @@ 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';
32
31
  const MAX_RANGE_DAYS = 31;
33
32
  const Body = z.object({
34
33
  start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
35
34
  end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
36
35
  room_ids: z.array(z.string().uuid()).optional(),
37
36
  });
38
- export async function handle(req, operator) {
37
+ export async function handle(req) {
39
38
  if (req.method === 'OPTIONS')
40
39
  return new Response('ok', { headers: corsHeaders });
41
40
  try {
@@ -80,18 +79,12 @@ export async function handle(req, operator) {
80
79
  throw roomsErr;
81
80
  const rooms = (roomsData ?? []);
82
81
  const dates = dateRange(start_date, end_date);
83
- const noticeFloorMs = hasBusinessHoursNotice(operator) ? earliestBookingStartMs(Date.now(), operator) : null;
84
82
  const results = await Promise.all(rooms.map(async (room) => {
85
83
  const days = await Promise.all(dates.map(async (dateStr) => {
86
84
  const windowStart = laWallToUtc(dateStr, 0, 0).getTime();
87
85
  const windowEnd = laWallToUtc(nextDateStr(dateStr), 0, 0).getTime();
88
86
  const rangeLiteral = `[${new Date(windowStart).toISOString()},${new Date(windowEnd).toISOString()})`;
89
87
  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
- }
95
88
  return {
96
89
  date: dateStr,
97
90
  status: statusForDay(room.booking_mode, busy, unparsed, windowStart, windowEnd),
@@ -43,8 +43,4 @@ 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>;
50
46
  export {};