@simplelayer/graniteer-core 0.0.2 → 0.1.2

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 (100) hide show
  1. package/index.js +2 -2
  2. package/package.json +98 -15
  3. package/src/adminBookingCredit.test.ts +451 -0
  4. package/src/adminBookingCredit.ts +239 -0
  5. package/src/availability.test.ts +25 -0
  6. package/src/availability.ts +201 -0
  7. package/src/bookingHoldReclaim.ts +94 -0
  8. package/src/checkoutSessionParams.ts +56 -0
  9. package/src/commonsContract.ts +175 -0
  10. package/src/conductorAdmin.ts +141 -0
  11. package/src/email-templates/email-change.tsx +92 -0
  12. package/src/email-templates/invite.tsx +79 -0
  13. package/src/email-templates/reauthentication.tsx +60 -0
  14. package/src/functions/admin-cancel-membership.ts +311 -0
  15. package/src/functions/admin-change-membership-plan.ts +308 -0
  16. package/src/functions/admin-charge-guest-print.ts +229 -0
  17. package/src/functions/admin-correct-booking.ts +333 -0
  18. package/src/functions/admin-create-commons-event.ts +244 -0
  19. package/src/functions/admin-debug-boldsign-doc.ts +93 -0
  20. package/src/functions/admin-door-write.ts +272 -0
  21. package/src/functions/admin-mark-booking-paid.ts +203 -0
  22. package/src/functions/admin-photo-upload.ts +128 -0
  23. package/src/functions/admin-remove-team-member.ts +150 -0
  24. package/src/functions/admin-reset-mfa.ts +138 -0
  25. package/src/functions/admin-reverse-coupon-redemption.ts +98 -0
  26. package/src/functions/admin-send-commons-agreement.ts +214 -0
  27. package/src/functions/admin-set-credit-amount.ts +123 -0
  28. package/src/functions/admin-skip-commons-contract.ts +165 -0
  29. package/src/functions/admin-undo-membership-cancel.ts +144 -0
  30. package/src/functions/admin-wall-photo-write.ts +141 -0
  31. package/src/functions/boldsign-sender-identity.ts +114 -0
  32. package/src/functions/booking-availability.ts +419 -0
  33. package/src/functions/booking-member-preview.ts +136 -0
  34. package/src/functions/day-pass-status.ts +89 -0
  35. package/src/functions/dayStatus.ts +71 -0
  36. package/src/functions/diag-webpush-test.ts +45 -0
  37. package/src/functions/event-access-store.ts +309 -0
  38. package/src/functions/ezeep-print-webhook.ts +213 -0
  39. package/src/functions/ezeep-usage-reconcile.ts +299 -0
  40. package/src/functions/get-signing-link.ts +211 -0
  41. package/src/functions/guest-print-setup-confirm.ts +128 -0
  42. package/src/functions/guest-print-submit.ts +149 -0
  43. package/src/functions/luma-webhook.ts +165 -0
  44. package/src/functions/migration-collision-alert.copy.ts +232 -0
  45. package/src/functions/migration-collision-alert.test.ts +349 -0
  46. package/src/functions/migration-collision-alert.ts +232 -0
  47. package/src/functions/office-assignment-end.ts +146 -0
  48. package/src/functions/portal-booking-access.ts +95 -0
  49. package/src/functions/portal-list-invoices.ts +99 -0
  50. package/src/functions/print-billing-recover.ts +97 -0
  51. package/src/functions/print-billing-run.ts +183 -0
  52. package/src/functions/public-facts.ts +168 -0
  53. package/src/functions/space-availability-range.acceptance.test.ts +161 -0
  54. package/src/functions/space-availability-range.ts +142 -0
  55. package/src/functions/sync-gcal-blackouts.ts +298 -0
  56. package/src/functions/timetable-event-register.ts +162 -0
  57. package/src/functions/timetable-event-status.ts +90 -0
  58. package/src/functions/timetable-spaces.ts +219 -0
  59. package/src/functions/touch-pass-reconciler.ts +689 -0
  60. package/src/functions/virtual-onboarding-purge.ts +134 -0
  61. package/src/functions/virtual-onboarding-submit.ts +315 -0
  62. package/src/functions/voice-inquiry.test.ts +301 -0
  63. package/src/functions/voice-inquiry.ts +198 -0
  64. package/src/functions/voice-tour-availability.ts +204 -0
  65. package/src/gcalSync.ts +142 -0
  66. package/src/ghlNote.ts +34 -0
  67. package/src/ghlTask.ts +48 -0
  68. package/src/ghlVoiceInquiry.ts +90 -0
  69. package/src/guestPrintCapture.test.ts +722 -0
  70. package/src/guestPrintCapture.ts +538 -0
  71. package/src/lumaGhl.ts +195 -0
  72. package/src/membership.ts +109 -0
  73. package/src/money.ts +36 -0
  74. package/src/ops.ts +97 -0
  75. package/src/pacificDate.ts +34 -0
  76. package/src/policyAcknowledgment.test.ts +50 -0
  77. package/src/policyAcknowledgment.ts +96 -0
  78. package/src/portalSession.ts +46 -0
  79. package/src/pricing.test.ts +660 -0
  80. package/src/pricing.ts +1025 -0
  81. package/src/printBilling.test.ts +750 -0
  82. package/src/printBilling.ts +891 -0
  83. package/src/printBillingAdapters.ts +169 -0
  84. package/src/printCorrections.test.ts +348 -0
  85. package/src/printCorrections.ts +496 -0
  86. package/src/rateLimit.ts +82 -0
  87. package/src/referralCredits.test.ts +31 -0
  88. package/src/referralCredits.ts +34 -0
  89. package/src/referralGrant.ts +321 -0
  90. package/src/rescheduleCredit.test.ts +521 -0
  91. package/src/rescheduleCredit.ts +337 -0
  92. package/src/reservationWifiCode.test.ts +69 -0
  93. package/src/reservationWifiCode.ts +81 -0
  94. package/src/retellCallAnalyzed.test.ts +167 -0
  95. package/src/retellCallAnalyzed.ts +113 -0
  96. package/src/retellSignature.test.ts +137 -0
  97. package/src/retellSignature.ts +82 -0
  98. package/src/slackAlert.ts +38 -0
  99. package/src/supabaseTestFakes.ts +131 -0
  100. package/src/tier1Agreement.ts +125 -0
