@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,711 @@
1
+ -- ============================================================================
2
+ -- Profit Studio Booking Engine — migration 0002_security_hardening
3
+ -- Engine schema version: 2.0.0-alpha.2
4
+ --
5
+ -- ENGINE-OWNED FILE. Do not edit. `booking-engine doctor` reports changes.
6
+ --
7
+ -- Fixes from the Phase 1 independent security review:
8
+ -- 1. booking_create rejects non-finite or out-of-window start times before
9
+ -- any slot computation ('infinity' made slot generation run until the
10
+ -- statement timeout); compute_slots is bounded for every input.
11
+ -- 2. Rate limits hold under concurrency (transaction advisory locks per
12
+ -- email and per client); IPv6 clients are grouped by /64; a missing,
13
+ -- blank or invalid client IP is one shared, limited bucket instead of
14
+ -- "no limit"; a site-wide hourly cap on website bookings (owner setting).
15
+ -- 3. Limits are checked after the slot check and never say which limit was
16
+ -- hit, so the endpoint no longer reveals whether an email has bookings.
17
+ -- 4. service_role can use the public read functions (server-side callers).
18
+ -- 5. add_admin requires a confirmed email; remove_admin reports no match.
19
+ -- 6. Client identifiers are hashed with a per-installation secret salt.
20
+ -- Existing data is preserved. Function signatures are unchanged.
21
+ -- ============================================================================
22
+
23
+ do $$
24
+ declare
25
+ v text;
26
+ begin
27
+ select e.schema_version into v from booking.engine_info e where e.id;
28
+ if v is distinct from '2.0.0-alpha.1' then
29
+ raise exception 'Booking Engine 0002_security_hardening expects schema 2.0.0-alpha.1, found %', coalesce(v, 'none');
30
+ end if;
31
+ end
32
+ $$;
33
+
34
+ -- ----------------------------------------------------------------------------
35
+ -- Schema additions (additive only)
36
+ -- ----------------------------------------------------------------------------
37
+
38
+ alter table booking.settings
39
+ add column max_website_bookings_per_hour int not null default 30
40
+ check (max_website_bookings_per_hour between 1 and 1000);
41
+ comment on column booking.settings.max_website_bookings_per_hour is
42
+ 'Site-wide cap on new website bookings per rolling hour: a circuit breaker against calendar-filling spam.';
43
+
44
+ create table booking.engine_secrets (
45
+ id boolean primary key default true check (id),
46
+ hash_salt text not null default (replace(gen_random_uuid()::text, '-', '') || replace(gen_random_uuid()::text, '-', ''))
47
+ );
48
+ comment on table booking.engine_secrets is 'Per-installation secrets (never exposed). hash_salt salts client identifiers in request_log.';
49
+ alter table booking.engine_secrets enable row level security;
50
+ revoke all on booking.engine_secrets from public, anon, authenticated, service_role;
51
+ insert into booking.engine_secrets default values;
52
+
53
+ -- Rows hashed without a salt are discarded; they only ever covered 24 hours.
54
+ delete from booking.request_log r where r.id is not null;
55
+
56
+ create index bookings_created_at on booking.bookings (created_at);
57
+
58
+ -- ----------------------------------------------------------------------------
59
+ -- Client identity for rate limiting
60
+ -- ----------------------------------------------------------------------------
61
+
62
+ -- Best-effort client IP from PostgREST request headers. Blank values are
63
+ -- ignored. Which header is trustworthy on hosted Supabase is still unverified
64
+ -- (docs/SECURITY.md).
65
+ create or replace function booking.client_ip()
66
+ returns text
67
+ language plpgsql
68
+ stable
69
+ set search_path = ''
70
+ as $$
71
+ declare
72
+ h jsonb;
73
+ begin
74
+ begin
75
+ h := nullif(current_setting('request.headers', true), '')::jsonb;
76
+ exception when others then
77
+ return null;
78
+ end;
79
+ if h is null or jsonb_typeof(h) <> 'object' then
80
+ return null;
81
+ end if;
82
+ return left(coalesce(
83
+ nullif(btrim(h ->> 'cf-connecting-ip'), ''),
84
+ nullif(btrim(h ->> 'x-real-ip'), ''),
85
+ nullif(btrim(split_part(h ->> 'x-forwarded-for', ',', 1)), '')
86
+ ), 64);
87
+ end;
88
+ $$;
89
+
90
+ -- Normalised client key: 'ip4:<address>', 'ip6:<network>/64' or 'unknown'.
91
+ create function booking.client_key()
92
+ returns text
93
+ language plpgsql
94
+ stable
95
+ set search_path = ''
96
+ as $$
97
+ declare
98
+ v text := booking.client_ip();
99
+ v_inet inet;
100
+ begin
101
+ if v is null then
102
+ return 'unknown';
103
+ end if;
104
+ begin
105
+ v_inet := v::inet;
106
+ exception when others then
107
+ return 'unknown';
108
+ end;
109
+ if family(v_inet) = 6 and v_inet << '::ffff:0:0/96'::inet then
110
+ v_inet := '0.0.0.0'::inet + (v_inet - '::ffff:0:0'::inet);
111
+ end if;
112
+ if family(v_inet) = 6 then
113
+ return 'ip6:' || host(network(set_masklen(v_inet, 64))) || '/64';
114
+ end if;
115
+ return 'ip4:' || host(v_inet);
116
+ end;
117
+ $$;
118
+
119
+ -- ----------------------------------------------------------------------------
120
+ -- Bounded slot computation (same signature, same results for valid input)
121
+ -- ----------------------------------------------------------------------------
122
+
123
+ create or replace function booking.compute_slots(
124
+ p_service_id uuid,
125
+ p_from date,
126
+ p_to date,
127
+ p_now timestamptz,
128
+ p_resource_id uuid default null
129
+ )
130
+ returns table (starts_at timestamptz, ends_at timestamptz, local_date date)
131
+ language sql
132
+ stable
133
+ set search_path = ''
134
+ as $$
135
+ with s as (
136
+ select st.timezone, st.slot_interval_minutes, st.min_notice_minutes, st.max_advance_days
137
+ from booking.settings st
138
+ where st.id
139
+ ),
140
+ svc as (
141
+ select sv.duration_minutes, sv.buffer_after_minutes
142
+ from booking.services sv
143
+ where sv.id = p_service_id and sv.is_active
144
+ ),
145
+ res as (
146
+ select r.id
147
+ from booking.resources r
148
+ where r.is_active
149
+ and (r.id = p_resource_id or (p_resource_id is null and r.is_default))
150
+ ),
151
+ -- At most 400 days; non-finite input yields no days at all.
152
+ days as (
153
+ select p_from + g.n as day
154
+ from generate_series(
155
+ 0,
156
+ case
157
+ 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
158
+ else least(p_to - p_from, 400)
159
+ end
160
+ ) as g(n)
161
+ ),
162
+ windows as (
163
+ select dd.day,
164
+ (dd.day + wh.start_time) at time zone s.timezone as open_at,
165
+ (dd.day + wh.end_time) at time zone s.timezone as close_at
166
+ from days dd
167
+ cross join s
168
+ join booking.working_hours wh on wh.weekday = extract(isodow from dd.day)::int
169
+ ),
170
+ candidates as (
171
+ select w.day,
172
+ g.slot_start,
173
+ g.slot_start + make_interval(mins => svc.duration_minutes) as slot_end,
174
+ g.slot_start + make_interval(mins => svc.duration_minutes + svc.buffer_after_minutes) as blocked_until
175
+ from windows w
176
+ cross join svc
177
+ cross join s
178
+ cross join lateral generate_series(
179
+ w.open_at,
180
+ w.close_at - make_interval(mins => svc.duration_minutes),
181
+ make_interval(mins => s.slot_interval_minutes)
182
+ ) as g(slot_start)
183
+ )
184
+ select c.slot_start, c.slot_end, c.day
185
+ from candidates c
186
+ cross join s
187
+ cross join res
188
+ where c.slot_start >= p_now + make_interval(mins => s.min_notice_minutes)
189
+ and c.day <= (p_now at time zone s.timezone)::date + s.max_advance_days
190
+ and not exists (
191
+ select 1
192
+ from booking.bookings b
193
+ where b.resource_id = res.id
194
+ and b.status in ('pending', 'confirmed')
195
+ and tstzrange(b.starts_at, b.blocked_until, '[)') && tstzrange(c.slot_start, c.blocked_until, '[)')
196
+ )
197
+ and not exists (
198
+ select 1
199
+ from booking.availability_exceptions e
200
+ where c.day between e.starts_on and e.ends_on
201
+ and (
202
+ e.start_time is null
203
+ or tstzrange((c.day + e.start_time) at time zone s.timezone,
204
+ (c.day + e.end_time) at time zone s.timezone, '[)')
205
+ && tstzrange(c.slot_start, c.slot_end, '[)')
206
+ )
207
+ )
208
+ order by c.slot_start;
209
+ $$;
210
+
211
+ -- ----------------------------------------------------------------------------
212
+ -- Public API
213
+ -- ----------------------------------------------------------------------------
214
+
215
+ create or replace function public.booking_get_availability(p_service_id uuid, p_from date, p_to date default null)
216
+ returns jsonb
217
+ language plpgsql
218
+ stable
219
+ security definer
220
+ set search_path = ''
221
+ as $$
222
+ declare
223
+ c_max_days constant int := 42;
224
+ v_to date := coalesce(p_to, p_from);
225
+ v_settings booking.settings%rowtype;
226
+ v_today date;
227
+ v_last date;
228
+ v_result jsonb;
229
+ begin
230
+ if p_service_id is null then
231
+ perform booking.raise_error('INVALID_INPUT', 'serviceId');
232
+ end if;
233
+ if p_from is null or not isfinite(p_from) then
234
+ perform booking.raise_error('INVALID_INPUT', 'from');
235
+ end if;
236
+ if not isfinite(v_to) or v_to < p_from or v_to - p_from >= c_max_days then
237
+ perform booking.raise_error('INVALID_INPUT', 'to');
238
+ end if;
239
+ if not exists (select 1 from booking.services sv where sv.id = p_service_id and sv.is_active) then
240
+ perform booking.raise_error('SERVICE_UNAVAILABLE');
241
+ end if;
242
+
243
+ select * into v_settings from booking.settings where id;
244
+ v_today := (now() at time zone v_settings.timezone)::date;
245
+ v_last := v_today + v_settings.max_advance_days;
246
+
247
+ with days as (
248
+ select p_from + g.n as day
249
+ from generate_series(0, v_to - p_from) as g(n)
250
+ ),
251
+ slots as (
252
+ select cs.starts_at, cs.ends_at, cs.local_date
253
+ from booking.compute_slots(p_service_id, greatest(p_from, v_today), least(v_to, v_last), now()) as cs
254
+ )
255
+ select jsonb_build_object(
256
+ 'serviceId', p_service_id,
257
+ 'timezone', v_settings.timezone,
258
+ 'from', to_char(p_from, 'YYYY-MM-DD'),
259
+ 'to', to_char(v_to, 'YYYY-MM-DD'),
260
+ 'days', coalesce(jsonb_agg(
261
+ jsonb_build_object(
262
+ 'date', to_char(dd.day, 'YYYY-MM-DD'),
263
+ 'status', case
264
+ when dd.day < v_today or dd.day > v_last then 'unavailable'
265
+ when not exists (select 1 from booking.working_hours wh where wh.weekday = extract(isodow from dd.day)::int)
266
+ or exists (select 1 from booking.availability_exceptions e
267
+ where dd.day between e.starts_on and e.ends_on and e.start_time is null) then 'closed'
268
+ when exists (select 1 from slots sl where sl.local_date = dd.day) then 'available'
269
+ else 'full'
270
+ end,
271
+ 'slots', coalesce((
272
+ select jsonb_agg(
273
+ jsonb_build_object(
274
+ 'startsAt', booking.iso(sl.starts_at),
275
+ 'endsAt', booking.iso(sl.ends_at),
276
+ 'time', to_char(sl.starts_at at time zone v_settings.timezone, 'HH24:MI')
277
+ ) order by sl.starts_at)
278
+ from slots sl
279
+ where sl.local_date = dd.day
280
+ ), '[]'::jsonb)
281
+ ) order by dd.day), '[]'::jsonb)
282
+ )
283
+ into v_result
284
+ from days dd;
285
+
286
+ return v_result;
287
+ end;
288
+ $$;
289
+
290
+ create or replace function public.booking_create(
291
+ p_service_id uuid,
292
+ p_starts_at timestamptz,
293
+ p_customer_name text,
294
+ p_customer_email text,
295
+ p_customer_phone text default null,
296
+ p_notes text default null
297
+ )
298
+ returns jsonb
299
+ language plpgsql
300
+ volatile
301
+ security definer
302
+ set search_path = ''
303
+ as $$
304
+ declare
305
+ c_client_limit_per_hour constant int := 10;
306
+ v_settings booking.settings%rowtype;
307
+ v_service booking.services%rowtype;
308
+ v_resource_id uuid;
309
+ v_name text := btrim(coalesce(p_customer_name, ''));
310
+ v_email text := lower(btrim(coalesce(p_customer_email, '')));
311
+ v_phone text := nullif(btrim(coalesce(p_customer_phone, '')), '');
312
+ v_notes text := nullif(btrim(coalesce(p_notes, '')), '');
313
+ v_local_day date;
314
+ v_client text;
315
+ v_bucket text;
316
+ v_limit int;
317
+ v_count int;
318
+ v_status text;
319
+ v_booking booking.bookings%rowtype;
320
+ v_attempt int := 0;
321
+ begin
322
+ -- 1. Validate the request itself (cheap, no table access).
323
+ if p_service_id is null then
324
+ perform booking.raise_error('INVALID_INPUT', 'serviceId');
325
+ end if;
326
+ if p_starts_at is null or not isfinite(p_starts_at) then
327
+ perform booking.raise_error('INVALID_INPUT', 'startsAt');
328
+ end if;
329
+ if char_length(v_name) < 1 or char_length(v_name) > 120 or v_name ~ '[[:cntrl:]]' then
330
+ perform booking.raise_error('INVALID_INPUT', 'customer.name');
331
+ end if;
332
+ if char_length(v_email) > 254
333
+ or v_email !~ '^[^@[:space:]<>()]+@[^@[:space:]<>()]+\.[^@[:space:]<>()]{2,}$' then
334
+ perform booking.raise_error('INVALID_INPUT', 'customer.email');
335
+ end if;
336
+ if v_phone is not null and (
337
+ char_length(v_phone) > 40
338
+ or v_phone !~ '^[0-9+()./[:space:]-]+$'
339
+ or char_length(regexp_replace(v_phone, '[^0-9]', '', 'g')) < 5) then
340
+ perform booking.raise_error('INVALID_INPUT', 'customer.phone');
341
+ end if;
342
+ if v_notes is not null and (char_length(v_notes) > 1000 or v_notes ~ '[\x01-\x08\x0B\x0C\x0E-\x1F\x7F]') then
343
+ perform booking.raise_error('INVALID_INPUT', 'notes');
344
+ end if;
345
+
346
+ select * into v_settings from booking.settings where id;
347
+ if v_settings.require_phone and v_phone is null then
348
+ perform booking.raise_error('INVALID_INPUT', 'customer.phone');
349
+ end if;
350
+
351
+ -- 2. Only times inside the booking window are worth computing.
352
+ if p_starts_at < now() or p_starts_at > now() + make_interval(days => v_settings.max_advance_days + 1) then
353
+ perform booking.raise_error('SLOT_UNAVAILABLE');
354
+ end if;
355
+
356
+ select * into v_service from booking.services where id = p_service_id and is_active;
357
+ if not found then
358
+ perform booking.raise_error('SERVICE_UNAVAILABLE');
359
+ end if;
360
+
361
+ select r.id into v_resource_id from booking.resources r where r.is_default and r.is_active;
362
+ if v_resource_id is null then
363
+ perform booking.raise_error('SLOT_UNAVAILABLE');
364
+ end if;
365
+
366
+ -- 3. The start must be a slot the engine offers right now.
367
+ v_local_day := (p_starts_at at time zone v_settings.timezone)::date;
368
+ if not exists (
369
+ select 1
370
+ from booking.compute_slots(p_service_id, v_local_day, v_local_day, now(), v_resource_id) as cs
371
+ where cs.starts_at = p_starts_at
372
+ ) then
373
+ perform booking.raise_error('SLOT_UNAVAILABLE');
374
+ end if;
375
+
376
+ -- 4. Abuse limits — after the slot check, without saying which limit was
377
+ -- hit, and serialised per email and per client so concurrent requests
378
+ -- cannot all slip under a limit. Lock order: email, then client.
379
+ perform pg_advisory_xact_lock(hashtextextended('booking_engine:email:' || v_email, 0));
380
+ select count(*) into v_count
381
+ from booking.bookings b
382
+ where lower(b.customer_email) = v_email
383
+ and b.status in ('pending', 'confirmed')
384
+ and b.starts_at > now();
385
+ if v_count >= v_settings.max_active_bookings_per_email then
386
+ perform booking.raise_error('RATE_LIMITED');
387
+ end if;
388
+
389
+ v_client := booking.client_key();
390
+ v_bucket := 'client:' || encode(sha256(convert_to(
391
+ (select es.hash_salt from booking.engine_secrets es where es.id) || ':' || v_client, 'UTF8')), 'hex');
392
+ perform pg_advisory_xact_lock(hashtextextended('booking_engine:' || v_bucket, 0));
393
+ v_limit := case when v_client = 'unknown' then v_settings.max_website_bookings_per_hour else c_client_limit_per_hour end;
394
+ select count(*) into v_count
395
+ from booking.request_log r
396
+ where r.bucket = v_bucket and r.created_at > now() - interval '1 hour';
397
+ if v_count >= v_limit then
398
+ perform booking.raise_error('RATE_LIMITED');
399
+ end if;
400
+
401
+ select count(*) into v_count
402
+ from booking.bookings b
403
+ where b.source = 'website' and b.created_at > now() - interval '1 hour';
404
+ if v_count >= v_settings.max_website_bookings_per_hour then
405
+ perform booking.raise_error('RATE_LIMITED');
406
+ end if;
407
+
408
+ v_status := case when v_settings.auto_confirm then 'confirmed' else 'pending' end;
409
+
410
+ -- 5. Insert. Under concurrency the exclusion constraint decides.
411
+ loop
412
+ v_attempt := v_attempt + 1;
413
+ begin
414
+ insert into booking.bookings (
415
+ reference, service_id, resource_id, starts_at, ends_at, blocked_until, status,
416
+ customer_name, customer_email, customer_phone, customer_notes,
417
+ service_name, price_cents, currency, source
418
+ ) values (
419
+ booking.new_reference(), v_service.id, v_resource_id, p_starts_at,
420
+ p_starts_at + make_interval(mins => v_service.duration_minutes),
421
+ p_starts_at + make_interval(mins => v_service.duration_minutes + v_service.buffer_after_minutes),
422
+ v_status, v_name, v_email, v_phone, v_notes,
423
+ v_service.name, v_service.price_cents, v_settings.currency, 'website'
424
+ )
425
+ returning * into v_booking;
426
+ exit;
427
+ exception
428
+ when exclusion_violation then
429
+ perform booking.raise_error('SLOT_UNAVAILABLE');
430
+ when unique_violation then
431
+ if v_attempt >= 3 then
432
+ raise;
433
+ end if;
434
+ end;
435
+ end loop;
436
+
437
+ insert into booking.booking_events (booking_id, event_type, to_status, actor)
438
+ values (v_booking.id, 'created', v_booking.status, 'customer');
439
+
440
+ insert into booking.request_log (bucket) values (v_bucket);
441
+ delete from booking.request_log r where r.created_at < now() - interval '1 day';
442
+
443
+ return jsonb_build_object(
444
+ 'reference', v_booking.reference,
445
+ 'status', v_booking.status,
446
+ 'startsAt', booking.iso(v_booking.starts_at),
447
+ 'endsAt', booking.iso(v_booking.ends_at),
448
+ 'date', to_char(v_booking.starts_at at time zone v_settings.timezone, 'YYYY-MM-DD'),
449
+ 'time', to_char(v_booking.starts_at at time zone v_settings.timezone, 'HH24:MI'),
450
+ 'serviceName', v_booking.service_name,
451
+ 'timezone', v_settings.timezone
452
+ );
453
+ end;
454
+ $$;
455
+
456
+ -- ----------------------------------------------------------------------------
457
+ -- Admin API
458
+ -- ----------------------------------------------------------------------------
459
+
460
+ create or replace function public.booking_admin_list_bookings(p_from date, p_to date, p_statuses text[] default null)
461
+ returns jsonb
462
+ language plpgsql
463
+ stable
464
+ security invoker
465
+ set search_path = ''
466
+ as $$
467
+ declare
468
+ v_tz text;
469
+ v_result jsonb;
470
+ begin
471
+ perform booking.require_admin();
472
+ if p_from is null or p_to is null or not isfinite(p_from) or not isfinite(p_to)
473
+ or p_to < p_from or p_to - p_from > 400 then
474
+ perform booking.raise_error('INVALID_INPUT', 'range');
475
+ end if;
476
+ if p_statuses is not null and exists (
477
+ select 1 from unnest(p_statuses) as st(v)
478
+ where st.v is null or st.v not in ('pending', 'confirmed', 'completed', 'cancelled', 'no_show')) then
479
+ perform booking.raise_error('INVALID_INPUT', 'statuses');
480
+ end if;
481
+
482
+ select s.timezone into v_tz from booking.settings s where s.id;
483
+
484
+ select coalesce(jsonb_agg(booking.booking_json(b, v_tz) order by b.starts_at), '[]'::jsonb)
485
+ into v_result
486
+ from booking.bookings b
487
+ where b.id in (
488
+ select b2.id
489
+ from booking.bookings b2
490
+ where b2.starts_at >= (p_from::timestamp at time zone v_tz)
491
+ and b2.starts_at < ((p_to + 1)::timestamp at time zone v_tz)
492
+ and (p_statuses is null or b2.status = any (p_statuses))
493
+ order by b2.starts_at
494
+ limit 1000
495
+ );
496
+ return v_result;
497
+ end;
498
+ $$;
499
+
500
+ create or replace function booking.settings_json()
501
+ returns jsonb
502
+ language sql
503
+ stable
504
+ set search_path = ''
505
+ as $$
506
+ select jsonb_build_object(
507
+ 'businessName', s.business_name,
508
+ 'timezone', s.timezone,
509
+ 'currency', s.currency,
510
+ 'locale', s.locale,
511
+ 'publicEmail', s.public_email,
512
+ 'publicPhone', s.public_phone,
513
+ 'address', s.address,
514
+ 'slotIntervalMinutes', s.slot_interval_minutes,
515
+ 'minNoticeMinutes', s.min_notice_minutes,
516
+ 'maxAdvanceDays', s.max_advance_days,
517
+ 'autoConfirm', s.auto_confirm,
518
+ 'requirePhone', s.require_phone,
519
+ 'maxActiveBookingsPerEmail', s.max_active_bookings_per_email,
520
+ 'maxWebsiteBookingsPerHour', s.max_website_bookings_per_hour,
521
+ 'updatedAt', booking.iso(s.updated_at)
522
+ )
523
+ from booking.settings s
524
+ where s.id;
525
+ $$;
526
+
527
+ create or replace function public.booking_admin_update_settings(p_settings jsonb)
528
+ returns jsonb
529
+ language plpgsql
530
+ volatile
531
+ security invoker
532
+ set search_path = ''
533
+ as $$
534
+ declare
535
+ v_allowed text[] := array['businessName', 'timezone', 'currency', 'locale', 'publicEmail', 'publicPhone',
536
+ 'address', 'slotIntervalMinutes', 'minNoticeMinutes', 'maxAdvanceDays',
537
+ 'autoConfirm', 'requirePhone', 'maxActiveBookingsPerEmail', 'maxWebsiteBookingsPerHour'];
538
+ v_key text;
539
+ v_email text;
540
+ begin
541
+ perform booking.require_admin();
542
+ if p_settings is null or jsonb_typeof(p_settings) <> 'object' then
543
+ perform booking.raise_error('INVALID_INPUT', 'settings');
544
+ end if;
545
+ for v_key in select jsonb_object_keys(p_settings) loop
546
+ if not (v_key = any (v_allowed)) then
547
+ perform booking.raise_error('INVALID_INPUT', v_key);
548
+ end if;
549
+ end loop;
550
+
551
+ v_email := lower(booking.j_text(p_settings, 'publicEmail', 254));
552
+ if v_email is not null and v_email !~ '^[^@[:space:]<>()]+@[^@[:space:]<>()]+\.[^@[:space:]<>()]{2,}$' then
553
+ perform booking.raise_error('INVALID_INPUT', 'publicEmail');
554
+ end if;
555
+ if p_settings ? 'currency' and coalesce(booking.j_text(p_settings, 'currency', 3), '') !~ '^[A-Z]{3}$' then
556
+ perform booking.raise_error('INVALID_INPUT', 'currency');
557
+ end if;
558
+ if p_settings ? 'locale'
559
+ and coalesce(booking.j_text(p_settings, 'locale', 35), '') !~ '^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$' then
560
+ perform booking.raise_error('INVALID_INPUT', 'locale');
561
+ end if;
562
+
563
+ update booking.settings set
564
+ business_name = case when p_settings ? 'businessName'
565
+ then booking.j_required_text(p_settings, 'businessName', 120) else business_name end,
566
+ timezone = case when p_settings ? 'timezone' then booking.j_required_text(p_settings, 'timezone', 64) else timezone end,
567
+ currency = case when p_settings ? 'currency' then booking.j_required_text(p_settings, 'currency', 3) else currency end,
568
+ locale = case when p_settings ? 'locale' then booking.j_required_text(p_settings, 'locale', 35) else locale end,
569
+ public_email = case when p_settings ? 'publicEmail' then v_email else public_email end,
570
+ public_phone = case when p_settings ? 'publicPhone' then booking.j_text(p_settings, 'publicPhone', 40) else public_phone end,
571
+ address = case when p_settings ? 'address' then booking.j_text(p_settings, 'address', 300) else address end,
572
+ slot_interval_minutes = case when p_settings ? 'slotIntervalMinutes'
573
+ then coalesce(booking.j_int(p_settings, 'slotIntervalMinutes', 5, 240), slot_interval_minutes) else slot_interval_minutes end,
574
+ min_notice_minutes = case when p_settings ? 'minNoticeMinutes'
575
+ then coalesce(booking.j_int(p_settings, 'minNoticeMinutes', 0, 43200), min_notice_minutes) else min_notice_minutes end,
576
+ max_advance_days = case when p_settings ? 'maxAdvanceDays'
577
+ then coalesce(booking.j_int(p_settings, 'maxAdvanceDays', 1, 730), max_advance_days) else max_advance_days end,
578
+ auto_confirm = case when p_settings ? 'autoConfirm'
579
+ then coalesce(booking.j_bool(p_settings, 'autoConfirm'), auto_confirm) else auto_confirm end,
580
+ require_phone = case when p_settings ? 'requirePhone'
581
+ then coalesce(booking.j_bool(p_settings, 'requirePhone'), require_phone) else require_phone end,
582
+ max_active_bookings_per_email = case when p_settings ? 'maxActiveBookingsPerEmail'
583
+ then coalesce(booking.j_int(p_settings, 'maxActiveBookingsPerEmail', 1, 50), max_active_bookings_per_email)
584
+ else max_active_bookings_per_email end,
585
+ max_website_bookings_per_hour = case when p_settings ? 'maxWebsiteBookingsPerHour'
586
+ then coalesce(booking.j_int(p_settings, 'maxWebsiteBookingsPerHour', 1, 1000), max_website_bookings_per_hour)
587
+ else max_website_bookings_per_hour end
588
+ where id;
589
+
590
+ return booking.settings_json();
591
+ end;
592
+ $$;
593
+
594
+ create or replace function public.booking_admin_apply_preset(p_preset jsonb)
595
+ returns jsonb
596
+ language plpgsql
597
+ volatile
598
+ security invoker
599
+ set search_path = ''
600
+ as $$
601
+ declare
602
+ v_item jsonb;
603
+ v_count int := 0;
604
+ begin
605
+ perform booking.require_admin();
606
+ if p_preset is null or coalesce(jsonb_typeof(p_preset), '') <> 'object'
607
+ or coalesce(jsonb_typeof(p_preset -> 'services'), '') <> 'array'
608
+ or jsonb_array_length(p_preset -> 'services') not between 1 and 50 then
609
+ perform booking.raise_error('INVALID_INPUT', 'preset');
610
+ end if;
611
+ if exists (select 1 from booking.services) then
612
+ perform booking.raise_error('CONFLICT', 'services_exist');
613
+ end if;
614
+
615
+ for v_item in select value from jsonb_array_elements(p_preset -> 'services') loop
616
+ if jsonb_typeof(v_item) <> 'object' then
617
+ perform booking.raise_error('INVALID_INPUT', 'preset.services');
618
+ end if;
619
+ v_count := v_count + 1;
620
+ perform public.booking_admin_save_service(
621
+ jsonb_strip_nulls(jsonb_build_object(
622
+ 'name', v_item -> 'name',
623
+ 'description', v_item -> 'description',
624
+ 'durationMinutes', v_item -> 'durationMinutes',
625
+ 'bufferAfterMinutes', v_item -> 'bufferAfterMinutes',
626
+ 'priceCents', v_item -> 'priceCents',
627
+ 'priceFrom', v_item -> 'priceFrom',
628
+ 'sortOrder', to_jsonb(v_count * 10)
629
+ )));
630
+ end loop;
631
+
632
+ if jsonb_typeof(p_preset -> 'workingHours') = 'array' then
633
+ perform public.booking_admin_set_working_hours(p_preset -> 'workingHours');
634
+ end if;
635
+ if jsonb_typeof(p_preset -> 'policies') = 'object' then
636
+ perform public.booking_admin_update_settings(p_preset -> 'policies');
637
+ end if;
638
+
639
+ return jsonb_build_object('servicesAdded', v_count);
640
+ end;
641
+ $$;
642
+
643
+ -- ----------------------------------------------------------------------------
644
+ -- Owner tools (SQL editor)
645
+ -- ----------------------------------------------------------------------------
646
+
647
+ create or replace function booking.add_admin(p_email text)
648
+ returns text
649
+ language plpgsql
650
+ volatile
651
+ set search_path = ''
652
+ as $$
653
+ declare
654
+ v_email text := lower(btrim(coalesce(p_email, '')));
655
+ v_ids uuid[];
656
+ v_confirmed boolean;
657
+ begin
658
+ select array_agg(u.id), bool_and(u.email_confirmed_at is not null)
659
+ into v_ids, v_confirmed
660
+ from auth.users u
661
+ where lower(u.email) = v_email;
662
+ if v_ids is null then
663
+ raise exception 'No Supabase Auth user with email "%". Create the user first: Authentication > Users > Add user.', v_email;
664
+ end if;
665
+ if array_length(v_ids, 1) > 1 then
666
+ raise exception 'More than one Auth user has email "%"; add the admin by user id instead.', v_email;
667
+ end if;
668
+ if not v_confirmed then
669
+ raise exception 'The Auth user "%" has not confirmed their email. Confirm it (or create the user with Auto Confirm) first.', v_email;
670
+ end if;
671
+ insert into booking.admins (user_id) values (v_ids[1]) on conflict (user_id) do nothing;
672
+ return 'Admin access granted to ' || v_email || ' (user ' || v_ids[1]::text || ')';
673
+ end;
674
+ $$;
675
+
676
+ create or replace function booking.remove_admin(p_email text)
677
+ returns text
678
+ language plpgsql
679
+ volatile
680
+ set search_path = ''
681
+ as $$
682
+ declare
683
+ v_email text := lower(btrim(coalesce(p_email, '')));
684
+ v_removed int;
685
+ begin
686
+ delete from booking.admins a
687
+ using auth.users u
688
+ where u.id = a.user_id and lower(u.email) = v_email;
689
+ get diagnostics v_removed = row_count;
690
+ if v_removed = 0 then
691
+ raise exception 'No admin with email "%" was found. List admins with: select u.email from booking.admins a join auth.users u on u.id = a.user_id;', v_email;
692
+ end if;
693
+ return 'Admin access removed from ' || v_email;
694
+ end;
695
+ $$;
696
+
697
+ -- ----------------------------------------------------------------------------
698
+ -- Privileges
699
+ -- ----------------------------------------------------------------------------
700
+
701
+ revoke all on function booking.client_key() from public, anon, authenticated, service_role;
702
+
703
+ -- Server-side callers (secret key → service_role) can use the public reads.
704
+ grant usage on schema booking to service_role;
705
+ grant select on booking.engine_info, booking.services, booking.working_hours to service_role;
706
+ grant select (id, business_name, timezone, currency, locale, public_email, public_phone, address,
707
+ slot_interval_minutes, min_notice_minutes, max_advance_days, auto_confirm, require_phone)
708
+ on booking.settings to service_role;
709
+ grant execute on function booking.hhmm(time) to service_role;
710
+
711
+ update booking.engine_info set schema_version = '2.0.0-alpha.2', updated_at = now() where id;