@simplelayer/graniteer-core 0.4.2 → 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 (120) 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/printBilling.js +47 -47
  101. package/dist/referralCodeLookup.d.ts +13 -0
  102. package/dist/referralCodeLookup.js +17 -0
  103. package/dist/referralCredits.d.ts +5 -0
  104. package/dist/referralCredits.js +5 -0
  105. package/dist/referralGrant.d.ts +4 -31
  106. package/dist/referralGrant.js +14 -234
  107. package/dist/runtime/env.d.ts +7 -0
  108. package/dist/runtime/env.js +32 -0
  109. package/dist/runtime/fs.d.ts +5 -0
  110. package/dist/runtime/fs.js +16 -0
  111. package/dist/runtime/serve.d.ts +8 -0
  112. package/dist/runtime/serve.js +12 -0
  113. package/dist/stripeConnectEvents.d.ts +11 -0
  114. package/dist/stripeConnectEvents.js +37 -0
  115. package/dist/supabaseTestFakes.js +7 -1
  116. package/dist/tenant-config.d.ts +8 -0
  117. package/dist/tenant-config.js +25 -0
  118. package/dist/tenantManifest.d.ts +85 -0
  119. package/dist/tenantManifest.js +43 -0
  120. package/package.json +59 -3
@@ -0,0 +1,279 @@
1
+ // Best-effort revoke of a booking's organizer door grants via the tenant
2
+ // middleware's signed /admin/event-access/revoke path (same e1 HMAC contract
3
+ // as event-access-admin.ts). Never throws; failures are ops-logged only.
4
+ import { logOps } from '../ops.js';
5
+ import { sha256Hex, signBusMessage } from '../busSignature.js';
6
+ import { getEventAccessBusBase } from '../tenant-config.js';
7
+ import { doorReadForOpsLog, isDoorStateCompleteForGrantRevoke, } from './booking-access-revoke-door-state.js';
8
+ /** @deprecated Granite City's literal default, kept for import compatibility.
9
+ * The actual default is resolved at call time from tenant-config.ts's
10
+ * getEventAccessBusBase(), which reads the EVENT_ACCESS_BUS_BASE env var. */
11
+ export const DEFAULT_EVENT_ACCESS_BUS_BASE = 'https://ftw.granitecity.io';
12
+ /** C6 code-side: revoke calls must stay at or below 8s. */
13
+ export const REVOKE_TIMEOUT_MS = 8_000;
14
+ const MAX_GRANTS_PER_BATCH = 5;
15
+ /** Hardening: cap in-process sweep batches (20 × 5 grants max per edge invocation). */
16
+ export const MAX_REVOKE_SWEEP_BATCHES = 20;
17
+ const REVOCABLE_STATUSES = ['active', 'pending', 'reconciling', 'revoke_failed'];
18
+ const SAFE_ERROR_CODE = /^[a-z_]{1,64}$/;
19
+ export const BOOKING_GRANT_REVOKE_ENABLED_ENV = 'BOOKING_GRANT_REVOKE_ENABLED';
20
+ /** Tests only: next revoke call throws (W1 marker-failed + revoke throw path). */
21
+ let forceRevokeThrowForTest = false;
22
+ export function setForceRevokeThrowForTest(enabled) {
23
+ forceRevokeThrowForTest = enabled;
24
+ }
25
+ /** Fail-closed: only the exact string 'true' arms revoke work. */
26
+ export function isBookingGrantRevokeEnabled() {
27
+ return Deno.env.get(BOOKING_GRANT_REVOKE_ENABLED_ENV) === 'true';
28
+ }
29
+ export function errorNameFromUnknown(e) {
30
+ if (e instanceof Error && e.name)
31
+ return e.name;
32
+ return 'Error';
33
+ }
34
+ /**
35
+ * CS-GM product decision (O3b / PR #21): partial refunds must NOT revoke organizer door access.
36
+ * The guest keeps a valid paid booking; grants remain until the booking window ends.
37
+ *
38
+ * Stripe emits `charge.refunded` on every refund leg, but `charge.refunded` is only `true` once
39
+ * the charge is fully refunded — that is the sole gate for organizer grant revoke on refund.
40
+ */
41
+ export function shouldRevokeOrganizerGrantsOnStripeChargeRefunded(charge) {
42
+ return charge.refunded === true;
43
+ }
44
+ function parseMiddlewareBody(text) {
45
+ if (!text)
46
+ return null;
47
+ try {
48
+ const parsed = JSON.parse(text);
49
+ return parsed && typeof parsed === 'object' ? parsed : null;
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
55
+ function middlewareErrorCode(parsed) {
56
+ const err = parsed?.error;
57
+ if (typeof err !== 'string' || !SAFE_ERROR_CODE.test(err))
58
+ return undefined;
59
+ return err;
60
+ }
61
+ function opsDoorReadDetail(parsed) {
62
+ const doorRead = doorReadForOpsLog(parsed?.door_read);
63
+ return doorRead ? { door_read: doorRead } : {};
64
+ }
65
+ async function signRevokeE1(secret, verb, ts, bodyHashHex) {
66
+ const msg = ['e1', verb, ts, bodyHashHex].join('\n');
67
+ return signBusMessage(msg, secret);
68
+ }
69
+ async function postRevoke(admin, opts) {
70
+ const outbound = { acting_user_id: opts.actingUserId, grant_id: opts.grantId };
71
+ const rawBody = JSON.stringify(outbound);
72
+ const bodyHash = await sha256Hex(rawBody);
73
+ const ts = String(Math.floor(Date.now() / 1000));
74
+ const signature = await signRevokeE1(opts.secret, 'revoke', ts, bodyHash);
75
+ let res;
76
+ try {
77
+ res = await fetch(`${opts.busBase}/admin/event-access/revoke`, {
78
+ method: 'POST',
79
+ headers: {
80
+ 'Content-Type': 'application/json',
81
+ 'X-Event-Access-Signature': signature,
82
+ 'X-Event-Access-Timestamp': ts,
83
+ },
84
+ body: rawBody,
85
+ signal: AbortSignal.timeout(REVOKE_TIMEOUT_MS),
86
+ });
87
+ }
88
+ catch (e) {
89
+ await logOps(admin, 'booking_access_revoke_call_error', {
90
+ reason: opts.reason,
91
+ grant_id: opts.grantId,
92
+ error_name: errorNameFromUnknown(e),
93
+ }, { severity: 'error', bookingId: opts.bookingId });
94
+ return;
95
+ }
96
+ const text = await res.text();
97
+ const parsed = parseMiddlewareBody(text);
98
+ if (res.ok) {
99
+ // C5 (flag-on): waits on O3(a) middleware — HTTP 200 must satisfy the C6 ruling read.
100
+ if (!isDoorStateCompleteForGrantRevoke(parsed)) {
101
+ await logOps(admin, 'booking_access_revoke_door_not_secured', {
102
+ reason: opts.reason,
103
+ grant_id: opts.grantId,
104
+ status: res.status,
105
+ ...opsDoorReadDetail(parsed),
106
+ }, { severity: 'error', bookingId: opts.bookingId });
107
+ }
108
+ return;
109
+ }
110
+ const errCode = middlewareErrorCode(parsed);
111
+ if (errCode === 'grant_not_found') {
112
+ return;
113
+ }
114
+ if (errCode === 'grant_not_revocable' || errCode === 'grant_already_revoked' || errCode === 'already_revoked') {
115
+ if (isDoorStateCompleteForGrantRevoke(parsed)) {
116
+ return;
117
+ }
118
+ // R1: not-revocable without a secured door is an error, not a warning.
119
+ await logOps(admin, 'booking_access_revoke_not_revocable', {
120
+ reason: opts.reason,
121
+ grant_id: opts.grantId,
122
+ status: res.status,
123
+ error_code: errCode,
124
+ ...opsDoorReadDetail(parsed),
125
+ }, { severity: 'error', bookingId: opts.bookingId });
126
+ return;
127
+ }
128
+ const detail = {
129
+ reason: opts.reason,
130
+ grant_id: opts.grantId,
131
+ status: res.status,
132
+ };
133
+ if (errCode)
134
+ detail.error_code = errCode;
135
+ await logOps(admin, 'booking_access_revoke_call_failed', detail, { severity: 'error', bookingId: opts.bookingId });
136
+ }
137
+ /**
138
+ * Revoke every active or upcoming organizer access grant for `bookingId`.
139
+ * Safe to call multiple times (cancel replay, Stripe redelivery after revoke).
140
+ */
141
+ export async function revokeBookingOrganizerAccessGrants(admin, opts) {
142
+ if (!isBookingGrantRevokeEnabled()) {
143
+ await logOps(admin, 'booking_access_revoke_skipped_disabled', {
144
+ reason: opts.reason,
145
+ }, { severity: 'info', bookingId: opts.bookingId });
146
+ return;
147
+ }
148
+ if (forceRevokeThrowForTest) {
149
+ forceRevokeThrowForTest = false;
150
+ throw new Error('forced revoke throw for test');
151
+ }
152
+ const busBase = opts.busBase ?? getEventAccessBusBase();
153
+ const triedGrantIds = new Set();
154
+ try {
155
+ const listRevocable = async () => {
156
+ const { data: grants, error: listErr } = await admin
157
+ .from('booking_access_grants')
158
+ .select('id,status,access_end')
159
+ .eq('booking_id', opts.bookingId)
160
+ .in('status', [...REVOCABLE_STATUSES]);
161
+ if (listErr) {
162
+ const code = listErr.code;
163
+ await logOps(admin, 'booking_access_revoke_lookup_failed', {
164
+ reason: opts.reason,
165
+ ...(typeof code === 'string' ? { error_code: code } : {}),
166
+ }, { severity: 'error', bookingId: opts.bookingId });
167
+ return null;
168
+ }
169
+ const rows = (grants ?? []);
170
+ // Hardening: stable ordering before batching.
171
+ return rows.filter((row) => row.id).sort((a, b) => a.id.localeCompare(b.id));
172
+ };
173
+ const clearAccessRevokeMarkerIfDone = async (knownNoRevocableGrants = false) => {
174
+ if (!knownNoRevocableGrants) {
175
+ const remaining = await listRevocable();
176
+ if (remaining === null || remaining.length > 0)
177
+ return;
178
+ }
179
+ await admin.from('bookings')
180
+ .update({ access_revoke_required_at: null })
181
+ .eq('id', opts.bookingId)
182
+ .not('access_revoke_required_at', 'is', null);
183
+ };
184
+ const initial = await listRevocable();
185
+ if (initial === null)
186
+ return;
187
+ if (initial.length === 0) {
188
+ await clearAccessRevokeMarkerIfDone(true);
189
+ return;
190
+ }
191
+ if (initial.length > MAX_GRANTS_PER_BATCH) {
192
+ await logOps(admin, 'booking_access_revoke_truncated', {
193
+ reason: opts.reason,
194
+ count: initial.length,
195
+ }, { severity: 'error', bookingId: opts.bookingId });
196
+ }
197
+ const { data: secretRaw, error: secretErr } = await admin.rpc('get_event_access_hmac_secret');
198
+ const secret = typeof secretRaw === 'string' ? secretRaw : null;
199
+ if (secretErr || !secret) {
200
+ await logOps(admin, 'booking_access_revoke_secret_missing', {
201
+ reason: opts.reason,
202
+ }, { severity: 'error', bookingId: opts.bookingId });
203
+ return;
204
+ }
205
+ // C6 code-side: Promise.allSettled batches (≤5) until done, stalled, or hardening cap.
206
+ let batches = 0;
207
+ let truncatedSweepLogged = false;
208
+ while (batches < MAX_REVOKE_SWEEP_BATCHES) {
209
+ const rows = batches === 0 ? initial : await listRevocable();
210
+ if (rows === null)
211
+ return;
212
+ if (rows.length === 0) {
213
+ await clearAccessRevokeMarkerIfDone(true);
214
+ break;
215
+ }
216
+ const pending = rows.filter((row) => !triedGrantIds.has(row.id));
217
+ if (pending.length === 0) {
218
+ await logOps(admin, 'booking_access_revoke_sweep_no_progress', {
219
+ reason: opts.reason,
220
+ grant_ids: rows.map((r) => r.id),
221
+ }, { severity: 'error', bookingId: opts.bookingId });
222
+ break;
223
+ }
224
+ if (batches > 0 && rows.length > MAX_GRANTS_PER_BATCH && !truncatedSweepLogged) {
225
+ await logOps(admin, 'booking_access_revoke_sweep_continued', {
226
+ reason: opts.reason,
227
+ count: rows.length,
228
+ batch: batches + 1,
229
+ }, { severity: 'info', bookingId: opts.bookingId });
230
+ truncatedSweepLogged = true;
231
+ }
232
+ const idsBefore = new Set(rows.map((r) => r.id));
233
+ const targets = pending.slice(0, MAX_GRANTS_PER_BATCH);
234
+ for (const row of targets)
235
+ triedGrantIds.add(row.id);
236
+ await Promise.allSettled(targets.map((row) => postRevoke(admin, {
237
+ busBase,
238
+ secret,
239
+ actingUserId: opts.actingUserId,
240
+ grantId: row.id,
241
+ bookingId: opts.bookingId,
242
+ reason: opts.reason,
243
+ })));
244
+ batches += 1;
245
+ const afterRows = await listRevocable();
246
+ if (afterRows === null)
247
+ return;
248
+ const idsAfter = new Set(afterRows.map((r) => r.id));
249
+ const removedCount = [...idsBefore].filter((id) => !idsAfter.has(id)).length;
250
+ if (removedCount === 0) {
251
+ await logOps(admin, 'booking_access_revoke_sweep_no_progress', {
252
+ reason: opts.reason,
253
+ grant_ids: afterRows.map((r) => r.id),
254
+ batches_run: batches,
255
+ }, { severity: 'error', bookingId: opts.bookingId });
256
+ break;
257
+ }
258
+ }
259
+ if (batches >= MAX_REVOKE_SWEEP_BATCHES) {
260
+ const remaining = await listRevocable();
261
+ if (remaining === null)
262
+ return;
263
+ if (remaining.length > 0) {
264
+ await logOps(admin, 'booking_access_revoke_sweep_incomplete', {
265
+ reason: opts.reason,
266
+ remaining_count: remaining.length,
267
+ batches_run: batches,
268
+ }, { severity: 'error', bookingId: opts.bookingId });
269
+ }
270
+ }
271
+ await clearAccessRevokeMarkerIfDone();
272
+ }
273
+ catch (e) {
274
+ await logOps(admin, 'booking_access_revoke_unexpected', {
275
+ reason: opts.reason,
276
+ error_name: errorNameFromUnknown(e),
277
+ }, { severity: 'error', bookingId: opts.bookingId });
278
+ }
279
+ }
@@ -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>;
@@ -4,6 +4,7 @@ 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';
7
8
  // Spells out a whole-dollar amount as words for TTS safety. Retell's TTS has
8
9
  // been observed mispronouncing digit-form 2-3 digit dollar amounts (e.g.
9
10
  // "$215" rendered as "two dollars and fifteen cents") — confirmed via audio
@@ -56,7 +57,7 @@ const AvailabilityBody = z.object({
56
57
  });
57
58
  const ListBody = z.object({ action: z.literal('list') });
58
59
  const Body = z.union([AvailabilityBody, ListBody]);
59
- export async function handle(req) {
60
+ export async function handle(req, operator) {
60
61
  if (req.method === 'OPTIONS')
61
62
  return new Response('ok', { headers: corsHeaders });
62
63
  try {
@@ -181,6 +182,8 @@ export async function handle(req) {
181
182
  // truth for what a customer is actually charged, so a wrong preview here
182
183
  // can never change a charge.
183
184
  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;
184
187
  const pctFor = makeDynamicPctResolver(supabase, room, nowMs);
185
188
  // Same contract as `pctFor`, for the list-ADJUSTING rules: a preview of a
186
189
  // peak-hour premium so the picker can show the uplift before the customer
@@ -227,7 +230,8 @@ export async function handle(req) {
227
230
  const rangeLiteral = `[${openUtc.toISOString()},${closeUtc.toISOString()})`;
228
231
  const busy = await getBusyRanges(supabase, room_id, rangeLiteral);
229
232
  const overlaps = (s, e) => busy.some(([bs, be]) => s < be && e > bs);
230
- const fullFree = !overlaps(openUtc.getTime(), closeUtc.getTime());
233
+ const fullFree = !overlaps(openUtc.getTime(), closeUtc.getTime()) &&
234
+ (noticeFloorMs === null || openUtc.getTime() >= noticeFloorMs);
231
235
  // Half-day windows come from the SAME resolver the charge path uses
232
236
  // (validateAndPriceDayBlock -> resolveHalfDayWindow), reading this
233
237
  // room's own override columns off the select('*') row above. A room
@@ -236,8 +240,10 @@ export async function handle(req) {
236
240
  // never an error for the whole request. Full-day is untouched by it.
237
241
  const amWin = resolveHalfDayWindow(room, 'half_am', wd, dStr, openUtc, closeUtc);
238
242
  const pmWin = resolveHalfDayWindow(room, 'half_pm', wd, dStr, openUtc, closeUtc);
239
- const amFree = amWin.ok && !overlaps(amWin.startUtc.getTime(), amWin.endUtc.getTime());
240
- const pmFree = pmWin.ok && !overlaps(pmWin.startUtc.getTime(), pmWin.endUtc.getTime());
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);
241
247
  // One pct per day (not per block) — a deliberate simplification for
242
248
  // this preview; see makeDynamicPctResolver. Occupancy for this day is
243
249
  // resolved once here, not once per block. isFullDayPrice=true: this
@@ -299,7 +305,8 @@ export async function handle(req) {
299
305
  for (let t = openUtc.getTime(); t + SLOT_MS <= closeUtc.getTime(); t += SLOT_MS) {
300
306
  const s = t;
301
307
  const e = t + SLOT_MS;
302
- const available = !busy.some(([bs, be]) => s < be && e > bs);
308
+ const available = !busy.some(([bs, be]) => s < be && e > bs) &&
309
+ (noticeFloorMs === null || s >= noticeFloorMs);
303
310
  // Occupancy (if any occupancy rule is in play) is resolved once for
304
311
  // this whole business day via `rangeLiteral`, not once per slot. This
305
312
  // is the ordinary per-slot preview (isFullDayPrice=false) — it never
@@ -336,6 +343,8 @@ export async function handle(req) {
336
343
  return false;
337
344
  if (bs < openUtc.getTime() || be > closeUtc.getTime())
338
345
  return false;
346
+ if (noticeFloorMs !== null && bs < noticeFloorMs)
347
+ return false;
339
348
  return !busy.some(([xs, xe]) => bs < xe && be > xs);
340
349
  });
341
350
  // Display-only preview of what pct would apply if the customer's final
@@ -28,9 +28,8 @@ import { checkConductorRateLimit, fetchConductorKey, insertConductorEvent, } fro
28
28
  const MODEL = 'claude-haiku-4-5-20251001';
29
29
  /** Short Q&A answer, not a report — deliberately not ls-quarterly-brief's 8000. */
30
30
  const MAX_TOKENS = 1024;
31
- const KB_LIMIT = 30;
32
- /** Per-article body cap, so one long runbook can't crowd out the other 29. */
33
- const KB_BODY_CHARS = 2500;
31
+ /** Per-article body cap. At most eight ranked articles are loaded, so each can keep more of its text. */
32
+ const KB_BODY_CHARS = 6000;
34
33
  const QUESTION_MAX_CHARS = 2000;
35
34
  /**
36
35
  * Bound on what gets stored in the audit row. MAX_TOKENS = 1024 caps a real
@@ -271,19 +270,43 @@ export async function handle(req, operator) {
271
270
  // future third audience value cannot silently start appearing in members'
272
271
  // prompts before anyone revisits this line.
273
272
  //
274
- // KNOWN v1 LIMITATION, not an oversight: "the 30 most recently updated
275
- // articles" is the whole of the relevance ranking. There is no search index or
276
- // embedding store in this repo to rank against, so an article that would have
277
- // answered the question can fall outside the window. Out of scope for v1.
273
+ // Ranking is public.search_kb_articles(), called on this same caller-JWT
274
+ // client. The function is SECURITY INVOKER, so RLS stays the authorization
275
+ // boundary; `audiences` is the same narrowing filter as the old select
276
+ // (member: ['member'], staff: ['admin','member']) and is applied again inside
277
+ // the function. A full-text miss falls back to newest-first there — still
278
+ // inside that audience list, still capped. This package does not apply that
279
+ // SQL. PGRST202 (function not in the PostgREST schema cache) means the
280
+ // operator has not applied the migration yet: fall back in-process to the
281
+ // previous newest-30 table select on the same caller-JWT client, so an
282
+ // upgrade without the RPC does not silently wipe the knowledge base. Any
283
+ // other RPC error, or a payload that is not an article array, still takes
284
+ // the fail-soft path below rather than telling the model the library is empty.
278
285
  const kbAudiences = actorType === 'staff' ? ['admin', 'member'] : ['member'];
279
- const { data: kbRows, error: kbErr } = await reader
280
- .from('kb_articles')
281
- .select('slug,title,audience,tool,tags,body_markdown')
282
- .in('audience', kbAudiences)
283
- .order('updated_at', { ascending: false })
284
- .limit(KB_LIMIT);
286
+ let { data: kbRows, error: kbErr } = await reader.rpc('search_kb_articles', {
287
+ q: question,
288
+ audiences: kbAudiences,
289
+ max_rows: 8,
290
+ });
291
+ if (kbErr?.code === 'PGRST202') {
292
+ console.warn('[conductor] search_kb_articles missing (PGRST202); falling back to newest-30 table select');
293
+ const fallback = await reader
294
+ .from('kb_articles')
295
+ .select('slug,title,audience,tool,tags,body_markdown')
296
+ .in('audience', kbAudiences)
297
+ .order('updated_at', { ascending: false })
298
+ .limit(30);
299
+ kbRows = fallback.data;
300
+ kbErr = fallback.error;
301
+ }
302
+ // null / non-array is "returned nothing", distinct from a real empty list
303
+ // (no articles in this audience). Only the former is a failed load.
304
+ const kbList = Array.isArray(kbRows) ? kbRows : null;
285
305
  if (kbErr)
286
306
  console.warn('[conductor] kb_articles read failed', kbErr.message);
307
+ else if (kbList === null)
308
+ console.warn('[conductor] kb_articles read failed', 'search_kb_articles returned nothing');
309
+ const kbUnavailable = Boolean(kbErr) || kbList === null;
287
310
  // Own-record context is member-only in v1. Staff Conductor answers
288
311
  // wayfinding from kb_articles only — there is no "which member" input, and
289
312
  // building a staff member-lookup is explicitly out of scope.
@@ -337,10 +360,10 @@ export async function handle(req, operator) {
337
360
  const open = `<<<${fence}>>>`;
338
361
  const close = `<<<END ${fence}>>>`;
339
362
  const fenced = (label, body) => [`## ${label}`, open, body, close].join('\n');
340
- const kbBlock = kbErr
363
+ const kbBlock = kbUnavailable
341
364
  ? '(Help articles could NOT be loaded for this request. This is not a statement that none exist.)'
342
- : (kbRows ?? []).length
343
- ? (kbRows ?? [])
365
+ : kbList.length
366
+ ? kbList
344
367
  .map((a) => {
345
368
  const tags = Array.isArray(a.tags) ? a.tags.join(', ') : '';
346
369
  return [
@@ -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 CreateBookingDeps {
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,11 +36,16 @@ export interface CreateBookingDeps {
34
36
  email: string;
35
37
  phone?: string;
36
38
  };
37
- }, supabase: unknown) => Promise<Record<string, unknown> | null>;
39
+ }, supabase: SupabaseLike) => Promise<Record<string, unknown> | null>;
38
40
  extractDoorAccess: (busResp: Record<string, unknown> | null) => unknown;
39
41
  }
40
42
  export declare function handle(req: Request, operator: {
41
43
  domain: string;
42
44
  actorEmail: string;
45
+ minNoticeBusinessHours?: number | null;
46
+ holidays?: string[] | null;
47
+ googleCalendarWriteback?: boolean | null;
48
+ stripeConnectedAccountId?: string | null;
49
+ stripeApplicationFeePercent?: number | null;
43
50
  }, deps: CreateBookingDeps): Promise<Response>;
44
51
  export {};
@@ -10,6 +10,10 @@ 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';
13
17
  const Contact = z.object({
14
18
  name: z.string().min(1).max(200),
15
19
  email: z.string().email(),
@@ -31,6 +35,7 @@ const Body = z.object({
31
35
  agreementAccepted: z.boolean().optional(),
32
36
  avRequest: z.boolean().optional(),
33
37
  avRequestNotes: z.string().max(1000).optional(),
38
+ source: z.unknown().optional(),
34
39
  });
35
40
  // Stripe rejects charges under $0.50. When credit + coupon leave a sub-minimum
36
41
  // remainder we treat the booking as fully covered rather than failing checkout.
@@ -121,7 +126,7 @@ export async function handle(req, operator, deps) {
121
126
  }
122
127
  tier1Terms = loaded.terms;
123
128
  }
124
- const priced = await validateAndPriceForRoom(supabase, room, parsed.data, nowMs, { isMember, allowDynamic: true });
129
+ const priced = await validateAndPriceForRoom(supabase, room, parsed.data, nowMs, { isMember, allowDynamic: true, notice: operator });
125
130
  if (!priced.ok) {
126
131
  return new Response(JSON.stringify({ error: priced.error }), {
127
132
  status: priced.status, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
@@ -132,6 +137,7 @@ export async function handle(req, operator, deps) {
132
137
  // Reclaim stale holds overlapping the range so abandoned carts don't block it.
133
138
  await reclaimStaleHoldsExceptCompletedTier3(supabase, room_id, rangeLiteral);
134
139
  const usesBoldSignAgreement = contractTier === 2 || contractTier === 3;
140
+ const bookingSource = sanitizeBookingSource(parsed.data.source);
135
141
  const holdExpires = new Date(Date.now() + 60 * 60 * 1000).toISOString();
136
142
  const effectiveHoldExpires = usesBoldSignAgreement
137
143
  ? new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
@@ -152,6 +158,8 @@ export async function handle(req, operator, deps) {
152
158
  contact_phone: contact.phone ?? null,
153
159
  is_member: isMember,
154
160
  policy_accepted_at: new Date().toISOString(),
161
+ // Only sent when present so an unmigrated database (no `source` column) keeps working.
162
+ ...(bookingSource ? { source: bookingSource } : {}),
155
163
  })
156
164
  .select('id')
157
165
  .single();
@@ -419,6 +427,7 @@ export async function handle(req, operator, deps) {
419
427
  catch (e) {
420
428
  await logOps(supabase, 'booking_side_effect_failed', { step: 'createCalendarEvent', message: String(e) }, { severity: 'warning', bookingId: booking_id });
421
429
  }
430
+ await writebackBookingCreated(operator, eff);
422
431
  }
423
432
  }
424
433
  catch (e) {
@@ -477,12 +486,21 @@ export async function handle(req, operator, deps) {
477
486
  status: 500, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
478
487
  });
479
488
  }
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
+ }
480
498
  const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
481
499
  const origin = req.headers.get('origin');
482
500
  const base = origin && /^https?:\/\//.test(origin) ? origin : `https://${operator.domain}`;
483
501
  const human = formatHumanTime(startUtc, endUtc);
484
502
  try {
485
- const session = await stripe.checkout.sessions.create({
503
+ const session = await createBookingCheckoutSession(stripe, {
486
504
  mode: 'payment',
487
505
  customer_email: contact.email,
488
506
  line_items: [{
@@ -494,12 +512,12 @@ export async function handle(req, operator, deps) {
494
512
  },
495
513
  }],
496
514
  metadata: { booking_id },
497
- expires_at: Math.floor(Date.now() / 1000) + 60 * 60,
515
+ expires_at: clampCheckoutExpiresAtSeconds(Date.now(), effectiveHoldExpires),
498
516
  success_url: `${base}/booking/confirmation?session_id={CHECKOUT_SESSION_ID}`,
499
517
  cancel_url: `${base}/meeting-rooms/${room.slug ?? ''}?canceled=1`,
500
518
  // TODO: enable Stripe automatic tax once tax registrations are configured.
501
519
  // automatic_tax: { enabled: true },
502
- });
520
+ }, chargePlan);
503
521
  await supabase
504
522
  .from('bookings')
505
523
  .update({ stripe_session_id: session.id })
@@ -3,4 +3,5 @@ export declare function handle(req: Request, operator: {
3
3
  actorEmail: string;
4
4
  stripeConnectedAccountId?: string | null;
5
5
  stripeApplicationFeePercent?: number | null;
6
+ planId?: string | null;
6
7
  }): Promise<Response>;
@@ -6,6 +6,7 @@ import { clientIp, checkRateLimit } from '../rateLimit.js';
6
6
  import { logOps } from '../ops.js';
7
7
  import { applyCheckoutCoupon, couponFailureBody, reverseCheckoutCoupon } from '../checkoutCoupon.js';
8
8
  import { buildDayPassSessionParams, computeApplicationFeeCents } from '../checkoutSessionParams.js';
9
+ import { hasEntitlement } from '../entitlements.js';
9
10
  const Body = z.object({
10
11
  plan_slug: z.string().min(1).max(80).regex(/^[a-z0-9-]+$/),
11
12
  email: z.string().email().max(255),
@@ -24,6 +25,11 @@ function todayLA() {
24
25
  export async function handle(req, operator) {
25
26
  if (req.method === 'OPTIONS')
26
27
  return new Response('ok', { headers: corsHeaders });
28
+ if (!hasEntitlement(operator, 'day_pass')) {
29
+ return new Response(JSON.stringify({ ok: false, error: 'feature_not_enabled', feature: 'day_pass' }), {
30
+ status: 403, headers: { ...corsHeaders, 'Content-Type': 'application/json' },
31
+ });
32
+ }
27
33
  // Set once a coupon reservation exists. Held at handler scope so the outer
28
34
  // catch can release it if anything after the reservation throws.
29
35
  let couponRedemptionId = null;
@@ -11,6 +11,7 @@ import { buildSubscriptionSessionParams } from '../checkoutSessionParams.js';
11
11
  // migration-checkout functions can reuse the exact same clamp/validation
12
12
  // arithmetic instead of duplicating it. Pure refactor: no behavior change.
13
13
  import { MAX_START_DATE_DAYS, pacificDateStr, addDaysStr } from '../pacificDate.js';
14
+ import { escapeLikePattern, isValidReferralCode } from '../referralCodeLookup.js';
14
15
  const Body = z.object({
15
16
  plan_slug: z.string().min(1).max(80).regex(/^[a-z0-9-]+$/),
16
17
  email: z.string().email().max(255),
@@ -205,12 +206,16 @@ export async function handle(req, operator) {
205
206
  // code, malicious input) is NOT an error -- it just means no referral
206
207
  // metadata gets attached, same as if the field had been omitted.
207
208
  let referralCode;
208
- if (referral_code) {
209
+ // Allowlist BEFORE any query: a code outside [A-Za-z0-9]{1,32} (e.g. a '*'
210
+ // wildcard) is treated exactly like an omitted/unknown code -- no lookup.
211
+ if (referral_code && isValidReferralCode(referral_code)) {
209
212
  try {
210
213
  const { data: referrer, error: refErr } = await supabase
211
214
  .from('memberships')
212
215
  .select('id')
213
- .eq('referral_code', referral_code)
216
+ .ilike('referral_code', escapeLikePattern(referral_code))
217
+ .order('id', { ascending: true })
218
+ .limit(1)
214
219
  .maybeSingle();
215
220
  if (!refErr && referrer)
216
221
  referralCode = referral_code;
@@ -13,5 +13,6 @@ export interface EventAccessAdminConfig {
13
13
  * bytecode (wrapper plus the core version it pulled in) is current, without
14
14
  * needing a real door/grant to test against. */
15
15
  buildMarker: string;
16
+ planId?: string | null;
16
17
  }
17
18
  export declare function createEventAccessAdminHandler(config: EventAccessAdminConfig): (req: Request) => Promise<Response>;