package/src/pricing.ts ADDED
@@ -0,0 +1,1025 @@
1
+ // Server-authoritative slot validation + price computation for room bookings.
2
+ // Used by create-booking and reschedule-booking so pricing can NEVER diverge.
3
+ //
4
+ // Both entry points return either { ok: false, error, status } (client-safe
5
+ // human message + HTTP status) or { ok: true, startUtc, endUtc, price_cents,
6
+ // rangeLiteral } describing a fully-validated booking window.
7
+
8
+ import type { SupabaseClient } from 'npm:@supabase/supabase-js@2';
9
+ import { getBusyRangesDetailed } from './availability.ts';
10
+ import { logOps } from './ops.ts';
11
+
12
+ // Minimum lead time required between "now" and a booking's start time.
13
+ // Mirrors the same purpose as GHL's `allowBookingAfter` setting on the tour
14
+ // calendars, but for meeting rooms — previously there was no floor at all
15
+ // beyond "not literally in the past" (see 2026-08-25 same-day-tour review).
16
+ const MIN_BOOKING_NOTICE_MS = 15 * 60 * 1000;
17
+
18
+ // Loose generics, matching _shared/ops.ts. A real createClient(url, key, opts)
19
+ // call infers SupabaseClient<any, 'public', 'public', ...>, which is NOT
20
+ // assignable to the un-inferred ReturnType<typeof createClient> default — that
21
+ // mismatch is what made every call site here fail deno check.
22
+ // deno-lint-ignore no-explicit-any
23
+ type SupabaseLike = SupabaseClient<any, any, any>;
24
+
25
+ export interface RoomForPricing {
26
+ id: string;
27
+ name: string;
28
+ hourly_cents: number;
29
+ day_cents: number | null;
30
+ half_day_cents: number | null;
31
+ min_booking_minutes: number;
32
+ booking_mode: string; // 'hourly' | 'day_block' | 'quote'
33
+ active: boolean;
34
+ /** Opt-in flag for meeting-room dynamic pricing. Absent/false = never discounted. */
35
+ dynamic_pricing_eligible?: boolean | null;
36
+ /**
37
+ * Optional ROOM-LEVEL override of the half-day booking windows, as LA wall
38
+ * clock 'HH:MM[:SS]' (same shape as business_hours.open_time/close_time).
39
+ * All four must be present for the override to apply — any missing/malformed
40
+ * one falls the room back to the generic open->1pm / 1pm->close split. See
41
+ * `resolveHalfDayWindow`.
42
+ */
43
+ half_day_am_start?: string | null;
44
+ half_day_am_end?: string | null;
45
+ half_day_pm_start?: string | null;
46
+ half_day_pm_end?: string | null;
47
+ /**
48
+ * Weekdays (0=Sun..6=Sat, same convention as
49
+ * room_dynamic_pricing_rules.day_of_week) on which this room offers a
50
+ * HALF-day at all. NULL = every day the room is open, i.e. today's
51
+ * behaviour. Never restricts full-day booking.
52
+ */
53
+ half_day_days_of_week?: number[] | null;
54
+ }
55
+
56
+ export interface PricingInputHourly {
57
+ start: string; // ISO
58
+ end: string; // ISO
59
+ }
60
+ export interface PricingInputDayBlock {
61
+ date: string; // YYYY-MM-DD (LA)
62
+ day_mode: 'full' | 'half_am' | 'half_pm';
63
+ }
64
+
65
+ export type PricingResult =
66
+ | {
67
+ ok: true;
68
+ startUtc: Date;
69
+ endUtc: Date;
70
+ price_cents: number;
71
+ rangeLiteral: string;
72
+ dynamic_discount_cents: number;
73
+ dynamic_discount_rule_type: string | null;
74
+ /**
75
+ * rule_type of the list-ADJUSTING rule that produced `price_cents`
76
+ * (`time_of_day_premium` / `flat_block`), or null when the list price
77
+ * came straight from the room's own columns. Purely for audit — the
78
+ * amount math never reads it. Distinct from
79
+ * `dynamic_discount_rule_type`, which explains the discount taken OFF
80
+ * this list.
81
+ */
82
+ list_rule_type: string | null;
83
+ }
84
+ | { ok: false; status: number; error: string };
85
+
86
+ function laOffsetHours(atUtc: Date): number {
87
+ const parts = new Intl.DateTimeFormat('en-US', {
88
+ timeZone: 'America/Los_Angeles',
89
+ timeZoneName: 'longOffset',
90
+ }).formatToParts(atUtc);
91
+ const tz = parts.find((p) => p.type === 'timeZoneName')?.value ?? 'GMT-08:00';
92
+ const m = tz.match(/GMT([+-])(\d{1,2}):?(\d{2})?/);
93
+ if (!m) return -8;
94
+ const sign = m[1] === '+' ? 1 : -1;
95
+ return sign * (parseInt(m[2], 10) + parseInt(m[3] || '0', 10) / 60);
96
+ }
97
+
98
+ function laParts(d: Date): { y: number; mo: number; day: number; hh: number; mm: number; wd: number } {
99
+ const fmt = new Intl.DateTimeFormat('en-US', {
100
+ timeZone: 'America/Los_Angeles',
101
+ year: 'numeric', month: '2-digit', day: '2-digit',
102
+ hour: '2-digit', minute: '2-digit', weekday: 'short', hour12: false,
103
+ }).formatToParts(d);
104
+ const get = (t: string) => fmt.find((p) => p.type === t)?.value ?? '';
105
+ const wd = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(get('weekday'));
106
+ return {
107
+ y: parseInt(get('year'), 10),
108
+ mo: parseInt(get('month'), 10),
109
+ day: parseInt(get('day'), 10),
110
+ hh: parseInt(get('hour'), 10) % 24,
111
+ mm: parseInt(get('minute'), 10),
112
+ wd,
113
+ };
114
+ }
115
+
116
+ function laWallToUtc(y: number, mo: number, d: number, hh: number, mm: number): Date {
117
+ const guess = new Date(Date.UTC(y, mo - 1, d, 12));
118
+ const off = laOffsetHours(guess);
119
+ return new Date(Date.UTC(y, mo - 1, d, hh - Math.trunc(off), mm));
120
+ }
121
+
122
+ export function formatHumanTime(startUtc: Date, endUtc: Date): string {
123
+ const dateFmt = new Intl.DateTimeFormat('en-US', {
124
+ timeZone: 'America/Los_Angeles', weekday: 'short', month: 'short', day: 'numeric',
125
+ });
126
+ const timeFmt = new Intl.DateTimeFormat('en-US', {
127
+ timeZone: 'America/Los_Angeles', hour: 'numeric', minute: '2-digit', hour12: true,
128
+ });
129
+ return `${dateFmt.format(startUtc)}, ${timeFmt.format(startUtc)}–${timeFmt.format(endUtc)} PT`;
130
+ }
131
+
132
+ interface HoursRow { room_id: string | null; open_time: string; close_time: string }
133
+
134
+ async function getHours(supabase: SupabaseLike, roomId: string, wd: number): Promise<HoursRow | null> {
135
+ const { data, error } = await supabase
136
+ .from('business_hours')
137
+ .select('*')
138
+ .eq('weekday', wd)
139
+ .or(`room_id.eq.${roomId},room_id.is.null`);
140
+ if (error) throw error;
141
+ // Room-specific row wins over the global (room_id IS NULL) row.
142
+ const rows = (data ?? []) as unknown as HoursRow[];
143
+ return rows.sort((a, b) => (a.room_id ? -1 : 1))[0] ?? null;
144
+ }
145
+
146
+ /**
147
+ * THE single source of truth for where a half-day block starts and ends.
148
+ * Pure — no DB access — so the charge path (`validateAndPriceDayBlock`) and the
149
+ * preview path (booking-availability's day_block loop) resolve the exact same
150
+ * window from the exact same room row. Do not reimplement either half of this
151
+ * (the weekday gate or the window math) at a call site; import it.
152
+ *
153
+ * Two layers, in order:
154
+ *
155
+ * 1. WEEKDAY GATE. `half_day_days_of_week` (0=Sun..6=Sat) lists the days this
156
+ * room offers a half-day at all. NULL/absent = every day the room is open
157
+ * (today's behaviour for every room). This gates HALF-day only — full-day
158
+ * booking never reads it.
159
+ * 2. WINDOW. When all four `half_day_*` time columns are set, the AM/PM
160
+ * boundaries come from them. Otherwise the generic split applies:
161
+ * open -> 1:00pm for AM, 1:00pm -> close for PM, exactly as before these
162
+ * columns existed. A partially-populated or malformed set of overrides
163
+ * therefore reads as "no override" rather than as an error — the fallback
164
+ * is the long-standing live behaviour, so failing that way changes nothing
165
+ * for a room whose columns are half-written.
166
+ *
167
+ * An override window is assumed to sit INSIDE the room's business hours; this
168
+ * does not clamp it (booking-availability's busy scan is bounded by
169
+ * open..close, so a window poking outside them would be conflict-checked only
170
+ * in part).
171
+ */
172
+ export function resolveHalfDayWindow(
173
+ room: RoomForPricing,
174
+ dayMode: 'half_am' | 'half_pm',
175
+ wd: number,
176
+ dateStr: string,
177
+ openUtc: Date,
178
+ closeUtc: Date,
179
+ ): { ok: true; startUtc: Date; endUtc: Date } | { ok: false; error: string } {
180
+ // Same null/non-array handling as day_of_week in the dynamic-pricing
181
+ // matchers: NULL means "every day", a present-but-not-an-array value is
182
+ // treated as matching nothing rather than as matching everything.
183
+ const dows = room.half_day_days_of_week;
184
+ if (dows != null && (!Array.isArray(dows) || !dows.includes(wd))) {
185
+ return { ok: false, error: 'Half-day booking is not available on this day for this room.' };
186
+ }
187
+
188
+ const [y, mo, d] = dateStr.split('-').map(Number);
189
+
190
+ const amStart = hhmmToMinutes(room.half_day_am_start ?? null);
191
+ const amEnd = hhmmToMinutes(room.half_day_am_end ?? null);
192
+ const pmStart = hhmmToMinutes(room.half_day_pm_start ?? null);
193
+ const pmEnd = hhmmToMinutes(room.half_day_pm_end ?? null);
194
+ const hasOverride = [amStart, amEnd, pmStart, pmEnd].every((m) => Number.isFinite(m));
195
+
196
+ if (!hasOverride) {
197
+ const oneUtc = laWallToUtc(y, mo, d, 13, 0);
198
+ return dayMode === 'half_am'
199
+ ? { ok: true, startUtc: openUtc, endUtc: oneUtc }
200
+ : { ok: true, startUtc: oneUtc, endUtc: closeUtc };
201
+ }
202
+
203
+ const startMin = dayMode === 'half_am' ? amStart : pmStart;
204
+ const endMin = dayMode === 'half_am' ? amEnd : pmEnd;
205
+ // An inverted or empty override window is a configuration error, not
206
+ // something to silently paper over with the generic split — refuse the block
207
+ // rather than sell a window nobody configured.
208
+ if (!(endMin > startMin)) {
209
+ return { ok: false, error: 'Half-day booking is not available for this room.' };
210
+ }
211
+
212
+ return {
213
+ ok: true,
214
+ startUtc: laWallToUtc(y, mo, d, Math.floor(startMin / 60), startMin % 60),
215
+ endUtc: laWallToUtc(y, mo, d, Math.floor(endMin / 60), endMin % 60),
216
+ };
217
+ }
218
+
219
+ export async function validateAndPriceDayBlock(
220
+ supabase: SupabaseLike,
221
+ room: RoomForPricing,
222
+ input: PricingInputDayBlock,
223
+ nowMs: number,
224
+ ): Promise<PricingResult> {
225
+ const { date, day_mode } = input;
226
+ if (!date || !day_mode) return { ok: false, status: 400, error: 'date and day_mode are required for this room' };
227
+
228
+ const [y, mo, d] = date.split('-').map(Number);
229
+ const wdGuess = new Date(Date.UTC(y, mo - 1, d, 12));
230
+ const wd = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(
231
+ new Intl.DateTimeFormat('en-US', { timeZone: 'America/Los_Angeles', weekday: 'short' }).format(wdGuess),
232
+ );
233
+ const h = await getHours(supabase, room.id, wd);
234
+ if (!h) return { ok: false, status: 400, error: 'Room is closed that day' };
235
+ const [openH, openM] = h.open_time.split(':').map(Number);
236
+ const [closeH, closeM] = h.close_time.split(':').map(Number);
237
+ const openUtc = laWallToUtc(y, mo, d, openH, openM);
238
+ const closeUtc = laWallToUtc(y, mo, d, closeH, closeM);
239
+
240
+ let startUtc: Date;
241
+ let endUtc: Date;
242
+ let price_cents: number;
243
+ if (day_mode === 'full') {
244
+ startUtc = openUtc; endUtc = closeUtc;
245
+ const dayRate = room.day_cents;
246
+ if (dayRate == null) return { ok: false, status: 400, error: 'Full-day booking not available for this room.' };
247
+ price_cents = dayRate;
248
+ } else {
249
+ if (room.half_day_cents == null) {
250
+ return { ok: false, status: 400, error: 'Half-day booking not available for this room.' };
251
+ }
252
+ // Window + weekday gate both live in resolveHalfDayWindow, shared with
253
+ // booking-availability so the preview can never offer a block this would
254
+ // then refuse.
255
+ const win = resolveHalfDayWindow(room, day_mode, wd, date, openUtc, closeUtc);
256
+ if (!win.ok) return { ok: false, status: 400, error: win.error };
257
+ startUtc = win.startUtc; endUtc = win.endUtc;
258
+ price_cents = room.half_day_cents;
259
+ }
260
+
261
+ if (startUtc.getTime() < nowMs + MIN_BOOKING_NOTICE_MS) {
262
+ return { ok: false, status: 400, error: 'Bookings need at least 15 minutes notice — please choose a later start time.' };
263
+ }
264
+ if (price_cents <= 0) return { ok: false, status: 400, error: 'invalid price' };
265
+
266
+ return {
267
+ ok: true,
268
+ startUtc, endUtc, price_cents,
269
+ rangeLiteral: `[${startUtc.toISOString()},${endUtc.toISOString()})`,
270
+ dynamic_discount_cents: 0,
271
+ dynamic_discount_rule_type: null,
272
+ list_rule_type: null,
273
+ };
274
+ }
275
+
276
+ export async function validateAndPriceHourly(
277
+ supabase: SupabaseLike,
278
+ room: RoomForPricing,
279
+ input: PricingInputHourly,
280
+ nowMs: number,
281
+ ): Promise<PricingResult> {
282
+ const { start, end } = input;
283
+ if (!start || !end) return { ok: false, status: 400, error: 'start and end are required' };
284
+ const startUtc = new Date(start);
285
+ const endUtc = new Date(end);
286
+ if (isNaN(startUtc.getTime()) || isNaN(endUtc.getTime())) {
287
+ return { ok: false, status: 400, error: 'invalid start/end' };
288
+ }
289
+ if (!(startUtc < endUtc)) return { ok: false, status: 400, error: 'end must be after start' };
290
+ if (startUtc.getTime() < nowMs + MIN_BOOKING_NOTICE_MS) {
291
+ return { ok: false, status: 400, error: 'Bookings need at least 15 minutes notice — please choose a later start time.' };
292
+ }
293
+ if (startUtc.getUTCSeconds() !== 0 || startUtc.getUTCMilliseconds() !== 0 ||
294
+ endUtc.getUTCSeconds() !== 0 || endUtc.getUTCMilliseconds() !== 0 ||
295
+ startUtc.getUTCMinutes() % 30 !== 0 || endUtc.getUTCMinutes() % 30 !== 0) {
296
+ return { ok: false, status: 400, error: 'times must align to :00 or :30' };
297
+ }
298
+ const durationMinutes = Math.round((endUtc.getTime() - startUtc.getTime()) / 60000);
299
+ if (durationMinutes < room.min_booking_minutes) {
300
+ return { ok: false, status: 400, error: `Minimum booking is ${room.min_booking_minutes} minutes.` };
301
+ }
302
+ const sLa = laParts(startUtc);
303
+ const eLa = laParts(endUtc);
304
+ if (sLa.y !== eLa.y || sLa.mo !== eLa.mo || sLa.day !== eLa.day) {
305
+ return { ok: false, status: 400, error: 'booking must be within a single day' };
306
+ }
307
+ const h = await getHours(supabase, room.id, sLa.wd);
308
+ if (!h) return { ok: false, status: 400, error: 'Room is closed that day' };
309
+ const [openH, openM] = h.open_time.split(':').map(Number);
310
+ const [closeH, closeM] = h.close_time.split(':').map(Number);
311
+ const openUtc = laWallToUtc(sLa.y, sLa.mo, sLa.day, openH, openM);
312
+ const closeUtc = laWallToUtc(sLa.y, sLa.mo, sLa.day, closeH, closeM);
313
+ if (startUtc < openUtc || endUtc > closeUtc) {
314
+ return { ok: false, status: 400, error: 'outside business hours' };
315
+ }
316
+
317
+ const slots = Math.round((endUtc.getTime() - startUtc.getTime()) / (30 * 60 * 1000));
318
+ const hourlyRate = room.hourly_cents;
319
+ const dayCap = room.day_cents;
320
+ let price_cents = Math.round((hourlyRate / 2) * slots);
321
+ if (dayCap && price_cents > dayCap) {
322
+ price_cents = dayCap;
323
+ }
324
+ if (price_cents <= 0) return { ok: false, status: 400, error: 'invalid price' };
325
+
326
+ return {
327
+ ok: true,
328
+ startUtc, endUtc, price_cents,
329
+ rangeLiteral: `[${startUtc.toISOString()},${endUtc.toISOString()})`,
330
+ dynamic_discount_cents: 0,
331
+ dynamic_discount_rule_type: null,
332
+ list_rule_type: null,
333
+ };
334
+ }
335
+
336
+ /**
337
+ * Entry point: dispatches to hourly or day_block based on room.booking_mode.
338
+ * `quote` rooms cannot be booked via checkout.
339
+ */
340
+
341
+ // ---------------------------------------------------------------------------
342
+ // Dynamic pricing (staff flash sales + automatic discounts)
343
+ // ---------------------------------------------------------------------------
344
+
345
+ export interface DynamicRuleRow {
346
+ id?: string;
347
+ room_id: string | null;
348
+ /**
349
+ * Two families, matched by two independent passes:
350
+ * DISCOUNT rules 'flash_sale' | 'same_day' | 'time_of_day' | 'occupancy'
351
+ * -> matchDynamicRules, produce dynamic_discount_cents
352
+ * LIST-ADJUSTING 'time_of_day_premium' | 'flat_block'
353
+ * -> matchListAdjustingRules, move price_cents itself
354
+ *
355
+ * The SIGN of a price change lives here, never in the sign of `pct`:
356
+ * `time_of_day_premium` carries a POSITIVE pct meaning a price INCREASE. A
357
+ * negative pct would satisfy bookings_amount_math_check while making
358
+ * list_amount_cents < charged_amount_cents on every receipt, and would be
359
+ * dropped by five separate guards before it ever reached the arithmetic.
360
+ */
361
+ rule_type: string;
362
+ /** NULL only for `flat_block`, which carries flat_price_cents instead. */
363
+ pct: number | null;
364
+ /** Absolute list price for a `flat_block` rule. NULL for every other type. */
365
+ flat_price_cents: number | null;
366
+ starts_at: string | null;
367
+ ends_at: string | null;
368
+ occupancy_threshold: number | null;
369
+ day_of_week: number[] | null;
370
+ window_start: string | null; // 'HH:MM[:SS]' LA wall clock
371
+ window_end: string | null;
372
+ /**
373
+ * Scopes this rule to bookings priced at the room's full-day rate only.
374
+ * NOT the same thing as room.booking_mode === 'day_block' — an hourly-mode
375
+ * room with a day_cents cap (e.g. Nook, Loft) also produces a full-day
376
+ * price once a booking's duration hits that cap, and this flag is what
377
+ * lets a promo target exactly that case on an hourly-mode room. See
378
+ * `isFullDayPrice` in matchDynamicRules/resolveDynamicDiscount.
379
+ */
380
+ day_block_only: boolean;
381
+ }
382
+
383
+ export interface DynamicContext {
384
+ startUtc: Date;
385
+ endUtc: Date;
386
+ rangeLiteral: string;
387
+ price_cents: number;
388
+ }
389
+
390
+ /** 'HH:MM[:SS]' -> minutes since LA midnight. NaN when malformed. */
391
+ function hhmmToMinutes(s: string | null): number {
392
+ if (!s) return NaN;
393
+ const m = s.match(/^(\d{1,2}):(\d{2})/);
394
+ if (!m) return NaN;
395
+ return parseInt(m[1], 10) * 60 + parseInt(m[2], 10);
396
+ }
397
+
398
+ const OCCUPANCY_MAX_SYNC_AGE_MS = 11 * 60 * 1000;
399
+
400
+ export interface ResolvedDynamicRules {
401
+ enabled: boolean;
402
+ rules: DynamicRuleRow[];
403
+ }
404
+
405
+ /**
406
+ * Step 1 of dynamic-pricing resolution: the global kill switch plus this
407
+ * room's (or global) active rule rows. Cheap and safe to call once per
408
+ * request and reuse across every slot/day being evaluated — the predicate
409
+ * matching in `matchDynamicRules` is pure in-memory work on this result.
410
+ *
411
+ * Returns `{ enabled: false, rules: [] }` when promotions are off or
412
+ * unreadable. Throws only on an unexpected rules-table query failure — same
413
+ * as the old inline behaviour this was extracted from.
414
+ */
415
+ export async function loadDynamicPricingRules(
416
+ supabase: SupabaseLike,
417
+ room: RoomForPricing,
418
+ ): Promise<ResolvedDynamicRules> {
419
+ const none: ResolvedDynamicRules = { enabled: false, rules: [] };
420
+
421
+ // 1. Global kill switch.
422
+ //
423
+ // NOTE: this key is named for *promotions* but now also gates *premiums*
424
+ // (`time_of_day_premium`) and productized `flat_block` rates, because both
425
+ // load through this same function. Turning it off therefore LOWERS Town
426
+ // Hall's peak-hour price rather than raising it — it is not a safe
427
+ // emergency "make everything cheap" switch in one direction only. Accepted
428
+ // and documented deliberately for this launch; if a future change needs to
429
+ // kill discounts without also killing premiums, add a separate
430
+ // `premiums_enabled` key rather than repurposing this one.
431
+ try {
432
+ const { data, error } = await supabase
433
+ .from('app_settings').select('value').eq('key', 'promotions_enabled').maybeSingle();
434
+ if (error) return none;
435
+ if ((data as { value?: string } | null)?.value !== 'true') return none;
436
+ } catch { return none; }
437
+
438
+ // 2. Candidate rules for this room (or global rows).
439
+ const { data: ruleData, error: ruleErr } = await supabase
440
+ .from('room_dynamic_pricing_rules')
441
+ .select('id,room_id,rule_type,pct,flat_price_cents,starts_at,ends_at,occupancy_threshold,day_of_week,window_start,window_end,day_block_only')
442
+ .eq('active', true)
443
+ .or(`room_id.eq.${room.id},room_id.is.null`);
444
+ if (ruleErr) throw ruleErr;
445
+ // This filter is where ALL sign/shape safety lives — neither
446
+ // matchDynamicRules nor matchListAdjustingRules re-validates it. A
447
+ // flat_block row has pct IS NULL by construction (see the DB shape CHECK),
448
+ // so it is validated on flat_price_cents instead; every other type must
449
+ // still carry a positive pct.
450
+ //
451
+ // Upper bound is 50, not 100: this mirrors the DB's own
452
+ // room_dynamic_pricing_rules_pct_check (`pct > 0 AND pct <= 50`), which is
453
+ // the ratified ceiling for every rule type that carries a pct, including
454
+ // time_of_day_premium (see 20260827120000's "Range stays 1..50 for every
455
+ // rule type that does use it"). The DB CHECK is authoritative, but this
456
+ // code previously trusted it blindly — a future migration that loosens or
457
+ // drops that constraint (or a service-role write that predates it) would
458
+ // have flowed straight into a live price with no independent code-level
459
+ // ceiling at all. This keeps the 50% cap enforced here too, so the two
460
+ // layers have to agree, not just one of them.
461
+ const rules = ((ruleData ?? []) as unknown as DynamicRuleRow[]).filter((r) =>
462
+ r?.rule_type === 'flat_block'
463
+ ? Number.isFinite(r.flat_price_cents) && (r.flat_price_cents as number) > 0
464
+ : Number.isFinite(r?.pct) && (r.pct as number) > 0 && (r.pct as number) <= 50);
465
+ return { enabled: true, rules };
466
+ }
467
+
468
+ /**
469
+ * How many `dynamic_pricing_eligible` rooms (including this one) are free
470
+ * over `rangeLiteral`. Fails closed to `null` ("cannot know") when the
471
+ * Google-calendar blackout sync is stale or missing, and treats any
472
+ * unparseable busy row as busy — same fail-safe as timetable-spaces.
473
+ *
474
+ * This is the expensive half of occupancy resolution (one availability query
475
+ * per eligible room) — callers should memoize it per distinct `rangeLiteral`
476
+ * rather than call it per slot.
477
+ */
478
+ export async function computeOccupancyFreeCount(
479
+ supabase: SupabaseLike,
480
+ room: RoomForPricing,
481
+ rangeLiteral: string,
482
+ nowMs: number,
483
+ ): Promise<number | null> {
484
+ const { data: sync, error: sErr } = await supabase
485
+ .from('sync_state').select('updated_at').eq('key', 'gcal-blackouts').maybeSingle();
486
+ if (sErr) throw sErr;
487
+ const updatedAt = (sync as { updated_at?: string } | null)?.updated_at;
488
+ const updatedMs = updatedAt ? new Date(updatedAt).getTime() : NaN;
489
+ if (!Number.isFinite(updatedMs) || nowMs - updatedMs > OCCUPANCY_MAX_SYNC_AGE_MS) return null;
490
+
491
+ const { data: roomsData, error: rErr } = await supabase
492
+ .from('rooms').select('id').eq('active', true).eq('dynamic_pricing_eligible', true);
493
+ if (rErr) throw rErr;
494
+ const ids = ((roomsData ?? []) as Array<{ id: string }>).map((r) => r.id);
495
+ let free = 0;
496
+ for (const id of ids) {
497
+ // The room being booked is, by definition, available for this window.
498
+ if (id === room.id) { free += 1; continue; }
499
+ const { busy, unparsed } = await getBusyRangesDetailed(
500
+ supabase as unknown as { from(t: string): unknown },
501
+ id,
502
+ rangeLiteral,
503
+ );
504
+ // Same fail-safe as timetable-spaces: an unparseable row reads as busy.
505
+ const isBusy = unparsed > 0 || busy.length > 0;
506
+ if (!isBusy) free += 1;
507
+ }
508
+ return free;
509
+ }
510
+
511
+ /**
512
+ * Step 2: given rules already loaded by `loadDynamicPricingRules`, finds the
513
+ * winning rule (if any) for a specific booking-window start time. Pure
514
+ * in-memory predicate matching except for the `occupancy` case, which defers
515
+ * to the caller-supplied `getFreeCount` so that resolution can be memoized
516
+ * once per request/day instead of once per slot.
517
+ *
518
+ * Precedence: any flash_sale beats every automatic rule; then largest pct;
519
+ * then a room-specific row beats a global (room_id IS NULL) row.
520
+ */
521
+ export async function matchDynamicRules(
522
+ resolved: ResolvedDynamicRules,
523
+ ctx: { startUtc: Date; isFullDayPrice?: boolean },
524
+ nowMs: number,
525
+ getFreeCount: () => Promise<number | null>,
526
+ ): Promise<{ pct: number; ruleType: string | null }> {
527
+ const none = { pct: 0, ruleType: null as string | null };
528
+ if (!resolved.enabled || resolved.rules.length === 0) return none;
529
+
530
+ const sLa = laParts(ctx.startUtc);
531
+ const nowLa = laParts(new Date(nowMs));
532
+ const startMinutes = sLa.hh * 60 + sLa.mm;
533
+ const isFullDayPrice = ctx.isFullDayPrice === true;
534
+
535
+ const matched: DynamicRuleRow[] = [];
536
+ for (const r of resolved.rules) {
537
+ // A discount is always a percentage. A row without one (i.e. flat_block)
538
+ // can never enter this pool — which also keeps the `winner.pct` sort below
539
+ // total. The `default:` case further down is the second half of the same
540
+ // property: an unrecognised rule_type (including time_of_day_premium) is
541
+ // simply a non-match, so a list-ADJUSTING rule can never leak in here and
542
+ // be read as a discount.
543
+ if (r.pct == null || !(r.pct > 0)) continue;
544
+ // day_block_only is an ADDITIONAL filter layered on top of rule_type
545
+ // matching below, not a replacement for it. A rule scoped this way never
546
+ // matches a booking that isn't priced at the room's full-day rate.
547
+ if (r.day_block_only && !isFullDayPrice) continue;
548
+ switch (r.rule_type) {
549
+ case 'flash_sale': {
550
+ const s = r.starts_at ? new Date(r.starts_at).getTime() : NaN;
551
+ const e = r.ends_at ? new Date(r.ends_at).getTime() : NaN;
552
+ if (Number.isFinite(s) && Number.isFinite(e) && nowMs >= s && nowMs <= e) matched.push(r);
553
+ break;
554
+ }
555
+ case 'same_day': {
556
+ if (sLa.y === nowLa.y && sLa.mo === nowLa.mo && sLa.day === nowLa.day) matched.push(r);
557
+ break;
558
+ }
559
+ case 'time_of_day': {
560
+ const dows = r.day_of_week;
561
+ if (dows != null && (!Array.isArray(dows) || !dows.includes(sLa.wd))) break;
562
+ const ws = hhmmToMinutes(r.window_start);
563
+ const we = hhmmToMinutes(r.window_end);
564
+ if (!Number.isFinite(ws) || !Number.isFinite(we)) break; // malformed rule = no match
565
+ if (startMinutes >= ws && startMinutes < we) matched.push(r);
566
+ break;
567
+ }
568
+ case 'occupancy': {
569
+ const threshold = r.occupancy_threshold;
570
+ if (threshold == null || !Number.isFinite(threshold)) break;
571
+ const free = await getFreeCount();
572
+ if (free !== null && free <= threshold) matched.push(r);
573
+ break;
574
+ }
575
+ default:
576
+ break; // unknown rule_type = no match
577
+ }
578
+ }
579
+ if (matched.length === 0) return none;
580
+
581
+ // Precedence: any flash_sale beats every automatic rule; then largest pct;
582
+ // then a room-specific row beats a global (room_id IS NULL) row.
583
+ const flash = matched.filter((r) => r.rule_type === 'flash_sale');
584
+ const pool = flash.length > 0 ? flash : matched;
585
+ const winner = pool.slice().sort((a, b) => {
586
+ // pct is non-null for every row that reached `matched` (guarded above).
587
+ const ap = a.pct ?? 0;
588
+ const bp = b.pct ?? 0;
589
+ if (bp !== ap) return bp - ap;
590
+ const aSpecific = a.room_id ? 0 : 1;
591
+ const bSpecific = b.room_id ? 0 : 1;
592
+ return aSpecific - bSpecific;
593
+ })[0];
594
+
595
+ return { pct: winner.pct ?? 0, ruleType: winner.rule_type };
596
+ }
597
+
598
+ // ---------------------------------------------------------------------------
599
+ // List-adjusting rules (premiums + flat blocks)
600
+ // ---------------------------------------------------------------------------
601
+ //
602
+ // A SECOND, independent winner-takes-all pass, over only `time_of_day_premium`
603
+ // and `flat_block`. It runs BEFORE the discount pass and moves `price_cents`
604
+ // (the list price) itself; the discount engine then runs unchanged on the
605
+ // adjusted list. Because of that ordering, `dynamic_discount_cents` stays
606
+ // strictly non-negative, `bookings_amount_math_check` still holds, and every
607
+ // "N% off" badge keeps meaning what it always meant.
608
+ //
609
+ // Splitting the single winner-takes-all pass in two is a genuine semantic
610
+ // change to a rule the rest of the system documents as absolute ("exactly one
611
+ // rule wins"). It is now "at most one list-adjuster, plus at most one
612
+ // discount". For the current rollout the two pools never collide (Town Hall
613
+ // carries only premium/flat rules, Commons only discounts), but a future rule
614
+ // author needs to know this.
615
+
616
+ export interface ListAdjustment {
617
+ kind: 'premium' | 'flat_block';
618
+ newPriceCents: number;
619
+ ruleType: string;
620
+ }
621
+
622
+ /**
623
+ * Step 2 for list adjustment, mirroring `matchDynamicRules`. Pure in-memory:
624
+ * neither of these rule types can depend on occupancy or on wall-clock now,
625
+ * so unlike the discount matcher this takes no `getFreeCount` and no `nowMs`.
626
+ *
627
+ * Unlike `matchDynamicRules` this DOES read `endUtc` — a flat block is defined
628
+ * by both of its bounds.
629
+ *
630
+ * Precedence: `flat_block` beats `time_of_day_premium` (an explicit product
631
+ * beats a modifier); then a room-specific row beats a global one.
632
+ */
633
+ export function matchListAdjustingRules(
634
+ resolved: ResolvedDynamicRules,
635
+ ctx: { startUtc: Date; endUtc: Date; isFullDayPrice?: boolean; price_cents: number },
636
+ ): ListAdjustment | null {
637
+ if (!resolved.enabled || resolved.rules.length === 0) return null;
638
+
639
+ const sLa = laParts(ctx.startUtc);
640
+ const eLa = laParts(ctx.endUtc);
641
+ const startMinutes = sLa.hh * 60 + sLa.mm;
642
+ const endMinutes = eLa.hh * 60 + eLa.mm;
643
+ const isFullDayPrice = ctx.isFullDayPrice === true;
644
+
645
+ const matched: DynamicRuleRow[] = [];
646
+ for (const r of resolved.rules) {
647
+ if (r.rule_type !== 'flat_block' && r.rule_type !== 'time_of_day_premium') continue;
648
+ // Same additional filter as the discount pass.
649
+ if (r.day_block_only && !isFullDayPrice) continue;
650
+
651
+ const dows = r.day_of_week;
652
+ if (dows != null && (!Array.isArray(dows) || !dows.includes(sLa.wd))) continue;
653
+ const ws = hhmmToMinutes(r.window_start);
654
+ const we = hhmmToMinutes(r.window_end);
655
+ if (!Number.isFinite(ws) || !Number.isFinite(we)) continue; // malformed rule = no match
656
+
657
+ if (r.rule_type === 'flat_block') {
658
+ // EXACT block equality, not containment. Containment leaks: Town Hall at
659
+ // $41/hr means a contained 11:00-15:00 booking would be charged the flat
660
+ // $164.00 — identical to what 4 hours costs hourly, and MORE than a
661
+ // 3-hour booking, for less time. Exact equality makes the block an
662
+ // unambiguous product: you buy 10-4, or you buy hours.
663
+ if (startMinutes === ws && endMinutes === we) matched.push(r);
664
+ continue;
665
+ }
666
+
667
+ // time_of_day_premium: same predicate as time_of_day (half-open [ws, we)),
668
+ // plus — never stack a peak-hour uplift on top of a booking that has
669
+ // already hit the room's day_cents cap. The customer bought the day.
670
+ if (isFullDayPrice) continue;
671
+ if (startMinutes >= ws && startMinutes < we) matched.push(r);
672
+ }
673
+ if (matched.length === 0) return null;
674
+
675
+ const flat = matched.filter((r) => r.rule_type === 'flat_block');
676
+ const pool = flat.length > 0 ? flat : matched;
677
+ const winner = pool.slice().sort((a, b) => {
678
+ const aSpecific = a.room_id ? 0 : 1;
679
+ const bSpecific = b.room_id ? 0 : 1;
680
+ return aSpecific - bSpecific;
681
+ })[0];
682
+
683
+ if (winner.rule_type === 'flat_block') {
684
+ const cents = winner.flat_price_cents;
685
+ if (cents == null || !Number.isFinite(cents) || cents <= 0) return null;
686
+ return { kind: 'flat_block', newPriceCents: cents, ruleType: winner.rule_type };
687
+ }
688
+
689
+ const pct = winner.pct;
690
+ if (pct == null || !Number.isFinite(pct) || pct <= 0) return null;
691
+ // Single half-up rounding, same shape as the discount formula.
692
+ const newPriceCents = ctx.price_cents + Math.round((ctx.price_cents * pct) / 100);
693
+ if (!Number.isFinite(newPriceCents) || newPriceCents <= 0) return null;
694
+ return { kind: 'premium', newPriceCents, ruleType: winner.rule_type };
695
+ }
696
+
697
+ /**
698
+ * Resolves the winning list-adjusting rule for a booking window, or null.
699
+ * Mirrors `resolveDynamicDiscount`.
700
+ *
701
+ * Re-applies the `dynamic_pricing_eligible` gate ITSELF: that flag is a
702
+ * caller-side gate, never checked inside loadDynamicPricingRules or either
703
+ * matcher, so any new entry point has to enforce it or an ineligible room
704
+ * silently gets repriced.
705
+ */
706
+ export async function resolveListAdjustment(
707
+ supabase: SupabaseLike,
708
+ room: RoomForPricing,
709
+ ctx: DynamicContext,
710
+ _nowMs: number,
711
+ ): Promise<ListAdjustment | null> {
712
+ if (room.dynamic_pricing_eligible !== true) return null;
713
+
714
+ const resolved = await loadDynamicPricingRules(supabase, room);
715
+ if (!resolved.enabled || resolved.rules.length === 0) return null;
716
+
717
+ // Same derivation as resolveDynamicDiscount: computed from the actual priced
718
+ // amount, never guessed from duration.
719
+ const effectiveDayCap = room.day_cents;
720
+ const isFullDayPrice = !!effectiveDayCap && effectiveDayCap > 0 && ctx.price_cents === effectiveDayCap;
721
+
722
+ return matchListAdjustingRules(resolved, {
723
+ startUtc: ctx.startUtc,
724
+ endUtc: ctx.endUtc,
725
+ isFullDayPrice,
726
+ price_cents: ctx.price_cents,
727
+ });
728
+ }
729
+
730
+ /**
731
+ * Resolves the winning dynamic-pricing rule for a booking window.
732
+ * Returns `{ cents: 0, ruleType: null }` whenever promotions are off, no rule
733
+ * matches, or a rule cannot be evaluated safely. Throws only on unexpected
734
+ * failures — the caller catches, logs `dynamic_pricing_failed`, and drops the
735
+ * discount.
736
+ */
737
+ export async function resolveDynamicDiscount(
738
+ supabase: SupabaseLike,
739
+ room: RoomForPricing,
740
+ ctx: DynamicContext,
741
+ nowMs: number,
742
+ ): Promise<{ cents: number; ruleType: string | null }> {
743
+ const none = { cents: 0, ruleType: null as string | null };
744
+
745
+ const resolved = await loadDynamicPricingRules(supabase, room);
746
+ if (!resolved.enabled || resolved.rules.length === 0) return none;
747
+
748
+ // Occupancy is expensive (one availability query per eligible room) — only
749
+ // compute it if an occupancy rule is actually in play, and memoize.
750
+ let freeCountPromise: Promise<number | null> | null = null;
751
+ const getFreeCount = (): Promise<number | null> => {
752
+ if (!freeCountPromise) freeCountPromise = computeOccupancyFreeCount(supabase, room, ctx.rangeLiteral, nowMs);
753
+ return freeCountPromise;
754
+ };
755
+
756
+ // True when THIS booking's own base price equals the room's full-day rate
757
+ // — a genuine day_block 'full' booking, or an hourly-mode booking (e.g.
758
+ // Nook, Loft) whose duration hit the day_cents cap. Computed from the
759
+ // actual priced amount, never guessed from duration, so it's correct even
760
+ // when a price coincidentally lands on the day rate without capping.
761
+ const effectiveDayCap = room.day_cents;
762
+ const isFullDayPrice = !!effectiveDayCap && effectiveDayCap > 0 && ctx.price_cents === effectiveDayCap;
763
+
764
+ const matched = await matchDynamicRules(resolved, { startUtc: ctx.startUtc, isFullDayPrice }, nowMs, getFreeCount);
765
+ if (matched.pct <= 0) return none;
766
+
767
+ const cents = Math.round((ctx.price_cents * matched.pct) / 100);
768
+ if (cents <= 0) return none;
769
+ return { cents, ruleType: matched.ruleType };
770
+ }
771
+
772
+ /**
773
+ * Preview-only helper for booking-availability: resolves the kill switch and
774
+ * this room's active dynamic pricing rules ONCE (lazily, on first call), then
775
+ * answers `pctFor(startUtc, occupancyRangeLiteral)` for as many slots/days as
776
+ * the caller needs. Occupancy is memoized per distinct `occupancyRangeLiteral`
777
+ * so an occupancy-type rule is resolved once per window (e.g. once per day),
778
+ * never once per slot.
779
+ *
780
+ * Never throws — any failure (including the room not being
781
+ * `dynamic_pricing_eligible`) resolves to pct 0, i.e. fails closed to "no
782
+ * discount". This never computes or returns cents; callers that need a
783
+ * price must go through `validateAndPriceForRoom`.
784
+ */
785
+ export function makeDynamicPctResolver(
786
+ supabase: SupabaseLike,
787
+ room: RoomForPricing,
788
+ nowMs: number,
789
+ ): (startUtc: Date, occupancyRangeLiteral: string, isFullDayPrice?: boolean) => Promise<number> {
790
+ let rulesPromise: Promise<ResolvedDynamicRules> | null = null;
791
+ const freeCountCache = new Map<string, Promise<number | null>>();
792
+
793
+ return async (startUtc: Date, occupancyRangeLiteral: string, isFullDayPrice = false): Promise<number> => {
794
+ try {
795
+ if (room.dynamic_pricing_eligible !== true) return 0;
796
+ if (!rulesPromise) rulesPromise = loadDynamicPricingRules(supabase, room);
797
+ const resolved = await rulesPromise;
798
+ if (!resolved.enabled || resolved.rules.length === 0) return 0;
799
+
800
+ const getFreeCount = (): Promise<number | null> => {
801
+ let p = freeCountCache.get(occupancyRangeLiteral);
802
+ if (!p) {
803
+ p = computeOccupancyFreeCount(supabase, room, occupancyRangeLiteral, nowMs);
804
+ freeCountCache.set(occupancyRangeLiteral, p);
805
+ }
806
+ return p;
807
+ };
808
+
809
+ const matched = await matchDynamicRules(resolved, { startUtc, isFullDayPrice }, nowMs, getFreeCount);
810
+ return matched.pct;
811
+ } catch {
812
+ return 0;
813
+ }
814
+ };
815
+ }
816
+
817
+ /**
818
+ * Preview-only counterpart of `makeDynamicPctResolver` for list-ADJUSTING
819
+ * rules. Same lazy-load + memoization shape and the same fail-closed
820
+ * behaviour: any failure (including the room not being
821
+ * `dynamic_pricing_eligible`) resolves to `null`, i.e. "no adjustment, show
822
+ * the plain computed price".
823
+ *
824
+ * As with the discount preview, this is display only —
825
+ * `validateAndPriceForRoom` remains the sole authority on what is charged.
826
+ */
827
+ export function makeListAdjustmentResolver(
828
+ supabase: SupabaseLike,
829
+ room: RoomForPricing,
830
+ ): (startUtc: Date, endUtc: Date, priceCents: number, isFullDayPrice?: boolean) => Promise<ListAdjustment | null> {
831
+ let rulesPromise: Promise<ResolvedDynamicRules> | null = null;
832
+
833
+ return async (startUtc, endUtc, priceCents, isFullDayPrice = false) => {
834
+ try {
835
+ if (room.dynamic_pricing_eligible !== true) return null;
836
+ if (!rulesPromise) rulesPromise = loadDynamicPricingRules(supabase, room);
837
+ const resolved = await rulesPromise;
838
+ if (!resolved.enabled || resolved.rules.length === 0) return null;
839
+ return matchListAdjustingRules(resolved, {
840
+ startUtc, endUtc, isFullDayPrice, price_cents: priceCents,
841
+ });
842
+ } catch {
843
+ return null;
844
+ }
845
+ };
846
+ }
847
+
848
+ /**
849
+ * Every `flat_block` rule active for this room, as offerable products for a
850
+ * given LA date. Preview only — the price a customer is actually charged is
851
+ * re-derived by `validateAndPriceForRoom` from the same rule rows, so a wrong
852
+ * offer here can never become a wrong charge (it becomes a rejected booking).
853
+ */
854
+ export async function listFlatBlockOffers(
855
+ supabase: SupabaseLike,
856
+ room: RoomForPricing,
857
+ dateStr: string,
858
+ openUtc: Date,
859
+ ): Promise<Array<{ start_iso: string; end_iso: string; price_cents: number; label: string }>> {
860
+ try {
861
+ if (room.dynamic_pricing_eligible !== true) return [];
862
+ const resolved = await loadDynamicPricingRules(supabase, room);
863
+ if (!resolved.enabled || resolved.rules.length === 0) return [];
864
+ const wd = laParts(openUtc).wd;
865
+ const [y, mo, d] = dateStr.split('-').map(Number);
866
+ const out: Array<{ start_iso: string; end_iso: string; price_cents: number; label: string }> = [];
867
+ for (const r of resolved.rules) {
868
+ if (r.rule_type !== 'flat_block') continue;
869
+ const dows = r.day_of_week;
870
+ if (dows != null && (!Array.isArray(dows) || !dows.includes(wd))) continue;
871
+ const ws = hhmmToMinutes(r.window_start);
872
+ const we = hhmmToMinutes(r.window_end);
873
+ if (!Number.isFinite(ws) || !Number.isFinite(we) || we <= ws) continue;
874
+ const cents = r.flat_price_cents;
875
+ if (cents == null || !Number.isFinite(cents) || cents <= 0) continue;
876
+ const s = laWallToUtc(y, mo, d, Math.floor(ws / 60), ws % 60);
877
+ const e = laWallToUtc(y, mo, d, Math.floor(we / 60), we % 60);
878
+ out.push({
879
+ start_iso: s.toISOString(),
880
+ end_iso: e.toISOString(),
881
+ price_cents: cents,
882
+ label: formatHumanTime(s, e),
883
+ });
884
+ }
885
+ return out;
886
+ } catch {
887
+ return [];
888
+ }
889
+ }
890
+
891
+ export async function validateAndPriceForRoom(
892
+ supabase: SupabaseLike,
893
+ room: RoomForPricing,
894
+ input: Partial<PricingInputHourly & PricingInputDayBlock>,
895
+ nowMs: number,
896
+ opts: {
897
+ /**
898
+ * Membership status, accepted for caller compatibility (e.g.
899
+ * reschedule-booking) but no longer read here — the member-rate
900
+ * mechanism is retired and every booker is priced off the room's
901
+ * public rate.
902
+ */
903
+ isMember?: boolean;
904
+ allowDynamic?: boolean;
905
+ /**
906
+ * Whether a NEW dynamic-pricing rule may be evaluated for this call.
907
+ * Defaults to the value of `allowDynamic` when omitted. Set to `false` for
908
+ * a caller that should only ever carry forward an existing discount (see
909
+ * `carryForward`) and never mint a fresh one — this is what
910
+ * `reschedule-booking` uses.
911
+ */
912
+ allowFreshDynamic?: boolean;
913
+ /**
914
+ * The discount the customer ALREADY holds on a prior booking of the same
915
+ * room, carried into a reschedule so a repricing can never silently charge
916
+ * them more than the deal they already bought. Carried as the BETTER of
917
+ * two bounds, never the worse: the original discount's absolute cents
918
+ * (never more dollars than they actually earned, even into a much longer
919
+ * or pricier new window -- this is what closes the flash-sale-then-
920
+ * reschedule exploit) and the original discount's PERCENTAGE applied to
921
+ * the new list price (so a shorter/cheaper new window still gets its
922
+ * proportional share). See the `Math.min(P, carryForward.discount_cents,
923
+ * Math.round(...))` line below -- do not change that formula without
924
+ * re-deriving both bounds.
925
+ */
926
+ carryForward?: { list_cents: number; discount_cents: number; rule_type: string | null };
927
+ } = {},
928
+ ): Promise<PricingResult> {
929
+ // `opts.isMember` reflects membership status for callers' own use (e.g.
930
+ // credit eligibility) — pricing no longer varies by it; every booker is
931
+ // priced off the room's public rate.
932
+ const allowDynamic = opts.allowDynamic === true;
933
+ const carryForward = opts.carryForward;
934
+ if (!room.active) return { ok: false, status: 404, error: 'Room not found' };
935
+ if (room.booking_mode === 'quote') {
936
+ return { ok: false, status: 400, error: 'This space is booked by quote, not instant checkout.' };
937
+ }
938
+ const isDayBlock = room.booking_mode === 'day_block';
939
+ const price = () => (isDayBlock
940
+ ? validateAndPriceDayBlock(supabase, room, { date: input.date!, day_mode: input.day_mode! }, nowMs)
941
+ : validateAndPriceHourly(supabase, room, { start: input.start!, end: input.end! }, nowMs));
942
+
943
+ const baseRaw = await price();
944
+ if (!baseRaw.ok) return baseRaw;
945
+
946
+ // === Stage 1: LIST ADJUSTMENT (premium / flat block) ===
947
+ //
948
+ // This runs BEFORE the discount block and is deliberately NOT gated on
949
+ // `opts.allowDynamic` or `opts.allowFreshDynamic`:
950
+ //
951
+ // - allowFreshDynamic exists to stop a RESCHEDULE minting a new DISCOUNT.
952
+ // A list adjustment is not a discount — it is the list price itself. A
953
+ // customer rescheduling OUT of a premium window must reprice DOWN, and
954
+ // one rescheduling INTO one must reprice UP, or the premium is a
955
+ // one-click bypass.
956
+ // - allowDynamic is what admin-create-booking's `skip_dynamic_discount`
957
+ // maps to. That flag means "waive the discount", not "waive the
958
+ // premium"; staff waiving a premium would need its own separate flag.
959
+ //
960
+ // Failure is swallowed to the unadjusted base price, same as the discount
961
+ // block below — a rules-table hiccup must never fail a checkout.
962
+ let base = baseRaw;
963
+ try {
964
+ const adj = await resolveListAdjustment(supabase, room, {
965
+ startUtc: baseRaw.startUtc,
966
+ endUtc: baseRaw.endUtc,
967
+ rangeLiteral: baseRaw.rangeLiteral,
968
+ price_cents: baseRaw.price_cents,
969
+ }, nowMs);
970
+ if (adj) base = { ...baseRaw, price_cents: adj.newPriceCents, list_rule_type: adj.ruleType };
971
+ } catch (e) {
972
+ try {
973
+ await logOps(supabase, 'list_adjustment_failed',
974
+ { message: e instanceof Error ? e.message : JSON.stringify(e), room_id: room.id },
975
+ { severity: 'warning' });
976
+ } catch { /* ignore */ }
977
+ }
978
+
979
+ // === Stage 2: DISCOUNT ===
980
+ // Strictly opt-in per call site + per room (allowDynamic/allowFreshDynamic),
981
+ // and applies the same percentage to the (possibly adjusted) list price for
982
+ // every booker.
983
+ if (!allowDynamic) return base;
984
+ const allowFreshDynamic = opts.allowFreshDynamic ?? allowDynamic;
985
+
986
+ const P = base.price_cents;
987
+ try {
988
+ const resolved = (allowFreshDynamic && room.dynamic_pricing_eligible === true)
989
+ ? await resolveDynamicDiscount(supabase, room, {
990
+ startUtc: base.startUtc,
991
+ endUtc: base.endUtc,
992
+ rangeLiteral: base.rangeLiteral,
993
+ price_cents: P,
994
+ }, nowMs)
995
+ : { cents: 0, ruleType: null as string | null };
996
+
997
+ // Carry-forward is deliberately NOT gated on room.dynamic_pricing_eligible,
998
+ // on app_settings.promotions_enabled, or on the original rule still existing.
999
+ // It honours a price ALREADY SOLD to this customer, which is not the same act
1000
+ // as granting a new promotion — an admin ending a sale or un-flagging a room
1001
+ // must not retroactively raise the price of a reschedule. Deliberate; do not
1002
+ // "fix" this by gating it like a fresh discount.
1003
+ let carriedCents = 0;
1004
+ let carriedRuleType: string | null = null;
1005
+ if (carryForward && carryForward.discount_cents > 0 && carryForward.list_cents > 0) {
1006
+ carriedCents = Math.min(P, carryForward.discount_cents, Math.round((P * carryForward.discount_cents) / carryForward.list_cents));
1007
+ carriedRuleType = carryForward.rule_type;
1008
+ }
1009
+
1010
+ // The customer gets the better of "what this new window earns on its own" and
1011
+ // "what they already had" — never worse than either.
1012
+ let cents = resolved.cents;
1013
+ let ruleType: string | null = resolved.ruleType;
1014
+ if (carriedCents > cents) { cents = carriedCents; ruleType = carriedRuleType; }
1015
+ if (cents <= 0) return base;
1016
+ return { ...base, dynamic_discount_cents: cents, dynamic_discount_rule_type: ruleType };
1017
+ } catch (e) {
1018
+ try {
1019
+ await logOps(supabase, 'dynamic_pricing_failed',
1020
+ { message: e instanceof Error ? e.message : JSON.stringify(e), room_id: room.id },
1021
+ { severity: 'warning' });
1022
+ } catch { /* ignore */ }
1023
+ return base;
1024
+ }
1025
+ }