@profitstudio/booking-engine 0.0.0-stage → 2.0.0-beta.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 (114) hide show
  1. package/CHANGELOG.md +578 -0
  2. package/LICENSE +21 -0
  3. package/README.md +18 -2
  4. package/THIRD_PARTY_NOTICES.md +41 -0
  5. package/bin/booking-engine.mjs +575 -0
  6. package/bin/connect.mjs +408 -0
  7. package/bin/photos.mjs +82 -0
  8. package/dist/admin/BookingAdmin.d.ts +29 -0
  9. package/dist/admin/BookingAdmin.js +338 -0
  10. package/dist/admin/admin.css +1423 -0
  11. package/dist/admin/alerts.d.ts +10 -0
  12. package/dist/admin/alerts.js +11 -0
  13. package/dist/admin/booking-detail.d.ts +47 -0
  14. package/dist/admin/booking-detail.js +159 -0
  15. package/dist/admin/content-inputs.d.ts +15 -0
  16. package/dist/admin/content-inputs.js +105 -0
  17. package/dist/admin/context.d.ts +41 -0
  18. package/dist/admin/context.js +8 -0
  19. package/dist/admin/drawer.d.ts +14 -0
  20. package/dist/admin/drawer.js +56 -0
  21. package/dist/admin/feedback.d.ts +32 -0
  22. package/dist/admin/feedback.js +70 -0
  23. package/dist/admin/fields.d.ts +27 -0
  24. package/dist/admin/fields.js +146 -0
  25. package/dist/admin/fonts/OFL-Geist-Mono.txt +93 -0
  26. package/dist/admin/fonts/OFL-Geist.txt +93 -0
  27. package/dist/admin/fonts/geist-latin-wght-normal.woff2 +0 -0
  28. package/dist/admin/fonts/geist-mono-latin-wght-normal.woff2 +0 -0
  29. package/dist/admin/icons.d.ts +66 -0
  30. package/dist/admin/icons.js +72 -0
  31. package/dist/admin/image-upload.d.ts +58 -0
  32. package/dist/admin/image-upload.js +111 -0
  33. package/dist/admin/index.d.ts +7 -0
  34. package/dist/admin/index.js +6 -0
  35. package/dist/admin/lucide.generated.d.ts +521 -0
  36. package/dist/admin/lucide.generated.js +76 -0
  37. package/dist/admin/sections/BookingsSection.d.ts +1 -0
  38. package/dist/admin/sections/BookingsSection.js +137 -0
  39. package/dist/admin/sections/EmailSection.d.ts +8 -0
  40. package/dist/admin/sections/EmailSection.js +184 -0
  41. package/dist/admin/sections/HoursSection.d.ts +1 -0
  42. package/dist/admin/sections/HoursSection.js +110 -0
  43. package/dist/admin/sections/OverviewSection.d.ts +1 -0
  44. package/dist/admin/sections/OverviewSection.js +427 -0
  45. package/dist/admin/sections/ServicesSection.d.ts +1 -0
  46. package/dist/admin/sections/ServicesSection.js +236 -0
  47. package/dist/admin/sections/SettingsSection.d.ts +10 -0
  48. package/dist/admin/sections/SettingsSection.js +96 -0
  49. package/dist/admin/sections/WebsiteSection.d.ts +1 -0
  50. package/dist/admin/sections/WebsiteSection.js +228 -0
  51. package/dist/admin/sections.d.ts +22 -0
  52. package/dist/admin/sections.js +29 -0
  53. package/dist/admin/setup.d.ts +1 -0
  54. package/dist/admin/setup.js +45 -0
  55. package/dist/admin/today.d.ts +43 -0
  56. package/dist/admin/today.js +115 -0
  57. package/dist/admin/ui.d.ts +134 -0
  58. package/dist/admin/ui.js +220 -0
  59. package/dist/calendar.d.ts +64 -0
  60. package/dist/calendar.js +139 -0
  61. package/dist/client.d.ts +147 -0
  62. package/dist/client.js +507 -0
  63. package/dist/config.d.ts +25 -0
  64. package/dist/config.js +120 -0
  65. package/dist/content/image.d.ts +20 -0
  66. package/dist/content/image.js +90 -0
  67. package/dist/content/resolve.d.ts +12 -0
  68. package/dist/content/resolve.js +73 -0
  69. package/dist/content/schema.d.ts +119 -0
  70. package/dist/content/schema.js +53 -0
  71. package/dist/content/store.d.ts +48 -0
  72. package/dist/content/store.js +123 -0
  73. package/dist/content/validate.d.ts +33 -0
  74. package/dist/content/validate.js +177 -0
  75. package/dist/errors.d.ts +19 -0
  76. package/dist/errors.js +94 -0
  77. package/dist/generated/manifest.d.ts +6 -0
  78. package/dist/generated/manifest.js +7 -0
  79. package/dist/index.d.ts +20 -0
  80. package/dist/index.js +20 -0
  81. package/dist/presets/hair-salon.d.ts +8 -0
  82. package/dist/presets/hair-salon.js +94 -0
  83. package/dist/presets/index.d.ts +5 -0
  84. package/dist/presets/index.js +6 -0
  85. package/dist/preview.d.ts +18 -0
  86. package/dist/preview.js +134 -0
  87. package/dist/semver.d.ts +16 -0
  88. package/dist/semver.js +55 -0
  89. package/dist/time.d.ts +31 -0
  90. package/dist/time.js +138 -0
  91. package/dist/types.d.ts +477 -0
  92. package/dist/types.js +3 -0
  93. package/dist/vite.d.ts +52 -0
  94. package/dist/vite.js +150 -0
  95. package/docs/BUILD-A-SITE.md +203 -0
  96. package/docs/EMAIL-SETUP.md +224 -0
  97. package/docs/INTEGRATION.md +1112 -0
  98. package/engine.manifest.json +90 -0
  99. package/functions/booking-mailer/deno.json +6 -0
  100. package/functions/booking-mailer/index.ts +44 -0
  101. package/functions/booking-mailer/mailer.js +156 -0
  102. package/functions/booking-mailer/providers/index.js +42 -0
  103. package/functions/booking-mailer/providers/resend.js +75 -0
  104. package/functions/booking-mailer/templates.js +345 -0
  105. package/migrations/0001_core.sql +1673 -0
  106. package/migrations/0002_security_hardening.sql +711 -0
  107. package/migrations/0003_private_definers_and_holds.sql +808 -0
  108. package/migrations/0004_verified_requests.sql +1702 -0
  109. package/migrations/0005_scoped_mailer_credential.sql +347 -0
  110. package/migrations/0006_trusted_client_ip.sql +56 -0
  111. package/migrations/0007_site_content.sql +380 -0
  112. package/migrations/0008_service_images_opening_times.sql +328 -0
  113. package/package.json +85 -4
  114. package/templates/BOOKING_ENGINE.md +61 -0
