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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/LICENSE +4 -0
  2. package/dist/bookingAgreementEmail.d.ts +34 -3
  3. package/dist/bookingAgreementEmail.js +100 -1
  4. package/dist/bookingEffects.d.ts +3 -1
  5. package/dist/bookingEffects.js +4 -3
  6. package/dist/bookingSource.d.ts +2 -0
  7. package/dist/bookingSource.js +11 -0
  8. package/dist/businessHours.d.ts +11 -0
  9. package/dist/businessHours.js +55 -0
  10. package/dist/checkoutSessionParams.d.ts +33 -0
  11. package/dist/checkoutSessionParams.js +71 -0
  12. package/dist/commonsSignedUnpaidCancellation.d.ts +154 -0
  13. package/dist/commonsSignedUnpaidCancellation.js +650 -0
  14. package/dist/connectBookingCharge.d.ts +49 -0
  15. package/dist/connectBookingCharge.js +72 -0
  16. package/dist/entitlements.d.ts +1 -1
  17. package/dist/entitlements.js +6 -1
  18. package/dist/functions/admin-acknowledge-contract-violation.d.ts +1 -0
  19. package/dist/functions/admin-acknowledge-contract-violation.js +120 -0
  20. package/dist/functions/admin-cancel-membership.js +109 -13
  21. package/dist/functions/admin-change-membership-plan.js +74 -18
  22. package/dist/functions/admin-charge-guest-print.d.ts +3 -1
  23. package/dist/functions/admin-charge-guest-print.js +8 -1
  24. package/dist/functions/admin-create-booking.d.ts +8 -3
  25. package/dist/functions/admin-create-booking.js +15 -2
  26. package/dist/functions/admin-create-commons-event.d.ts +3 -1
  27. package/dist/functions/admin-create-commons-event.js +8 -1
  28. package/dist/functions/admin-door-write.d.ts +3 -1
  29. package/dist/functions/admin-door-write.js +8 -1
  30. package/dist/functions/admin-issue-day-pass.d.ts +1 -0
  31. package/dist/functions/admin-issue-day-pass.js +8 -1
  32. package/dist/functions/admin-mark-booking-paid.d.ts +6 -1
  33. package/dist/functions/admin-mark-booking-paid.js +27 -3
  34. package/dist/functions/admin-request-trial.js +22 -1
  35. package/dist/functions/auth-email-hook.js +42 -2
  36. package/dist/functions/booking-access-revoke-backstop.d.ts +11 -0
  37. package/dist/functions/booking-access-revoke-backstop.js +121 -0
  38. package/dist/functions/booking-access-revoke-door-state.d.ts +22 -0
  39. package/dist/functions/booking-access-revoke-door-state.js +61 -0
  40. package/dist/functions/booking-access-revoke.d.ts +35 -0
  41. package/dist/functions/booking-access-revoke.js +279 -0
  42. package/dist/functions/booking-availability.d.ts +2 -1
  43. package/dist/functions/booking-availability.js +14 -5
  44. package/dist/functions/conductor.js +39 -16
  45. package/dist/functions/create-booking.d.ts +10 -3
  46. package/dist/functions/create-booking.js +22 -4
  47. package/dist/functions/create-day-pass-checkout.d.ts +1 -0
  48. package/dist/functions/create-day-pass-checkout.js +6 -0
  49. package/dist/functions/create-subscription-checkout.js +7 -2
  50. package/dist/functions/event-access-admin.d.ts +1 -0
  51. package/dist/functions/event-access-admin.js +23 -1
  52. package/dist/functions/event-access-store.js +18 -0
  53. package/dist/functions/guest-print-setup-confirm.d.ts +3 -1
  54. package/dist/functions/guest-print-setup-confirm.js +8 -1
  55. package/dist/functions/guest-print-submit.d.ts +3 -1
  56. package/dist/functions/guest-print-submit.js +8 -1
  57. package/dist/functions/manage-booking.d.ts +9 -1
  58. package/dist/functions/manage-booking.js +140 -6
  59. package/dist/functions/mcp.d.ts +2 -2
  60. package/dist/functions/mcp.js +2 -2
  61. package/dist/functions/member-door-action.d.ts +3 -1
  62. package/dist/functions/member-door-action.js +9 -2
  63. package/dist/functions/membership-door-sync.d.ts +18 -0
  64. package/dist/functions/membership-door-sync.js +76 -6
  65. package/dist/functions/office-assignment-end.d.ts +3 -1
  66. package/dist/functions/office-assignment-end.js +8 -1
  67. package/dist/functions/portal-submit-event.d.ts +1 -0
  68. package/dist/functions/portal-submit-event.js +4 -0
  69. package/dist/functions/reschedule-booking.d.ts +11 -4
  70. package/dist/functions/reschedule-booking.js +39 -2
  71. package/dist/functions/review-ratings.js +1 -1
  72. package/dist/functions/space-availability-range.d.ts +2 -1
  73. package/dist/functions/space-availability-range.js +8 -1
  74. package/dist/functions/stripe-db-reconcile.js +8 -1
  75. package/dist/functions/stripe-webhook.d.ts +4 -0
  76. package/dist/functions/stripe-webhook.js +328 -17
  77. package/dist/functions/sync-gcal-blackouts.js +1 -1
  78. package/dist/functions/timetable-event-register.d.ts +3 -1
  79. package/dist/functions/timetable-event-register.js +8 -1
  80. package/dist/functions/touch-pass-signup.d.ts +3 -1
  81. package/dist/functions/touch-pass-signup.js +9 -2
  82. package/dist/functions/voice-booking.d.ts +1 -1
  83. package/dist/functions/voice-day-pass.d.ts +2 -1
  84. package/dist/functions/voice-day-pass.js +4 -0
  85. package/dist/functions/voice-inquiry.d.ts +3 -1
  86. package/dist/functions/voice-inquiry.js +9 -2
  87. package/dist/functions/voice-membership-signup.d.ts +2 -2
  88. package/dist/functions/voice-tour-booking.d.ts +1 -1
  89. package/dist/gcalBookingEvents.d.ts +59 -0
  90. package/dist/gcalBookingEvents.js +182 -0
  91. package/dist/gcalSync.d.ts +1 -0
  92. package/dist/gcalSync.js +5 -0
  93. package/dist/membershipSubscriptionItems.d.ts +87 -0
  94. package/dist/membershipSubscriptionItems.js +71 -0
  95. package/dist/membershipWelcome.d.ts +1 -1
  96. package/dist/outbox.d.ts +64 -0
  97. package/dist/outbox.js +70 -0
  98. package/dist/pricing.d.ts +10 -2
  99. package/dist/pricing.js +14 -9
  100. package/dist/referralCodeLookup.d.ts +13 -0
  101. package/dist/referralCodeLookup.js +17 -0
  102. package/dist/referralCredits.d.ts +5 -0
  103. package/dist/referralCredits.js +5 -0
  104. package/dist/referralGrant.d.ts +4 -31
  105. package/dist/referralGrant.js +14 -234
  106. package/dist/runtime/env.d.ts +7 -0
  107. package/dist/runtime/env.js +32 -0
  108. package/dist/runtime/fs.d.ts +5 -0
  109. package/dist/runtime/fs.js +16 -0
  110. package/dist/runtime/serve.d.ts +8 -0
  111. package/dist/runtime/serve.js +12 -0
  112. package/dist/stripeConnectEvents.d.ts +11 -0
  113. package/dist/stripeConnectEvents.js +37 -0
  114. package/dist/supabaseTestFakes.js +7 -1
  115. package/dist/tenant-config.d.ts +8 -0
  116. package/dist/tenant-config.js +25 -0
  117. package/dist/tenantManifest.d.ts +85 -0
  118. package/dist/tenantManifest.js +43 -0
  119. package/package.json +59 -3
