@profitstudio/booking-engine 0.0.0-stage → 2.0.0-beta.1

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 +562 -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 +22 -0
  9. package/dist/admin/BookingAdmin.js +337 -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 +37 -0
  14. package/dist/admin/booking-detail.js +149 -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 +37 -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 +6 -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 +182 -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 +1109 -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,1673 @@
1
+ -- ============================================================================
2
+ -- Profit Studio Booking Engine — migration 0001_core
3
+ -- Engine schema version: 2.0.0-alpha.1
4
+ --
5
+ -- ENGINE-OWNED FILE. Do not edit. `booking-engine doctor` reports changes.
6
+ -- Changes ship as NEW migrations in new engine versions.
7
+ --
8
+ -- What this creates
9
+ -- * schema "booking" — private tables. It is NOT added to the Data API's
10
+ -- exposed schemas, so tables are never reachable by URL.
11
+ -- * public.booking_* functions — the only API surface (PostgREST RPC).
12
+ --
13
+ -- Security model (see docs/SECURITY.md)
14
+ -- * RLS is enabled on every table. Default is deny.
15
+ -- * Public reads of public data (business profile, active services, opening
16
+ -- hours) are SECURITY INVOKER functions over column-limited grants + RLS.
17
+ -- * Exactly TWO functions are SECURITY DEFINER, on purpose:
18
+ -- booking_get_availability — must see existing bookings to compute free
19
+ -- slots; returns times only, never people.
20
+ -- booking_create — must insert into a table anon cannot touch;
21
+ -- validates every input and re-checks the slot.
22
+ -- * Admin functions are SECURITY INVOKER: admins pass RLS because
23
+ -- booking.is_admin() is true for them. Each also checks explicitly, so a
24
+ -- non-admin gets NOT_AUTHORIZED instead of an empty result.
25
+ -- * Every function pins search_path = ''. EXECUTE is revoked from PUBLIC and
26
+ -- granted per role explicitly at the end of this file.
27
+ -- * Double booking is impossible at the database level: an exclusion
28
+ -- constraint over (resource, time range incl. buffer) for active bookings.
29
+ --
30
+ -- Error contract: errors are raised with SQLSTATE P0001 and the message
31
+ -- 'booking_engine:<CODE>'; DETAIL carries the field or reason, if any.
32
+ -- ============================================================================
33
+
34
+ do $$
35
+ begin
36
+ if to_regnamespace('booking') is not null then
37
+ raise exception 'Booking Engine 0001_core: schema "booking" already exists. This migration must run exactly once.';
38
+ end if;
39
+ end
40
+ $$;
41
+
42
+ create extension if not exists btree_gist with schema extensions;
43
+
44
+ create schema booking;
45
+ comment on schema booking is
46
+ 'Profit Studio Booking Engine (engine-owned). Private: accessed through public.booking_* functions only.';
47
+
48
+ -- ----------------------------------------------------------------------------
49
+ -- Tables
50
+ -- ----------------------------------------------------------------------------
51
+
52
+ create table booking.engine_info (
53
+ id boolean primary key default true check (id),
54
+ engine text not null default 'profitstudio-booking-engine',
55
+ schema_version text not null,
56
+ installed_at timestamptz not null default now(),
57
+ updated_at timestamptz not null default now()
58
+ );
59
+ comment on table booking.engine_info is 'One row. The engine schema version the database is at; checked by the client.';
60
+
61
+ create table booking.settings (
62
+ id boolean primary key default true check (id),
63
+ -- Business profile (public)
64
+ business_name text not null default 'My Business'
65
+ check (char_length(btrim(business_name)) between 1 and 120),
66
+ timezone text not null default 'UTC' check (char_length(timezone) between 1 and 64),
67
+ currency text not null default 'USD' check (currency ~ '^[A-Z]{3}$'),
68
+ locale text not null default 'en-US' check (locale ~ '^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$'),
69
+ public_email text check (public_email is null or char_length(public_email) <= 254),
70
+ public_phone text check (public_phone is null or char_length(public_phone) <= 40),
71
+ address text check (address is null or char_length(address) <= 300),
72
+ -- Booking policies
73
+ slot_interval_minutes int not null default 15 check (slot_interval_minutes between 5 and 240),
74
+ min_notice_minutes int not null default 120 check (min_notice_minutes between 0 and 43200),
75
+ max_advance_days int not null default 60 check (max_advance_days between 1 and 730),
76
+ auto_confirm boolean not null default false,
77
+ require_phone boolean not null default true,
78
+ max_active_bookings_per_email int not null default 3 check (max_active_bookings_per_email between 1 and 50),
79
+ updated_at timestamptz not null default now()
80
+ );
81
+ comment on table booking.settings is 'One row. Business profile and booking policies, edited in the admin dashboard.';
82
+
83
+ create table booking.resources (
84
+ id uuid primary key default gen_random_uuid(),
85
+ name text not null check (char_length(btrim(name)) between 1 and 120),
86
+ is_default boolean not null default false,
87
+ is_active boolean not null default true,
88
+ created_at timestamptz not null default now()
89
+ );
90
+ create unique index resources_single_default on booking.resources (is_default) where is_default;
91
+ comment on table booking.resources is
92
+ 'What a booking occupies (a chair, a person, a room). 2.0 uses one default resource; staff/rooms arrive in a later version without changing the conflict rule.';
93
+
94
+ create table booking.services (
95
+ id uuid primary key default gen_random_uuid(),
96
+ name text not null check (char_length(btrim(name)) between 1 and 120),
97
+ description text check (description is null or char_length(description) <= 2000),
98
+ duration_minutes int not null check (duration_minutes between 5 and 720),
99
+ buffer_after_minutes int not null default 0 check (buffer_after_minutes between 0 and 240),
100
+ price_cents int check (price_cents is null or price_cents between 0 and 100000000),
101
+ price_from boolean not null default false,
102
+ is_active boolean not null default true,
103
+ sort_order int not null default 0 check (sort_order between -100000 and 100000),
104
+ created_at timestamptz not null default now(),
105
+ updated_at timestamptz not null default now()
106
+ );
107
+ comment on column booking.services.buffer_after_minutes is 'Cleanup time after the service. Blocks the calendar but is not shown to customers.';
108
+ comment on column booking.services.price_from is 'Display hint: the price is a starting price ("from $65").';
109
+
110
+ create table booking.working_hours (
111
+ id uuid primary key default gen_random_uuid(),
112
+ weekday smallint not null check (weekday between 1 and 7),
113
+ start_time time not null,
114
+ end_time time not null,
115
+ check (start_time < end_time),
116
+ constraint working_hours_no_overlap exclude using gist (
117
+ weekday with =,
118
+ tsrange('2000-01-01'::date + start_time, '2000-01-01'::date + end_time, '[)') with &&
119
+ )
120
+ );
121
+ comment on table booking.working_hours is
122
+ 'Weekly opening hours in the business time zone. ISO weekday: 1 = Monday … 7 = Sunday. Several rows per day = breaks.';
123
+
124
+ create table booking.availability_exceptions (
125
+ id uuid primary key default gen_random_uuid(),
126
+ starts_on date not null,
127
+ ends_on date not null,
128
+ start_time time,
129
+ end_time time,
130
+ reason text check (reason is null or char_length(reason) <= 200),
131
+ created_at timestamptz not null default now(),
132
+ check (ends_on >= starts_on),
133
+ check (ends_on - starts_on <= 366),
134
+ check (
135
+ (start_time is null and end_time is null)
136
+ or (start_time is not null and end_time is not null and start_time < end_time)
137
+ )
138
+ );
139
+ create index availability_exceptions_dates on booking.availability_exceptions (starts_on, ends_on);
140
+ comment on table booking.availability_exceptions is
141
+ 'Closures in business-local dates: whole days (no times) or a time range on each day of the range.';
142
+
143
+ create table booking.bookings (
144
+ id uuid primary key default gen_random_uuid(),
145
+ reference text not null unique check (reference ~ '^[A-HJ-NP-Z2-9]{8}$'),
146
+ service_id uuid not null references booking.services (id) on delete restrict,
147
+ resource_id uuid not null references booking.resources (id) on delete restrict,
148
+ starts_at timestamptz not null,
149
+ ends_at timestamptz not null,
150
+ blocked_until timestamptz not null,
151
+ status text not null default 'pending'
152
+ check (status in ('pending', 'confirmed', 'completed', 'cancelled', 'no_show')),
153
+ customer_name text not null check (char_length(customer_name) between 1 and 120),
154
+ customer_email text not null check (char_length(customer_email) between 3 and 254),
155
+ customer_phone text check (customer_phone is null or char_length(customer_phone) between 5 and 40),
156
+ customer_notes text check (customer_notes is null or char_length(customer_notes) <= 1000),
157
+ service_name text not null,
158
+ price_cents int,
159
+ currency text not null,
160
+ source text not null default 'website' check (source in ('website', 'admin')),
161
+ created_at timestamptz not null default now(),
162
+ updated_at timestamptz not null default now(),
163
+ status_changed_at timestamptz not null default now(),
164
+ check (ends_at > starts_at),
165
+ check (blocked_until >= ends_at),
166
+ constraint bookings_no_overlap exclude using gist (
167
+ resource_id with =,
168
+ tstzrange(starts_at, blocked_until, '[)') with &&
169
+ ) where (status in ('pending', 'confirmed'))
170
+ );
171
+ create index bookings_starts_at on booking.bookings (starts_at);
172
+ create index bookings_resource_starts_at on booking.bookings (resource_id, starts_at);
173
+ create index bookings_service on booking.bookings (service_id);
174
+ create index bookings_email on booking.bookings (lower(customer_email), starts_at);
175
+ comment on constraint bookings_no_overlap on booking.bookings is
176
+ 'The double-booking guarantee: two active bookings can never overlap on one resource, including buffer time. Holds under concurrent requests.';
177
+ comment on column booking.bookings.service_name is 'Snapshot at booking time; later service edits do not rewrite history.';
178
+
179
+ create table booking.booking_events (
180
+ id uuid primary key default gen_random_uuid(),
181
+ booking_id uuid not null references booking.bookings (id) on delete cascade,
182
+ event_type text not null check (event_type in ('created', 'status_changed')),
183
+ from_status text,
184
+ to_status text,
185
+ actor text not null check (actor in ('customer', 'admin', 'system')),
186
+ actor_user_id uuid,
187
+ created_at timestamptz not null default now()
188
+ );
189
+ create index booking_events_booking on booking.booking_events (booking_id, created_at);
190
+ comment on table booking.booking_events is
191
+ 'Append-only history of every booking. Future notification modules read from here.';
192
+
193
+ create table booking.admins (
194
+ user_id uuid primary key references auth.users (id) on delete cascade,
195
+ created_at timestamptz not null default now()
196
+ );
197
+ comment on table booking.admins is 'Supabase Auth users allowed into the admin dashboard. Managed with booking.add_admin(email).';
198
+
199
+ create table booking.request_log (
200
+ id uuid primary key default gen_random_uuid(),
201
+ bucket text not null,
202
+ created_at timestamptz not null default now()
203
+ );
204
+ create index request_log_bucket on booking.request_log (bucket, created_at);
205
+ comment on table booking.request_log is
206
+ 'Rate-limit counters for public booking creation. Stores SHA-256 hashes only, kept for 24 hours.';
207
+
208
+ insert into booking.settings default values;
209
+ insert into booking.resources (name, is_default) values ('Main calendar', true);
210
+
211
+ -- ----------------------------------------------------------------------------
212
+ -- Triggers
213
+ -- ----------------------------------------------------------------------------
214
+
215
+ create function booking.touch_updated_at()
216
+ returns trigger
217
+ language plpgsql
218
+ set search_path = ''
219
+ as $$
220
+ begin
221
+ new.updated_at := now();
222
+ return new;
223
+ end;
224
+ $$;
225
+
226
+ create function booking.validate_settings()
227
+ returns trigger
228
+ language plpgsql
229
+ set search_path = ''
230
+ as $$
231
+ begin
232
+ if not exists (select 1 from pg_catalog.pg_timezone_names z where z.name = new.timezone) then
233
+ raise exception using errcode = 'P0001', message = 'booking_engine:INVALID_INPUT', detail = 'timezone';
234
+ end if;
235
+ new.updated_at := now();
236
+ return new;
237
+ end;
238
+ $$;
239
+
240
+ create trigger settings_validate before insert or update on booking.settings
241
+ for each row execute function booking.validate_settings();
242
+ create trigger services_touch before update on booking.services
243
+ for each row execute function booking.touch_updated_at();
244
+ create trigger bookings_touch before update on booking.bookings
245
+ for each row execute function booking.touch_updated_at();
246
+
247
+ -- ----------------------------------------------------------------------------
248
+ -- Internal helpers (schema booking; not callable through the API)
249
+ -- ----------------------------------------------------------------------------
250
+
251
+ create function booking.raise_error(p_code text, p_detail text default null)
252
+ returns void
253
+ language plpgsql
254
+ set search_path = ''
255
+ as $$
256
+ begin
257
+ raise exception using
258
+ errcode = 'P0001',
259
+ message = 'booking_engine:' || p_code,
260
+ detail = coalesce(p_detail, '');
261
+ end;
262
+ $$;
263
+
264
+ create function booking.is_admin()
265
+ returns boolean
266
+ language sql
267
+ stable
268
+ set search_path = ''
269
+ as $$
270
+ select exists (select 1 from booking.admins a where a.user_id = (select auth.uid()));
271
+ $$;
272
+
273
+ create function booking.require_admin()
274
+ returns uuid
275
+ language plpgsql
276
+ stable
277
+ set search_path = ''
278
+ as $$
279
+ declare
280
+ v_uid uuid := auth.uid();
281
+ begin
282
+ if v_uid is null or not booking.is_admin() then
283
+ perform booking.raise_error('NOT_AUTHORIZED');
284
+ end if;
285
+ return v_uid;
286
+ end;
287
+ $$;
288
+
289
+ create function booking.iso(p timestamptz)
290
+ returns text
291
+ language sql
292
+ stable
293
+ set search_path = ''
294
+ as $$
295
+ select to_char(p at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"');
296
+ $$;
297
+
298
+ create function booking.hhmm(p time)
299
+ returns text
300
+ language sql
301
+ immutable
302
+ set search_path = ''
303
+ as $$
304
+ select case when p = '24:00'::time then '24:00' else to_char(p, 'HH24:MI') end;
305
+ $$;
306
+
307
+ -- JSON input readers for admin functions. Each raises INVALID_INPUT(<key>)
308
+ -- on a wrong type or range; a missing key or JSON null returns NULL.
309
+ create function booking.j_text(p jsonb, p_key text, p_max_len int)
310
+ returns text
311
+ language plpgsql
312
+ stable
313
+ set search_path = ''
314
+ as $$
315
+ declare
316
+ t text := jsonb_typeof(p -> p_key);
317
+ v text;
318
+ begin
319
+ if t is null or t = 'null' then
320
+ return null;
321
+ end if;
322
+ if t <> 'string' then
323
+ perform booking.raise_error('INVALID_INPUT', p_key);
324
+ end if;
325
+ v := btrim(p ->> p_key);
326
+ if char_length(v) > p_max_len or v ~ '[\x01-\x08\x0B\x0C\x0E-\x1F\x7F]' then
327
+ perform booking.raise_error('INVALID_INPUT', p_key);
328
+ end if;
329
+ return nullif(v, '');
330
+ end;
331
+ $$;
332
+
333
+ create function booking.j_required_text(p jsonb, p_key text, p_max_len int)
334
+ returns text
335
+ language plpgsql
336
+ stable
337
+ set search_path = ''
338
+ as $$
339
+ declare
340
+ v text := booking.j_text(p, p_key, p_max_len);
341
+ begin
342
+ if v is null then
343
+ perform booking.raise_error('INVALID_INPUT', p_key);
344
+ end if;
345
+ return v;
346
+ end;
347
+ $$;
348
+
349
+ create function booking.j_int(p jsonb, p_key text, p_min int, p_max int)
350
+ returns int
351
+ language plpgsql
352
+ stable
353
+ set search_path = ''
354
+ as $$
355
+ declare
356
+ t text := jsonb_typeof(p -> p_key);
357
+ v numeric;
358
+ begin
359
+ if t is null or t = 'null' then
360
+ return null;
361
+ end if;
362
+ if t <> 'number' then
363
+ perform booking.raise_error('INVALID_INPUT', p_key);
364
+ end if;
365
+ v := (p ->> p_key)::numeric;
366
+ if v <> trunc(v) or v < p_min or v > p_max then
367
+ perform booking.raise_error('INVALID_INPUT', p_key);
368
+ end if;
369
+ return v::int;
370
+ end;
371
+ $$;
372
+
373
+ create function booking.j_bool(p jsonb, p_key text)
374
+ returns boolean
375
+ language plpgsql
376
+ stable
377
+ set search_path = ''
378
+ as $$
379
+ declare
380
+ t text := jsonb_typeof(p -> p_key);
381
+ begin
382
+ if t is null or t = 'null' then
383
+ return null;
384
+ end if;
385
+ if t <> 'boolean' then
386
+ perform booking.raise_error('INVALID_INPUT', p_key);
387
+ end if;
388
+ return (p ->> p_key)::boolean;
389
+ end;
390
+ $$;
391
+
392
+ -- 'HH:MM' (24-hour). '24:00' only when p_allow_24 (an end of day).
393
+ create function booking.j_time(p jsonb, p_key text, p_allow_24 boolean)
394
+ returns time
395
+ language plpgsql
396
+ stable
397
+ set search_path = ''
398
+ as $$
399
+ declare
400
+ v text := booking.j_text(p, p_key, 5);
401
+ begin
402
+ if v is null then
403
+ return null;
404
+ end if;
405
+ if v ~ '^([01][0-9]|2[0-3]):[0-5][0-9]$' or (p_allow_24 and v = '24:00') then
406
+ return v::time;
407
+ end if;
408
+ perform booking.raise_error('INVALID_INPUT', p_key);
409
+ return null;
410
+ end;
411
+ $$;
412
+
413
+ create function booking.j_date(p jsonb, p_key text)
414
+ returns date
415
+ language plpgsql
416
+ stable
417
+ set search_path = ''
418
+ as $$
419
+ declare
420
+ v text := booking.j_text(p, p_key, 10);
421
+ d date;
422
+ begin
423
+ if v is null then
424
+ return null;
425
+ end if;
426
+ if v !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$' then
427
+ perform booking.raise_error('INVALID_INPUT', p_key);
428
+ end if;
429
+ begin
430
+ d := v::date;
431
+ exception when others then
432
+ perform booking.raise_error('INVALID_INPUT', p_key);
433
+ end;
434
+ if to_char(d, 'YYYY-MM-DD') <> v then
435
+ perform booking.raise_error('INVALID_INPUT', p_key);
436
+ end if;
437
+ return d;
438
+ end;
439
+ $$;
440
+
441
+ -- Random 8-character booking reference without look-alike characters.
442
+ create function booking.new_reference()
443
+ returns text
444
+ language sql
445
+ volatile
446
+ set search_path = ''
447
+ as $$
448
+ select string_agg(
449
+ substr('ABCDEFGHJKLMNPQRSTUVWXYZ23456789', (get_byte(r.b, i.n) % 32) + 1, 1),
450
+ '' order by i.n)
451
+ from (select uuid_send(gen_random_uuid()) as b) as r
452
+ cross join unnest(array[0, 1, 2, 3, 4, 5, 10, 11]) as i(n);
453
+ $$;
454
+
455
+ -- Best-effort client IP from the request headers PostgREST exposes.
456
+ -- Unverified on hosted Supabase: see docs/SECURITY.md.
457
+ create function booking.client_ip()
458
+ returns text
459
+ language plpgsql
460
+ stable
461
+ set search_path = ''
462
+ as $$
463
+ declare
464
+ h jsonb;
465
+ v text;
466
+ begin
467
+ begin
468
+ h := nullif(current_setting('request.headers', true), '')::jsonb;
469
+ exception when others then
470
+ return null;
471
+ end;
472
+ if h is null then
473
+ return null;
474
+ end if;
475
+ v := coalesce(h ->> 'cf-connecting-ip', h ->> 'x-real-ip', split_part(h ->> 'x-forwarded-for', ',', 1));
476
+ return left(nullif(btrim(v), ''), 64);
477
+ end;
478
+ $$;
479
+
480
+ -- THE availability algorithm. Pure function of the tables and p_now.
481
+ -- Slots are generated per opening window as absolute instants:
482
+ -- open/close = (local date + local time) AT TIME ZONE business tz,
483
+ -- then stepped by the slot interval in real elapsed time.
484
+ -- So on DST days a nonexistent local time is never offered and a repeated
485
+ -- local hour is offered as two distinct instants.
486
+ create function booking.compute_slots(
487
+ p_service_id uuid,
488
+ p_from date,
489
+ p_to date,
490
+ p_now timestamptz,
491
+ p_resource_id uuid default null
492
+ )
493
+ returns table (starts_at timestamptz, ends_at timestamptz, local_date date)
494
+ language sql
495
+ stable
496
+ set search_path = ''
497
+ as $$
498
+ with s as (
499
+ select st.timezone, st.slot_interval_minutes, st.min_notice_minutes, st.max_advance_days
500
+ from booking.settings st
501
+ where st.id
502
+ ),
503
+ svc as (
504
+ select sv.duration_minutes, sv.buffer_after_minutes
505
+ from booking.services sv
506
+ where sv.id = p_service_id and sv.is_active
507
+ ),
508
+ res as (
509
+ select r.id
510
+ from booking.resources r
511
+ where r.is_active
512
+ and (r.id = p_resource_id or (p_resource_id is null and r.is_default))
513
+ ),
514
+ days as (
515
+ select d::date as day
516
+ from generate_series(p_from::timestamp, p_to::timestamp, interval '1 day') as d
517
+ ),
518
+ windows as (
519
+ select dd.day,
520
+ (dd.day + wh.start_time) at time zone s.timezone as open_at,
521
+ (dd.day + wh.end_time) at time zone s.timezone as close_at
522
+ from days dd
523
+ cross join s
524
+ join booking.working_hours wh on wh.weekday = extract(isodow from dd.day)::int
525
+ ),
526
+ candidates as (
527
+ select w.day,
528
+ g.slot_start,
529
+ g.slot_start + make_interval(mins => svc.duration_minutes) as slot_end,
530
+ g.slot_start + make_interval(mins => svc.duration_minutes + svc.buffer_after_minutes) as blocked_until
531
+ from windows w
532
+ cross join svc
533
+ cross join s
534
+ cross join lateral generate_series(
535
+ w.open_at,
536
+ w.close_at - make_interval(mins => svc.duration_minutes),
537
+ make_interval(mins => s.slot_interval_minutes)
538
+ ) as g(slot_start)
539
+ )
540
+ select c.slot_start, c.slot_end, c.day
541
+ from candidates c
542
+ cross join s
543
+ cross join res
544
+ where c.slot_start >= p_now + make_interval(mins => s.min_notice_minutes)
545
+ and c.day <= (p_now at time zone s.timezone)::date + s.max_advance_days
546
+ and not exists (
547
+ select 1
548
+ from booking.bookings b
549
+ where b.resource_id = res.id
550
+ and b.status in ('pending', 'confirmed')
551
+ and tstzrange(b.starts_at, b.blocked_until, '[)') && tstzrange(c.slot_start, c.blocked_until, '[)')
552
+ )
553
+ and not exists (
554
+ select 1
555
+ from booking.availability_exceptions e
556
+ where c.day between e.starts_on and e.ends_on
557
+ and (
558
+ e.start_time is null
559
+ or tstzrange((c.day + e.start_time) at time zone s.timezone,
560
+ (c.day + e.end_time) at time zone s.timezone, '[)')
561
+ && tstzrange(c.slot_start, c.slot_end, '[)')
562
+ )
563
+ )
564
+ order by c.slot_start;
565
+ $$;
566
+
567
+ create function booking.booking_json(b booking.bookings, p_tz text)
568
+ returns jsonb
569
+ language sql
570
+ stable
571
+ set search_path = ''
572
+ as $$
573
+ select jsonb_build_object(
574
+ 'id', b.id,
575
+ 'reference', b.reference,
576
+ 'status', b.status,
577
+ 'startsAt', booking.iso(b.starts_at),
578
+ 'endsAt', booking.iso(b.ends_at),
579
+ 'date', to_char(b.starts_at at time zone p_tz, 'YYYY-MM-DD'),
580
+ 'time', to_char(b.starts_at at time zone p_tz, 'HH24:MI'),
581
+ 'endTime', to_char(b.ends_at at time zone p_tz, 'HH24:MI'),
582
+ 'serviceId', b.service_id,
583
+ 'serviceName', b.service_name,
584
+ 'priceCents', b.price_cents,
585
+ 'currency', b.currency,
586
+ 'customer', jsonb_build_object('name', b.customer_name, 'email', b.customer_email, 'phone', b.customer_phone),
587
+ 'notes', b.customer_notes,
588
+ 'source', b.source,
589
+ 'createdAt', booking.iso(b.created_at),
590
+ 'statusChangedAt', booking.iso(b.status_changed_at)
591
+ );
592
+ $$;
593
+
594
+ create function booking.service_json(sv booking.services)
595
+ returns jsonb
596
+ language sql
597
+ stable
598
+ set search_path = ''
599
+ as $$
600
+ select jsonb_build_object(
601
+ 'id', sv.id,
602
+ 'name', sv.name,
603
+ 'description', sv.description,
604
+ 'durationMinutes', sv.duration_minutes,
605
+ 'bufferAfterMinutes', sv.buffer_after_minutes,
606
+ 'priceCents', sv.price_cents,
607
+ 'priceFrom', sv.price_from,
608
+ 'isActive', sv.is_active,
609
+ 'sortOrder', sv.sort_order,
610
+ 'createdAt', booking.iso(sv.created_at),
611
+ 'updatedAt', booking.iso(sv.updated_at)
612
+ );
613
+ $$;
614
+
615
+ create function booking.settings_json()
616
+ returns jsonb
617
+ language sql
618
+ stable
619
+ set search_path = ''
620
+ as $$
621
+ select jsonb_build_object(
622
+ 'businessName', s.business_name,
623
+ 'timezone', s.timezone,
624
+ 'currency', s.currency,
625
+ 'locale', s.locale,
626
+ 'publicEmail', s.public_email,
627
+ 'publicPhone', s.public_phone,
628
+ 'address', s.address,
629
+ 'slotIntervalMinutes', s.slot_interval_minutes,
630
+ 'minNoticeMinutes', s.min_notice_minutes,
631
+ 'maxAdvanceDays', s.max_advance_days,
632
+ 'autoConfirm', s.auto_confirm,
633
+ 'requirePhone', s.require_phone,
634
+ 'maxActiveBookingsPerEmail', s.max_active_bookings_per_email,
635
+ 'updatedAt', booking.iso(s.updated_at)
636
+ )
637
+ from booking.settings s
638
+ where s.id;
639
+ $$;
640
+
641
+ -- Owner tools, run in the Supabase SQL editor (role postgres). Not exposed.
642
+ create function booking.add_admin(p_email text)
643
+ returns text
644
+ language plpgsql
645
+ volatile
646
+ set search_path = ''
647
+ as $$
648
+ declare
649
+ v_email text := lower(btrim(coalesce(p_email, '')));
650
+ v_ids uuid[];
651
+ begin
652
+ select array_agg(u.id) into v_ids from auth.users u where lower(u.email) = v_email;
653
+ if v_ids is null then
654
+ raise exception 'No Supabase Auth user with email "%". Create the user first: Authentication > Users > Add user.', v_email;
655
+ end if;
656
+ if array_length(v_ids, 1) > 1 then
657
+ raise exception 'More than one Auth user has email "%"; add the admin by user id instead.', v_email;
658
+ end if;
659
+ insert into booking.admins (user_id) values (v_ids[1]) on conflict (user_id) do nothing;
660
+ return 'Admin access granted to ' || v_email;
661
+ end;
662
+ $$;
663
+
664
+ create function booking.remove_admin(p_email text)
665
+ returns text
666
+ language plpgsql
667
+ volatile
668
+ set search_path = ''
669
+ as $$
670
+ declare
671
+ v_email text := lower(btrim(coalesce(p_email, '')));
672
+ begin
673
+ delete from booking.admins a
674
+ using auth.users u
675
+ where u.id = a.user_id and lower(u.email) = v_email;
676
+ return 'Admin access removed from ' || v_email;
677
+ end;
678
+ $$;
679
+
680
+ -- ----------------------------------------------------------------------------
681
+ -- Row Level Security — default deny; explicit policies only
682
+ -- ----------------------------------------------------------------------------
683
+
684
+ alter table booking.engine_info enable row level security;
685
+ alter table booking.settings enable row level security;
686
+ alter table booking.resources enable row level security;
687
+ alter table booking.services enable row level security;
688
+ alter table booking.working_hours enable row level security;
689
+ alter table booking.availability_exceptions enable row level security;
690
+ alter table booking.bookings enable row level security;
691
+ alter table booking.booking_events enable row level security;
692
+ alter table booking.admins enable row level security;
693
+ alter table booking.request_log enable row level security; -- no policies: definer-only
694
+
695
+ create policy engine_info_read on booking.engine_info
696
+ for select to anon, authenticated using (true);
697
+
698
+ create policy settings_read on booking.settings
699
+ for select to anon, authenticated using (true);
700
+ create policy settings_admin_update on booking.settings
701
+ for update to authenticated
702
+ using ((select booking.is_admin())) with check ((select booking.is_admin()));
703
+
704
+ create policy resources_admin_read on booking.resources
705
+ for select to authenticated using ((select booking.is_admin()));
706
+
707
+ create policy services_public_read on booking.services
708
+ for select to anon using (is_active);
709
+ create policy services_authenticated_read on booking.services
710
+ for select to authenticated using (is_active or (select booking.is_admin()));
711
+ create policy services_admin_insert on booking.services
712
+ for insert to authenticated with check ((select booking.is_admin()));
713
+ create policy services_admin_update on booking.services
714
+ for update to authenticated
715
+ using ((select booking.is_admin())) with check ((select booking.is_admin()));
716
+ create policy services_admin_delete on booking.services
717
+ for delete to authenticated using ((select booking.is_admin()));
718
+
719
+ create policy working_hours_read on booking.working_hours
720
+ for select to anon, authenticated using (true);
721
+ create policy working_hours_admin_insert on booking.working_hours
722
+ for insert to authenticated with check ((select booking.is_admin()));
723
+ create policy working_hours_admin_update on booking.working_hours
724
+ for update to authenticated
725
+ using ((select booking.is_admin())) with check ((select booking.is_admin()));
726
+ create policy working_hours_admin_delete on booking.working_hours
727
+ for delete to authenticated using ((select booking.is_admin()));
728
+
729
+ create policy exceptions_admin_read on booking.availability_exceptions
730
+ for select to authenticated using ((select booking.is_admin()));
731
+ create policy exceptions_admin_insert on booking.availability_exceptions
732
+ for insert to authenticated with check ((select booking.is_admin()));
733
+ create policy exceptions_admin_update on booking.availability_exceptions
734
+ for update to authenticated
735
+ using ((select booking.is_admin())) with check ((select booking.is_admin()));
736
+ create policy exceptions_admin_delete on booking.availability_exceptions
737
+ for delete to authenticated using ((select booking.is_admin()));
738
+
739
+ create policy bookings_admin_read on booking.bookings
740
+ for select to authenticated using ((select booking.is_admin()));
741
+ create policy bookings_admin_insert on booking.bookings
742
+ for insert to authenticated with check ((select booking.is_admin()));
743
+ create policy bookings_admin_update on booking.bookings
744
+ for update to authenticated
745
+ using ((select booking.is_admin())) with check ((select booking.is_admin()));
746
+
747
+ create policy booking_events_admin_read on booking.booking_events
748
+ for select to authenticated using ((select booking.is_admin()));
749
+ create policy booking_events_admin_insert on booking.booking_events
750
+ for insert to authenticated with check ((select booking.is_admin()));
751
+
752
+ create policy admins_read_own on booking.admins
753
+ for select to authenticated using (user_id = (select auth.uid()));
754
+
755
+ -- ----------------------------------------------------------------------------
756
+ -- Public API — SECURITY INVOKER reads of public data
757
+ -- ----------------------------------------------------------------------------
758
+
759
+ create function public.booking_engine_info()
760
+ returns jsonb
761
+ language sql
762
+ stable
763
+ security invoker
764
+ set search_path = ''
765
+ as $$
766
+ select jsonb_build_object('engine', e.engine, 'schemaVersion', e.schema_version)
767
+ from booking.engine_info e
768
+ where e.id;
769
+ $$;
770
+ comment on function public.booking_engine_info() is
771
+ 'Public. Engine name and database schema version, for the client compatibility check.';
772
+
773
+ create function public.booking_get_business()
774
+ returns jsonb
775
+ language sql
776
+ stable
777
+ security invoker
778
+ set search_path = ''
779
+ as $$
780
+ select jsonb_build_object(
781
+ 'name', s.business_name,
782
+ 'timezone', s.timezone,
783
+ 'currency', s.currency,
784
+ 'locale', s.locale,
785
+ 'contact', jsonb_build_object('email', s.public_email, 'phone', s.public_phone, 'address', s.address),
786
+ 'policies', jsonb_build_object(
787
+ 'slotIntervalMinutes', s.slot_interval_minutes,
788
+ 'minNoticeMinutes', s.min_notice_minutes,
789
+ 'maxAdvanceDays', s.max_advance_days,
790
+ 'autoConfirm', s.auto_confirm,
791
+ 'requirePhone', s.require_phone
792
+ ),
793
+ 'openingHours', coalesce((
794
+ select jsonb_agg(
795
+ jsonb_build_object('weekday', w.weekday, 'start', booking.hhmm(w.start_time), 'end', booking.hhmm(w.end_time))
796
+ order by w.weekday, w.start_time)
797
+ from booking.working_hours w
798
+ ), '[]'::jsonb)
799
+ )
800
+ from booking.settings s
801
+ where s.id;
802
+ $$;
803
+ comment on function public.booking_get_business() is
804
+ 'Public. Business profile, public booking policies and weekly opening hours.';
805
+
806
+ create function public.booking_list_services()
807
+ returns jsonb
808
+ language sql
809
+ stable
810
+ security invoker
811
+ set search_path = ''
812
+ as $$
813
+ select coalesce(jsonb_agg(
814
+ jsonb_build_object(
815
+ 'id', sv.id,
816
+ 'name', sv.name,
817
+ 'description', sv.description,
818
+ 'durationMinutes', sv.duration_minutes,
819
+ 'priceCents', sv.price_cents,
820
+ 'priceFrom', sv.price_from,
821
+ 'currency', (select s.currency from booking.settings s where s.id)
822
+ ) order by sv.sort_order, sv.name), '[]'::jsonb)
823
+ from booking.services sv
824
+ where sv.is_active;
825
+ $$;
826
+ comment on function public.booking_list_services() is 'Public. Active services in display order.';
827
+
828
+ -- ----------------------------------------------------------------------------
829
+ -- Public API — the two intentional SECURITY DEFINER functions
830
+ -- ----------------------------------------------------------------------------
831
+
832
+ create function public.booking_get_availability(p_service_id uuid, p_from date, p_to date default null)
833
+ returns jsonb
834
+ language plpgsql
835
+ stable
836
+ security definer
837
+ set search_path = ''
838
+ as $$
839
+ declare
840
+ c_max_days constant int := 42;
841
+ v_to date := coalesce(p_to, p_from);
842
+ v_settings booking.settings%rowtype;
843
+ v_today date;
844
+ v_last date;
845
+ v_result jsonb;
846
+ begin
847
+ if p_service_id is null then
848
+ perform booking.raise_error('INVALID_INPUT', 'serviceId');
849
+ end if;
850
+ if p_from is null then
851
+ perform booking.raise_error('INVALID_INPUT', 'from');
852
+ end if;
853
+ if v_to < p_from or v_to - p_from >= c_max_days then
854
+ perform booking.raise_error('INVALID_INPUT', 'to');
855
+ end if;
856
+ if not exists (select 1 from booking.services sv where sv.id = p_service_id and sv.is_active) then
857
+ perform booking.raise_error('SERVICE_UNAVAILABLE');
858
+ end if;
859
+
860
+ select * into v_settings from booking.settings where id;
861
+ v_today := (now() at time zone v_settings.timezone)::date;
862
+ v_last := v_today + v_settings.max_advance_days;
863
+
864
+ with days as (
865
+ select d::date as day
866
+ from generate_series(p_from::timestamp, v_to::timestamp, interval '1 day') as d
867
+ ),
868
+ slots as (
869
+ select cs.starts_at, cs.ends_at, cs.local_date
870
+ from booking.compute_slots(p_service_id, greatest(p_from, v_today), least(v_to, v_last), now()) as cs
871
+ )
872
+ select jsonb_build_object(
873
+ 'serviceId', p_service_id,
874
+ 'timezone', v_settings.timezone,
875
+ 'from', to_char(p_from, 'YYYY-MM-DD'),
876
+ 'to', to_char(v_to, 'YYYY-MM-DD'),
877
+ 'days', coalesce(jsonb_agg(
878
+ jsonb_build_object(
879
+ 'date', to_char(dd.day, 'YYYY-MM-DD'),
880
+ 'status', case
881
+ when dd.day < v_today or dd.day > v_last then 'unavailable'
882
+ when not exists (select 1 from booking.working_hours wh where wh.weekday = extract(isodow from dd.day)::int)
883
+ or exists (select 1 from booking.availability_exceptions e
884
+ where dd.day between e.starts_on and e.ends_on and e.start_time is null) then 'closed'
885
+ when exists (select 1 from slots sl where sl.local_date = dd.day) then 'available'
886
+ else 'full'
887
+ end,
888
+ 'slots', coalesce((
889
+ select jsonb_agg(
890
+ jsonb_build_object(
891
+ 'startsAt', booking.iso(sl.starts_at),
892
+ 'endsAt', booking.iso(sl.ends_at),
893
+ 'time', to_char(sl.starts_at at time zone v_settings.timezone, 'HH24:MI')
894
+ ) order by sl.starts_at)
895
+ from slots sl
896
+ where sl.local_date = dd.day
897
+ ), '[]'::jsonb)
898
+ ) order by dd.day), '[]'::jsonb)
899
+ )
900
+ into v_result
901
+ from days dd;
902
+
903
+ return v_result;
904
+ end;
905
+ $$;
906
+ comment on function public.booking_get_availability(uuid, date, date) is
907
+ 'Public, SECURITY DEFINER by design: reads existing bookings to compute free slots and returns times only. Dates are business-local; at most 42 days per call.';
908
+
909
+ create function public.booking_create(
910
+ p_service_id uuid,
911
+ p_starts_at timestamptz,
912
+ p_customer_name text,
913
+ p_customer_email text,
914
+ p_customer_phone text default null,
915
+ p_notes text default null
916
+ )
917
+ returns jsonb
918
+ language plpgsql
919
+ volatile
920
+ security definer
921
+ set search_path = ''
922
+ as $$
923
+ declare
924
+ c_ip_limit_per_hour constant int := 10;
925
+ v_settings booking.settings%rowtype;
926
+ v_service booking.services%rowtype;
927
+ v_resource_id uuid;
928
+ v_name text := btrim(coalesce(p_customer_name, ''));
929
+ v_email text := lower(btrim(coalesce(p_customer_email, '')));
930
+ v_phone text := nullif(btrim(coalesce(p_customer_phone, '')), '');
931
+ v_notes text := nullif(btrim(coalesce(p_notes, '')), '');
932
+ v_local_day date;
933
+ v_ip text;
934
+ v_ip_bucket text;
935
+ v_count int;
936
+ v_status text;
937
+ v_booking booking.bookings%rowtype;
938
+ v_attempt int := 0;
939
+ begin
940
+ -- 1. Validate the request itself.
941
+ if p_service_id is null then
942
+ perform booking.raise_error('INVALID_INPUT', 'serviceId');
943
+ end if;
944
+ if p_starts_at is null then
945
+ perform booking.raise_error('INVALID_INPUT', 'startsAt');
946
+ end if;
947
+ if char_length(v_name) < 1 or char_length(v_name) > 120 or v_name ~ '[[:cntrl:]]' then
948
+ perform booking.raise_error('INVALID_INPUT', 'customer.name');
949
+ end if;
950
+ if char_length(v_email) > 254
951
+ or v_email !~ '^[^@[:space:]<>()]+@[^@[:space:]<>()]+\.[^@[:space:]<>()]{2,}$' then
952
+ perform booking.raise_error('INVALID_INPUT', 'customer.email');
953
+ end if;
954
+ if v_phone is not null and (
955
+ char_length(v_phone) > 40
956
+ or v_phone !~ '^[0-9+()./[:space:]-]+$'
957
+ or char_length(regexp_replace(v_phone, '[^0-9]', '', 'g')) < 5) then
958
+ perform booking.raise_error('INVALID_INPUT', 'customer.phone');
959
+ end if;
960
+ if v_notes is not null and (char_length(v_notes) > 1000 or v_notes ~ '[\x01-\x08\x0B\x0C\x0E-\x1F\x7F]') then
961
+ perform booking.raise_error('INVALID_INPUT', 'notes');
962
+ end if;
963
+
964
+ select * into v_settings from booking.settings where id;
965
+ if v_settings.require_phone and v_phone is null then
966
+ perform booking.raise_error('INVALID_INPUT', 'customer.phone');
967
+ end if;
968
+
969
+ select * into v_service from booking.services where id = p_service_id and is_active;
970
+ if not found then
971
+ perform booking.raise_error('SERVICE_UNAVAILABLE');
972
+ end if;
973
+
974
+ select r.id into v_resource_id from booking.resources r where r.is_default and r.is_active;
975
+ if v_resource_id is null then
976
+ perform booking.raise_error('SLOT_UNAVAILABLE');
977
+ end if;
978
+
979
+ -- 2. Abuse limits (see docs/SECURITY.md).
980
+ select count(*) into v_count
981
+ from booking.bookings b
982
+ where lower(b.customer_email) = v_email
983
+ and b.status in ('pending', 'confirmed')
984
+ and b.starts_at > now();
985
+ if v_count >= v_settings.max_active_bookings_per_email then
986
+ perform booking.raise_error('RATE_LIMITED', 'email');
987
+ end if;
988
+
989
+ v_ip := booking.client_ip();
990
+ if v_ip is not null then
991
+ v_ip_bucket := 'ip:' || encode(sha256(convert_to(v_ip, 'UTF8')), 'hex');
992
+ select count(*) into v_count
993
+ from booking.request_log r
994
+ where r.bucket = v_ip_bucket and r.created_at > now() - interval '1 hour';
995
+ if v_count >= c_ip_limit_per_hour then
996
+ perform booking.raise_error('RATE_LIMITED', 'ip');
997
+ end if;
998
+ end if;
999
+
1000
+ -- 3. The start must be a slot the engine offers right now: inside opening
1001
+ -- hours, on the slot grid, after the notice period, inside the booking
1002
+ -- window, outside closures, and free.
1003
+ v_local_day := (p_starts_at at time zone v_settings.timezone)::date;
1004
+ if not exists (
1005
+ select 1
1006
+ from booking.compute_slots(p_service_id, v_local_day, v_local_day, now(), v_resource_id) as cs
1007
+ where cs.starts_at = p_starts_at
1008
+ ) then
1009
+ perform booking.raise_error('SLOT_UNAVAILABLE');
1010
+ end if;
1011
+
1012
+ v_status := case when v_settings.auto_confirm then 'confirmed' else 'pending' end;
1013
+
1014
+ -- 4. Insert. Under concurrency the exclusion constraint decides: a second
1015
+ -- request for an overlapping time waits for the first and then fails.
1016
+ loop
1017
+ v_attempt := v_attempt + 1;
1018
+ begin
1019
+ insert into booking.bookings (
1020
+ reference, service_id, resource_id, starts_at, ends_at, blocked_until, status,
1021
+ customer_name, customer_email, customer_phone, customer_notes,
1022
+ service_name, price_cents, currency, source
1023
+ ) values (
1024
+ booking.new_reference(), v_service.id, v_resource_id, p_starts_at,
1025
+ p_starts_at + make_interval(mins => v_service.duration_minutes),
1026
+ p_starts_at + make_interval(mins => v_service.duration_minutes + v_service.buffer_after_minutes),
1027
+ v_status, v_name, v_email, v_phone, v_notes,
1028
+ v_service.name, v_service.price_cents, v_settings.currency, 'website'
1029
+ )
1030
+ returning * into v_booking;
1031
+ exit;
1032
+ exception
1033
+ when exclusion_violation then
1034
+ perform booking.raise_error('SLOT_UNAVAILABLE');
1035
+ when unique_violation then
1036
+ if v_attempt >= 3 then
1037
+ raise;
1038
+ end if;
1039
+ end;
1040
+ end loop;
1041
+
1042
+ insert into booking.booking_events (booking_id, event_type, to_status, actor)
1043
+ values (v_booking.id, 'created', v_booking.status, 'customer');
1044
+
1045
+ if v_ip_bucket is not null then
1046
+ insert into booking.request_log (bucket) values (v_ip_bucket);
1047
+ delete from booking.request_log r where r.created_at < now() - interval '1 day';
1048
+ end if;
1049
+
1050
+ return jsonb_build_object(
1051
+ 'reference', v_booking.reference,
1052
+ 'status', v_booking.status,
1053
+ 'startsAt', booking.iso(v_booking.starts_at),
1054
+ 'endsAt', booking.iso(v_booking.ends_at),
1055
+ 'date', to_char(v_booking.starts_at at time zone v_settings.timezone, 'YYYY-MM-DD'),
1056
+ 'time', to_char(v_booking.starts_at at time zone v_settings.timezone, 'HH24:MI'),
1057
+ 'serviceName', v_booking.service_name,
1058
+ 'timezone', v_settings.timezone
1059
+ );
1060
+ end;
1061
+ $$;
1062
+ comment on function public.booking_create(uuid, timestamptz, text, text, text, text) is
1063
+ 'Public, SECURITY DEFINER by design: the only way to create a booking. Validates input, applies abuse limits, re-checks the slot, and relies on the exclusion constraint under concurrency.';
1064
+
1065
+ -- ----------------------------------------------------------------------------
1066
+ -- Admin API — SECURITY INVOKER; RLS + an explicit admin check
1067
+ -- ----------------------------------------------------------------------------
1068
+
1069
+ create function public.booking_admin_whoami()
1070
+ returns jsonb
1071
+ language sql
1072
+ stable
1073
+ security invoker
1074
+ set search_path = ''
1075
+ as $$
1076
+ select jsonb_build_object(
1077
+ 'userId', auth.uid(),
1078
+ 'email', auth.jwt() ->> 'email',
1079
+ 'isAdmin', booking.is_admin()
1080
+ );
1081
+ $$;
1082
+
1083
+ create function public.booking_admin_list_bookings(p_from date, p_to date, p_statuses text[] default null)
1084
+ returns jsonb
1085
+ language plpgsql
1086
+ stable
1087
+ security invoker
1088
+ set search_path = ''
1089
+ as $$
1090
+ declare
1091
+ v_tz text;
1092
+ v_result jsonb;
1093
+ begin
1094
+ perform booking.require_admin();
1095
+ if p_from is null or p_to is null or p_to < p_from or p_to - p_from > 400 then
1096
+ perform booking.raise_error('INVALID_INPUT', 'range');
1097
+ end if;
1098
+ if p_statuses is not null and exists (
1099
+ select 1 from unnest(p_statuses) as st(v)
1100
+ where st.v is null or st.v not in ('pending', 'confirmed', 'completed', 'cancelled', 'no_show')) then
1101
+ perform booking.raise_error('INVALID_INPUT', 'statuses');
1102
+ end if;
1103
+
1104
+ select s.timezone into v_tz from booking.settings s where s.id;
1105
+
1106
+ select coalesce(jsonb_agg(booking.booking_json(b, v_tz) order by b.starts_at), '[]'::jsonb)
1107
+ into v_result
1108
+ from booking.bookings b
1109
+ where b.id in (
1110
+ select b2.id
1111
+ from booking.bookings b2
1112
+ where b2.starts_at >= (p_from::timestamp at time zone v_tz)
1113
+ and b2.starts_at < ((p_to + 1)::timestamp at time zone v_tz)
1114
+ and (p_statuses is null or b2.status = any (p_statuses))
1115
+ order by b2.starts_at
1116
+ limit 1000
1117
+ );
1118
+ return v_result;
1119
+ end;
1120
+ $$;
1121
+
1122
+ create function public.booking_admin_set_booking_status(p_booking_id uuid, p_status text)
1123
+ returns jsonb
1124
+ language plpgsql
1125
+ volatile
1126
+ security invoker
1127
+ set search_path = ''
1128
+ as $$
1129
+ declare
1130
+ v_uid uuid;
1131
+ v_tz text;
1132
+ b booking.bookings%rowtype;
1133
+ v_from text;
1134
+ begin
1135
+ v_uid := booking.require_admin();
1136
+ if p_status is null or p_status not in ('confirmed', 'cancelled', 'completed', 'no_show') then
1137
+ perform booking.raise_error('INVALID_INPUT', 'status');
1138
+ end if;
1139
+
1140
+ select * into b from booking.bookings where id = p_booking_id for update;
1141
+ if not found then
1142
+ perform booking.raise_error('NOT_FOUND', 'booking');
1143
+ end if;
1144
+ select s.timezone into v_tz from booking.settings s where s.id;
1145
+
1146
+ if b.status = p_status then
1147
+ return booking.booking_json(b, v_tz);
1148
+ end if;
1149
+ if not (
1150
+ (b.status = 'pending' and p_status in ('confirmed', 'cancelled'))
1151
+ or (b.status = 'confirmed' and p_status in ('cancelled', 'completed', 'no_show'))
1152
+ ) then
1153
+ perform booking.raise_error('INVALID_TRANSITION', b.status || '->' || p_status);
1154
+ end if;
1155
+ if p_status in ('completed', 'no_show') and b.starts_at > now() then
1156
+ perform booking.raise_error('INVALID_TRANSITION', 'not_started');
1157
+ end if;
1158
+
1159
+ v_from := b.status;
1160
+ update booking.bookings
1161
+ set status = p_status, status_changed_at = now()
1162
+ where id = b.id
1163
+ returning * into b;
1164
+
1165
+ insert into booking.booking_events (booking_id, event_type, from_status, to_status, actor, actor_user_id)
1166
+ values (b.id, 'status_changed', v_from, p_status, 'admin', v_uid);
1167
+
1168
+ return booking.booking_json(b, v_tz);
1169
+ end;
1170
+ $$;
1171
+
1172
+ create function public.booking_admin_list_services()
1173
+ returns jsonb
1174
+ language plpgsql
1175
+ stable
1176
+ security invoker
1177
+ set search_path = ''
1178
+ as $$
1179
+ declare
1180
+ v_result jsonb;
1181
+ begin
1182
+ perform booking.require_admin();
1183
+ select coalesce(jsonb_agg(booking.service_json(sv) order by sv.sort_order, sv.name), '[]'::jsonb)
1184
+ into v_result
1185
+ from booking.services sv;
1186
+ return v_result;
1187
+ end;
1188
+ $$;
1189
+
1190
+ create function public.booking_admin_save_service(p_service jsonb)
1191
+ returns jsonb
1192
+ language plpgsql
1193
+ volatile
1194
+ security invoker
1195
+ set search_path = ''
1196
+ as $$
1197
+ declare
1198
+ v_allowed text[] := array['id', 'name', 'description', 'durationMinutes', 'bufferAfterMinutes',
1199
+ 'priceCents', 'priceFrom', 'isActive', 'sortOrder'];
1200
+ v_key text;
1201
+ v_id uuid;
1202
+ sv booking.services%rowtype;
1203
+ begin
1204
+ perform booking.require_admin();
1205
+ if p_service is null or jsonb_typeof(p_service) <> 'object' then
1206
+ perform booking.raise_error('INVALID_INPUT', 'service');
1207
+ end if;
1208
+ for v_key in select jsonb_object_keys(p_service) loop
1209
+ if not (v_key = any (v_allowed)) then
1210
+ perform booking.raise_error('INVALID_INPUT', v_key);
1211
+ end if;
1212
+ end loop;
1213
+
1214
+ if jsonb_typeof(p_service -> 'id') = 'string' then
1215
+ begin
1216
+ v_id := (p_service ->> 'id')::uuid;
1217
+ exception when others then
1218
+ perform booking.raise_error('INVALID_INPUT', 'id');
1219
+ end;
1220
+ elsif p_service ? 'id' and jsonb_typeof(p_service -> 'id') <> 'null' then
1221
+ perform booking.raise_error('INVALID_INPUT', 'id');
1222
+ end if;
1223
+
1224
+ if p_service ? 'durationMinutes' or v_id is null then
1225
+ if booking.j_int(p_service, 'durationMinutes', 5, 720) is null then
1226
+ perform booking.raise_error('INVALID_INPUT', 'durationMinutes');
1227
+ end if;
1228
+ end if;
1229
+
1230
+ if v_id is null then
1231
+ insert into booking.services (
1232
+ name, description, duration_minutes, buffer_after_minutes, price_cents, price_from, is_active, sort_order
1233
+ ) values (
1234
+ booking.j_required_text(p_service, 'name', 120),
1235
+ booking.j_text(p_service, 'description', 2000),
1236
+ booking.j_int(p_service, 'durationMinutes', 5, 720),
1237
+ coalesce(booking.j_int(p_service, 'bufferAfterMinutes', 0, 240), 0),
1238
+ booking.j_int(p_service, 'priceCents', 0, 100000000),
1239
+ coalesce(booking.j_bool(p_service, 'priceFrom'), false),
1240
+ coalesce(booking.j_bool(p_service, 'isActive'), true),
1241
+ coalesce(booking.j_int(p_service, 'sortOrder', -100000, 100000), 0)
1242
+ )
1243
+ returning * into sv;
1244
+ else
1245
+ update booking.services set
1246
+ name = case when p_service ? 'name' then booking.j_required_text(p_service, 'name', 120) else name end,
1247
+ description = case when p_service ? 'description' then booking.j_text(p_service, 'description', 2000) else description end,
1248
+ duration_minutes = case when p_service ? 'durationMinutes'
1249
+ then booking.j_int(p_service, 'durationMinutes', 5, 720) else duration_minutes end,
1250
+ buffer_after_minutes = case when p_service ? 'bufferAfterMinutes'
1251
+ then coalesce(booking.j_int(p_service, 'bufferAfterMinutes', 0, 240), 0) else buffer_after_minutes end,
1252
+ price_cents = case when p_service ? 'priceCents' then booking.j_int(p_service, 'priceCents', 0, 100000000) else price_cents end,
1253
+ price_from = case when p_service ? 'priceFrom' then coalesce(booking.j_bool(p_service, 'priceFrom'), false) else price_from end,
1254
+ is_active = case when p_service ? 'isActive' then coalesce(booking.j_bool(p_service, 'isActive'), true) else is_active end,
1255
+ sort_order = case when p_service ? 'sortOrder'
1256
+ then coalesce(booking.j_int(p_service, 'sortOrder', -100000, 100000), 0) else sort_order end
1257
+ where id = v_id
1258
+ returning * into sv;
1259
+ if not found then
1260
+ perform booking.raise_error('NOT_FOUND', 'service');
1261
+ end if;
1262
+ end if;
1263
+ return booking.service_json(sv);
1264
+ exception
1265
+ when check_violation then
1266
+ perform booking.raise_error('INVALID_INPUT', 'service');
1267
+ return null;
1268
+ end;
1269
+ $$;
1270
+
1271
+ create function public.booking_admin_delete_service(p_service_id uuid)
1272
+ returns jsonb
1273
+ language plpgsql
1274
+ volatile
1275
+ security invoker
1276
+ set search_path = ''
1277
+ as $$
1278
+ begin
1279
+ perform booking.require_admin();
1280
+ if exists (select 1 from booking.bookings b where b.service_id = p_service_id) then
1281
+ perform booking.raise_error('CONFLICT', 'service_has_bookings');
1282
+ end if;
1283
+ delete from booking.services sv where sv.id = p_service_id;
1284
+ if not found then
1285
+ perform booking.raise_error('NOT_FOUND', 'service');
1286
+ end if;
1287
+ return jsonb_build_object('deleted', true);
1288
+ end;
1289
+ $$;
1290
+
1291
+ create function public.booking_admin_get_working_hours()
1292
+ returns jsonb
1293
+ language plpgsql
1294
+ stable
1295
+ security invoker
1296
+ set search_path = ''
1297
+ as $$
1298
+ declare
1299
+ v_result jsonb;
1300
+ begin
1301
+ perform booking.require_admin();
1302
+ select coalesce(jsonb_agg(
1303
+ jsonb_build_object('weekday', w.weekday, 'start', booking.hhmm(w.start_time), 'end', booking.hhmm(w.end_time))
1304
+ order by w.weekday, w.start_time), '[]'::jsonb)
1305
+ into v_result
1306
+ from booking.working_hours w;
1307
+ return v_result;
1308
+ end;
1309
+ $$;
1310
+
1311
+ create function public.booking_admin_set_working_hours(p_hours jsonb)
1312
+ returns jsonb
1313
+ language plpgsql
1314
+ volatile
1315
+ security invoker
1316
+ set search_path = ''
1317
+ as $$
1318
+ declare
1319
+ v_item jsonb;
1320
+ v_weekday int;
1321
+ v_start time;
1322
+ v_end time;
1323
+ begin
1324
+ perform booking.require_admin();
1325
+ if p_hours is null or jsonb_typeof(p_hours) <> 'array' or jsonb_array_length(p_hours) > 70 then
1326
+ perform booking.raise_error('INVALID_INPUT', 'hours');
1327
+ end if;
1328
+
1329
+ delete from booking.working_hours w where w.id is not null;
1330
+
1331
+ for v_item in select value from jsonb_array_elements(p_hours) loop
1332
+ if jsonb_typeof(v_item) <> 'object' then
1333
+ perform booking.raise_error('INVALID_INPUT', 'hours');
1334
+ end if;
1335
+ v_weekday := booking.j_int(v_item, 'weekday', 1, 7);
1336
+ v_start := booking.j_time(v_item, 'start', false);
1337
+ v_end := booking.j_time(v_item, 'end', true);
1338
+ if v_weekday is null or v_start is null or v_end is null then
1339
+ perform booking.raise_error('INVALID_INPUT', 'hours');
1340
+ end if;
1341
+ if v_start >= v_end then
1342
+ perform booking.raise_error('INVALID_INPUT', 'hours.order');
1343
+ end if;
1344
+ insert into booking.working_hours (weekday, start_time, end_time) values (v_weekday, v_start, v_end);
1345
+ end loop;
1346
+
1347
+ return public.booking_admin_get_working_hours();
1348
+ exception
1349
+ when exclusion_violation then
1350
+ perform booking.raise_error('INVALID_INPUT', 'hours.overlap');
1351
+ return null;
1352
+ end;
1353
+ $$;
1354
+
1355
+ create function public.booking_admin_list_exceptions()
1356
+ returns jsonb
1357
+ language plpgsql
1358
+ stable
1359
+ security invoker
1360
+ set search_path = ''
1361
+ as $$
1362
+ declare
1363
+ v_result jsonb;
1364
+ begin
1365
+ perform booking.require_admin();
1366
+ select coalesce(jsonb_agg(
1367
+ jsonb_build_object(
1368
+ 'id', e.id,
1369
+ 'kind', 'closed',
1370
+ 'startsOn', to_char(e.starts_on, 'YYYY-MM-DD'),
1371
+ 'endsOn', to_char(e.ends_on, 'YYYY-MM-DD'),
1372
+ 'startTime', case when e.start_time is null then null else booking.hhmm(e.start_time) end,
1373
+ 'endTime', case when e.end_time is null then null else booking.hhmm(e.end_time) end,
1374
+ 'reason', e.reason
1375
+ ) order by e.starts_on, e.start_time nulls first), '[]'::jsonb)
1376
+ into v_result
1377
+ from booking.availability_exceptions e;
1378
+ return v_result;
1379
+ end;
1380
+ $$;
1381
+
1382
+ create function public.booking_admin_add_exception(p_exception jsonb)
1383
+ returns jsonb
1384
+ language plpgsql
1385
+ volatile
1386
+ security invoker
1387
+ set search_path = ''
1388
+ as $$
1389
+ declare
1390
+ v_allowed text[] := array['startsOn', 'endsOn', 'startTime', 'endTime', 'reason'];
1391
+ v_key text;
1392
+ v_starts date;
1393
+ v_ends date;
1394
+ v_start_time time;
1395
+ v_end_time time;
1396
+ v_id uuid;
1397
+ begin
1398
+ perform booking.require_admin();
1399
+ if p_exception is null or jsonb_typeof(p_exception) <> 'object' then
1400
+ perform booking.raise_error('INVALID_INPUT', 'exception');
1401
+ end if;
1402
+ for v_key in select jsonb_object_keys(p_exception) loop
1403
+ if not (v_key = any (v_allowed)) then
1404
+ perform booking.raise_error('INVALID_INPUT', v_key);
1405
+ end if;
1406
+ end loop;
1407
+
1408
+ v_starts := booking.j_date(p_exception, 'startsOn');
1409
+ v_ends := coalesce(booking.j_date(p_exception, 'endsOn'), v_starts);
1410
+ v_start_time := booking.j_time(p_exception, 'startTime', false);
1411
+ v_end_time := booking.j_time(p_exception, 'endTime', true);
1412
+ if v_starts is null then
1413
+ perform booking.raise_error('INVALID_INPUT', 'startsOn');
1414
+ end if;
1415
+ if v_ends < v_starts or v_ends - v_starts > 366 then
1416
+ perform booking.raise_error('INVALID_INPUT', 'endsOn');
1417
+ end if;
1418
+ if (v_start_time is null) <> (v_end_time is null) or (v_start_time is not null and v_start_time >= v_end_time) then
1419
+ perform booking.raise_error('INVALID_INPUT', 'startTime');
1420
+ end if;
1421
+
1422
+ insert into booking.availability_exceptions (starts_on, ends_on, start_time, end_time, reason)
1423
+ values (v_starts, v_ends, v_start_time, v_end_time, booking.j_text(p_exception, 'reason', 200))
1424
+ returning id into v_id;
1425
+
1426
+ return jsonb_build_object('id', v_id);
1427
+ end;
1428
+ $$;
1429
+
1430
+ create function public.booking_admin_delete_exception(p_exception_id uuid)
1431
+ returns jsonb
1432
+ language plpgsql
1433
+ volatile
1434
+ security invoker
1435
+ set search_path = ''
1436
+ as $$
1437
+ begin
1438
+ perform booking.require_admin();
1439
+ delete from booking.availability_exceptions e where e.id = p_exception_id;
1440
+ if not found then
1441
+ perform booking.raise_error('NOT_FOUND', 'exception');
1442
+ end if;
1443
+ return jsonb_build_object('deleted', true);
1444
+ end;
1445
+ $$;
1446
+
1447
+ create function public.booking_admin_get_settings()
1448
+ returns jsonb
1449
+ language plpgsql
1450
+ stable
1451
+ security invoker
1452
+ set search_path = ''
1453
+ as $$
1454
+ begin
1455
+ perform booking.require_admin();
1456
+ return booking.settings_json();
1457
+ end;
1458
+ $$;
1459
+
1460
+ create function public.booking_admin_update_settings(p_settings jsonb)
1461
+ returns jsonb
1462
+ language plpgsql
1463
+ volatile
1464
+ security invoker
1465
+ set search_path = ''
1466
+ as $$
1467
+ declare
1468
+ v_allowed text[] := array['businessName', 'timezone', 'currency', 'locale', 'publicEmail', 'publicPhone',
1469
+ 'address', 'slotIntervalMinutes', 'minNoticeMinutes', 'maxAdvanceDays',
1470
+ 'autoConfirm', 'requirePhone', 'maxActiveBookingsPerEmail'];
1471
+ v_key text;
1472
+ v_email text;
1473
+ begin
1474
+ perform booking.require_admin();
1475
+ if p_settings is null or jsonb_typeof(p_settings) <> 'object' then
1476
+ perform booking.raise_error('INVALID_INPUT', 'settings');
1477
+ end if;
1478
+ for v_key in select jsonb_object_keys(p_settings) loop
1479
+ if not (v_key = any (v_allowed)) then
1480
+ perform booking.raise_error('INVALID_INPUT', v_key);
1481
+ end if;
1482
+ end loop;
1483
+
1484
+ v_email := lower(booking.j_text(p_settings, 'publicEmail', 254));
1485
+ if v_email is not null and v_email !~ '^[^@[:space:]<>()]+@[^@[:space:]<>()]+\.[^@[:space:]<>()]{2,}$' then
1486
+ perform booking.raise_error('INVALID_INPUT', 'publicEmail');
1487
+ end if;
1488
+ if p_settings ? 'currency' and coalesce(booking.j_text(p_settings, 'currency', 3), '') !~ '^[A-Z]{3}$' then
1489
+ perform booking.raise_error('INVALID_INPUT', 'currency');
1490
+ end if;
1491
+ if p_settings ? 'locale'
1492
+ and coalesce(booking.j_text(p_settings, 'locale', 35), '') !~ '^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$' then
1493
+ perform booking.raise_error('INVALID_INPUT', 'locale');
1494
+ end if;
1495
+
1496
+ update booking.settings set
1497
+ business_name = case when p_settings ? 'businessName'
1498
+ then booking.j_required_text(p_settings, 'businessName', 120) else business_name end,
1499
+ timezone = case when p_settings ? 'timezone' then booking.j_required_text(p_settings, 'timezone', 64) else timezone end,
1500
+ currency = case when p_settings ? 'currency' then booking.j_required_text(p_settings, 'currency', 3) else currency end,
1501
+ locale = case when p_settings ? 'locale' then booking.j_required_text(p_settings, 'locale', 35) else locale end,
1502
+ public_email = case when p_settings ? 'publicEmail' then v_email else public_email end,
1503
+ public_phone = case when p_settings ? 'publicPhone' then booking.j_text(p_settings, 'publicPhone', 40) else public_phone end,
1504
+ address = case when p_settings ? 'address' then booking.j_text(p_settings, 'address', 300) else address end,
1505
+ slot_interval_minutes = case when p_settings ? 'slotIntervalMinutes'
1506
+ then coalesce(booking.j_int(p_settings, 'slotIntervalMinutes', 5, 240), slot_interval_minutes) else slot_interval_minutes end,
1507
+ min_notice_minutes = case when p_settings ? 'minNoticeMinutes'
1508
+ then coalesce(booking.j_int(p_settings, 'minNoticeMinutes', 0, 43200), min_notice_minutes) else min_notice_minutes end,
1509
+ max_advance_days = case when p_settings ? 'maxAdvanceDays'
1510
+ then coalesce(booking.j_int(p_settings, 'maxAdvanceDays', 1, 730), max_advance_days) else max_advance_days end,
1511
+ auto_confirm = case when p_settings ? 'autoConfirm'
1512
+ then coalesce(booking.j_bool(p_settings, 'autoConfirm'), auto_confirm) else auto_confirm end,
1513
+ require_phone = case when p_settings ? 'requirePhone'
1514
+ then coalesce(booking.j_bool(p_settings, 'requirePhone'), require_phone) else require_phone end,
1515
+ max_active_bookings_per_email = case when p_settings ? 'maxActiveBookingsPerEmail'
1516
+ then coalesce(booking.j_int(p_settings, 'maxActiveBookingsPerEmail', 1, 50), max_active_bookings_per_email)
1517
+ else max_active_bookings_per_email end
1518
+ where id;
1519
+
1520
+ return booking.settings_json();
1521
+ end;
1522
+ $$;
1523
+
1524
+ create function public.booking_admin_apply_preset(p_preset jsonb)
1525
+ returns jsonb
1526
+ language plpgsql
1527
+ volatile
1528
+ security invoker
1529
+ set search_path = ''
1530
+ as $$
1531
+ declare
1532
+ v_item jsonb;
1533
+ v_count int := 0;
1534
+ begin
1535
+ perform booking.require_admin();
1536
+ if p_preset is null or jsonb_typeof(p_preset) <> 'object'
1537
+ or jsonb_typeof(p_preset -> 'services') <> 'array'
1538
+ or jsonb_array_length(p_preset -> 'services') not between 1 and 50 then
1539
+ perform booking.raise_error('INVALID_INPUT', 'preset');
1540
+ end if;
1541
+ if exists (select 1 from booking.services) then
1542
+ perform booking.raise_error('CONFLICT', 'services_exist');
1543
+ end if;
1544
+
1545
+ for v_item in select value from jsonb_array_elements(p_preset -> 'services') loop
1546
+ if jsonb_typeof(v_item) <> 'object' then
1547
+ perform booking.raise_error('INVALID_INPUT', 'preset.services');
1548
+ end if;
1549
+ v_count := v_count + 1;
1550
+ perform public.booking_admin_save_service(
1551
+ jsonb_strip_nulls(jsonb_build_object(
1552
+ 'name', v_item -> 'name',
1553
+ 'description', v_item -> 'description',
1554
+ 'durationMinutes', v_item -> 'durationMinutes',
1555
+ 'bufferAfterMinutes', v_item -> 'bufferAfterMinutes',
1556
+ 'priceCents', v_item -> 'priceCents',
1557
+ 'priceFrom', v_item -> 'priceFrom',
1558
+ 'sortOrder', to_jsonb(v_count * 10)
1559
+ )));
1560
+ end loop;
1561
+
1562
+ if jsonb_typeof(p_preset -> 'workingHours') = 'array' then
1563
+ perform public.booking_admin_set_working_hours(p_preset -> 'workingHours');
1564
+ end if;
1565
+ if jsonb_typeof(p_preset -> 'policies') = 'object' then
1566
+ perform public.booking_admin_update_settings(p_preset -> 'policies');
1567
+ end if;
1568
+
1569
+ return jsonb_build_object('servicesAdded', v_count);
1570
+ end;
1571
+ $$;
1572
+
1573
+ -- ----------------------------------------------------------------------------
1574
+ -- Privileges — explicit, least privilege
1575
+ -- ----------------------------------------------------------------------------
1576
+
1577
+ revoke all on all tables in schema booking from public, anon, authenticated, service_role;
1578
+ revoke all on all sequences in schema booking from public, anon, authenticated, service_role;
1579
+ revoke all on all functions in schema booking from public, anon, authenticated, service_role;
1580
+ revoke all on schema booking from public;
1581
+
1582
+ grant usage on schema booking to anon, authenticated;
1583
+
1584
+ -- Public data (row access further limited by RLS).
1585
+ grant select on booking.engine_info to anon, authenticated;
1586
+ grant select (id, business_name, timezone, currency, locale, public_email, public_phone, address,
1587
+ slot_interval_minutes, min_notice_minutes, max_advance_days, auto_confirm, require_phone)
1588
+ on booking.settings to anon;
1589
+ grant select on booking.services to anon;
1590
+ grant select on booking.working_hours to anon;
1591
+
1592
+ -- Signed-in users. Every row is still behind RLS: admins pass, others do not.
1593
+ grant select, update on booking.settings to authenticated;
1594
+ grant select on booking.resources to authenticated;
1595
+ grant select, insert, update, delete on booking.services to authenticated;
1596
+ grant select, insert, update, delete on booking.working_hours to authenticated;
1597
+ grant select, insert, update, delete on booking.availability_exceptions to authenticated;
1598
+ grant select, insert, update on booking.bookings to authenticated;
1599
+ grant select, insert on booking.booking_events to authenticated;
1600
+ grant select on booking.admins to authenticated;
1601
+
1602
+ -- Helpers used inside SECURITY INVOKER admin functions.
1603
+ grant execute on function
1604
+ booking.raise_error(text, text),
1605
+ booking.is_admin(),
1606
+ booking.require_admin(),
1607
+ booking.iso(timestamptz),
1608
+ booking.hhmm(time),
1609
+ booking.j_text(jsonb, text, int),
1610
+ booking.j_required_text(jsonb, text, int),
1611
+ booking.j_int(jsonb, text, int, int),
1612
+ booking.j_bool(jsonb, text),
1613
+ booking.j_time(jsonb, text, boolean),
1614
+ booking.j_date(jsonb, text),
1615
+ booking.booking_json(booking.bookings, text),
1616
+ booking.service_json(booking.services),
1617
+ booking.settings_json()
1618
+ to authenticated;
1619
+ -- booking.hhmm is used by the anon-callable booking_get_business().
1620
+ grant execute on function booking.hhmm(time) to anon;
1621
+
1622
+ -- API functions: revoke the PostgreSQL default (PUBLIC) and Supabase's default
1623
+ -- grants (anon, authenticated, service_role in schema public) — by exact
1624
+ -- signature, so a project's own functions are never touched — then grant on
1625
+ -- purpose.
1626
+ revoke all on function
1627
+ public.booking_engine_info(),
1628
+ public.booking_get_business(),
1629
+ public.booking_list_services(),
1630
+ public.booking_get_availability(uuid, date, date),
1631
+ public.booking_create(uuid, timestamptz, text, text, text, text),
1632
+ public.booking_admin_whoami(),
1633
+ public.booking_admin_list_bookings(date, date, text[]),
1634
+ public.booking_admin_set_booking_status(uuid, text),
1635
+ public.booking_admin_list_services(),
1636
+ public.booking_admin_save_service(jsonb),
1637
+ public.booking_admin_delete_service(uuid),
1638
+ public.booking_admin_get_working_hours(),
1639
+ public.booking_admin_set_working_hours(jsonb),
1640
+ public.booking_admin_list_exceptions(),
1641
+ public.booking_admin_add_exception(jsonb),
1642
+ public.booking_admin_delete_exception(uuid),
1643
+ public.booking_admin_get_settings(),
1644
+ public.booking_admin_update_settings(jsonb),
1645
+ public.booking_admin_apply_preset(jsonb)
1646
+ from public, anon, authenticated, service_role;
1647
+
1648
+ grant execute on function
1649
+ public.booking_engine_info(),
1650
+ public.booking_get_business(),
1651
+ public.booking_list_services(),
1652
+ public.booking_get_availability(uuid, date, date),
1653
+ public.booking_create(uuid, timestamptz, text, text, text, text)
1654
+ to anon, authenticated, service_role;
1655
+
1656
+ grant execute on function
1657
+ public.booking_admin_whoami(),
1658
+ public.booking_admin_list_bookings(date, date, text[]),
1659
+ public.booking_admin_set_booking_status(uuid, text),
1660
+ public.booking_admin_list_services(),
1661
+ public.booking_admin_save_service(jsonb),
1662
+ public.booking_admin_delete_service(uuid),
1663
+ public.booking_admin_get_working_hours(),
1664
+ public.booking_admin_set_working_hours(jsonb),
1665
+ public.booking_admin_list_exceptions(),
1666
+ public.booking_admin_add_exception(jsonb),
1667
+ public.booking_admin_delete_exception(uuid),
1668
+ public.booking_admin_get_settings(),
1669
+ public.booking_admin_update_settings(jsonb),
1670
+ public.booking_admin_apply_preset(jsonb)
1671
+ to authenticated;
1672
+
1673
+ insert into booking.engine_info (schema_version) values ('2.0.0-alpha.1');