@@ -0,0 +1,808 @@
1
+ -- ============================================================================
2
+ -- Profit Studio Booking Engine — migration 0003_private_definers_and_holds
3
+ -- Engine schema version: 2.0.0-alpha.3
4
+ --
5
+ -- ENGINE-OWNED FILE. Do not edit. `booking-engine doctor` reports changes.
6
+ --
7
+ -- 1. No SECURITY DEFINER function remains in an API-exposed schema (Supabase
8
+ -- lints 0028/0029 inspect the exposed schemas). The two privileged
9
+ -- operations move to the private schema `booking`:
10
+ -- booking.get_availability booking.create_booking
11
+ -- public.booking_get_availability and public.booking_create become thin
12
+ -- SECURITY INVOKER wrappers with unchanged signatures and results.
13
+ -- 2. Booking holds. A website request is `pending` and holds its time only
14
+ -- until `hold_expires_at` (owner setting `pending_hold_minutes`, default
15
+ -- 24 h, never past the appointment start). A lapsed hold stops blocking
16
+ -- availability and is released (status `expired`) inside the same
17
+ -- transaction as an overlapping new booking. The owner can still confirm
18
+ -- an expired request if its time is free.
19
+ -- 3. Instant confirmation is disabled until email verification exists, so an
20
+ -- anonymous, unverified request can never occupy the calendar permanently.
21
+ -- 4. public.booking_admin_request_diagnostics(): admin-only view of the
22
+ -- request headers that identify the caller (verifies rate limiting on a
23
+ -- real host).
24
+ -- 5. Explicit deny-all policies on the two definer-only tables.
25
+ --
26
+ -- Existing data is preserved. Pending requests get a fresh hold window from
27
+ -- the time of the upgrade; auto_confirm is switched off (see CHANGELOG).
28
+ -- ============================================================================
29
+
30
+ do $$
31
+ declare
32
+ v text;
33
+ begin
34
+ select e.schema_version into v from booking.engine_info e where e.id;
35
+ if v is distinct from '2.0.0-alpha.2' then
36
+ raise exception 'Booking Engine 0003_private_definers_and_holds expects schema 2.0.0-alpha.2, found %', coalesce(v, 'none');
37
+ end if;
38
+ end
39
+ $$;
40
+
41
+ -- ----------------------------------------------------------------------------
42
+ -- Schema (additive; one widened check, one new invariant)
43
+ -- ----------------------------------------------------------------------------
44
+
45
+ alter table booking.settings
46
+ add column pending_hold_minutes int not null default 1440
47
+ check (pending_hold_minutes between 15 and 10080);
48
+ comment on column booking.settings.pending_hold_minutes is
49
+ 'How long a new website request holds its time before it becomes available to others again.';
50
+
51
+ update booking.settings set auto_confirm = false where id and auto_confirm;
52
+ alter table booking.settings
53
+ add constraint settings_instant_confirmation_requires_verification check (not auto_confirm);
54
+ comment on constraint settings_instant_confirmation_requires_verification on booking.settings is
55
+ 'Instant confirmation stays off until booking requests are verified (email module): unverified requests must not occupy the calendar permanently.';
56
+
57
+ alter table booking.bookings add column hold_expires_at timestamptz;
58
+ comment on column booking.bookings.hold_expires_at is
59
+ 'A pending website request blocks its time only until this moment. NULL for confirmed and admin bookings.';
60
+ alter table booking.bookings drop constraint bookings_status_check;
61
+ alter table booking.bookings add constraint bookings_status_check
62
+ check (status in ('pending', 'confirmed', 'completed', 'cancelled', 'no_show', 'expired'));
63
+ update booking.bookings b
64
+ set hold_expires_at = least(now() + interval '1440 minutes', b.starts_at)
65
+ where b.status = 'pending';
66
+ alter table booking.bookings add constraint bookings_hold_only_for_requests
67
+ check (hold_expires_at is null or status in ('pending', 'expired'));
68
+ create index bookings_pending_holds on booking.bookings (hold_expires_at) where status = 'pending';
69
+
70
+ -- ----------------------------------------------------------------------------
71
+ -- Holds
72
+ -- ----------------------------------------------------------------------------
73
+
74
+ -- What a booking's status means right now: a pending request whose hold has
75
+ -- lapsed is "expired" even before the row is updated.
76
+ create function booking.effective_status(p_status text, p_hold_expires_at timestamptz)
77
+ returns text
78
+ language sql
79
+ stable
80
+ set search_path = ''
81
+ as $$
82
+ select case
83
+ when p_status = 'pending' and p_hold_expires_at is not null and p_hold_expires_at <= now() then 'expired'
84
+ else p_status
85
+ end;
86
+ $$;
87
+
88
+ -- Same algorithm as before; a pending request blocks its time only while its
89
+ -- hold is live (judged at p_now).
90
+ create or replace function booking.compute_slots(
91
+ p_service_id uuid,
92
+ p_from date,
93
+ p_to date,
94
+ p_now timestamptz,
95
+ p_resource_id uuid default null
96
+ )
97
+ returns table (starts_at timestamptz, ends_at timestamptz, local_date date)
98
+ language sql
99
+ stable
100
+ set search_path = ''
101
+ as $$
102
+ with s as (
103
+ select st.timezone, st.slot_interval_minutes, st.min_notice_minutes, st.max_advance_days
104
+ from booking.settings st
105
+ where st.id
106
+ ),
107
+ svc as (
108
+ select sv.duration_minutes, sv.buffer_after_minutes
109
+ from booking.services sv
110
+ where sv.id = p_service_id and sv.is_active
111
+ ),
112
+ res as (
113
+ select r.id
114
+ from booking.resources r
115
+ where r.is_active
116
+ and (r.id = p_resource_id or (p_resource_id is null and r.is_default))
117
+ ),
118
+ days as (
119
+ select p_from + g.n as day
120
+ from generate_series(
121
+ 0,
122
+ case
123
+ when p_from is null or p_to is null or not isfinite(p_from) or not isfinite(p_to) or not isfinite(p_now) then -1
124
+ else least(p_to - p_from, 400)
125
+ end
126
+ ) as g(n)
127
+ ),
128
+ windows as (
129
+ select dd.day,
130
+ (dd.day + wh.start_time) at time zone s.timezone as open_at,
131
+ (dd.day + wh.end_time) at time zone s.timezone as close_at
132
+ from days dd
133
+ cross join s
134
+ join booking.working_hours wh on wh.weekday = extract(isodow from dd.day)::int
135
+ ),
136
+ candidates as (
137
+ select w.day,
138
+ g.slot_start,
139
+ g.slot_start + make_interval(mins => svc.duration_minutes) as slot_end,
140
+ g.slot_start + make_interval(mins => svc.duration_minutes + svc.buffer_after_minutes) as blocked_until
141
+ from windows w
142
+ cross join svc
143
+ cross join s
144
+ cross join lateral generate_series(
145
+ w.open_at,
146
+ w.close_at - make_interval(mins => svc.duration_minutes),
147
+ make_interval(mins => s.slot_interval_minutes)
148
+ ) as g(slot_start)
149
+ )
150
+ select c.slot_start, c.slot_end, c.day
151
+ from candidates c
152
+ cross join s
153
+ cross join res
154
+ where c.slot_start >= p_now + make_interval(mins => s.min_notice_minutes)
155
+ and c.day <= (p_now at time zone s.timezone)::date + s.max_advance_days
156
+ and not exists (
157
+ select 1
158
+ from booking.bookings b
159
+ where b.resource_id = res.id
160
+ and b.status in ('pending', 'confirmed')
161
+ and (b.status = 'confirmed' or b.hold_expires_at is null or b.hold_expires_at > p_now)
162
+ and tstzrange(b.starts_at, b.blocked_until, '[)') && tstzrange(c.slot_start, c.blocked_until, '[)')
163
+ )
164
+ and not exists (
165
+ select 1
166
+ from booking.availability_exceptions e
167
+ where c.day between e.starts_on and e.ends_on
168
+ and (
169
+ e.start_time is null
170
+ or tstzrange((c.day + e.start_time) at time zone s.timezone,
171
+ (c.day + e.end_time) at time zone s.timezone, '[)')
172
+ && tstzrange(c.slot_start, c.slot_end, '[)')
173
+ )
174
+ )
175
+ order by c.slot_start;
176
+ $$;
177
+
178
+ -- ----------------------------------------------------------------------------
179
+ -- The two privileged operations — private schema, not reachable by URL
180
+ -- ----------------------------------------------------------------------------
181
+
182
+ create function booking.get_availability(p_service_id uuid, p_from date, p_to date default null)
183
+ returns jsonb
184
+ language plpgsql
185
+ stable
186
+ security definer
187
+ set search_path = ''
188
+ as $$
189
+ declare
190
+ c_max_days constant int := 42;
191
+ v_to date := coalesce(p_to, p_from);
192
+ v_settings booking.settings%rowtype;
193
+ v_today date;
194
+ v_last date;
195
+ v_result jsonb;
196
+ begin
197
+ if p_service_id is null then
198
+ perform booking.raise_error('INVALID_INPUT', 'serviceId');
199
+ end if;
200
+ if p_from is null or not isfinite(p_from) then
201
+ perform booking.raise_error('INVALID_INPUT', 'from');
202
+ end if;
203
+ if not isfinite(v_to) or v_to < p_from or v_to - p_from >= c_max_days then
204
+ perform booking.raise_error('INVALID_INPUT', 'to');
205
+ end if;
206
+ if not exists (select 1 from booking.services sv where sv.id = p_service_id and sv.is_active) then
207
+ perform booking.raise_error('SERVICE_UNAVAILABLE');
208
+ end if;
209
+
210
+ select * into v_settings from booking.settings where id;
211
+ v_today := (now() at time zone v_settings.timezone)::date;
212
+ v_last := v_today + v_settings.max_advance_days;
213
+
214
+ with days as (
215
+ select p_from + g.n as day
216
+ from generate_series(0, v_to - p_from) as g(n)
217
+ ),
218
+ slots as (
219
+ select cs.starts_at, cs.ends_at, cs.local_date
220
+ from booking.compute_slots(p_service_id, greatest(p_from, v_today), least(v_to, v_last), now()) as cs
221
+ )
222
+ select jsonb_build_object(
223
+ 'serviceId', p_service_id,
224
+ 'timezone', v_settings.timezone,
225
+ 'from', to_char(p_from, 'YYYY-MM-DD'),
226
+ 'to', to_char(v_to, 'YYYY-MM-DD'),
227
+ 'days', coalesce(jsonb_agg(
228
+ jsonb_build_object(
229
+ 'date', to_char(dd.day, 'YYYY-MM-DD'),
230
+ 'status', case
231
+ when dd.day < v_today or dd.day > v_last then 'unavailable'
232
+ when not exists (select 1 from booking.working_hours wh where wh.weekday = extract(isodow from dd.day)::int)
233
+ or exists (select 1 from booking.availability_exceptions e
234
+ where dd.day between e.starts_on and e.ends_on and e.start_time is null) then 'closed'
235
+ when exists (select 1 from slots sl where sl.local_date = dd.day) then 'available'
236
+ else 'full'
237
+ end,
238
+ 'slots', coalesce((
239
+ select jsonb_agg(
240
+ jsonb_build_object(
241
+ 'startsAt', booking.iso(sl.starts_at),
242
+ 'endsAt', booking.iso(sl.ends_at),
243
+ 'time', to_char(sl.starts_at at time zone v_settings.timezone, 'HH24:MI')
244
+ ) order by sl.starts_at)
245
+ from slots sl
246
+ where sl.local_date = dd.day
247
+ ), '[]'::jsonb)
248
+ ) order by dd.day), '[]'::jsonb)
249
+ )
250
+ into v_result
251
+ from days dd;
252
+
253
+ return v_result;
254
+ end;
255
+ $$;
256
+ comment on function booking.get_availability(uuid, date, date) is
257
+ 'PRIVILEGED (SECURITY DEFINER), private schema: reads existing bookings to compute free slots and returns times only. Reached through public.booking_get_availability.';
258
+
259
+ create function booking.create_booking(
260
+ p_service_id uuid,
261
+ p_starts_at timestamptz,
262
+ p_customer_name text,
263
+ p_customer_email text,
264
+ p_customer_phone text default null,
265
+ p_notes text default null
266
+ )
267
+ returns jsonb
268
+ language plpgsql
269
+ volatile
270
+ security definer
271
+ set search_path = ''
272
+ as $$
273
+ declare
274
+ c_client_limit_per_hour constant int := 10;
275
+ v_settings booking.settings%rowtype;
276
+ v_service booking.services%rowtype;
277
+ v_resource_id uuid;
278
+ v_name text := btrim(coalesce(p_customer_name, ''));
279
+ v_email text := lower(btrim(coalesce(p_customer_email, '')));
280
+ v_phone text := nullif(btrim(coalesce(p_customer_phone, '')), '');
281
+ v_notes text := nullif(btrim(coalesce(p_notes, '')), '');
282
+ v_local_day date;
283
+ v_blocked_until timestamptz;
284
+ v_hold_expires_at timestamptz;
285
+ v_client text;
286
+ v_bucket text;
287
+ v_limit int;
288
+ v_count int;
289
+ v_booking booking.bookings%rowtype;
290
+ v_attempt int := 0;
291
+ begin
292
+ -- 1. Validate the request itself (cheap, no table access).
293
+ if p_service_id is null then
294
+ perform booking.raise_error('INVALID_INPUT', 'serviceId');
295
+ end if;
296
+ if p_starts_at is null or not isfinite(p_starts_at) then
297
+ perform booking.raise_error('INVALID_INPUT', 'startsAt');
298
+ end if;
299
+ if char_length(v_name) < 1 or char_length(v_name) > 120 or v_name ~ '[[:cntrl:]]' then
300
+ perform booking.raise_error('INVALID_INPUT', 'customer.name');
301
+ end if;
302
+ if char_length(v_email) > 254
303
+ or v_email !~ '^[^@[:space:]<>()]+@[^@[:space:]<>()]+\.[^@[:space:]<>()]{2,}$' then
304
+ perform booking.raise_error('INVALID_INPUT', 'customer.email');
305
+ end if;
306
+ if v_phone is not null and (
307
+ char_length(v_phone) > 40
308
+ or v_phone !~ '^[0-9+()./[:space:]-]+$'
309
+ or char_length(regexp_replace(v_phone, '[^0-9]', '', 'g')) < 5) then
310
+ perform booking.raise_error('INVALID_INPUT', 'customer.phone');
311
+ end if;
312
+ if v_notes is not null and (char_length(v_notes) > 1000 or v_notes ~ '[\x01-\x08\x0B\x0C\x0E-\x1F\x7F]') then
313
+ perform booking.raise_error('INVALID_INPUT', 'notes');
314
+ end if;
315
+
316
+ select * into v_settings from booking.settings where id;
317
+ if v_settings.require_phone and v_phone is null then
318
+ perform booking.raise_error('INVALID_INPUT', 'customer.phone');
319
+ end if;
320
+
321
+ -- 2. Only times inside the booking window are worth computing.
322
+ if p_starts_at < now() or p_starts_at > now() + make_interval(days => v_settings.max_advance_days + 1) then
323
+ perform booking.raise_error('SLOT_UNAVAILABLE');
324
+ end if;
325
+
326
+ select * into v_service from booking.services where id = p_service_id and is_active;
327
+ if not found then
328
+ perform booking.raise_error('SERVICE_UNAVAILABLE');
329
+ end if;
330
+
331
+ select r.id into v_resource_id from booking.resources r where r.is_default and r.is_active;
332
+ if v_resource_id is null then
333
+ perform booking.raise_error('SLOT_UNAVAILABLE');
334
+ end if;
335
+
336
+ -- 3. The start must be a slot the engine offers right now (lapsed holds
337
+ -- do not count as taken).
338
+ v_local_day := (p_starts_at at time zone v_settings.timezone)::date;
339
+ if not exists (
340
+ select 1
341
+ from booking.compute_slots(p_service_id, v_local_day, v_local_day, now(), v_resource_id) as cs
342
+ where cs.starts_at = p_starts_at
343
+ ) then
344
+ perform booking.raise_error('SLOT_UNAVAILABLE');
345
+ end if;
346
+
347
+ -- 4. Abuse limits — after the slot check, without saying which limit was
348
+ -- hit, serialised per email and per client. Lock order: email, client.
349
+ perform pg_advisory_xact_lock(hashtextextended('booking_engine:email:' || v_email, 0));
350
+ select count(*) into v_count
351
+ from booking.bookings b
352
+ where lower(b.customer_email) = v_email
353
+ and b.status in ('pending', 'confirmed')
354
+ and (b.status = 'confirmed' or b.hold_expires_at is null or b.hold_expires_at > now())
355
+ and b.starts_at > now();
356
+ if v_count >= v_settings.max_active_bookings_per_email then
357
+ perform booking.raise_error('RATE_LIMITED');
358
+ end if;
359
+
360
+ v_client := booking.client_key();
361
+ v_bucket := 'client:' || encode(sha256(convert_to(
362
+ (select es.hash_salt from booking.engine_secrets es where es.id) || ':' || v_client, 'UTF8')), 'hex');
363
+ perform pg_advisory_xact_lock(hashtextextended('booking_engine:' || v_bucket, 0));
364
+ v_limit := case when v_client = 'unknown' then v_settings.max_website_bookings_per_hour else c_client_limit_per_hour end;
365
+ select count(*) into v_count
366
+ from booking.request_log r
367
+ where r.bucket = v_bucket and r.created_at > now() - interval '1 hour';
368
+ if v_count >= v_limit then
369
+ perform booking.raise_error('RATE_LIMITED');
370
+ end if;
371
+
372
+ select count(*) into v_count
373
+ from booking.bookings b
374
+ where b.source = 'website' and b.created_at > now() - interval '1 hour';
375
+ if v_count >= v_settings.max_website_bookings_per_hour then
376
+ perform booking.raise_error('RATE_LIMITED');
377
+ end if;
378
+
379
+ -- 5. Release lapsed holds that overlap this time, in this transaction, so
380
+ -- the exclusion constraint only sees live holds and confirmed bookings.
381
+ v_blocked_until := p_starts_at + make_interval(mins => v_service.duration_minutes + v_service.buffer_after_minutes);
382
+ with lapsed as (
383
+ update booking.bookings b
384
+ set status = 'expired', status_changed_at = now()
385
+ where b.status = 'pending'
386
+ and b.hold_expires_at is not null
387
+ and b.hold_expires_at <= now()
388
+ and b.resource_id = v_resource_id
389
+ and tstzrange(b.starts_at, b.blocked_until, '[)') && tstzrange(p_starts_at, v_blocked_until, '[)')
390
+ returning b.id
391
+ )
392
+ insert into booking.booking_events (booking_id, event_type, from_status, to_status, actor)
393
+ select l.id, 'status_changed', 'pending', 'expired', 'system' from lapsed l;
394
+
395
+ -- 6. Insert a request that holds its time for the owner's hold window.
396
+ v_hold_expires_at := least(now() + make_interval(mins => v_settings.pending_hold_minutes), p_starts_at);
397
+ loop
398
+ v_attempt := v_attempt + 1;
399
+ begin
400
+ insert into booking.bookings (
401
+ reference, service_id, resource_id, starts_at, ends_at, blocked_until, status, hold_expires_at,
402
+ customer_name, customer_email, customer_phone, customer_notes,
403
+ service_name, price_cents, currency, source
404
+ ) values (
405
+ booking.new_reference(), v_service.id, v_resource_id, p_starts_at,
406
+ p_starts_at + make_interval(mins => v_service.duration_minutes),
407
+ v_blocked_until, 'pending', v_hold_expires_at,
408
+ v_name, v_email, v_phone, v_notes,
409
+ v_service.name, v_service.price_cents, v_settings.currency, 'website'
410
+ )
411
+ returning * into v_booking;
412
+ exit;
413
+ exception
414
+ when exclusion_violation then
415
+ perform booking.raise_error('SLOT_UNAVAILABLE');
416
+ when unique_violation then
417
+ if v_attempt >= 3 then
418
+ raise;
419
+ end if;
420
+ end;
421
+ end loop;
422
+
423
+ insert into booking.booking_events (booking_id, event_type, to_status, actor)
424
+ values (v_booking.id, 'created', v_booking.status, 'customer');
425
+
426
+ insert into booking.request_log (bucket) values (v_bucket);
427
+ delete from booking.request_log r where r.created_at < now() - interval '1 day';
428
+
429
+ return jsonb_build_object(
430
+ 'reference', v_booking.reference,
431
+ 'status', v_booking.status,
432
+ 'startsAt', booking.iso(v_booking.starts_at),
433
+ 'endsAt', booking.iso(v_booking.ends_at),
434
+ 'date', to_char(v_booking.starts_at at time zone v_settings.timezone, 'YYYY-MM-DD'),
435
+ 'time', to_char(v_booking.starts_at at time zone v_settings.timezone, 'HH24:MI'),
436
+ 'serviceName', v_booking.service_name,
437
+ 'timezone', v_settings.timezone,
438
+ 'holdExpiresAt', booking.iso(v_booking.hold_expires_at)
439
+ );
440
+ end;
441
+ $$;
442
+ comment on function booking.create_booking(uuid, timestamptz, text, text, text, text) is
443
+ 'PRIVILEGED (SECURITY DEFINER), private schema: the only way to create a booking. Validates input, re-checks the slot, applies abuse limits, releases lapsed holds and relies on the exclusion constraint under concurrency. Reached through public.booking_create.';
444
+
445
+ -- ----------------------------------------------------------------------------
446
+ -- Public API: thin SECURITY INVOKER wrappers (same signatures, same results)
447
+ -- ----------------------------------------------------------------------------
448
+
449
+ create or replace function public.booking_get_availability(p_service_id uuid, p_from date, p_to date default null)
450
+ returns jsonb
451
+ language sql
452
+ stable
453
+ security invoker
454
+ set search_path = ''
455
+ as $$
456
+ select booking.get_availability(p_service_id, p_from, p_to);
457
+ $$;
458
+ comment on function public.booking_get_availability(uuid, date, date) is
459
+ 'Public. Free slots for one service over business-local dates (at most 42 days). Times only, never people.';
460
+
461
+ create or replace function public.booking_create(
462
+ p_service_id uuid,
463
+ p_starts_at timestamptz,
464
+ p_customer_name text,
465
+ p_customer_email text,
466
+ p_customer_phone text default null,
467
+ p_notes text default null
468
+ )
469
+ returns jsonb
470
+ language sql
471
+ volatile
472
+ security invoker
473
+ set search_path = ''
474
+ as $$
475
+ select booking.create_booking(p_service_id, p_starts_at, p_customer_name, p_customer_email, p_customer_phone, p_notes);
476
+ $$;
477
+ comment on function public.booking_create(uuid, timestamptz, text, text, text, text) is
478
+ 'Public. Creates a booking request that holds its time for the owner''s hold window.';
479
+
480
+ create or replace function public.booking_get_business()
481
+ returns jsonb
482
+ language sql
483
+ stable
484
+ security invoker
485
+ set search_path = ''
486
+ as $$
487
+ select jsonb_build_object(
488
+ 'name', s.business_name,
489
+ 'timezone', s.timezone,
490
+ 'currency', s.currency,
491
+ 'locale', s.locale,
492
+ 'contact', jsonb_build_object('email', s.public_email, 'phone', s.public_phone, 'address', s.address),
493
+ 'policies', jsonb_build_object(
494
+ 'slotIntervalMinutes', s.slot_interval_minutes,
495
+ 'minNoticeMinutes', s.min_notice_minutes,
496
+ 'maxAdvanceDays', s.max_advance_days,
497
+ 'autoConfirm', s.auto_confirm,
498
+ 'requirePhone', s.require_phone,
499
+ 'pendingHoldMinutes', s.pending_hold_minutes
500
+ ),
501
+ 'openingHours', coalesce((
502
+ select jsonb_agg(
503
+ jsonb_build_object('weekday', w.weekday, 'start', booking.hhmm(w.start_time), 'end', booking.hhmm(w.end_time))
504
+ order by w.weekday, w.start_time)
505
+ from booking.working_hours w
506
+ ), '[]'::jsonb)
507
+ )
508
+ from booking.settings s
509
+ where s.id;
510
+ $$;
511
+
512
+ -- ----------------------------------------------------------------------------
513
+ -- Admin API
514
+ -- ----------------------------------------------------------------------------
515
+
516
+ create or replace function booking.booking_json(b booking.bookings, p_tz text)
517
+ returns jsonb
518
+ language sql
519
+ stable
520
+ set search_path = ''
521
+ as $$
522
+ select jsonb_build_object(
523
+ 'id', b.id,
524
+ 'reference', b.reference,
525
+ 'status', booking.effective_status(b.status, b.hold_expires_at),
526
+ 'holdExpiresAt', booking.iso(b.hold_expires_at),
527
+ 'startsAt', booking.iso(b.starts_at),
528
+ 'endsAt', booking.iso(b.ends_at),
529
+ 'date', to_char(b.starts_at at time zone p_tz, 'YYYY-MM-DD'),
530
+ 'time', to_char(b.starts_at at time zone p_tz, 'HH24:MI'),
531
+ 'endTime', to_char(b.ends_at at time zone p_tz, 'HH24:MI'),
532
+ 'serviceId', b.service_id,
533
+ 'serviceName', b.service_name,
534
+ 'priceCents', b.price_cents,
535
+ 'currency', b.currency,
536
+ 'customer', jsonb_build_object('name', b.customer_name, 'email', b.customer_email, 'phone', b.customer_phone),
537
+ 'notes', b.customer_notes,
538
+ 'source', b.source,
539
+ 'createdAt', booking.iso(b.created_at),
540
+ 'statusChangedAt', booking.iso(b.status_changed_at)
541
+ );
542
+ $$;
543
+
544
+ create or replace function public.booking_admin_list_bookings(p_from date, p_to date, p_statuses text[] default null)
545
+ returns jsonb
546
+ language plpgsql
547
+ stable
548
+ security invoker
549
+ set search_path = ''
550
+ as $$
551
+ declare
552
+ v_tz text;
553
+ v_result jsonb;
554
+ begin
555
+ perform booking.require_admin();
556
+ if p_from is null or p_to is null or not isfinite(p_from) or not isfinite(p_to)
557
+ or p_to < p_from or p_to - p_from > 400 then
558
+ perform booking.raise_error('INVALID_INPUT', 'range');
559
+ end if;
560
+ if p_statuses is not null and exists (
561
+ select 1 from unnest(p_statuses) as st(v)
562
+ where st.v is null or st.v not in ('pending', 'confirmed', 'completed', 'cancelled', 'no_show', 'expired')) then
563
+ perform booking.raise_error('INVALID_INPUT', 'statuses');
564
+ end if;
565
+
566
+ select s.timezone into v_tz from booking.settings s where s.id;
567
+
568
+ select coalesce(jsonb_agg(booking.booking_json(b, v_tz) order by b.starts_at), '[]'::jsonb)
569
+ into v_result
570
+ from booking.bookings b
571
+ where b.id in (
572
+ select b2.id
573
+ from booking.bookings b2
574
+ where b2.starts_at >= (p_from::timestamp at time zone v_tz)
575
+ and b2.starts_at < ((p_to + 1)::timestamp at time zone v_tz)
576
+ and (p_statuses is null or booking.effective_status(b2.status, b2.hold_expires_at) = any (p_statuses))
577
+ order by b2.starts_at
578
+ limit 1000
579
+ );
580
+ return v_result;
581
+ end;
582
+ $$;
583
+
584
+ create or replace function public.booking_admin_set_booking_status(p_booking_id uuid, p_status text)
585
+ returns jsonb
586
+ language plpgsql
587
+ volatile
588
+ security invoker
589
+ set search_path = ''
590
+ as $$
591
+ declare
592
+ v_uid uuid;
593
+ v_tz text;
594
+ b booking.bookings%rowtype;
595
+ v_from text;
596
+ begin
597
+ v_uid := booking.require_admin();
598
+ if p_status is null or p_status not in ('confirmed', 'cancelled', 'completed', 'no_show') then
599
+ perform booking.raise_error('INVALID_INPUT', 'status');
600
+ end if;
601
+
602
+ select * into b from booking.bookings where id = p_booking_id for update;
603
+ if not found then
604
+ perform booking.raise_error('NOT_FOUND', 'booking');
605
+ end if;
606
+ select s.timezone into v_tz from booking.settings s where s.id;
607
+
608
+ v_from := booking.effective_status(b.status, b.hold_expires_at);
609
+ if v_from = p_status then
610
+ return booking.booking_json(b, v_tz);
611
+ end if;
612
+ if not (
613
+ (v_from in ('pending', 'expired') and p_status in ('confirmed', 'cancelled'))
614
+ or (v_from = 'confirmed' and p_status in ('cancelled', 'completed', 'no_show'))
615
+ ) then
616
+ perform booking.raise_error('INVALID_TRANSITION', v_from || '->' || p_status);
617
+ end if;
618
+ if p_status in ('completed', 'no_show') and b.starts_at > now() then
619
+ perform booking.raise_error('INVALID_TRANSITION', 'not_started');
620
+ end if;
621
+
622
+ begin
623
+ update booking.bookings
624
+ set status = p_status, hold_expires_at = null, status_changed_at = now()
625
+ where id = b.id
626
+ returning * into b;
627
+ exception
628
+ when exclusion_violation then
629
+ -- An expired request's time was booked by someone else meanwhile.
630
+ perform booking.raise_error('CONFLICT', 'slot_taken');
631
+ end;
632
+
633
+ insert into booking.booking_events (booking_id, event_type, from_status, to_status, actor, actor_user_id)
634
+ values (b.id, 'status_changed', v_from, p_status, 'admin', v_uid);
635
+
636
+ return booking.booking_json(b, v_tz);
637
+ end;
638
+ $$;
639
+
640
+ create or replace function booking.settings_json()
641
+ returns jsonb
642
+ language sql
643
+ stable
644
+ set search_path = ''
645
+ as $$
646
+ select jsonb_build_object(
647
+ 'businessName', s.business_name,
648
+ 'timezone', s.timezone,
649
+ 'currency', s.currency,
650
+ 'locale', s.locale,
651
+ 'publicEmail', s.public_email,
652
+ 'publicPhone', s.public_phone,
653
+ 'address', s.address,
654
+ 'slotIntervalMinutes', s.slot_interval_minutes,
655
+ 'minNoticeMinutes', s.min_notice_minutes,
656
+ 'maxAdvanceDays', s.max_advance_days,
657
+ 'autoConfirm', s.auto_confirm,
658
+ 'requirePhone', s.require_phone,
659
+ 'maxActiveBookingsPerEmail', s.max_active_bookings_per_email,
660
+ 'maxWebsiteBookingsPerHour', s.max_website_bookings_per_hour,
661
+ 'pendingHoldMinutes', s.pending_hold_minutes,
662
+ 'updatedAt', booking.iso(s.updated_at)
663
+ )
664
+ from booking.settings s
665
+ where s.id;
666
+ $$;
667
+
668
+ create or replace function public.booking_admin_update_settings(p_settings jsonb)
669
+ returns jsonb
670
+ language plpgsql
671
+ volatile
672
+ security invoker
673
+ set search_path = ''
674
+ as $$
675
+ declare
676
+ v_allowed text[] := array['businessName', 'timezone', 'currency', 'locale', 'publicEmail', 'publicPhone',
677
+ 'address', 'slotIntervalMinutes', 'minNoticeMinutes', 'maxAdvanceDays',
678
+ 'autoConfirm', 'requirePhone', 'maxActiveBookingsPerEmail',
679
+ 'maxWebsiteBookingsPerHour', 'pendingHoldMinutes'];
680
+ v_key text;
681
+ v_email text;
682
+ begin
683
+ perform booking.require_admin();
684
+ if p_settings is null or jsonb_typeof(p_settings) <> 'object' then
685
+ perform booking.raise_error('INVALID_INPUT', 'settings');
686
+ end if;
687
+ for v_key in select jsonb_object_keys(p_settings) loop
688
+ if not (v_key = any (v_allowed)) then
689
+ perform booking.raise_error('INVALID_INPUT', v_key);
690
+ end if;
691
+ end loop;
692
+ if coalesce(booking.j_bool(p_settings, 'autoConfirm'), false) then
693
+ -- Instant confirmation needs verified requests (email module).
694
+ perform booking.raise_error('INVALID_INPUT', 'autoConfirm');
695
+ end if;
696
+
697
+ v_email := lower(booking.j_text(p_settings, 'publicEmail', 254));
698
+ if v_email is not null and v_email !~ '^[^@[:space:]<>()]+@[^@[:space:]<>()]+\.[^@[:space:]<>()]{2,}$' then
699
+ perform booking.raise_error('INVALID_INPUT', 'publicEmail');
700
+ end if;
701
+ if p_settings ? 'currency' and coalesce(booking.j_text(p_settings, 'currency', 3), '') !~ '^[A-Z]{3}$' then
702
+ perform booking.raise_error('INVALID_INPUT', 'currency');
703
+ end if;
704
+ if p_settings ? 'locale'
705
+ and coalesce(booking.j_text(p_settings, 'locale', 35), '') !~ '^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$' then
706
+ perform booking.raise_error('INVALID_INPUT', 'locale');
707
+ end if;
708
+
709
+ update booking.settings set
710
+ business_name = case when p_settings ? 'businessName'
711
+ then booking.j_required_text(p_settings, 'businessName', 120) else business_name end,
712
+ timezone = case when p_settings ? 'timezone' then booking.j_required_text(p_settings, 'timezone', 64) else timezone end,
713
+ currency = case when p_settings ? 'currency' then booking.j_required_text(p_settings, 'currency', 3) else currency end,
714
+ locale = case when p_settings ? 'locale' then booking.j_required_text(p_settings, 'locale', 35) else locale end,
715
+ public_email = case when p_settings ? 'publicEmail' then v_email else public_email end,
716
+ public_phone = case when p_settings ? 'publicPhone' then booking.j_text(p_settings, 'publicPhone', 40) else public_phone end,
717
+ address = case when p_settings ? 'address' then booking.j_text(p_settings, 'address', 300) else address end,
718
+ slot_interval_minutes = case when p_settings ? 'slotIntervalMinutes'
719
+ then coalesce(booking.j_int(p_settings, 'slotIntervalMinutes', 5, 240), slot_interval_minutes) else slot_interval_minutes end,
720
+ min_notice_minutes = case when p_settings ? 'minNoticeMinutes'
721
+ then coalesce(booking.j_int(p_settings, 'minNoticeMinutes', 0, 43200), min_notice_minutes) else min_notice_minutes end,
722
+ max_advance_days = case when p_settings ? 'maxAdvanceDays'
723
+ then coalesce(booking.j_int(p_settings, 'maxAdvanceDays', 1, 730), max_advance_days) else max_advance_days end,
724
+ require_phone = case when p_settings ? 'requirePhone'
725
+ then coalesce(booking.j_bool(p_settings, 'requirePhone'), require_phone) else require_phone end,
726
+ max_active_bookings_per_email = case when p_settings ? 'maxActiveBookingsPerEmail'
727
+ then coalesce(booking.j_int(p_settings, 'maxActiveBookingsPerEmail', 1, 50), max_active_bookings_per_email)
728
+ else max_active_bookings_per_email end,
729
+ max_website_bookings_per_hour = case when p_settings ? 'maxWebsiteBookingsPerHour'
730
+ then coalesce(booking.j_int(p_settings, 'maxWebsiteBookingsPerHour', 1, 1000), max_website_bookings_per_hour)
731
+ else max_website_bookings_per_hour end,
732
+ pending_hold_minutes = case when p_settings ? 'pendingHoldMinutes'
733
+ then coalesce(booking.j_int(p_settings, 'pendingHoldMinutes', 15, 10080), pending_hold_minutes)
734
+ else pending_hold_minutes end
735
+ where id;
736
+
737
+ return booking.settings_json();
738
+ end;
739
+ $$;
740
+
741
+ create function public.booking_admin_request_diagnostics()
742
+ returns jsonb
743
+ language plpgsql
744
+ stable
745
+ security invoker
746
+ set search_path = ''
747
+ as $$
748
+ declare
749
+ h jsonb;
750
+ begin
751
+ perform booking.require_admin();
752
+ begin
753
+ h := nullif(current_setting('request.headers', true), '')::jsonb;
754
+ exception when others then
755
+ h := null;
756
+ end;
757
+ return jsonb_build_object(
758
+ 'headerNames', coalesce((
759
+ select jsonb_agg(k.name order by k.name)
760
+ from jsonb_object_keys(coalesce(h, '{}'::jsonb)) as k(name)
761
+ where k.name not in ('authorization', 'apikey', 'cookie')
762
+ ), '[]'::jsonb),
763
+ 'cfConnectingIp', h ->> 'cf-connecting-ip',
764
+ 'xRealIp', h ->> 'x-real-ip',
765
+ 'xForwardedFor', h ->> 'x-forwarded-for',
766
+ 'clientKey', booking.client_key()
767
+ );
768
+ end;
769
+ $$;
770
+ comment on function public.booking_admin_request_diagnostics() is
771
+ 'Admin only. The caller-identifying request headers as the database sees them (never credentials), to verify rate limiting on a real host.';
772
+
773
+ -- ----------------------------------------------------------------------------
774
+ -- Explicit deny-all policies on definer-only tables (intent, and Supabase lint 0008)
775
+ -- ----------------------------------------------------------------------------
776
+
777
+ create policy request_log_no_api_access on booking.request_log
778
+ for all to anon, authenticated using (false) with check (false);
779
+ create policy engine_secrets_no_api_access on booking.engine_secrets
780
+ for all to anon, authenticated using (false) with check (false);
781
+
782
+ -- ----------------------------------------------------------------------------
783
+ -- Privileges
784
+ -- ----------------------------------------------------------------------------
785
+
786
+ revoke all on function
787
+ booking.get_availability(uuid, date, date),
788
+ booking.create_booking(uuid, timestamptz, text, text, text, text),
789
+ booking.effective_status(text, timestamptz),
790
+ public.booking_admin_request_diagnostics()
791
+ from public, anon, authenticated, service_role;
792
+
793
+ -- The private privileged functions are executable by the API roles but not
794
+ -- reachable by URL (schema `booking` is not exposed); the public wrappers are
795
+ -- the only entry points.
796
+ grant execute on function
797
+ booking.get_availability(uuid, date, date),
798
+ booking.create_booking(uuid, timestamptz, text, text, text, text)
799
+ to anon, authenticated, service_role;
800
+
801
+ grant execute on function booking.effective_status(text, timestamptz) to authenticated;
802
+ -- The diagnostics read only the caller's own request headers.
803
+ grant execute on function booking.client_ip(), booking.client_key() to authenticated;
804
+ grant execute on function public.booking_admin_request_diagnostics() to authenticated;
805
+
806
+ grant select (pending_hold_minutes) on booking.settings to anon, service_role;
807
+
808
+ update booking.engine_info set schema_version = '2.0.0-alpha.3', updated_at = now() where id;