@@ -18,6 +18,7 @@ import { createClient } from '@supabase/supabase-js';
18
18
  import { resolvePortalSession } from '../portalSession.js';
19
19
  import { checkRateLimit } from '../rateLimit.js';
20
20
  import { logOps } from '../ops.js';
21
+ import { hasEntitlement } from '../entitlements.js';
21
22
  const corsHeaders = {
22
23
  'Access-Control-Allow-Origin': '*',
23
24
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -54,6 +55,9 @@ export async function handle(req, config) {
54
55
  const ok = await checkRateLimit(admin, 'portal-submit-event', email, 10, 3600);
55
56
  if (!ok)
56
57
  return json(429, { error: 'rate_limited' });
58
+ if (!hasEntitlement(config, 'events')) {
59
+ return json(403, { ok: false, error: 'feature_not_enabled', feature: 'events' });
60
+ }
57
61
  let body;
58
62
  try {
59
63
  body = await req.json();
@@ -1,3 +1,4 @@
1
+ import type { SupabaseClient } from '@supabase/supabase-js';
1
2
  interface EffectsBookingRow {
2
3
  id: string;
3
4
  contact_name: string | null;
@@ -17,9 +18,10 @@ interface EffectsBookingRow {
17
18
  usage_instructions?: string | null;
18
19
  } | null;
19
20
  }
21
+ type SupabaseLike = SupabaseClient<any, any, any>;
20
22
  export interface RescheduleBookingDeps {
21
- notifyGhl: (admin: unknown, row: EffectsBookingRow, doorAccess: unknown) => Promise<void>;
22
- createCalendarEvent: (admin: unknown, row: EffectsBookingRow) => Promise<void>;
23
+ notifyGhl: (admin: SupabaseLike, row: EffectsBookingRow, doorAccess: unknown) => Promise<void>;
24
+ createCalendarEvent: (admin: SupabaseLike, row: EffectsBookingRow) => Promise<void>;
23
25
  parseTstzRange: (range: string) => {
24
26
  startISO: string;
25
27
  endISO: string;
@@ -34,17 +36,22 @@ export interface RescheduleBookingDeps {
34
36
  email: string;
35
37
  phone?: string;
36
38
  };
37
- }, admin: unknown) => Promise<Record<string, unknown> | null>;
39
+ }, admin: SupabaseLike) => Promise<Record<string, unknown> | null>;
38
40
  busCancel: (input: {
39
41
  bookingId: string;
40
42
  roomKey: string;
41
43
  startUtc: string;
42
44
  endUtc: string;
43
- }, admin: unknown) => Promise<unknown>;
45
+ }, admin: SupabaseLike) => Promise<unknown>;
44
46
  extractDoorAccess: (busResp: Record<string, unknown> | null) => unknown;
