@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,1702 @@
1
+ -- ============================================================================
2
+ -- Profit Studio Booking Engine — migration 0004_verified_requests
3
+ -- Engine schema version: 2.0.0-alpha.4
4
+ --
5
+ -- ENGINE-OWNED FILE. Do not edit. `booking-engine doctor` reports changes.
6
+ --
7
+ -- Verified booking requests and essential emails
8
+ -- (docs/adr/0002-verified-booking-requests.md):
9
+ --
10
+ -- * booking_request — validates and rate-limits, holds the time as an
11
+ -- `unverified` booking for the verification window only (default 15 min)
12
+ -- and queues a 6-digit one-time code email (only a salted hash is stored;
13
+ -- 5 attempts; at most 3 re-sends).
14
+ -- * booking_verify — proves email ownership, rechecks the time, applies the
15
+ -- per-email booking cap and turns the hold into `pending` (owner approval)
16
+ -- or `confirmed` (instant confirmation). Idempotent.
17
+ -- * booking_cancel_request — the visitor releases their own unverified hold
18
+ -- (the request id they were given is the capability).
19
+ -- * Unverified requests are invisible to the owner and deleted when they lapse.
20
+ -- * Every email is a row in a transactional outbox (written in the same
21
+ -- transaction as the change that causes it, once per de-duplication key),
22
+ -- sent by the `booking-mailer` Edge Function. The database starts the
23
+ -- function itself (pg_net + Vault, when configured) and a pg_cron job
24
+ -- runs maintenance and retries; the website never calls the mailer.
25
+ -- * Online booking stays off until a test email has been delivered.
26
+ -- * booking_create is closed: it raises VERIFICATION_REQUIRED.
27
+ --
28
+ -- Existing data is preserved. Online booking is OFF after the upgrade until
29
+ -- email sending is set up (see CHANGELOG).
30
+ -- ============================================================================
31
+
32
+ do $$
33
+ declare
34
+ v text;
35
+ begin
36
+ select e.schema_version into v from booking.engine_info e where e.id;
37
+ if v is distinct from '2.0.0-alpha.3' then
38
+ raise exception 'Booking Engine 0004_verified_requests expects schema 2.0.0-alpha.3, found %', coalesce(v, 'none');
39
+ end if;
40
+ end
41
+ $$;
42
+
43
+ -- ----------------------------------------------------------------------------
44
+ -- Schema
45
+ -- ----------------------------------------------------------------------------
46
+
47
+ alter table booking.bookings drop constraint bookings_status_check;
48
+ alter table booking.bookings add constraint bookings_status_check
49
+ check (status in ('unverified', 'pending', 'confirmed', 'completed', 'cancelled', 'no_show', 'expired'));
50
+ alter table booking.bookings drop constraint bookings_hold_only_for_requests;
51
+ alter table booking.bookings add constraint bookings_hold_only_for_requests
52
+ check (hold_expires_at is null or status in ('unverified', 'pending', 'expired'));
53
+ alter table booking.bookings add constraint bookings_unverified_is_held
54
+ check (status <> 'unverified' or hold_expires_at is not null);
55
+ alter table booking.bookings drop constraint bookings_no_overlap;
56
+ alter table booking.bookings add constraint bookings_no_overlap exclude using gist (
57
+ resource_id with =,
58
+ tstzrange(starts_at, blocked_until, '[)') with &&
59
+ ) where (status in ('unverified', 'pending', 'confirmed'));
60
+ comment on constraint bookings_no_overlap on booking.bookings is
61
+ 'The double-booking guarantee: verification holds, requests and confirmed bookings never overlap on one resource, including buffer time. Holds under concurrent requests.';
62
+ alter table booking.bookings add column email_verified_at timestamptz;
63
+ comment on column booking.bookings.email_verified_at is
64
+ 'When the customer proved they control customer_email. NULL for bookings made before verification existed (2.0.0-alpha.3 and earlier) and for admin bookings.';
65
+ create index bookings_unverified_holds on booking.bookings (hold_expires_at) where status = 'unverified';
66
+
67
+ alter table booking.settings drop constraint settings_instant_confirmation_requires_verification;
68
+ alter table booking.settings
69
+ add column owner_notification_email text
70
+ check (owner_notification_email is null or char_length(owner_notification_email) <= 254),
71
+ add column verification_window_minutes int not null default 15
72
+ check (verification_window_minutes between 5 and 30),
73
+ add column max_verification_emails_per_day int not null default 50
74
+ check (max_verification_emails_per_day between 1 and 5000),
75
+ add column online_booking_enabled boolean not null default false;
76
+ comment on column booking.settings.owner_notification_email is
77
+ 'Where new-request alerts go. When empty, the public business email is used.';
78
+ comment on column booking.settings.verification_window_minutes is
79
+ 'How long a customer has to enter their code. The time is held for them meanwhile.';
80
+ comment on column booking.settings.max_verification_emails_per_day is
81
+ 'Site-wide ceiling on code emails per 24 hours (cost and abuse control). The default fits Resend''s free plan.';
82
+ comment on column booking.settings.online_booking_enabled is
83
+ 'Website booking accepts requests only when on. It can be switched on once a test email has been delivered.';
84
+
85
+ create table booking.verifications (
86
+ id uuid primary key,
87
+ booking_id uuid unique references booking.bookings (id) on delete set null,
88
+ code_hash text not null,
89
+ expires_at timestamptz not null,
90
+ attempts int not null default 0 check (attempts >= 0),
91
+ sends int not null default 1 check (sends >= 1),
92
+ last_sent_at timestamptz not null default now(),
93
+ verified_at timestamptz,
94
+ created_at timestamptz not null default now()
95
+ );
96
+ comment on table booking.verifications is
97
+ 'One-time codes for booking requests (the request id is this row''s id). Only salted SHA-256 hashes are stored. Rows are deleted after a day.';
98
+
99
+ create table booking.email_outbox (
100
+ id uuid primary key default gen_random_uuid(),
101
+ kind text not null check (kind in (
102
+ 'verification_code', 'request_received', 'booking_confirmed', 'booking_declined',
103
+ 'booking_cancelled', 'request_expired', 'owner_new_request', 'test')),
104
+ recipient text not null check (char_length(recipient) between 3 and 254),
105
+ booking_id uuid references booking.bookings (id) on delete set null,
106
+ payload jsonb not null,
107
+ dedupe_key text not null unique,
108
+ status text not null default 'pending' check (status in ('pending', 'sending', 'sent', 'failed', 'cancelled')),
109
+ attempts int not null default 0 check (attempts >= 0),
110
+ next_attempt_at timestamptz not null default now(),
111
+ locked_until timestamptz,
112
+ provider_message_id text,
113
+ last_error text,
114
+ created_at timestamptz not null default clock_timestamp(), -- keeps emails of one transaction in order
115
+ sent_at timestamptz
116
+ );
117
+ create index email_outbox_due on booking.email_outbox (next_attempt_at) where status in ('pending', 'sending');
118
+ create index email_outbox_kind_created on booking.email_outbox (kind, created_at);
119
+ create index email_outbox_recipient_created on booking.email_outbox (recipient, created_at);
120
+ create index email_outbox_booking on booking.email_outbox (booking_id);
121
+ comment on table booking.email_outbox is
122
+ 'Transactional outbox: each email is written in the same transaction as the change that causes it, once per dedupe_key, and sent by the booking-mailer Edge Function. Codes are removed once sent or no longer usable. Code emails are kept 2 days, others 30 days.';
123
+
124
+ create table booking.mailer_state (
125
+ id boolean primary key default true check (id),
126
+ last_attempt_at timestamptz,
127
+ last_success_at timestamptz,
128
+ last_failure_at timestamptz,
129
+ last_error text
130
+ );
131
+ insert into booking.mailer_state default values;
132
+ comment on table booking.mailer_state is 'Health of email sending, shown in the dashboard. last_success_at unlocks online booking.';
133
+
134
+ -- ----------------------------------------------------------------------------
135
+ -- Helpers
136
+ -- ----------------------------------------------------------------------------
137
+
138
+ create or replace function booking.effective_status(p_status text, p_hold_expires_at timestamptz)
139
+ returns text
140
+ language sql
141
+ stable
142
+ set search_path = ''
143
+ as $$
144
+ select case
145
+ when p_status in ('unverified', 'pending') and p_hold_expires_at is not null and p_hold_expires_at <= now() then 'expired'
146
+ else p_status
147
+ end;
148
+ $$;
149
+
150
+ create function booking.mask_email(p_email text)
151
+ returns text
152
+ language sql
153
+ immutable
154
+ set search_path = ''
155
+ as $$
156
+ select case
157
+ when p_email is null or position('@' in p_email) < 2 then '***'
158
+ else left(p_email, 1) || '***' || substr(p_email, position('@' in p_email))
159
+ end;
160
+ $$;
161
+
162
+ -- Six digits from the CSPRNG behind gen_random_uuid() (modulo bias < 0.03 %).
163
+ create function booking.new_code()
164
+ returns text
165
+ language sql
166
+ volatile
167
+ set search_path = ''
168
+ as $$
169
+ select lpad(((((get_byte(r.b, 0)::bigint << 24) | (get_byte(r.b, 1) << 16) | (get_byte(r.b, 2) << 8) | get_byte(r.b, 3))
170
+ % 1000000))::text, 6, '0')
171
+ from (select uuid_send(gen_random_uuid()) as b) as r;
172
+ $$;
173
+
174
+ create function booking.code_hash(p_verification_id uuid, p_code text)
175
+ returns text
176
+ language sql
177
+ stable
178
+ set search_path = ''
179
+ as $$
180
+ select encode(sha256(convert_to(
181
+ (select es.hash_salt from booking.engine_secrets es where es.id) || ':' || p_verification_id::text || ':' || p_code,
182
+ 'UTF8')), 'hex');
183
+ $$;
184
+
185
+ -- What a customer is shown about their own booking (BookingConfirmation).
186
+ create function booking.public_booking_json(b booking.bookings)
187
+ returns jsonb
188
+ language sql
189
+ stable
190
+ set search_path = ''
191
+ as $$
192
+ select jsonb_build_object(
193
+ 'reference', b.reference,
194
+ 'status', booking.effective_status(b.status, b.hold_expires_at),
195
+ 'startsAt', booking.iso(b.starts_at),
196
+ 'endsAt', booking.iso(b.ends_at),
197
+ 'date', to_char(b.starts_at at time zone s.timezone, 'YYYY-MM-DD'),
198
+ 'time', to_char(b.starts_at at time zone s.timezone, 'HH24:MI'),
199
+ 'serviceName', b.service_name,
200
+ 'timezone', s.timezone,
201
+ 'holdExpiresAt', case when b.status = 'pending' then booking.iso(b.hold_expires_at) end
202
+ )
203
+ from booking.settings s
204
+ where s.id;
205
+ $$;
206
+
207
+ -- Everything an email about one booking needs, captured when it is queued.
208
+ create function booking.booking_email_payload(b booking.bookings, p_include_contact boolean)
209
+ returns jsonb
210
+ language sql
211
+ stable
212
+ set search_path = ''
213
+ as $$
214
+ select jsonb_strip_nulls(jsonb_build_object(
215
+ 'businessName', s.business_name,
216
+ 'businessEmail', s.public_email,
217
+ 'businessPhone', s.public_phone,
218
+ 'address', s.address,
219
+ 'timezone', s.timezone,
220
+ 'locale', s.locale,
221
+ 'currency', b.currency,
222
+ 'reference', b.reference,
223
+ 'serviceName', b.service_name,
224
+ 'startsAt', booking.iso(b.starts_at),
225
+ 'endsAt', booking.iso(b.ends_at),
226
+ 'priceCents', b.price_cents,
227
+ 'status', b.status,
228
+ 'holdExpiresAt', case when b.status = 'pending' then booking.iso(b.hold_expires_at) end,
229
+ 'customerName', b.customer_name,
230
+ 'customerEmail', case when p_include_contact then b.customer_email end,
231
+ 'customerPhone', case when p_include_contact then b.customer_phone end,
232
+ 'notes', case when p_include_contact then b.customer_notes end
233
+ ))
234
+ from booking.settings s
235
+ where s.id;
236
+ $$;
237
+
238
+ -- Queue one email, at most once per de-duplication key. No recipient, no email.
239
+ create function booking.enqueue_email(p_kind text, p_recipient text, p_booking_id uuid, p_payload jsonb, p_dedupe_key text)
240
+ returns boolean
241
+ language plpgsql
242
+ volatile
243
+ set search_path = ''
244
+ as $$
245
+ begin
246
+ if p_recipient is null or btrim(p_recipient) = '' then
247
+ return false;
248
+ end if;
249
+ insert into booking.email_outbox (kind, recipient, booking_id, payload, dedupe_key)
250
+ values (p_kind, lower(btrim(p_recipient)), p_booking_id, p_payload, p_dedupe_key)
251
+ on conflict (dedupe_key) do nothing;
252
+ return found;
253
+ end;
254
+ $$;
255
+
256
+ -- Ask the booking-mailer Edge Function to run now (at most once per
257
+ -- transaction; pg_net sends the request after commit). A no-op until pg_net
258
+ -- and the two Vault secrets exist; the scheduled job also starts it. It runs
259
+ -- inside the transaction that queued an email (a booking request, a status
260
+ -- change), so it never raises: a wiring problem must not block a booking —
261
+ -- the email stays queued for the scheduled job and the dashboard shows it.
262
+ create function booking.kick_mailer()
263
+ returns boolean
264
+ language plpgsql
265
+ volatile
266
+ security definer
267
+ set search_path = ''
268
+ as $$
269
+ declare
270
+ v_url text;
271
+ v_key text;
272
+ begin
273
+ if coalesce(current_setting('booking_engine.mailer_kicked', true), '') = 'on' then
274
+ return false;
275
+ end if;
276
+ begin
277
+ if to_regprocedure('net.http_post(text,jsonb,jsonb,jsonb,integer)') is null
278
+ or to_regclass('vault.decrypted_secrets') is null then
279
+ return false;
280
+ end if;
281
+ execute 'select max(d.decrypted_secret) filter (where d.name = $1), max(d.decrypted_secret) filter (where d.name = $2)
282
+ from vault.decrypted_secrets d where d.name in ($1, $2)'
283
+ into v_url, v_key
284
+ using 'booking_engine_mailer_url', 'booking_engine_mailer_key';
285
+ if v_url is null or v_key is null then
286
+ return false;
287
+ end if;
288
+ execute 'select net.http_post(url => $1, body => $2, params => $3, headers => $4, timeout_milliseconds => $5)'
289
+ using v_url, '{}'::jsonb, '{}'::jsonb,
290
+ jsonb_build_object('Content-Type', 'application/json', 'apikey', v_key), 30000;
291
+ exception when others then
292
+ return false;
293
+ end;
294
+ perform set_config('booking_engine.mailer_kicked', 'on', true);
295
+ return true;
296
+ end;
297
+ $$;
298
+ comment on function booking.kick_mailer() is
299
+ 'PRIVILEGED (SECURITY DEFINER), private schema. Starts the booking-mailer Edge Function through pg_net with the secret key kept in Vault (booking_engine_mailer_url, booking_engine_mailer_key).';
300
+
301
+ create function booking.email_outbox_after_insert()
302
+ returns trigger
303
+ language plpgsql
304
+ security definer
305
+ set search_path = ''
306
+ as $$
307
+ begin
308
+ perform booking.kick_mailer();
309
+ return null;
310
+ end;
311
+ $$;
312
+ create trigger email_outbox_kick after insert on booking.email_outbox
313
+ for each row execute function booking.email_outbox_after_insert();
314
+
315
+ -- Release lapsed holds without waiting on rows another transaction is working
316
+ -- on: lapsed verification holds are deleted (with their personal data);
317
+ -- lapsed requests become `expired` and a verified customer is told once.
318
+ -- With a resource and range, only overlapping holds; without, all of them.
319
+ create function booking.expire_lapsed(
320
+ p_resource_id uuid default null,
321
+ p_from timestamptz default null,
322
+ p_to timestamptz default null
323
+ )
324
+ returns int
325
+ language plpgsql
326
+ volatile
327
+ set search_path = ''
328
+ as $$
329
+ declare
330
+ r booking.bookings%rowtype;
331
+ n int;
332
+ begin
333
+ with lapsed as (
334
+ select b.id
335
+ from booking.bookings b
336
+ where b.status = 'unverified'
337
+ and b.hold_expires_at <= now()
338
+ and (p_resource_id is null or (b.resource_id = p_resource_id
339
+ and tstzrange(b.starts_at, b.blocked_until, '[)') && tstzrange(p_from, p_to, '[)')))
340
+ for update skip locked
341
+ )
342
+ delete from booking.bookings b using lapsed l where b.id = l.id;
343
+ get diagnostics n = row_count;
344
+
345
+ for r in
346
+ with lapsed as (
347
+ select b.id
348
+ from booking.bookings b
349
+ where b.status = 'pending'
350
+ and b.hold_expires_at is not null
351
+ and b.hold_expires_at <= now()
352
+ and (p_resource_id is null or (b.resource_id = p_resource_id
353
+ and tstzrange(b.starts_at, b.blocked_until, '[)') && tstzrange(p_from, p_to, '[)')))
354
+ for update skip locked
355
+ )
356
+ update booking.bookings b
357
+ set status = 'expired', status_changed_at = now()
358
+ from lapsed l
359
+ where b.id = l.id
360
+ returning b.*
361
+ loop
362
+ insert into booking.booking_events (booking_id, event_type, from_status, to_status, actor)
363
+ values (r.id, 'status_changed', 'pending', 'expired', 'system');
364
+ if r.email_verified_at is not null then
365
+ perform booking.enqueue_email('request_expired', r.customer_email, r.id,
366
+ booking.booking_email_payload(r, false), 'request_expired:' || r.id);
367
+ end if;
368
+ n := n + 1;
369
+ end loop;
370
+ return n;
371
+ end;
372
+ $$;
373
+
374
+ -- Availability: verification holds block like requests while their hold is
375
+ -- live. p_ignore_booking_id leaves one booking out (rechecking its own time).
376
+ drop function booking.compute_slots(uuid, date, date, timestamptz, uuid);
377
+ create function booking.compute_slots(
378
+ p_service_id uuid,
379
+ p_from date,
380
+ p_to date,
381
+ p_now timestamptz,
382
+ p_resource_id uuid default null,
383
+ p_ignore_booking_id uuid default null
384
+ )
385
+ returns table (starts_at timestamptz, ends_at timestamptz, local_date date)
386
+ language sql
387
+ stable
388
+ set search_path = ''
389
+ as $$
390
+ with s as (
391
+ select st.timezone, st.slot_interval_minutes, st.min_notice_minutes, st.max_advance_days
392
+ from booking.settings st
393
+ where st.id
394
+ ),
395
+ svc as (
396
+ select sv.duration_minutes, sv.buffer_after_minutes
397
+ from booking.services sv
398
+ where sv.id = p_service_id and sv.is_active
399
+ ),
400
+ res as (
401
+ select r.id
402
+ from booking.resources r
403
+ where r.is_active
404
+ and (r.id = p_resource_id or (p_resource_id is null and r.is_default))
405
+ ),
406
+ days as (
407
+ select p_from + g.n as day
408
+ from generate_series(
409
+ 0,
410
+ case
411
+ 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
412
+ else least(p_to - p_from, 400)
413
+ end
414
+ ) as g(n)
415
+ ),
416
+ windows as (
417
+ select dd.day,
418
+ (dd.day + wh.start_time) at time zone s.timezone as open_at,
419
+ (dd.day + wh.end_time) at time zone s.timezone as close_at
420
+ from days dd
421
+ cross join s
422
+ join booking.working_hours wh on wh.weekday = extract(isodow from dd.day)::int
423
+ ),
424
+ candidates as (
425
+ select w.day,
426
+ g.slot_start,
427
+ g.slot_start + make_interval(mins => svc.duration_minutes) as slot_end,
428
+ g.slot_start + make_interval(mins => svc.duration_minutes + svc.buffer_after_minutes) as blocked_until
429
+ from windows w
430
+ cross join svc
431
+ cross join s
432
+ cross join lateral generate_series(
433
+ w.open_at,
434
+ w.close_at - make_interval(mins => svc.duration_minutes),
435
+ make_interval(mins => s.slot_interval_minutes)
436
+ ) as g(slot_start)
437
+ )
438
+ select c.slot_start, c.slot_end, c.day
439
+ from candidates c
440
+ cross join s
441
+ cross join res
442
+ where c.slot_start >= p_now + make_interval(mins => s.min_notice_minutes)
443
+ and c.day <= (p_now at time zone s.timezone)::date + s.max_advance_days
444
+ and not exists (
445
+ select 1
446
+ from booking.bookings b
447
+ where b.resource_id = res.id
448
+ and b.status in ('unverified', 'pending', 'confirmed')
449
+ and (b.status = 'confirmed' or b.hold_expires_at is null or b.hold_expires_at > p_now)
450
+ and (p_ignore_booking_id is null or b.id <> p_ignore_booking_id)
451
+ and tstzrange(b.starts_at, b.blocked_until, '[)') && tstzrange(c.slot_start, c.blocked_until, '[)')
452
+ )
453
+ and not exists (
454
+ select 1
455
+ from booking.availability_exceptions e
456
+ where c.day between e.starts_on and e.ends_on
457
+ and (
458
+ e.start_time is null
459
+ or tstzrange((c.day + e.start_time) at time zone s.timezone,
460
+ (c.day + e.end_time) at time zone s.timezone, '[)')
461
+ && tstzrange(c.slot_start, c.slot_end, '[)')
462
+ )
463
+ )
464
+ order by c.slot_start;
465
+ $$;
466
+
467
+ -- Housekeeping for the mailer and the scheduled job: release lapsed holds,
468
+ -- withdraw code emails that can no longer be used, give up on emails whose
469
+ -- sending keeps being interrupted, apply retention.
470
+ create function booking.run_maintenance()
471
+ returns jsonb
472
+ language plpgsql
473
+ volatile
474
+ security definer
475
+ set search_path = ''
476
+ as $$
477
+ declare
478
+ v_released int;
479
+ v_withdrawn int;
480
+ begin
481
+ v_released := booking.expire_lapsed();
482
+
483
+ update booking.email_outbox o
484
+ set status = 'cancelled', payload = o.payload - 'code', locked_until = null
485
+ where o.kind = 'verification_code'
486
+ and o.status in ('pending', 'sending')
487
+ and (o.locked_until is null or o.locked_until <= now())
488
+ and ((o.payload ->> 'expiresAt')::timestamptz <= now()
489
+ or not exists (select 1 from booking.bookings b where b.id = o.booking_id and b.status = 'unverified'));
490
+ get diagnostics v_withdrawn = row_count;
491
+
492
+ update booking.email_outbox o
493
+ set status = 'failed', locked_until = null,
494
+ payload = case when o.kind = 'verification_code' then o.payload - 'code' else o.payload end,
495
+ last_error = coalesce(o.last_error, 'Sending was interrupted repeatedly')
496
+ where o.status = 'sending' and o.locked_until <= now() and o.attempts >= 5;
497
+
498
+ delete from booking.email_outbox o
499
+ where o.status in ('sent', 'failed', 'cancelled')
500
+ and o.created_at < now() - case when o.kind = 'verification_code' then interval '2 days' else interval '30 days' end;
501
+ delete from booking.verifications v where v.created_at < now() - interval '1 day';
502
+
503
+ return jsonb_build_object('released', v_released, 'withdrawn', v_withdrawn);
504
+ end;
505
+ $$;
506
+ comment on function booking.run_maintenance() is
507
+ 'PRIVILEGED (SECURITY DEFINER), private schema. Releases lapsed holds and keeps the outbox tidy. Used by booking_mailer_claim and booking.mailer_tick.';
508
+
509
+ -- The scheduled job (pg_cron, every minute): maintenance, then start the
510
+ -- mailer only when an email is due.
511
+ create function booking.mailer_tick()
512
+ returns jsonb
513
+ language plpgsql
514
+ volatile
515
+ set search_path = ''
516
+ as $$
517
+ declare
518
+ v jsonb;
519
+ v_kicked boolean := false;
520
+ begin
521
+ v := booking.run_maintenance();
522
+ if exists (
523
+ select 1 from booking.email_outbox o
524
+ where o.status in ('pending', 'sending') and o.next_attempt_at <= now()
525
+ and (o.locked_until is null or o.locked_until <= now())
526
+ ) then
527
+ v_kicked := booking.kick_mailer();
528
+ end if;
529
+ return v || jsonb_build_object('kicked', v_kicked);
530
+ end;
531
+ $$;
532
+ comment on function booking.mailer_tick() is
533
+ 'Run every minute by pg_cron (see `booking-engine mailer-sql`): maintenance, then starts booking-mailer if an email is due.';
534
+
535
+ -- Whether the automatic sending is wired up (booleans only; never values).
536
+ create function booking.mailer_wiring()
537
+ returns jsonb
538
+ language plpgsql
539
+ stable
540
+ security definer
541
+ set search_path = ''
542
+ as $$
543
+ declare
544
+ v_url boolean := false;
545
+ v_key boolean := false;
546
+ v_schedule boolean := false;
547
+ v_net boolean := false;
548
+ begin
549
+ -- Optional extensions: missing or unreadable means "not set up", never an error.
550
+ begin
551
+ if to_regclass('vault.secrets') is not null then
552
+ execute 'select coalesce(bool_or(s.name = $1), false), coalesce(bool_or(s.name = $2), false)
553
+ from vault.secrets s where s.name in ($1, $2)'
554
+ into v_url, v_key
555
+ using 'booking_engine_mailer_url', 'booking_engine_mailer_key';
556
+ end if;
557
+ exception when others then
558
+ v_url := false;
559
+ v_key := false;
560
+ end;
561
+ begin
562
+ if to_regclass('cron.job') is not null then
563
+ execute 'select exists (select 1 from cron.job j where j.jobname = $1 and j.active)'
564
+ into v_schedule
565
+ using 'booking-engine-mailer';
566
+ end if;
567
+ exception when others then
568
+ v_schedule := false;
569
+ end;
570
+ begin
571
+ v_net := to_regprocedure('net.http_post(text,jsonb,jsonb,jsonb,integer)') is not null;
572
+ exception when others then
573
+ v_net := false;
574
+ end;
575
+ return jsonb_build_object('pgNet', v_net, 'mailerUrl', v_url, 'mailerKey', v_key, 'schedule', v_schedule);
576
+ end;
577
+ $$;
578
+
579
+ -- ----------------------------------------------------------------------------
580
+ -- Privileged booking operations (private schema, not reachable by URL)
581
+ -- ----------------------------------------------------------------------------
582
+
583
+ create function booking.request_booking(
584
+ p_service_id uuid,
585
+ p_starts_at timestamptz,
586
+ p_customer_name text,
587
+ p_customer_email text,
588
+ p_customer_phone text default null,
589
+ p_notes text default null
590
+ )
591
+ returns jsonb
592
+ language plpgsql
593
+ volatile
594
+ security definer
595
+ set search_path = ''
596
+ as $$
597
+ declare
598
+ c_client_limit_per_hour constant int := 10;
599
+ c_codes_per_address_per_hour constant int := 5;
600
+ c_codes_per_address_per_day constant int := 10;
601
+ v_settings booking.settings%rowtype;
602
+ v_service booking.services%rowtype;
603
+ v_resource_id uuid;
604
+ v_name text := btrim(coalesce(p_customer_name, ''));
605
+ v_email text := lower(btrim(coalesce(p_customer_email, '')));
606
+ v_phone text := nullif(btrim(coalesce(p_customer_phone, '')), '');
607
+ v_notes text := nullif(btrim(coalesce(p_notes, '')), '');
608
+ v_local_day date;
609
+ v_blocked_until timestamptz;
610
+ v_hold timestamptz;
611
+ v_client text;
612
+ v_bucket text;
613
+ v_limit int;
614
+ v_hour int;
615
+ v_day int;
616
+ v_booking booking.bookings%rowtype;
617
+ v_request_id uuid := gen_random_uuid();
618
+ v_code text;
619
+ v_attempt int := 0;
620
+ begin
621
+ -- 1. The request itself (cheap, no table access).
622
+ if p_service_id is null then
623
+ perform booking.raise_error('INVALID_INPUT', 'serviceId');
624
+ end if;
625
+ if p_starts_at is null or not isfinite(p_starts_at) then
626
+ perform booking.raise_error('INVALID_INPUT', 'startsAt');
627
+ end if;
628
+ if char_length(v_name) < 1 or char_length(v_name) > 120 or v_name ~ '[[:cntrl:]]' then
629
+ perform booking.raise_error('INVALID_INPUT', 'customer.name');
630
+ end if;
631
+ if char_length(v_email) > 254
632
+ or v_email !~ '^[^@[:space:]<>()]+@[^@[:space:]<>()]+\.[^@[:space:]<>()]{2,}$' then
633
+ perform booking.raise_error('INVALID_INPUT', 'customer.email');
634
+ end if;
635
+ if v_phone is not null and (
636
+ char_length(v_phone) > 40
637
+ or v_phone !~ '^[0-9+()./[:space:]-]+$'
638
+ or char_length(regexp_replace(v_phone, '[^0-9]', '', 'g')) < 5) then
639
+ perform booking.raise_error('INVALID_INPUT', 'customer.phone');
640
+ end if;
641
+ if v_notes is not null and (char_length(v_notes) > 1000 or v_notes ~ '[\x01-\x08\x0B\x0C\x0E-\x1F\x7F]') then
642
+ perform booking.raise_error('INVALID_INPUT', 'notes');
643
+ end if;
644
+
645
+ select * into v_settings from booking.settings where id;
646
+ if not v_settings.online_booking_enabled then
647
+ perform booking.raise_error('BOOKING_DISABLED');
648
+ end if;
649
+ if v_settings.require_phone and v_phone is null then
650
+ perform booking.raise_error('INVALID_INPUT', 'customer.phone');
651
+ end if;
652
+
653
+ -- 2. Only times inside the booking window are worth checking.
654
+ if p_starts_at < now() or p_starts_at > now() + make_interval(days => v_settings.max_advance_days + 1) then
655
+ perform booking.raise_error('SLOT_UNAVAILABLE');
656
+ end if;
657
+ select * into v_service from booking.services where id = p_service_id and is_active;
658
+ if not found then
659
+ perform booking.raise_error('SERVICE_UNAVAILABLE');
660
+ end if;
661
+ select r.id into v_resource_id from booking.resources r where r.is_default and r.is_active;
662
+ if v_resource_id is null then
663
+ perform booking.raise_error('SLOT_UNAVAILABLE');
664
+ end if;
665
+
666
+ -- 3. Abuse and cost limits. They count code emails and requests, never
667
+ -- bookings, so a refusal says nothing about anyone's appointments.
668
+ -- Lock order everywhere: address, client, site, then rows.
669
+ perform pg_advisory_xact_lock(hashtextextended('booking_engine:email:' || v_email, 0));
670
+ select count(*) filter (where o.created_at > now() - interval '1 hour'), count(*)
671
+ into v_hour, v_day
672
+ from booking.email_outbox o
673
+ where o.recipient = v_email and o.kind = 'verification_code' and o.created_at > now() - interval '1 day';
674
+ if v_hour >= c_codes_per_address_per_hour or v_day >= c_codes_per_address_per_day then
675
+ perform booking.raise_error('RATE_LIMITED');
676
+ end if;
677
+
678
+ v_client := booking.client_key();
679
+ v_bucket := 'client:' || encode(sha256(convert_to(
680
+ (select es.hash_salt from booking.engine_secrets es where es.id) || ':' || v_client, 'UTF8')), 'hex');
681
+ perform pg_advisory_xact_lock(hashtextextended('booking_engine:' || v_bucket, 0));
682
+ v_limit := case when v_client = 'unknown' then v_settings.max_website_bookings_per_hour else c_client_limit_per_hour end;
683
+ select count(*) into v_hour
684
+ from booking.request_log r
685
+ where r.bucket = v_bucket and r.created_at > now() - interval '1 hour';
686
+ if v_hour >= v_limit then
687
+ perform booking.raise_error('RATE_LIMITED');
688
+ end if;
689
+
690
+ perform pg_advisory_xact_lock(hashtextextended('booking_engine:site', 0));
691
+ select count(*) into v_hour
692
+ from booking.request_log r
693
+ where r.bucket = 'site' and r.created_at > now() - interval '1 hour';
694
+ if v_hour >= v_settings.max_website_bookings_per_hour then
695
+ perform booking.raise_error('RATE_LIMITED');
696
+ end if;
697
+ select count(*) into v_day
698
+ from booking.email_outbox o
699
+ where o.kind = 'verification_code' and o.created_at > now() - interval '1 day';
700
+ if v_day >= v_settings.max_verification_emails_per_day then
701
+ perform booking.raise_error('RATE_LIMITED');
702
+ end if;
703
+
704
+ -- 4. One open verification per address: a new request replaces the last
705
+ -- one (its time becomes free again, also for this customer).
706
+ delete from booking.bookings b where b.status = 'unverified' and lower(b.customer_email) = v_email;
707
+
708
+ -- 5. The start must be a slot the engine offers right now.
709
+ v_local_day := (p_starts_at at time zone v_settings.timezone)::date;
710
+ if not exists (
711
+ select 1
712
+ from booking.compute_slots(p_service_id, v_local_day, v_local_day, now(), v_resource_id) as cs
713
+ where cs.starts_at = p_starts_at
714
+ ) then
715
+ perform booking.raise_error('SLOT_UNAVAILABLE');
716
+ end if;
717
+
718
+ -- 6. Release lapsed holds overlapping this time, then hold it briefly.
719
+ v_blocked_until := p_starts_at + make_interval(mins => v_service.duration_minutes + v_service.buffer_after_minutes);
720
+ perform booking.expire_lapsed(v_resource_id, p_starts_at, v_blocked_until);
721
+ v_hold := least(now() + make_interval(mins => v_settings.verification_window_minutes), p_starts_at);
722
+ loop
723
+ v_attempt := v_attempt + 1;
724
+ begin
725
+ insert into booking.bookings (
726
+ reference, service_id, resource_id, starts_at, ends_at, blocked_until, status, hold_expires_at,
727
+ customer_name, customer_email, customer_phone, customer_notes,
728
+ service_name, price_cents, currency, source
729
+ ) values (
730
+ booking.new_reference(), v_service.id, v_resource_id, p_starts_at,
731
+ p_starts_at + make_interval(mins => v_service.duration_minutes),
732
+ v_blocked_until, 'unverified', v_hold,
733
+ v_name, v_email, v_phone, v_notes,
734
+ v_service.name, v_service.price_cents, v_settings.currency, 'website'
735
+ )
736
+ returning * into v_booking;
737
+ exit;
738
+ exception
739
+ when exclusion_violation then
740
+ perform booking.raise_error('SLOT_UNAVAILABLE');
741
+ when unique_violation then
742
+ if v_attempt >= 3 then
743
+ raise;
744
+ end if;
745
+ end;
746
+ end loop;
747
+
748
+ insert into booking.booking_events (booking_id, event_type, to_status, actor)
749
+ values (v_booking.id, 'created', 'unverified', 'customer');
750
+
751
+ -- 7. The one-time code (stored only as a salted hash) and its email. The
752
+ -- email carries no text the requester typed: it may reach someone who
753
+ -- never asked for it.
754
+ v_code := booking.new_code();
755
+ insert into booking.verifications (id, booking_id, code_hash, expires_at)
756
+ values (v_request_id, v_booking.id, booking.code_hash(v_request_id, v_code), v_hold);
757
+ perform booking.enqueue_email('verification_code', v_email, v_booking.id,
758
+ (booking.booking_email_payload(v_booking, false) - 'customerName' - 'status')
759
+ || jsonb_build_object('code', v_code, 'expiresAt', booking.iso(v_hold),
760
+ 'minutesValid', v_settings.verification_window_minutes),
761
+ 'verification_code:' || v_request_id || ':1');
762
+
763
+ insert into booking.request_log (bucket) values (v_bucket), ('site');
764
+ delete from booking.request_log r where r.created_at < now() - interval '1 day';
765
+
766
+ return jsonb_build_object(
767
+ 'requestId', v_request_id,
768
+ 'expiresAt', booking.iso(v_hold),
769
+ 'email', booking.mask_email(v_email),
770
+ 'codeLength', 6,
771
+ 'resendAfterSeconds', 60,
772
+ 'resendsLeft', 3
773
+ );
774
+ end;
775
+ $$;
776
+ comment on function booking.request_booking(uuid, timestamptz, text, text, text, text) is
777
+ 'PRIVILEGED (SECURITY DEFINER), private schema. Validates and rate-limits a booking request, holds its time only for the verification window and queues a one-time code email. Reached through public.booking_request.';
778
+
779
+ create function booking.verify_booking(p_request_id uuid, p_code text)
780
+ returns jsonb
781
+ language plpgsql
782
+ volatile
783
+ security definer
784
+ set search_path = ''
785
+ as $$
786
+ declare
787
+ c_max_attempts constant int := 5;
788
+ v_code text := regexp_replace(coalesce(p_code, ''), '[[:space:]-]', '', 'g');
789
+ v booking.verifications%rowtype;
790
+ b booking.bookings%rowtype;
791
+ v_settings booking.settings%rowtype;
792
+ v_local_day date;
793
+ v_count int;
794
+ v_status text;
795
+ begin
796
+ if p_request_id is null then
797
+ perform booking.raise_error('INVALID_INPUT', 'requestId');
798
+ end if;
799
+ if v_code !~ '^[0-9]{6}$' then
800
+ perform booking.raise_error('INVALID_INPUT', 'code');
801
+ end if;
802
+
803
+ -- Results are returned, not raised, so counted attempts are kept.
804
+ select * into v from booking.verifications where id = p_request_id for update;
805
+ if not found then
806
+ return jsonb_build_object('result', 'expired');
807
+ end if;
808
+ select * into b from booking.bookings where id = v.booking_id for update;
809
+
810
+ -- Already verified: the same code gives the same answer (retries, double clicks).
811
+ if v.verified_at is not null then
812
+ if b.id is not null and v.code_hash = booking.code_hash(v.id, v_code) then
813
+ return jsonb_build_object('result', 'verified', 'booking', booking.public_booking_json(b));
814
+ end if;
815
+ return jsonb_build_object('result', 'invalid_code', 'attemptsLeft', 0);
816
+ end if;
817
+
818
+ if v.attempts >= c_max_attempts then
819
+ if b.id is not null and b.status = 'unverified' then
820
+ delete from booking.bookings where id = b.id;
821
+ end if;
822
+ return jsonb_build_object('result', 'locked');
823
+ end if;
824
+
825
+ if b.id is null or b.status <> 'unverified' or v.expires_at <= now() or b.hold_expires_at <= now() then
826
+ if b.id is not null and b.status = 'unverified' then
827
+ delete from booking.bookings where id = b.id;
828
+ end if;
829
+ return jsonb_build_object('result', 'expired');
830
+ end if;
831
+
832
+ if v.code_hash <> booking.code_hash(v.id, v_code) then
833
+ update booking.verifications set attempts = attempts + 1 where id = v.id returning * into v;
834
+ if v.attempts >= c_max_attempts then
835
+ delete from booking.bookings where id = b.id;
836
+ return jsonb_build_object('result', 'locked');
837
+ end if;
838
+ return jsonb_build_object('result', 'invalid_code', 'attemptsLeft', c_max_attempts - v.attempts);
839
+ end if;
840
+
841
+ -- The code is right. Recheck the time as it was offered when requested:
842
+ -- the hold kept other customers out, but the owner may have closed it.
843
+ select * into v_settings from booking.settings where id;
844
+ v_local_day := (b.starts_at at time zone v_settings.timezone)::date;
845
+ if b.starts_at <= now() or not exists (
846
+ select 1
847
+ from booking.compute_slots(b.service_id, v_local_day, v_local_day, b.created_at, b.resource_id, b.id) as cs
848
+ where cs.starts_at = b.starts_at
849
+ ) then
850
+ delete from booking.bookings where id = b.id;
851
+ return jsonb_build_object('result', 'slot_unavailable');
852
+ end if;
853
+
854
+ -- The per-address cap applies only now: the person asking owns the address.
855
+ perform pg_advisory_xact_lock(hashtextextended('booking_engine:verified:' || lower(b.customer_email), 0));
856
+ select count(*) into v_count
857
+ from booking.bookings x
858
+ where lower(x.customer_email) = lower(b.customer_email)
859
+ and x.id <> b.id
860
+ and x.status in ('pending', 'confirmed')
861
+ and (x.status = 'confirmed' or x.hold_expires_at is null or x.hold_expires_at > now())
862
+ and x.starts_at > now();
863
+ if v_count >= v_settings.max_active_bookings_per_email then
864
+ delete from booking.bookings where id = b.id;
865
+ return jsonb_build_object('result', 'too_many_bookings');
866
+ end if;
867
+
868
+ v_status := case when v_settings.auto_confirm then 'confirmed' else 'pending' end;
869
+ update booking.bookings
870
+ set status = v_status,
871
+ email_verified_at = now(),
872
+ status_changed_at = now(),
873
+ hold_expires_at = case when v_status = 'pending'
874
+ then least(now() + make_interval(mins => v_settings.pending_hold_minutes), b.starts_at) end
875
+ where id = b.id
876
+ returning * into b;
877
+ update booking.verifications set verified_at = now() where id = v.id;
878
+
879
+ insert into booking.booking_events (booking_id, event_type, from_status, to_status, actor)
880
+ values (b.id, 'status_changed', 'unverified', v_status, 'customer');
881
+
882
+ perform booking.enqueue_email(
883
+ case when v_status = 'confirmed' then 'booking_confirmed' else 'request_received' end,
884
+ b.customer_email, b.id, booking.booking_email_payload(b, false),
885
+ case when v_status = 'confirmed' then 'booking_confirmed:' else 'request_received:' end || b.id);
886
+ perform booking.enqueue_email('owner_new_request',
887
+ coalesce(v_settings.owner_notification_email, v_settings.public_email), b.id,
888
+ booking.booking_email_payload(b, true), 'owner_new_request:' || b.id);
889
+
890
+ return jsonb_build_object('result', 'verified', 'booking', booking.public_booking_json(b));
891
+ end;
892
+ $$;
893
+ comment on function booking.verify_booking(uuid, text) is
894
+ 'PRIVILEGED (SECURITY DEFINER), private schema. Checks a one-time code (5 attempts, single use), rechecks the time and turns the hold into a request or a confirmed booking; queues the customer and owner emails. Idempotent. Reached through public.booking_verify.';
895
+
896
+ create function booking.resend_code(p_request_id uuid)
897
+ returns jsonb
898
+ language plpgsql
899
+ volatile
900
+ security definer
901
+ set search_path = ''
902
+ as $$
903
+ declare
904
+ c_max_sends constant int := 4; -- the first email and 3 re-sends
905
+ c_codes_per_address_per_hour constant int := 5;
906
+ c_codes_per_address_per_day constant int := 10;
907
+ v_email text;
908
+ v booking.verifications%rowtype;
909
+ b booking.bookings%rowtype;
910
+ v_settings booking.settings%rowtype;
911
+ v_hour int;
912
+ v_day int;
913
+ v_code text;
914
+ begin
915
+ if p_request_id is null then
916
+ perform booking.raise_error('INVALID_INPUT', 'requestId');
917
+ end if;
918
+
919
+ -- Advisory locks first (address, site), then rows: the order request_booking uses.
920
+ select lower(x.customer_email) into v_email
921
+ from booking.verifications vv
922
+ join booking.bookings x on x.id = vv.booking_id
923
+ where vv.id = p_request_id;
924
+ if v_email is null then
925
+ return jsonb_build_object('result', 'expired');
926
+ end if;
927
+ perform pg_advisory_xact_lock(hashtextextended('booking_engine:email:' || v_email, 0));
928
+ perform pg_advisory_xact_lock(hashtextextended('booking_engine:site', 0));
929
+
930
+ select * into v from booking.verifications where id = p_request_id for update;
931
+ select * into b from booking.bookings where id = v.booking_id for update;
932
+ if v.verified_at is not null then
933
+ return jsonb_build_object('result', 'verified');
934
+ end if;
935
+ if b.id is null or b.status <> 'unverified' or v.attempts >= 5
936
+ or v.expires_at <= now() or b.hold_expires_at <= now() then
937
+ if b.id is not null and b.status = 'unverified' then
938
+ delete from booking.bookings where id = b.id;
939
+ end if;
940
+ return jsonb_build_object('result', 'expired');
941
+ end if;
942
+ if v.sends >= c_max_sends then
943
+ return jsonb_build_object('result', 'limit_reached');
944
+ end if;
945
+ if v.last_sent_at > now() - interval '60 seconds' then
946
+ return jsonb_build_object('result', 'too_soon',
947
+ 'retryAfterSeconds', greatest(1, ceil(60 - extract(epoch from now() - v.last_sent_at))::int));
948
+ end if;
949
+
950
+ select * into v_settings from booking.settings where id;
951
+ select count(*) filter (where o.created_at > now() - interval '1 hour'), count(*)
952
+ into v_hour, v_day
953
+ from booking.email_outbox o
954
+ where o.recipient = v_email and o.kind = 'verification_code' and o.created_at > now() - interval '1 day';
955
+ if v_hour >= c_codes_per_address_per_hour or v_day >= c_codes_per_address_per_day then
956
+ perform booking.raise_error('RATE_LIMITED');
957
+ end if;
958
+ select count(*) into v_day
959
+ from booking.email_outbox o
960
+ where o.kind = 'verification_code' and o.created_at > now() - interval '1 day';
961
+ if v_day >= v_settings.max_verification_emails_per_day then
962
+ perform booking.raise_error('RATE_LIMITED');
963
+ end if;
964
+
965
+ -- A new code; the earlier one stops working. The window is not extended.
966
+ v_code := booking.new_code();
967
+ update booking.verifications
968
+ set code_hash = booking.code_hash(v.id, v_code), attempts = 0, sends = sends + 1, last_sent_at = now()
969
+ where id = v.id
970
+ returning * into v;
971
+ update booking.email_outbox o
972
+ set status = 'cancelled', payload = o.payload - 'code', locked_until = null
973
+ where o.kind = 'verification_code' and o.booking_id = b.id and o.status in ('pending', 'sending');
974
+ perform booking.enqueue_email('verification_code', b.customer_email, b.id,
975
+ (booking.booking_email_payload(b, false) - 'customerName' - 'status')
976
+ || jsonb_build_object('code', v_code, 'expiresAt', booking.iso(v.expires_at),
977
+ 'minutesValid', v_settings.verification_window_minutes),
978
+ 'verification_code:' || v.id || ':' || v.sends);
979
+
980
+ return jsonb_build_object('result', 'sent', 'expiresAt', booking.iso(v.expires_at),
981
+ 'resendsLeft', c_max_sends - v.sends, 'resendAfterSeconds', 60);
982
+ end;
983
+ $$;
984
+ comment on function booking.resend_code(uuid) is
985
+ 'PRIVILEGED (SECURITY DEFINER), private schema. A new one-time code for an open request (at most 3 re-sends, 60 s apart, same expiry). Reached through public.booking_resend_code.';
986
+
987
+ -- The visitor changed their mind (another time, a mistyped address): release
988
+ -- the hold at once instead of keeping the time from everyone until it lapses.
989
+ -- Only the holder of the request id can do this; a verified request is the
990
+ -- owner's to decline.
991
+ create function booking.cancel_request(p_request_id uuid)
992
+ returns jsonb
993
+ language plpgsql
994
+ volatile
995
+ security definer
996
+ set search_path = ''
997
+ as $$
998
+ declare
999
+ v booking.verifications%rowtype;
1000
+ b booking.bookings%rowtype;
1001
+ begin
1002
+ if p_request_id is null then
1003
+ perform booking.raise_error('INVALID_INPUT', 'requestId');
1004
+ end if;
1005
+ select * into v from booking.verifications where id = p_request_id for update;
1006
+ if not found then
1007
+ return jsonb_build_object('result', 'expired');
1008
+ end if;
1009
+ if v.verified_at is not null then
1010
+ return jsonb_build_object('result', 'verified');
1011
+ end if;
1012
+ select * into b from booking.bookings where id = v.booking_id for update;
1013
+ if b.id is null or b.status <> 'unverified' then
1014
+ return jsonb_build_object('result', 'expired');
1015
+ end if;
1016
+ -- Withdraw its unsent code email first (the row keeps no link once the booking is gone).
1017
+ update booking.email_outbox o
1018
+ set status = 'cancelled', payload = o.payload - 'code', locked_until = null
1019
+ where o.kind = 'verification_code' and o.booking_id = b.id and o.status in ('pending', 'sending')
1020
+ and (o.locked_until is null or o.locked_until <= now());
1021
+ delete from booking.bookings where id = b.id;
1022
+ return jsonb_build_object('result', 'cancelled');
1023
+ end;
1024
+ $$;
1025
+ comment on function booking.cancel_request(uuid) is
1026
+ 'PRIVILEGED (SECURITY DEFINER), private schema. Releases an unverified hold for the holder of its request id. Reached through public.booking_cancel_request.';
1027
+
1028
+ -- ----------------------------------------------------------------------------
1029
+ -- Public API
1030
+ -- ----------------------------------------------------------------------------
1031
+
1032
+ create function public.booking_request(
1033
+ p_service_id uuid,
1034
+ p_starts_at timestamptz,
1035
+ p_customer_name text,
1036
+ p_customer_email text,
1037
+ p_customer_phone text default null,
1038
+ p_notes text default null
1039
+ )
1040
+ returns jsonb
1041
+ language sql
1042
+ volatile
1043
+ security invoker
1044
+ set search_path = ''
1045
+ as $$
1046
+ select booking.request_booking(p_service_id, p_starts_at, p_customer_name, p_customer_email, p_customer_phone, p_notes);
1047
+ $$;
1048
+ comment on function public.booking_request(uuid, timestamptz, text, text, text, text) is
1049
+ 'Public. Starts a booking request: holds the time for the verification window and emails a one-time code. Reveals nothing about other bookings.';
1050
+
1051
+ create function public.booking_verify(p_request_id uuid, p_code text)
1052
+ returns jsonb
1053
+ language sql
1054
+ volatile
1055
+ security invoker
1056
+ set search_path = ''
1057
+ as $$
1058
+ select booking.verify_booking(p_request_id, p_code);
1059
+ $$;
1060
+ comment on function public.booking_verify(uuid, text) is
1061
+ 'Public. Checks the one-time code and turns the hold into a request (or a confirmed booking).';
1062
+
1063
+ create function public.booking_resend_code(p_request_id uuid)
1064
+ returns jsonb
1065
+ language sql
1066
+ volatile
1067
+ security invoker
1068
+ set search_path = ''
1069
+ as $$
1070
+ select booking.resend_code(p_request_id);
1071
+ $$;
1072
+ comment on function public.booking_resend_code(uuid) is 'Public. Emails a new one-time code for an open request.';
1073
+
1074
+ create function public.booking_cancel_request(p_request_id uuid)
1075
+ returns jsonb
1076
+ language sql
1077
+ volatile
1078
+ security invoker
1079
+ set search_path = ''
1080
+ as $$
1081
+ select booking.cancel_request(p_request_id);
1082
+ $$;
1083
+ comment on function public.booking_cancel_request(uuid) is
1084
+ 'Public. Releases the caller''s own unverified hold (identified by its request id) so the time is free again at once.';
1085
+
1086
+ -- The unverified path is closed; the signature stays so older sites get a clear error.
1087
+ create or replace function public.booking_create(
1088
+ p_service_id uuid,
1089
+ p_starts_at timestamptz,
1090
+ p_customer_name text,
1091
+ p_customer_email text,
1092
+ p_customer_phone text default null,
1093
+ p_notes text default null
1094
+ )
1095
+ returns jsonb
1096
+ language plpgsql
1097
+ volatile
1098
+ security invoker
1099
+ set search_path = ''
1100
+ as $$
1101
+ begin
1102
+ raise exception using errcode = 'P0001', message = 'booking_engine:VERIFICATION_REQUIRED', detail = '';
1103
+ end;
1104
+ $$;
1105
+ comment on function public.booking_create(uuid, timestamptz, text, text, text, text) is
1106
+ 'Closed since 2.0.0-alpha.4: bookings need a verified email. Use booking_request and booking_verify.';
1107
+ drop function booking.create_booking(uuid, timestamptz, text, text, text, text);
1108
+
1109
+ create or replace function public.booking_get_business()
1110
+ returns jsonb
1111
+ language sql
1112
+ stable
1113
+ security invoker
1114
+ set search_path = ''
1115
+ as $$
1116
+ select jsonb_build_object(
1117
+ 'name', s.business_name,
1118
+ 'timezone', s.timezone,
1119
+ 'currency', s.currency,
1120
+ 'locale', s.locale,
1121
+ 'contact', jsonb_build_object('email', s.public_email, 'phone', s.public_phone, 'address', s.address),
1122
+ 'policies', jsonb_build_object(
1123
+ 'slotIntervalMinutes', s.slot_interval_minutes,
1124
+ 'minNoticeMinutes', s.min_notice_minutes,
1125
+ 'maxAdvanceDays', s.max_advance_days,
1126
+ 'autoConfirm', s.auto_confirm,
1127
+ 'requirePhone', s.require_phone,
1128
+ 'pendingHoldMinutes', s.pending_hold_minutes,
1129
+ 'onlineBookingEnabled', s.online_booking_enabled,
1130
+ 'verificationWindowMinutes', s.verification_window_minutes
1131
+ ),
1132
+ 'openingHours', coalesce((
1133
+ select jsonb_agg(
1134
+ jsonb_build_object('weekday', w.weekday, 'start', booking.hhmm(w.start_time), 'end', booking.hhmm(w.end_time))
1135
+ order by w.weekday, w.start_time)
1136
+ from booking.working_hours w
1137
+ ), '[]'::jsonb)
1138
+ )
1139
+ from booking.settings s
1140
+ where s.id;
1141
+ $$;
1142
+
1143
+ -- ----------------------------------------------------------------------------
1144
+ -- Admin API
1145
+ -- ----------------------------------------------------------------------------
1146
+
1147
+ create or replace function booking.booking_json(b booking.bookings, p_tz text)
1148
+ returns jsonb
1149
+ language sql
1150
+ stable
1151
+ set search_path = ''
1152
+ as $$
1153
+ select jsonb_build_object(
1154
+ 'id', b.id,
1155
+ 'reference', b.reference,
1156
+ 'status', booking.effective_status(b.status, b.hold_expires_at),
1157
+ 'holdExpiresAt', booking.iso(b.hold_expires_at),
1158
+ 'emailVerified', b.email_verified_at is not null,
1159
+ 'startsAt', booking.iso(b.starts_at),
1160
+ 'endsAt', booking.iso(b.ends_at),
1161
+ 'date', to_char(b.starts_at at time zone p_tz, 'YYYY-MM-DD'),
1162
+ 'time', to_char(b.starts_at at time zone p_tz, 'HH24:MI'),
1163
+ 'endTime', to_char(b.ends_at at time zone p_tz, 'HH24:MI'),
1164
+ 'serviceId', b.service_id,
1165
+ 'serviceName', b.service_name,
1166
+ 'priceCents', b.price_cents,
1167
+ 'currency', b.currency,
1168
+ 'customer', jsonb_build_object('name', b.customer_name, 'email', b.customer_email, 'phone', b.customer_phone),
1169
+ 'notes', b.customer_notes,
1170
+ 'source', b.source,
1171
+ 'createdAt', booking.iso(b.created_at),
1172
+ 'statusChangedAt', booking.iso(b.status_changed_at)
1173
+ );
1174
+ $$;
1175
+
1176
+ -- Unverified holds are not requests yet: the owner never sees them.
1177
+ create or replace function public.booking_admin_list_bookings(p_from date, p_to date, p_statuses text[] default null)
1178
+ returns jsonb
1179
+ language plpgsql
1180
+ stable
1181
+ security invoker
1182
+ set search_path = ''
1183
+ as $$
1184
+ declare
1185
+ v_tz text;
1186
+ v_result jsonb;
1187
+ begin
1188
+ perform booking.require_admin();
1189
+ if p_from is null or p_to is null or not isfinite(p_from) or not isfinite(p_to)
1190
+ or p_to < p_from or p_to - p_from > 400 then
1191
+ perform booking.raise_error('INVALID_INPUT', 'range');
1192
+ end if;
1193
+ if p_statuses is not null and exists (
1194
+ select 1 from unnest(p_statuses) as st(v)
1195
+ where st.v is null or st.v not in ('pending', 'confirmed', 'completed', 'cancelled', 'no_show', 'expired')) then
1196
+ perform booking.raise_error('INVALID_INPUT', 'statuses');
1197
+ end if;
1198
+
1199
+ select s.timezone into v_tz from booking.settings s where s.id;
1200
+
1201
+ select coalesce(jsonb_agg(booking.booking_json(b, v_tz) order by b.starts_at), '[]'::jsonb)
1202
+ into v_result
1203
+ from booking.bookings b
1204
+ where b.id in (
1205
+ select b2.id
1206
+ from booking.bookings b2
1207
+ where b2.status <> 'unverified'
1208
+ and b2.starts_at >= (p_from::timestamp at time zone v_tz)
1209
+ and b2.starts_at < ((p_to + 1)::timestamp at time zone v_tz)
1210
+ and (p_statuses is null or booking.effective_status(b2.status, b2.hold_expires_at) = any (p_statuses))
1211
+ order by b2.starts_at
1212
+ limit 1000
1213
+ );
1214
+ return v_result;
1215
+ end;
1216
+ $$;
1217
+
1218
+ create or replace function public.booking_admin_set_booking_status(p_booking_id uuid, p_status text)
1219
+ returns jsonb
1220
+ language plpgsql
1221
+ volatile
1222
+ security invoker
1223
+ set search_path = ''
1224
+ as $$
1225
+ declare
1226
+ v_uid uuid;
1227
+ v_tz text;
1228
+ b booking.bookings%rowtype;
1229
+ v_from text;
1230
+ v_stored text;
1231
+ begin
1232
+ v_uid := booking.require_admin();
1233
+ if p_status is null or p_status not in ('confirmed', 'cancelled', 'completed', 'no_show') then
1234
+ perform booking.raise_error('INVALID_INPUT', 'status');
1235
+ end if;
1236
+
1237
+ select * into b from booking.bookings where id = p_booking_id for update;
1238
+ if not found or b.status = 'unverified' then
1239
+ perform booking.raise_error('NOT_FOUND', 'booking');
1240
+ end if;
1241
+ select s.timezone into v_tz from booking.settings s where s.id;
1242
+
1243
+ v_stored := b.status;
1244
+ v_from := booking.effective_status(b.status, b.hold_expires_at);
1245
+ if v_from = p_status then
1246
+ return booking.booking_json(b, v_tz);
1247
+ end if;
1248
+ if not (
1249
+ (v_from in ('pending', 'expired') and p_status in ('confirmed', 'cancelled'))
1250
+ or (v_from = 'confirmed' and p_status in ('cancelled', 'completed', 'no_show'))
1251
+ ) then
1252
+ perform booking.raise_error('INVALID_TRANSITION', v_from || '->' || p_status);
1253
+ end if;
1254
+ if p_status in ('completed', 'no_show') and b.starts_at > now() then
1255
+ perform booking.raise_error('INVALID_TRANSITION', 'not_started');
1256
+ end if;
1257
+
1258
+ begin
1259
+ update booking.bookings
1260
+ set status = p_status, hold_expires_at = null, status_changed_at = now()
1261
+ where id = b.id
1262
+ returning * into b;
1263
+ exception
1264
+ when exclusion_violation then
1265
+ -- An expired request's time was taken by someone else meanwhile.
1266
+ perform booking.raise_error('CONFLICT', 'slot_taken');
1267
+ end;
1268
+
1269
+ insert into booking.booking_events (booking_id, event_type, from_status, to_status, actor, actor_user_id)
1270
+ values (b.id, 'status_changed', v_from, p_status, 'admin', v_uid);
1271
+
1272
+ -- Tell the customer. Only verified addresses are emailed; a customer whose
1273
+ -- request was already reported as expired is not told twice.
1274
+ if b.email_verified_at is not null then
1275
+ if p_status = 'confirmed' then
1276
+ perform booking.enqueue_email('booking_confirmed', b.customer_email, b.id,
1277
+ booking.booking_email_payload(b, false), 'booking_confirmed:' || b.id);
1278
+ elsif p_status = 'cancelled' and v_from = 'confirmed' then
1279
+ perform booking.enqueue_email('booking_cancelled', b.customer_email, b.id,
1280
+ booking.booking_email_payload(b, false), 'booking_cancelled:' || b.id);
1281
+ elsif p_status = 'cancelled' and v_stored = 'pending' then
1282
+ perform booking.enqueue_email('booking_declined', b.customer_email, b.id,
1283
+ booking.booking_email_payload(b, false), 'booking_declined:' || b.id);
1284
+ end if;
1285
+ end if;
1286
+
1287
+ return booking.booking_json(b, v_tz);
1288
+ end;
1289
+ $$;
1290
+
1291
+ create or replace function booking.settings_json()
1292
+ returns jsonb
1293
+ language sql
1294
+ stable
1295
+ set search_path = ''
1296
+ as $$
1297
+ select jsonb_build_object(
1298
+ 'businessName', s.business_name,
1299
+ 'timezone', s.timezone,
1300
+ 'currency', s.currency,
1301
+ 'locale', s.locale,
1302
+ 'publicEmail', s.public_email,
1303
+ 'publicPhone', s.public_phone,
1304
+ 'address', s.address,
1305
+ 'slotIntervalMinutes', s.slot_interval_minutes,
1306
+ 'minNoticeMinutes', s.min_notice_minutes,
1307
+ 'maxAdvanceDays', s.max_advance_days,
1308
+ 'autoConfirm', s.auto_confirm,
1309
+ 'requirePhone', s.require_phone,
1310
+ 'maxActiveBookingsPerEmail', s.max_active_bookings_per_email,
1311
+ 'maxWebsiteBookingsPerHour', s.max_website_bookings_per_hour,
1312
+ 'pendingHoldMinutes', s.pending_hold_minutes,
1313
+ 'ownerNotificationEmail', s.owner_notification_email,
1314
+ 'verificationWindowMinutes', s.verification_window_minutes,
1315
+ 'maxVerificationEmailsPerDay', s.max_verification_emails_per_day,
1316
+ 'onlineBookingEnabled', s.online_booking_enabled,
1317
+ 'updatedAt', booking.iso(s.updated_at)
1318
+ )
1319
+ from booking.settings s
1320
+ where s.id;
1321
+ $$;
1322
+
1323
+ create or replace function public.booking_admin_update_settings(p_settings jsonb)
1324
+ returns jsonb
1325
+ language plpgsql
1326
+ volatile
1327
+ security invoker
1328
+ set search_path = ''
1329
+ as $$
1330
+ declare
1331
+ v_allowed text[] := array['businessName', 'timezone', 'currency', 'locale', 'publicEmail', 'publicPhone',
1332
+ 'address', 'slotIntervalMinutes', 'minNoticeMinutes', 'maxAdvanceDays',
1333
+ 'autoConfirm', 'requirePhone', 'maxActiveBookingsPerEmail',
1334
+ 'maxWebsiteBookingsPerHour', 'pendingHoldMinutes', 'ownerNotificationEmail',
1335
+ 'verificationWindowMinutes', 'maxVerificationEmailsPerDay', 'onlineBookingEnabled'];
1336
+ c_email_re constant text := '^[^@[:space:]<>()]+@[^@[:space:]<>()]+\.[^@[:space:]<>()]{2,}$';
1337
+ v_key text;
1338
+ v_email text;
1339
+ v_owner_email text;
1340
+ begin
1341
+ perform booking.require_admin();
1342
+ if p_settings is null or jsonb_typeof(p_settings) <> 'object' then
1343
+ perform booking.raise_error('INVALID_INPUT', 'settings');
1344
+ end if;
1345
+ for v_key in select jsonb_object_keys(p_settings) loop
1346
+ if not (v_key = any (v_allowed)) then
1347
+ perform booking.raise_error('INVALID_INPUT', v_key);
1348
+ end if;
1349
+ end loop;
1350
+
1351
+ v_email := lower(booking.j_text(p_settings, 'publicEmail', 254));
1352
+ if v_email is not null and v_email !~ c_email_re then
1353
+ perform booking.raise_error('INVALID_INPUT', 'publicEmail');
1354
+ end if;
1355
+ v_owner_email := lower(booking.j_text(p_settings, 'ownerNotificationEmail', 254));
1356
+ if v_owner_email is not null and v_owner_email !~ c_email_re then
1357
+ perform booking.raise_error('INVALID_INPUT', 'ownerNotificationEmail');
1358
+ end if;
1359
+ if p_settings ? 'currency' and coalesce(booking.j_text(p_settings, 'currency', 3), '') !~ '^[A-Z]{3}$' then
1360
+ perform booking.raise_error('INVALID_INPUT', 'currency');
1361
+ end if;
1362
+ if p_settings ? 'locale'
1363
+ and coalesce(booking.j_text(p_settings, 'locale', 35), '') !~ '^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$' then
1364
+ perform booking.raise_error('INVALID_INPUT', 'locale');
1365
+ end if;
1366
+ if coalesce(booking.j_bool(p_settings, 'onlineBookingEnabled'), false)
1367
+ and not exists (select 1 from booking.mailer_state m where m.id and m.last_success_at is not null) then
1368
+ -- Customers must be able to receive their code: deliver a test email first.
1369
+ perform booking.raise_error('INVALID_INPUT', 'onlineBookingEnabled');
1370
+ end if;
1371
+
1372
+ update booking.settings set
1373
+ business_name = case when p_settings ? 'businessName'
1374
+ then booking.j_required_text(p_settings, 'businessName', 120) else business_name end,
1375
+ timezone = case when p_settings ? 'timezone' then booking.j_required_text(p_settings, 'timezone', 64) else timezone end,
1376
+ currency = case when p_settings ? 'currency' then booking.j_required_text(p_settings, 'currency', 3) else currency end,
1377
+ locale = case when p_settings ? 'locale' then booking.j_required_text(p_settings, 'locale', 35) else locale end,
1378
+ public_email = case when p_settings ? 'publicEmail' then v_email else public_email end,
1379
+ public_phone = case when p_settings ? 'publicPhone' then booking.j_text(p_settings, 'publicPhone', 40) else public_phone end,
1380
+ address = case when p_settings ? 'address' then booking.j_text(p_settings, 'address', 300) else address end,
1381
+ slot_interval_minutes = case when p_settings ? 'slotIntervalMinutes'
1382
+ then coalesce(booking.j_int(p_settings, 'slotIntervalMinutes', 5, 240), slot_interval_minutes) else slot_interval_minutes end,
1383
+ min_notice_minutes = case when p_settings ? 'minNoticeMinutes'
1384
+ then coalesce(booking.j_int(p_settings, 'minNoticeMinutes', 0, 43200), min_notice_minutes) else min_notice_minutes end,
1385
+ max_advance_days = case when p_settings ? 'maxAdvanceDays'
1386
+ then coalesce(booking.j_int(p_settings, 'maxAdvanceDays', 1, 730), max_advance_days) else max_advance_days end,
1387
+ auto_confirm = case when p_settings ? 'autoConfirm'
1388
+ then coalesce(booking.j_bool(p_settings, 'autoConfirm'), auto_confirm) else auto_confirm end,
1389
+ require_phone = case when p_settings ? 'requirePhone'
1390
+ then coalesce(booking.j_bool(p_settings, 'requirePhone'), require_phone) else require_phone end,
1391
+ max_active_bookings_per_email = case when p_settings ? 'maxActiveBookingsPerEmail'
1392
+ then coalesce(booking.j_int(p_settings, 'maxActiveBookingsPerEmail', 1, 50), max_active_bookings_per_email)
1393
+ else max_active_bookings_per_email end,
1394
+ max_website_bookings_per_hour = case when p_settings ? 'maxWebsiteBookingsPerHour'
1395
+ then coalesce(booking.j_int(p_settings, 'maxWebsiteBookingsPerHour', 1, 1000), max_website_bookings_per_hour)
1396
+ else max_website_bookings_per_hour end,
1397
+ pending_hold_minutes = case when p_settings ? 'pendingHoldMinutes'
1398
+ then coalesce(booking.j_int(p_settings, 'pendingHoldMinutes', 15, 10080), pending_hold_minutes)
1399
+ else pending_hold_minutes end,
1400
+ owner_notification_email = case when p_settings ? 'ownerNotificationEmail' then v_owner_email else owner_notification_email end,
1401
+ verification_window_minutes = case when p_settings ? 'verificationWindowMinutes'
1402
+ then coalesce(booking.j_int(p_settings, 'verificationWindowMinutes', 5, 30), verification_window_minutes)
1403
+ else verification_window_minutes end,
1404
+ max_verification_emails_per_day = case when p_settings ? 'maxVerificationEmailsPerDay'
1405
+ then coalesce(booking.j_int(p_settings, 'maxVerificationEmailsPerDay', 1, 5000), max_verification_emails_per_day)
1406
+ else max_verification_emails_per_day end,
1407
+ online_booking_enabled = case when p_settings ? 'onlineBookingEnabled'
1408
+ then coalesce(booking.j_bool(p_settings, 'onlineBookingEnabled'), online_booking_enabled)
1409
+ else online_booking_enabled end
1410
+ where id;
1411
+
1412
+ return booking.settings_json();
1413
+ end;
1414
+ $$;
1415
+
1416
+ create function public.booking_admin_email_status()
1417
+ returns jsonb
1418
+ language plpgsql
1419
+ stable
1420
+ security invoker
1421
+ set search_path = ''
1422
+ as $$
1423
+ declare
1424
+ v_result jsonb;
1425
+ begin
1426
+ perform booking.require_admin();
1427
+ select jsonb_build_object(
1428
+ 'mailer', (select jsonb_build_object(
1429
+ 'lastAttemptAt', booking.iso(m.last_attempt_at),
1430
+ 'lastSuccessAt', booking.iso(m.last_success_at),
1431
+ 'lastFailureAt', booking.iso(m.last_failure_at),
1432
+ 'lastError', m.last_error)
1433
+ from booking.mailer_state m where m.id),
1434
+ 'wiring', booking.mailer_wiring(),
1435
+ 'counts', (select jsonb_build_object(
1436
+ 'queued', count(*) filter (where o.status in ('pending', 'sending')),
1437
+ 'failedLast7Days', count(*) filter (where o.status = 'failed' and o.created_at > now() - interval '7 days'),
1438
+ 'sentLast24h', count(*) filter (where o.status = 'sent' and o.sent_at > now() - interval '1 day'),
1439
+ 'codesLast24h', count(*) filter (where o.kind = 'verification_code' and o.created_at > now() - interval '1 day'))
1440
+ from booking.email_outbox o),
1441
+ 'recent', coalesce((
1442
+ select jsonb_agg(x.j order by x.created_at desc)
1443
+ from (
1444
+ select o.created_at, jsonb_build_object(
1445
+ 'id', o.id, 'kind', o.kind, 'status', o.status, 'recipient', booking.mask_email(o.recipient),
1446
+ 'attempts', o.attempts, 'createdAt', booking.iso(o.created_at), 'sentAt', booking.iso(o.sent_at),
1447
+ 'lastError', o.last_error) as j
1448
+ from booking.email_outbox o
1449
+ order by o.created_at desc
1450
+ limit 20
1451
+ ) as x), '[]'::jsonb)
1452
+ ) into v_result;
1453
+ return v_result;
1454
+ end;
1455
+ $$;
1456
+ comment on function public.booking_admin_email_status() is
1457
+ 'Admin only. Email sending health, wiring (booleans), counts and the 20 latest emails (masked recipients, never contents).';
1458
+
1459
+ create function public.booking_admin_send_test_email(p_recipient text)
1460
+ returns jsonb
1461
+ language plpgsql
1462
+ volatile
1463
+ security invoker
1464
+ set search_path = ''
1465
+ as $$
1466
+ declare
1467
+ c_tests_per_hour constant int := 10;
1468
+ v_email text := lower(btrim(coalesce(p_recipient, '')));
1469
+ v_count int;
1470
+ begin
1471
+ perform booking.require_admin();
1472
+ if char_length(v_email) > 254 or v_email !~ '^[^@[:space:]<>()]+@[^@[:space:]<>()]+\.[^@[:space:]<>()]{2,}$' then
1473
+ perform booking.raise_error('INVALID_INPUT', 'recipient');
1474
+ end if;
1475
+ select count(*) into v_count
1476
+ from booking.email_outbox o
1477
+ where o.kind = 'test' and o.created_at > now() - interval '1 hour';
1478
+ if v_count >= c_tests_per_hour then
1479
+ perform booking.raise_error('RATE_LIMITED');
1480
+ end if;
1481
+ perform booking.enqueue_email('test', v_email, null,
1482
+ (select jsonb_strip_nulls(jsonb_build_object('businessName', s.business_name, 'businessEmail', s.public_email,
1483
+ 'timezone', s.timezone, 'locale', s.locale))
1484
+ from booking.settings s where s.id),
1485
+ 'test:' || gen_random_uuid());
1486
+ return jsonb_build_object('queued', true);
1487
+ end;
1488
+ $$;
1489
+ comment on function public.booking_admin_send_test_email(text) is
1490
+ 'Admin only. Queues a test email (at most 10 an hour). A delivered test email unlocks online booking.';
1491
+
1492
+ -- ----------------------------------------------------------------------------
1493
+ -- Mailer API — the booking-mailer Edge Function only (service_role)
1494
+ -- ----------------------------------------------------------------------------
1495
+
1496
+ create function public.booking_mailer_claim(p_limit int default 10)
1497
+ returns jsonb
1498
+ language plpgsql
1499
+ volatile
1500
+ security invoker
1501
+ set search_path = ''
1502
+ as $$
1503
+ declare
1504
+ v_limit int := least(greatest(coalesce(p_limit, 10), 1), 50);
1505
+ v_result jsonb;
1506
+ begin
1507
+ perform booking.run_maintenance();
1508
+ update booking.mailer_state set last_attempt_at = now() where id;
1509
+
1510
+ with due as (
1511
+ select o.id
1512
+ from booking.email_outbox o
1513
+ where o.status in ('pending', 'sending')
1514
+ and o.next_attempt_at <= now()
1515
+ and (o.locked_until is null or o.locked_until <= now())
1516
+ order by o.created_at
1517
+ limit v_limit
1518
+ for update skip locked
1519
+ ),
1520
+ claimed as (
1521
+ update booking.email_outbox o
1522
+ set status = 'sending', locked_until = now() + interval '2 minutes', attempts = o.attempts + 1
1523
+ from due
1524
+ where o.id = due.id
1525
+ returning o.id, o.kind, o.recipient, o.payload, o.attempts, o.created_at
1526
+ )
1527
+ select coalesce(jsonb_agg(jsonb_build_object(
1528
+ 'id', c.id, 'kind', c.kind, 'to', c.recipient, 'payload', c.payload, 'attempt', c.attempts)
1529
+ order by c.created_at), '[]'::jsonb)
1530
+ into v_result
1531
+ from claimed c;
1532
+ return v_result;
1533
+ end;
1534
+ $$;
1535
+ comment on function public.booking_mailer_claim(int) is
1536
+ 'service_role only (booking-mailer). Runs maintenance, then leases up to p_limit due emails for 2 minutes.';
1537
+
1538
+ create function public.booking_mailer_report(
1539
+ p_id uuid,
1540
+ p_attempt int,
1541
+ p_ok boolean,
1542
+ p_provider_id text default null,
1543
+ p_error text default null,
1544
+ p_permanent boolean default false
1545
+ )
1546
+ returns jsonb
1547
+ language plpgsql
1548
+ volatile
1549
+ security invoker
1550
+ set search_path = ''
1551
+ as $$
1552
+ declare
1553
+ c_max_attempts constant int := 5;
1554
+ o booking.email_outbox%rowtype;
1555
+ v_give_up boolean;
1556
+ v_error text := left(coalesce(nullif(btrim(p_error), ''), 'Unknown error'), 500);
1557
+ begin
1558
+ select * into o from booking.email_outbox where id = p_id for update;
1559
+ if not found or o.status <> 'sending' or o.attempts is distinct from p_attempt then
1560
+ return jsonb_build_object('updated', false);
1561
+ end if;
1562
+ if coalesce(p_ok, false) then
1563
+ update booking.email_outbox
1564
+ set status = 'sent', sent_at = now(), provider_message_id = left(p_provider_id, 200), locked_until = null,
1565
+ last_error = null,
1566
+ payload = case when kind = 'verification_code' then payload - 'code' else payload end
1567
+ where id = p_id;
1568
+ update booking.mailer_state set last_success_at = now() where id;
1569
+ else
1570
+ v_give_up := coalesce(p_permanent, false) or o.attempts >= c_max_attempts;
1571
+ update booking.email_outbox
1572
+ set status = case when v_give_up then 'failed' else 'pending' end,
1573
+ next_attempt_at = now() + interval '1 minute' * power(4, least(o.attempts, 4) - 1),
1574
+ locked_until = null,
1575
+ last_error = v_error,
1576
+ payload = case when v_give_up and kind = 'verification_code' then payload - 'code' else payload end
1577
+ where id = p_id;
1578
+ update booking.mailer_state set last_failure_at = now(), last_error = v_error where id;
1579
+ end if;
1580
+ return jsonb_build_object('updated', true);
1581
+ end;
1582
+ $$;
1583
+ comment on function public.booking_mailer_report(uuid, int, boolean, text, text, boolean) is
1584
+ 'service_role only (booking-mailer). Records one delivery result for a leased email; retries after 1, 4, 16 and 64 minutes, then gives up.';
1585
+
1586
+ create function public.booking_mailer_report_unconfigured(p_error text)
1587
+ returns void
1588
+ language sql
1589
+ volatile
1590
+ security invoker
1591
+ set search_path = ''
1592
+ as $$
1593
+ update booking.mailer_state
1594
+ set last_attempt_at = now(), last_failure_at = now(),
1595
+ last_error = left(coalesce(nullif(btrim(p_error), ''), 'Email sending is not configured'), 500)
1596
+ where id;
1597
+ $$;
1598
+ comment on function public.booking_mailer_report_unconfigured(text) is
1599
+ 'service_role only (booking-mailer). Records that the function is missing its provider settings; nothing is claimed.';
1600
+
1601
+ -- ----------------------------------------------------------------------------
1602
+ -- RLS
1603
+ -- ----------------------------------------------------------------------------
1604
+
1605
+ alter table booking.verifications enable row level security;
1606
+ alter table booking.email_outbox enable row level security;
1607
+ alter table booking.mailer_state enable row level security;
1608
+
1609
+ create policy verifications_no_api_access on booking.verifications
1610
+ for all to anon, authenticated using (false) with check (false);
1611
+ create policy email_outbox_admin_read on booking.email_outbox
1612
+ for select to authenticated using ((select booking.is_admin()));
1613
+ create policy email_outbox_admin_insert on booking.email_outbox
1614
+ for insert to authenticated with check ((select booking.is_admin()));
1615
+ create policy mailer_state_admin_read on booking.mailer_state
1616
+ for select to authenticated using ((select booking.is_admin()));
1617
+
1618
+ -- ----------------------------------------------------------------------------
1619
+ -- Privileges
1620
+ -- ----------------------------------------------------------------------------
1621
+
1622
+ revoke all on booking.verifications, booking.email_outbox, booking.mailer_state
1623
+ from public, anon, authenticated, service_role;
1624
+
1625
+ -- Admins (through the INVOKER admin functions): queue emails and read their
1626
+ -- status, never their contents.
1627
+ grant select (id, kind, recipient, booking_id, dedupe_key, status, attempts, next_attempt_at, locked_until,
1628
+ provider_message_id, last_error, created_at, sent_at)
1629
+ on booking.email_outbox to authenticated;
1630
+ grant insert (kind, recipient, booking_id, payload, dedupe_key) on booking.email_outbox to authenticated;
1631
+ grant select on booking.mailer_state to authenticated;
1632
+
1633
+ -- The mailer (secret key → service_role): lease and report.
1634
+ grant select, update on booking.email_outbox to service_role;
1635
+ grant select, update on booking.mailer_state to service_role;
1636
+
1637
+ grant select (online_booking_enabled, verification_window_minutes) on booking.settings to anon, service_role;
1638
+
1639
+ -- New functions start with no access (PostgreSQL grants EXECUTE to PUBLIC by
1640
+ -- default); then grant on purpose.
1641
+ revoke execute on all functions in schema booking from public;
1642
+ revoke all on function
1643
+ booking.mask_email(text),
1644
+ booking.new_code(),
1645
+ booking.code_hash(uuid, text),
1646
+ booking.public_booking_json(booking.bookings),
1647
+ booking.booking_email_payload(booking.bookings, boolean),
1648
+ booking.enqueue_email(text, text, uuid, jsonb, text),
1649
+ booking.kick_mailer(),
1650
+ booking.email_outbox_after_insert(),
1651
+ booking.expire_lapsed(uuid, timestamptz, timestamptz),
1652
+ booking.compute_slots(uuid, date, date, timestamptz, uuid, uuid),
1653
+ booking.run_maintenance(),
1654
+ booking.mailer_tick(),
1655
+ booking.mailer_wiring(),
1656
+ booking.request_booking(uuid, timestamptz, text, text, text, text),
1657
+ booking.verify_booking(uuid, text),
1658
+ booking.resend_code(uuid),
1659
+ booking.cancel_request(uuid),
1660
+ public.booking_request(uuid, timestamptz, text, text, text, text),
1661
+ public.booking_verify(uuid, text),
1662
+ public.booking_resend_code(uuid),
1663
+ public.booking_cancel_request(uuid),
1664
+ public.booking_admin_email_status(),
1665
+ public.booking_admin_send_test_email(text),
1666
+ public.booking_mailer_claim(int),
1667
+ public.booking_mailer_report(uuid, int, boolean, text, text, boolean),
1668
+ public.booking_mailer_report_unconfigured(text)
1669
+ from public, anon, authenticated, service_role;
1670
+
1671
+ -- Public booking flow: the wrappers and the private privileged functions they
1672
+ -- call (executable, but not reachable by URL: schema `booking` is not exposed).
1673
+ grant execute on function
1674
+ public.booking_request(uuid, timestamptz, text, text, text, text),
1675
+ public.booking_verify(uuid, text),
1676
+ public.booking_resend_code(uuid),
1677
+ public.booking_cancel_request(uuid),
1678
+ booking.request_booking(uuid, timestamptz, text, text, text, text),
1679
+ booking.verify_booking(uuid, text),
1680
+ booking.resend_code(uuid),
1681
+ booking.cancel_request(uuid)
1682
+ to anon, authenticated, service_role;
1683
+
1684
+ -- Admin.
1685
+ grant execute on function
1686
+ public.booking_admin_email_status(),
1687
+ public.booking_admin_send_test_email(text),
1688
+ booking.mask_email(text),
1689
+ booking.mailer_wiring(),
1690
+ booking.enqueue_email(text, text, uuid, jsonb, text),
1691
+ booking.booking_email_payload(booking.bookings, boolean)
1692
+ to authenticated;
1693
+
1694
+ -- Mailer.
1695
+ grant execute on function
1696
+ public.booking_mailer_claim(int),
1697
+ public.booking_mailer_report(uuid, int, boolean, text, text, boolean),
1698
+ public.booking_mailer_report_unconfigured(text),
1699
+ booking.run_maintenance()
1700
+ to service_role;
1701
+
1702
+ update booking.engine_info set schema_version = '2.0.0-alpha.4', updated_at = now() where id;