45
47
  }
46
48
  export declare function handle(req: Request, operator: {
47
49
  domain: string;
48
50
  actorEmail: string;
51
+ minNoticeBusinessHours?: number | null;
52
+ holidays?: string[] | null;
53
+ googleCalendarWriteback?: boolean | null;
54
+ stripeConnectedAccountId?: string | null;
55
+ stripeApplicationFeePercent?: number | null;
49
56
  }, deps: RescheduleBookingDeps): Promise<Response>;
50
57
  export {};
@@ -11,6 +11,8 @@ import { resolveIsMember } from '../membership.js';
11
11
  import { buildRescheduleCreditGrants } from '../rescheduleCredit.js';
12
12
  import { resolveContractTier, loadTier1Terms, insertTier1Agreement, signerIpFrom, signerUserAgentFrom, } from '../tier1Agreement.js';
13
13
  import { JWT } from 'google-auth-library';
14
+ import { writebackBookingCancelled, writebackBookingCreated } from '../gcalBookingEvents.js';
15
+ import { createBookingCheckoutSession, planBookingCharge } from '../connectBookingCharge.js';
14
16
  const corsHeaders = {
15
17
  'Access-Control-Allow-Origin': '*',
16
18
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -134,6 +136,7 @@ export async function handle(req, operator, deps) {
134
136
  isMember,
135
137
  allowDynamic: true,
136
138
  allowFreshDynamic: false,
139
+ notice: operator,
137
140
  carryForward: {
138
141
  list_cents: O.list_amount_cents ?? 0,
139
142
  discount_cents: O.dynamic_discount_cents ?? 0,
@@ -189,15 +192,36 @@ export async function handle(req, operator, deps) {
189
192
  return json(500, { error: 'reserve_failed' });
190
193
  }
191
194
  const NEW_ID = newBk.id;
195
+ // Validate Connect account/fee config BEFORE the original booking is
196
+ // cancelled and credited: a bad config must not destroy a confirmed booking.
197
+ // Nothing is reserved yet (credits/coupon come later), so only the new row
198
+ // needs cleanup.
199
+ const connectPreflight = planBookingCharge(operator, 1);
200
+ if ('error' in connectPreflight) {
201
+ await admin.from('bookings').update({ status: 'expired' }).eq('id', NEW_ID);
202
+ await logOps(admin, 'booking_connect_config_invalid', { error: connectPreflight.error, path: 'reschedule-booking', stage: 'preflight' }, { severity: 'error', bookingId: O.id });
203
+ return json(500, { error: 'payments_misconfigured' });
204
+ }
192
205
  // 6. Guarded cancel of ORIGINAL (paid → cancelled_credited).
193
206
  const { data: cancelled, error: cErr } = await admin
194
207
  .from('bookings')
195
208
  .update({ status: 'cancelled_credited' })
196
209
  .eq('id', O.id)
197
210
  .eq('status', 'paid')
211
+ .is('access_revoke_required_at', null)
198
212
  .select('id');
199
213
  if (cErr || !cancelled || cancelled.length === 0) {
200
214
  await admin.from('bookings').update({ status: 'expired' }).eq('id', NEW_ID);
215
+ if (!cErr) {
216
+ const { data: flagRow } = await admin
217
+ .from('bookings')
218
+ .select('status,access_revoke_required_at')
219
+ .eq('id', O.id)
220
+ .maybeSingle();
221
+ if (flagRow && flagRow.status === 'paid' && flagRow.access_revoke_required_at) {
222
+ return json(409, { error: 'booking_flagged_contact_support' });
223
+ }
224
+ }
201
225
  return json(409, { error: 'already_changed' });
202
226
  }
203
227
  // Issue credit for the amount originally charged, split into up to TWO
@@ -227,6 +251,8 @@ export async function handle(req, operator, deps) {
227
251
  }
228
252
  }
229
253
  }
254
+ // Opt-in, fail-soft: remove the original booking's write-back event.
255
+ await writebackBookingCancelled(operator, room.google_calendar_id, O.id);
230
256
  // Best-effort delete of ORIGINAL calendar event.
231
257
  try {
232
258
  await deleteCalendarEvent(room.google_calendar_id, O.google_event_id);
@@ -491,6 +517,7 @@ export async function handle(req, operator, deps) {
491
517
  catch (e) {
492
518
  await logOps(admin, 'booking_side_effect_failed', { step: 'createCalendarEvent', message: String(e) }, { severity: 'warning', bookingId: NEW_ID });
493
519
  }
520
+ await writebackBookingCreated(operator, eff);
494
521
  }
495
522
  }
496
523
  catch (e) {
@@ -514,12 +541,22 @@ export async function handle(req, operator, deps) {
514
541
  await unwindCarriedCoupon('reschedule_missing_stripe_key');
515
542
  return json(500, { error: 'Payments not configured' });
516
543
  }
544
+ const chargePlan = planBookingCharge(operator, charged);
545
+ if ('error' in chargePlan) {
546
+ await admin.rpc('credit_reservation_release', {
547
+ p_booking_id: NEW_ID,
548
+ p_reason: 'reschedule_payments_misconfigured',
549
+ });
550
+ await unwindCarriedCoupon('reschedule_payments_misconfigured');
551
+ await logOps(admin, 'booking_connect_config_invalid', { error: chargePlan.error, path: 'reschedule-booking' }, { severity: 'error', bookingId: NEW_ID });
552
+ return json(500, { error: 'payments_misconfigured' });
553
+ }
517
554
  const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
518
555
  const origin = req.headers.get('origin');
519
556
  const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
520
557
  const human = formatHumanTime(startUtc, endUtc);
521
558
  try {
522
- const session = await stripe.checkout.sessions.create({
559
+ const session = await createBookingCheckoutSession(stripe, {
523
560
  mode: 'payment',
524
561
  customer_email: O.contact_email,
525
562
  line_items: [{
@@ -536,7 +573,7 @@ export async function handle(req, operator, deps) {
536
573
  cancel_url: token
537
574
  ? `${base}/manage-booking/?token=${encodeURIComponent(token)}`
538
575
  : `${base}/portal/bookings`,
539
- });
576
+ }, chargePlan);
540
577
  await admin
541
578
  .from('bookings')
542
579
  .update({ stripe_session_id: session.id })
@@ -1,7 +1,7 @@
1
1
  // Public, read-only review-ratings endpoint.
2
2
  //
3
3
  // Fetches the Google Places and Yelp Fusion ratings for the business and
4
- // returns a small JSON payload. Exists so granitecity.io — a prerendered
4
+ // returns a small JSON payload. Exists so the operator's site — a prerendered
5
5
  // SPA where everything in the client bundle is public — never has to embed
6
6
  // a vendor API key or a hand-typed review number in src/. Vendor keys live
7
7
  // only in this function's environment (see env var names below).
@@ -1 +1,2 @@
1
- export declare function handle(req: Request): Promise<Response>;
1
+ import type { NoticeConfig } from '../businessHours.js';
2
+ export declare function handle(req: Request, operator?: NoticeConfig | null): Promise<Response>;
@@ -28,13 +28,14 @@ import { z } from 'zod';
28
28
  import { getBusyRangesDetailed, laWallToUtc } from '../availability.js';
29
29
  import { clientIp, checkRateLimit } from '../rateLimit.js';
30
30
  import { dateRange, nextDateStr, statusForDay } from './dayStatus.js';
31
+ import { earliestBookingStartMs, hasBusinessHoursNotice } from '../businessHours.js';
31
32
  const MAX_RANGE_DAYS = 31;
32
33
  const Body = z.object({
33
34
  start_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
34
35
  end_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
35
36
  room_ids: z.array(z.string().uuid()).optional(),
36
37
  });
37
- export async function handle(req) {
38
+ export async function handle(req, operator) {
38
39
  if (req.method === 'OPTIONS')
39
40
  return new Response('ok', { headers: corsHeaders });
40
41
  try {
@@ -79,12 +80,18 @@ export async function handle(req) {
79
80
  throw roomsErr;
80
81
  const rooms = (roomsData ?? []);
81
82
  const dates = dateRange(start_date, end_date);
83
+ const noticeFloorMs = hasBusinessHoursNotice(operator) ? earliestBookingStartMs(Date.now(), operator) : null;
82
84
  const results = await Promise.all(rooms.map(async (room) => {
83
85
  const days = await Promise.all(dates.map(async (dateStr) => {
84
86
  const windowStart = laWallToUtc(dateStr, 0, 0).getTime();
85
87
  const windowEnd = laWallToUtc(nextDateStr(dateStr), 0, 0).getTime();
86
88
  const rangeLiteral = `[${new Date(windowStart).toISOString()},${new Date(windowEnd).toISOString()})`;
87
89
  const { busy, unparsed } = await getBusyRangesDetailed(supabase, room.id, rangeLiteral);
90
+ // Opt-in notice window: treat everything before the earliest bookable
91
+ // start as busy so the public calendar never advertises it as open.
92
+ if (noticeFloorMs !== null && noticeFloorMs > windowStart) {
93
+ busy.push([windowStart, Math.min(noticeFloorMs, windowEnd)]);
94
+ }
88
95
  return {
89
96
  date: dateStr,
90
97
  status: statusForDay(room.booking_mode, busy, unparsed, windowStart, windowEnd),
@@ -10,6 +10,7 @@
10
10
  // fallback). Uses the operator's own STRIPE_SECRET_KEY only.
11
11
  import { createClient } from '@supabase/supabase-js';
12
12
  import Stripe from 'stripe';
13
+ import { findBaseItem } from '../membershipSubscriptionItems.js';
13
14
  const WINDOW_DAYS = 7;
14
15
  const STRIPE_LIVE = new Set(['active', 'trialing', 'past_due', 'unpaid', 'incomplete']);
15
16
  const DB_ENTITLED = new Set(['active', 'trialing', 'past_due']);
@@ -48,6 +49,12 @@ function subCurrentPeriodEndISO(sub) {
48
49
  const top = sub.current_period_end;
49
50
  if (typeof top === 'number')
50
51
  return new Date(top * 1000).toISOString();
52
+ // Prefer the base (non-addon) item; fall back to the old items.data[0]
53
+ // behavior when findBaseItem can't resolve exactly one, so this never
54
+ // regresses for a shape it used to handle.
55
+ const baseItemCpe = findBaseItem(sub)?.current_period_end;
56
+ if (typeof baseItemCpe === 'number')
57
+ return new Date(baseItemCpe * 1000).toISOString();
51
58
  const itemCpe = sub.items?.data?.[0]?.current_period_end;
52
59
  if (typeof itemCpe === 'number')
53
60
  return new Date(itemCpe * 1000).toISOString();
@@ -197,7 +204,7 @@ export async function handle(req, operator) {
197
204
  for (const s of paidSessions) {
198
205
  const checkoutType = s.metadata?.checkout_type ?? null;
199
206
  // frAIdays lunch pre-orders use a standalone Stripe Payment Link and are
200
- // tracked outside gc-io entirely (Luma/luma-receiver), not in `bookings`.
207
+ // tracked outside this platform entirely (Luma/luma-receiver), not in `bookings`.
201
208
  // Skip them here rather than false-alarming on every lunch order.
202
209
  const FRAIDAYS_LUNCH_PAYMENT_LINK = 'plink_1U3fBDIRhYejQaS5rlYIQF5P';
203
210
  if (s.payment_link === FRAIDAYS_LUNCH_PAYMENT_LINK)
@@ -43,4 +43,8 @@ export interface StripeWebhookConfig {
43
43
  }>;
44
44
  }
45
45
  export declare function createStripeWebhookHandler(config: StripeWebhookConfig): (req: Request) => Promise<Response>;
46
+ export interface StripeConnectWebhookOperator {
47
+ stripeConnectedAccountId: string | null | undefined;
48
+ }
49
+ export declare function createStripeConnectWebhookHandler(config: StripeWebhookConfig & StripeConnectWebhookOperator): (req: Request) => Promise<Response>;
46
50
  export {};