@mccaskie-labs/workbench-bookings 0.2.1 → 0.3.0

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.
@@ -0,0 +1,707 @@
1
+ // The bookings tables' third migration (docs/capabilities/20-capacity-calendar.md,
2
+ // part 2): dated sessions and series, the waiting list and attendance.
3
+ //
4
+ // - A session is a dated thing people book places on: a tour departure, a
5
+ // workshop, one class of a term, a food truck's stop (bookable false: it is
6
+ // only shown). The owner makes them on a page, so they live here and not in
7
+ // bookings.json. Sessions with the same `series` are a term: a series
8
+ // booking holds its places in every session of it.
9
+ // - A place is taken under the account's lock, as every booking is. What is
10
+ // taken on a session is its own bookings, the bookings of its series, and
11
+ // the places being held for people offered one from the waiting list.
12
+ // - While anyone is waiting for a session, a freed place goes to the list and
13
+ // not to whoever happens to load the page next: bookings_join answers
14
+ // { "refused": "waitlist" } and the cron's bookings_offers offers it to the
15
+ // first person in line it fits, for a set time.
16
+ // - Cancelling a session cancels every booking on it in the same step and
17
+ // answers them, so the app can email everyone the reason and refund.
18
+ // - Only adds. The one function replaced, bookings_cleanup, keeps its
19
+ // signature and also clears what this file made. The down file reverses
20
+ // only this file. Service role only, as before.
21
+ import { ROW } from "./migration-resources.js";
22
+ const CLEANUP_BEFORE = `create or replace function public.bookings_cleanup(p_now timestamptz, p_days integer)
23
+ returns jsonb
24
+ language plpgsql
25
+ security invoker
26
+ set search_path = ''
27
+ as $$
28
+ declare
29
+ n integer;
30
+ begin
31
+ delete from public.bookings where block_end < p_now - make_interval(days => p_days);
32
+ get diagnostics n = row_count;
33
+ return jsonb_build_object('bookings', n);
34
+ end;
35
+ $$;
36
+ `;
37
+ const SIGNATURES = [
38
+ ["bookings_session_taken", "public.booking_sessions, timestamptz, uuid"],
39
+ ["bookings_session_row", "public.booking_sessions, timestamptz"],
40
+ ["bookings_wait_row", "public.booking_waitlist"],
41
+ ["bookings_session_save", "uuid, text, text, uuid, timestamptz, timestamptz, text, text, text, integer, integer, boolean, timestamptz"],
42
+ ["bookings_session_get", "uuid, timestamptz"],
43
+ ["bookings_sessions_list", "text, timestamptz, timestamptz, text, uuid, boolean, timestamptz"],
44
+ ["bookings_session_cancel", "uuid, text, text, timestamptz"],
45
+ ["bookings_join", "uuid, uuid, text, integer, text, text, text, text, text, text, text, timestamptz, timestamptz, integer, timestamptz, timestamptz, uuid"],
46
+ ["bookings_rejoin", "uuid, uuid, timestamptz, timestamptz, timestamptz"],
47
+ ["bookings_rearm", "uuid, timestamptz, timestamptz"],
48
+ ["bookings_wait", "text, uuid, uuid, integer, text, text, text, text, text, timestamptz"],
49
+ ["bookings_wait_by_hash", "text"],
50
+ ["bookings_wait_leave", "text, timestamptz"],
51
+ ["bookings_offers", "timestamptz, timestamptz, integer"],
52
+ ["bookings_offer_token", "uuid, text"],
53
+ ["bookings_accept", "text, text, text, timestamptz, timestamptz, integer, timestamptz, timestamptz"],
54
+ ["bookings_mark", "uuid, text, uuid, boolean, timestamptz"],
55
+ ["bookings_roll", "uuid, text, timestamptz"],
56
+ ["bookings_sessions_short", "timestamptz, timestamptz, integer"],
57
+ ];
58
+ const grants = SIGNATURES.map(([fn, args]) => `revoke execute on function public.${fn}(${args}) from public, anon, authenticated;\ngrant execute on function public.${fn}(${args}) to service_role;`).join("\n");
59
+ const drops = [...SIGNATURES].reverse().map(([fn, args]) => `drop function public.${fn}(${args});`).join("\n");
60
+ export const bookingsSessionsMigration = {
61
+ up: `create table public.booking_sessions (
62
+ id uuid primary key default gen_random_uuid(),
63
+ account text not null check (char_length(account) between 1 and 200),
64
+ service text not null check (service ~ '^[a-z][a-z0-9-]{0,39}$'),
65
+ series uuid,
66
+ starts_at timestamptz not null,
67
+ ends_at timestamptz not null,
68
+ place text check (char_length(place) <= 200),
69
+ map_url text check (char_length(map_url) <= 500 and map_url ~ '^https://'),
70
+ note text check (char_length(note) <= 500),
71
+ capacity integer not null check (capacity between 1 and 1000),
72
+ min_places integer check (min_places between 1 and 1000),
73
+ bookable boolean not null default true,
74
+ status text not null default 'open' check (status in ('open', 'cancelled')),
75
+ reason text check (char_length(reason) <= 200),
76
+ min_asked_at timestamptz,
77
+ sequence integer not null default 0 check (sequence >= 0),
78
+ created_at timestamptz not null default now(),
79
+ updated_at timestamptz not null default now(),
80
+ check (starts_at < ends_at),
81
+ check (min_places is null or min_places <= capacity)
82
+ );
83
+
84
+ comment on table public.booking_sessions is 'Dated sessions people book places on (workbench-bookings): a departure, a workshop, one class of a term (series), a stop on a schedule (bookable false). Where, when, how many places and the owner''s public note. No personal details. Deleted with the bookings clean-up, retention_days after it ends. Service role only.';
85
+
86
+ create index booking_sessions_account_time on public.booking_sessions (account, starts_at);
87
+ create index booking_sessions_series on public.booking_sessions (series, starts_at) where series is not null;
88
+ create index booking_sessions_min on public.booking_sessions (starts_at) where status = 'open' and min_places is not null and min_asked_at is null;
89
+
90
+ alter table public.bookings add column session uuid references public.booking_sessions (id);
91
+ alter table public.bookings add column series uuid;
92
+ alter table public.bookings add constraint bookings_session_or_series check (session is null or series is null);
93
+
94
+ comment on column public.bookings.session is 'The session the booking holds places on, when it is for one (booking_sessions).';
95
+ comment on column public.bookings.series is 'The series the booking holds places on in every session, when it is for a whole term.';
96
+
97
+ create index bookings_session on public.bookings (session) where session is not null;
98
+ create index bookings_series on public.bookings (series) where series is not null;
99
+
100
+ create table public.booking_waitlist (
101
+ id uuid primary key default gen_random_uuid(),
102
+ position bigint generated always as identity,
103
+ account text not null check (char_length(account) between 1 and 200),
104
+ session uuid references public.booking_sessions (id) on delete cascade,
105
+ series uuid,
106
+ places smallint not null default 1 check (places between 1 and 100),
107
+ customer_name text not null check (char_length(customer_name) between 1 and 100),
108
+ customer_email text not null check (char_length(customer_email) between 3 and 254),
109
+ customer_phone text check (char_length(customer_phone) <= 40),
110
+ member text check (char_length(member) between 1 and 200),
111
+ token_hash text not null unique check (token_hash ~ '^[0-9a-f]{64}$'),
112
+ status text not null default 'waiting' check (status in ('waiting', 'offered', 'booked', 'expired', 'left')),
113
+ offered_until timestamptz,
114
+ booking uuid,
115
+ created_at timestamptz not null default now(),
116
+ updated_at timestamptz not null default now(),
117
+ check ((session is null) <> (series is null)),
118
+ check (status = 'offered' or offered_until is null)
119
+ );
120
+
121
+ comment on table public.booking_waitlist is 'People waiting for a place on a full session or series (workbench-bookings): how many places, and the name, email and optional phone they typed. Deleted when the session is, or 30 days after they left, booked or the offer ran out. Service role only.';
122
+
123
+ create index booking_waitlist_session on public.booking_waitlist (session, position) where status in ('waiting', 'offered');
124
+ create index booking_waitlist_series on public.booking_waitlist (series, position) where status in ('waiting', 'offered');
125
+ create index booking_waitlist_offers on public.booking_waitlist (offered_until) where status = 'offered';
126
+
127
+ create table public.booking_attendance (
128
+ booking uuid not null references public.bookings (id) on delete cascade,
129
+ session uuid not null default '00000000-0000-0000-0000-000000000000',
130
+ came boolean not null,
131
+ marked_at timestamptz not null default now(),
132
+ primary key (booking, session)
133
+ );
134
+
135
+ comment on table public.booking_attendance is 'Who came (workbench-bookings): one mark for a booking, or one for each session of a series booking (session is all zeros for a booking that has no session). Deleted with the booking. Service role only.';
136
+
137
+ alter table public.booking_sessions enable row level security;
138
+ alter table public.booking_waitlist enable row level security;
139
+ alter table public.booking_attendance enable row level security;
140
+
141
+ revoke all on public.booking_sessions, public.booking_waitlist, public.booking_attendance from anon, authenticated;
142
+
143
+ ${ROW(3)}
144
+ -- The places taken on a session: its own bookings, its series' bookings, and
145
+ -- the places held for people offered one from the waiting list (p_offer
146
+ -- leaves out the offer being taken up).
147
+ create function public.bookings_session_taken(s public.booking_sessions, p_now timestamptz, p_offer uuid)
148
+ returns integer
149
+ language sql
150
+ stable
151
+ security invoker
152
+ set search_path = ''
153
+ as $$
154
+ select (coalesce((select sum(b.places) from public.bookings b
155
+ where b.status in ('pending', 'confirmed') and (b.session = s.id or (s.series is not null and b.series = s.series))), 0)
156
+ + coalesce((select sum(w.places) from public.booking_waitlist w
157
+ where w.status = 'offered' and w.offered_until > p_now and w.id is distinct from p_offer
158
+ and (w.session = s.id or (s.series is not null and w.series = s.series))), 0))::integer;
159
+ $$;
160
+
161
+ -- A session as the package reads it, with the places taken and how many
162
+ -- people are waiting.
163
+ create function public.bookings_session_row(s public.booking_sessions, p_now timestamptz)
164
+ returns jsonb
165
+ language sql
166
+ stable
167
+ security invoker
168
+ set search_path = ''
169
+ as $$
170
+ select jsonb_build_object('id', s.id, 'account', s.account, 'service', s.service, 'series', s.series, 'starts_at', s.starts_at, 'ends_at', s.ends_at,
171
+ 'place', s.place, 'map_url', s.map_url, 'note', s.note, 'capacity', s.capacity, 'min_places', s.min_places, 'bookable', s.bookable,
172
+ 'status', s.status, 'reason', s.reason, 'sequence', s.sequence,
173
+ 'taken', public.bookings_session_taken(s, p_now, null),
174
+ 'waiting', (select count(*) from public.booking_waitlist w where w.status = 'waiting' and (w.session = s.id or (s.series is not null and w.series = s.series))));
175
+ $$;
176
+
177
+ create function public.bookings_wait_row(w public.booking_waitlist)
178
+ returns jsonb
179
+ language sql
180
+ immutable
181
+ security invoker
182
+ set search_path = ''
183
+ as $$
184
+ select jsonb_build_object('id', w.id, 'account', w.account, 'session', w.session, 'series', w.series, 'places', w.places, 'member', w.member,
185
+ 'customer', jsonb_build_object('name', w.customer_name, 'email', w.customer_email, 'phone', w.customer_phone),
186
+ 'status', w.status, 'offered_until', w.offered_until, 'booking', w.booking, 'created_at', w.created_at);
187
+ $$;
188
+
189
+ -- Makes a session (p_id null) or changes one of the account's. A new time
190
+ -- moves every booking on it and answers them, with their reminders cleared
191
+ -- for the package to set again. Fewer places than are taken is refused.
192
+ -- Answers { session, moved }, null for a session that isn't the account's or
193
+ -- is cancelled, or { "refused": "too_small" }.
194
+ create function public.bookings_session_save(p_id uuid, p_account text, p_service text, p_series uuid, p_start timestamptz, p_end timestamptz, p_place text, p_map_url text, p_note text,
195
+ p_capacity integer, p_min integer, p_bookable boolean, p_now timestamptz)
196
+ returns jsonb
197
+ language plpgsql
198
+ security invoker
199
+ set search_path = ''
200
+ as $$
201
+ declare
202
+ s public.booking_sessions;
203
+ v_moved jsonb := '[]'::jsonb;
204
+ v_retimed boolean;
205
+ begin
206
+ perform pg_advisory_xact_lock(hashtext('workbench-bookings:' || p_account));
207
+ if p_id is null then
208
+ insert into public.booking_sessions (account, service, series, starts_at, ends_at, place, map_url, note, capacity, min_places, bookable, created_at, updated_at)
209
+ values (p_account, p_service, p_series, p_start, p_end, p_place, p_map_url, p_note, p_capacity, p_min, p_bookable, p_now, p_now)
210
+ returning * into s;
211
+ return jsonb_build_object('session', public.bookings_session_row(s, p_now), 'moved', v_moved);
212
+ end if;
213
+ select * into s from public.booking_sessions where id = p_id and account = p_account and status = 'open';
214
+ if not found then
215
+ return null;
216
+ end if;
217
+ if public.bookings_session_taken(s, p_now, null) > p_capacity then
218
+ return jsonb_build_object('refused', 'too_small');
219
+ end if;
220
+ v_retimed := s.starts_at <> p_start or s.ends_at <> p_end;
221
+ update public.booking_sessions
222
+ set starts_at = p_start, ends_at = p_end, place = p_place, map_url = p_map_url, note = p_note, capacity = p_capacity, min_places = p_min, bookable = p_bookable,
223
+ sequence = sequence + 1, min_asked_at = case when v_retimed then null else min_asked_at end, updated_at = p_now
224
+ where id = p_id
225
+ returning * into s;
226
+ if v_retimed then
227
+ with u as (
228
+ update public.bookings b
229
+ set starts_at = p_start, ends_at = p_end, block_end = p_end, sequence = b.sequence + 1, reminders_sent = 0, next_reminder_at = null, claim = null, claimed_until = null, updated_at = p_now
230
+ where b.session = p_id and b.status in ('pending', 'confirmed')
231
+ returning b.*
232
+ )
233
+ select coalesce(jsonb_agg(public.bookings_row(u) order by u.created_at, u.id), '[]'::jsonb) into v_moved from u;
234
+ end if;
235
+ return jsonb_build_object('session', public.bookings_session_row(s, p_now), 'moved', v_moved);
236
+ end;
237
+ $$;
238
+
239
+ create function public.bookings_session_get(p_id uuid, p_now timestamptz)
240
+ returns jsonb
241
+ language sql
242
+ stable
243
+ security invoker
244
+ set search_path = ''
245
+ as $$
246
+ select public.bookings_session_row(s, p_now) from public.booking_sessions s where s.id = p_id;
247
+ $$;
248
+
249
+ -- The account's sessions that end after p_from and start before p_to,
250
+ -- earliest first, for one service or one series when asked. p_all also gives
251
+ -- the cancelled ones (the owner's list). At most 500.
252
+ create function public.bookings_sessions_list(p_account text, p_from timestamptz, p_to timestamptz, p_service text, p_series uuid, p_all boolean, p_now timestamptz)
253
+ returns jsonb
254
+ language sql
255
+ stable
256
+ security invoker
257
+ set search_path = ''
258
+ as $$
259
+ select coalesce(jsonb_agg(public.bookings_session_row(s, p_now) order by s.starts_at, s.id), '[]'::jsonb)
260
+ from (select * from public.booking_sessions
261
+ where account = p_account and ends_at > p_from and starts_at < p_to
262
+ and (p_service is null or service = p_service) and (p_series is null or series = p_series) and (p_all or status = 'open')
263
+ order by starts_at, id limit 500) s;
264
+ $$;
265
+
266
+ -- Sets a booking's next reminder after its session moved.
267
+ create function public.bookings_rearm(p_id uuid, p_next timestamptz, p_now timestamptz)
268
+ returns boolean
269
+ language plpgsql
270
+ security invoker
271
+ set search_path = ''
272
+ as $$
273
+ begin
274
+ update public.bookings set next_reminder_at = p_next, updated_at = p_now where id = p_id and status = 'confirmed';
275
+ return found;
276
+ end;
277
+ $$;
278
+
279
+ -- Cancels one of the account's sessions and, in the same step, every booking
280
+ -- on it and every wait for it. Answers { session, cancelled } with the
281
+ -- bookings it cancelled, and affected: the series bookings that lose this
282
+ -- one date and stand. Null when it isn't the account's or is already
283
+ -- cancelled.
284
+ create function public.bookings_session_cancel(p_id uuid, p_account text, p_reason text, p_now timestamptz)
285
+ returns jsonb
286
+ language plpgsql
287
+ security invoker
288
+ set search_path = ''
289
+ as $$
290
+ declare
291
+ s public.booking_sessions;
292
+ v_cancelled jsonb;
293
+ v_affected jsonb;
294
+ begin
295
+ perform pg_advisory_xact_lock(hashtext('workbench-bookings:' || p_account));
296
+ update public.booking_sessions set status = 'cancelled', reason = left(p_reason, 200), sequence = sequence + 1, updated_at = p_now
297
+ where id = p_id and account = p_account and status = 'open'
298
+ returning * into s;
299
+ if not found then
300
+ return null;
301
+ end if;
302
+ with u as (
303
+ update public.bookings b
304
+ set status = 'cancelled', reason = 'session_cancelled', sequence = b.sequence + 1, next_reminder_at = null, hold_until = null, claim = null, claimed_until = null, updated_at = p_now
305
+ where b.session = p_id and b.status in ('pending', 'confirmed')
306
+ returning b.*
307
+ )
308
+ select coalesce(jsonb_agg(public.bookings_row(u) order by u.created_at, u.id), '[]'::jsonb) into v_cancelled from u;
309
+ select coalesce(jsonb_agg(public.bookings_row(b) order by b.created_at, b.id), '[]'::jsonb) into v_affected
310
+ from public.bookings b where s.series is not null and b.series = s.series and b.status in ('pending', 'confirmed');
311
+ update public.booking_waitlist set status = 'expired', offered_until = null, updated_at = p_now where session = p_id and status in ('waiting', 'offered');
312
+ return jsonb_build_object('session', public.bookings_session_row(s, p_now), 'cancelled', v_cancelled, 'affected', v_affected);
313
+ end;
314
+ $$;
315
+
316
+ -- Books p_places on a session (p_session) or on every session still to come
317
+ -- of a series (p_series), if each has room, under the account's lock. With
318
+ -- p_offer, takes up a waiting list offer, whose held places are its own.
319
+ -- Answers the booking, or { "refused": "closed" | "too_many" | "waitlist" |
320
+ -- "taken" }: closed for a session that is cancelled, not bookable, or starts
321
+ -- before p_min_start; waitlist when a place is free but people are waiting
322
+ -- for it.
323
+ create function public.bookings_join(p_session uuid, p_series uuid, p_account text, p_places integer, p_status text, p_name text, p_email text, p_phone text, p_note text, p_member text, p_hash text,
324
+ p_next_reminder timestamptz, p_hold_until timestamptz, p_max integer, p_min_start timestamptz, p_now timestamptz, p_offer uuid)
325
+ returns jsonb
326
+ language plpgsql
327
+ security invoker
328
+ set search_path = ''
329
+ as $$
330
+ declare
331
+ b public.bookings;
332
+ s public.booking_sessions;
333
+ v_first public.booking_sessions;
334
+ v_last timestamptz;
335
+ v_count integer := 0;
336
+ begin
337
+ if p_status not in ('pending', 'confirmed') then
338
+ raise exception using errcode = '22023', message = 'bookings: a new booking is pending or confirmed';
339
+ end if;
340
+ if (p_session is null) = (p_series is null) then
341
+ raise exception using errcode = '22023', message = 'bookings: a session or a series, one of them';
342
+ end if;
343
+ if p_places is null or p_places < 1 or p_places > 100 then
344
+ raise exception using errcode = '22023', message = 'bookings: places is 1 to 100';
345
+ end if;
346
+ perform pg_advisory_xact_lock(hashtext('workbench-bookings:' || p_account));
347
+ if (select count(*) from public.bookings
348
+ where account = p_account and lower(customer_email) = lower(p_email) and status in ('pending', 'confirmed') and ends_at > p_now) >= p_max then
349
+ return jsonb_build_object('refused', 'too_many');
350
+ end if;
351
+ for s in
352
+ select * from public.booking_sessions x
353
+ where x.account = p_account and ((p_session is not null and x.id = p_session) or (p_series is not null and x.series = p_series and x.status = 'open' and x.starts_at >= p_min_start))
354
+ order by x.starts_at, x.id
355
+ loop
356
+ if s.status <> 'open' or not s.bookable or s.starts_at < p_min_start then
357
+ return jsonb_build_object('refused', 'closed');
358
+ end if;
359
+ if public.bookings_session_taken(s, p_now, p_offer) + p_places > s.capacity then
360
+ return jsonb_build_object('refused', 'taken');
361
+ end if;
362
+ if p_offer is null and exists (select 1 from public.booking_waitlist w
363
+ where w.status = 'waiting' and (w.session = s.id or (s.series is not null and w.series = s.series))) then
364
+ return jsonb_build_object('refused', 'waitlist');
365
+ end if;
366
+ if v_count = 0 then
367
+ v_first := s;
368
+ end if;
369
+ v_last := s.ends_at;
370
+ v_count := v_count + 1;
371
+ end loop;
372
+ if v_count = 0 then
373
+ return jsonb_build_object('refused', 'closed');
374
+ end if;
375
+ insert into public.bookings (account, service, starts_at, ends_at, block_end, status, places, session, series, customer_name, customer_email, customer_phone, note, member, token_hash,
376
+ next_reminder_at, hold_until, created_at, updated_at)
377
+ values (p_account, v_first.service, v_first.starts_at, v_last, v_last, p_status, p_places, p_session, p_series, p_name, p_email, p_phone, p_note, p_member, p_hash,
378
+ case when p_status = 'confirmed' then p_next_reminder end, case when p_status = 'pending' then p_hold_until end, p_now, p_now)
379
+ returning * into b;
380
+ return public.bookings_row(b);
381
+ end;
382
+ $$;
383
+
384
+ -- Moves a booking that is on a session to another session of the same
385
+ -- service, if it has room. Answers the booking, null when it has ended or
386
+ -- isn't on a session, or { "refused": "closed" | "waitlist" | "taken" }.
387
+ create function public.bookings_rejoin(p_id uuid, p_session uuid, p_next_reminder timestamptz, p_min_start timestamptz, p_now timestamptz)
388
+ returns jsonb
389
+ language plpgsql
390
+ security invoker
391
+ set search_path = ''
392
+ as $$
393
+ declare
394
+ b public.bookings;
395
+ s public.booking_sessions;
396
+ begin
397
+ select * into b from public.bookings where id = p_id;
398
+ if not found or b.status not in ('pending', 'confirmed') or b.session is null then
399
+ return null;
400
+ end if;
401
+ perform pg_advisory_xact_lock(hashtext('workbench-bookings:' || b.account));
402
+ select * into s from public.booking_sessions where id = p_session and account = b.account and service = b.service;
403
+ if not found or s.status <> 'open' or not s.bookable or s.starts_at < p_min_start then
404
+ return jsonb_build_object('refused', 'closed');
405
+ end if;
406
+ if public.bookings_session_taken(s, p_now, null) + b.places > s.capacity then
407
+ return jsonb_build_object('refused', 'taken');
408
+ end if;
409
+ if exists (select 1 from public.booking_waitlist w where w.status = 'waiting' and (w.session = s.id or (s.series is not null and w.series = s.series))) then
410
+ return jsonb_build_object('refused', 'waitlist');
411
+ end if;
412
+ update public.bookings
413
+ set session = s.id, starts_at = s.starts_at, ends_at = s.ends_at, block_end = s.ends_at, sequence = sequence + 1, reminders_sent = 0,
414
+ next_reminder_at = case when status = 'confirmed' then p_next_reminder end, claim = null, claimed_until = null, updated_at = p_now
415
+ where id = p_id and status in ('pending', 'confirmed')
416
+ returning * into b;
417
+ if not found then
418
+ return null;
419
+ end if;
420
+ return public.bookings_row(b);
421
+ end;
422
+ $$;
423
+
424
+ -- Joins the waiting list for a session or a series that has no room for
425
+ -- p_places. Answers the entry, or { "refused": "closed" | "not_full" |
426
+ -- "already" }: not_full when the places are free and nobody is waiting (book
427
+ -- instead), already when this email is waiting for it.
428
+ create function public.bookings_wait(p_account text, p_session uuid, p_series uuid, p_places integer, p_name text, p_email text, p_phone text, p_member text, p_hash text, p_now timestamptz)
429
+ returns jsonb
430
+ language plpgsql
431
+ security invoker
432
+ set search_path = ''
433
+ as $$
434
+ declare
435
+ w public.booking_waitlist;
436
+ s public.booking_sessions;
437
+ v_count integer := 0;
438
+ v_room boolean := true;
439
+ begin
440
+ if (p_session is null) = (p_series is null) then
441
+ raise exception using errcode = '22023', message = 'bookings: a session or a series, one of them';
442
+ end if;
443
+ perform pg_advisory_xact_lock(hashtext('workbench-bookings:' || p_account));
444
+ for s in
445
+ select * from public.booking_sessions x
446
+ where x.account = p_account and ((p_session is not null and x.id = p_session) or (p_series is not null and x.series = p_series and x.status = 'open' and x.starts_at > p_now))
447
+ loop
448
+ if s.status <> 'open' or not s.bookable or s.starts_at <= p_now then
449
+ return jsonb_build_object('refused', 'closed');
450
+ end if;
451
+ v_count := v_count + 1;
452
+ if public.bookings_session_taken(s, p_now, null) + p_places > s.capacity
453
+ or exists (select 1 from public.booking_waitlist q where q.status = 'waiting' and (q.session = s.id or (s.series is not null and q.series = s.series))) then
454
+ v_room := false;
455
+ end if;
456
+ end loop;
457
+ if v_count = 0 then
458
+ return jsonb_build_object('refused', 'closed');
459
+ end if;
460
+ if v_room then
461
+ return jsonb_build_object('refused', 'not_full');
462
+ end if;
463
+ if exists (select 1 from public.booking_waitlist q
464
+ where q.account = p_account and q.status in ('waiting', 'offered') and lower(q.customer_email) = lower(p_email)
465
+ and q.session is not distinct from p_session and q.series is not distinct from p_series) then
466
+ return jsonb_build_object('refused', 'already');
467
+ end if;
468
+ insert into public.booking_waitlist (account, session, series, places, customer_name, customer_email, customer_phone, member, token_hash, created_at, updated_at)
469
+ values (p_account, p_session, p_series, p_places, p_name, p_email, p_phone, p_member, p_hash, p_now, p_now)
470
+ returning * into w;
471
+ return public.bookings_wait_row(w);
472
+ end;
473
+ $$;
474
+
475
+ create function public.bookings_wait_by_hash(p_hash text)
476
+ returns jsonb
477
+ language sql
478
+ stable
479
+ security invoker
480
+ set search_path = ''
481
+ as $$
482
+ select public.bookings_wait_row(w) from public.booking_waitlist w where w.token_hash = p_hash;
483
+ $$;
484
+
485
+ -- Leaves the list, or turns an offer down (its held places are freed).
486
+ create function public.bookings_wait_leave(p_hash text, p_now timestamptz)
487
+ returns jsonb
488
+ language plpgsql
489
+ security invoker
490
+ set search_path = ''
491
+ as $$
492
+ declare
493
+ w public.booking_waitlist;
494
+ begin
495
+ update public.booking_waitlist set status = 'left', offered_until = null, updated_at = p_now
496
+ where token_hash = p_hash and status in ('waiting', 'offered')
497
+ returning * into w;
498
+ if not found then
499
+ return null;
500
+ end if;
501
+ return public.bookings_wait_row(w);
502
+ end;
503
+ $$;
504
+
505
+ -- The cron's waiting list step. Offers that ran out and waits for sessions
506
+ -- that have started are closed; then each person waiting, first come first
507
+ -- served, is offered the places if they are free now (in every session still
508
+ -- to come, for a series), held until p_until. The line is kept by position,
509
+ -- a counter, so two people who join in the same instant still have an order. Someone whose party doesn't fit
510
+ -- is passed over for the next. Answers the new offers, up to p_limit.
511
+ create function public.bookings_offers(p_now timestamptz, p_until timestamptz, p_limit integer)
512
+ returns jsonb
513
+ language plpgsql
514
+ security invoker
515
+ set search_path = ''
516
+ as $$
517
+ declare
518
+ w public.booking_waitlist;
519
+ s public.booking_sessions;
520
+ v_out jsonb := '[]'::jsonb;
521
+ v_fits boolean;
522
+ v_count integer;
523
+ begin
524
+ update public.booking_waitlist set status = 'expired', offered_until = null, updated_at = p_now where status = 'offered' and offered_until <= p_now;
525
+ update public.booking_waitlist q set status = 'expired', updated_at = p_now
526
+ where q.status = 'waiting'
527
+ and ((q.session is not null and exists (select 1 from public.booking_sessions x where x.id = q.session and (x.status <> 'open' or x.starts_at <= p_now)))
528
+ or (q.series is not null and not exists (select 1 from public.booking_sessions x where x.series = q.series and x.account = q.account and x.status = 'open' and x.starts_at > p_now)));
529
+ for w in select * from public.booking_waitlist where status = 'waiting' order by position limit 1000 loop
530
+ exit when jsonb_array_length(v_out) >= p_limit;
531
+ perform pg_advisory_xact_lock(hashtext('workbench-bookings:' || w.account));
532
+ -- Someone may have left or been offered while this waited for the lock.
533
+ perform 1 from public.booking_waitlist where id = w.id and status = 'waiting';
534
+ continue when not found;
535
+ v_fits := true;
536
+ v_count := 0;
537
+ for s in
538
+ select * from public.booking_sessions x
539
+ where x.account = w.account and x.status = 'open' and x.bookable and x.starts_at > p_now and (x.id = w.session or (w.series is not null and x.series = w.series))
540
+ loop
541
+ v_count := v_count + 1;
542
+ if public.bookings_session_taken(s, p_now, null) + w.places > s.capacity then
543
+ v_fits := false;
544
+ end if;
545
+ end loop;
546
+ continue when v_count = 0 or not v_fits;
547
+ update public.booking_waitlist set status = 'offered', offered_until = p_until, updated_at = p_now where id = w.id returning * into w;
548
+ v_out := v_out || jsonb_build_array(public.bookings_wait_row(w));
549
+ end loop;
550
+ return v_out;
551
+ end;
552
+ $$;
553
+
554
+ -- Gives an offered entry a fresh secret for the link in its offer email (only
555
+ -- its SHA-256 is kept, so the one from when they joined can't be sent again).
556
+ create function public.bookings_offer_token(p_id uuid, p_hash text)
557
+ returns boolean
558
+ language plpgsql
559
+ security invoker
560
+ set search_path = ''
561
+ as $$
562
+ begin
563
+ update public.booking_waitlist set token_hash = p_hash where id = p_id and status = 'offered';
564
+ return found;
565
+ end;
566
+ $$;
567
+
568
+ -- Takes up an offer: books the held places with the details given when they
569
+ -- joined the list. Answers the booking, null when there is no live offer for
570
+ -- this secret, or what bookings_join refused.
571
+ create function public.bookings_accept(p_hash text, p_booking_hash text, p_status text, p_next_reminder timestamptz, p_hold_until timestamptz, p_max integer, p_min_start timestamptz, p_now timestamptz)
572
+ returns jsonb
573
+ language plpgsql
574
+ security invoker
575
+ set search_path = ''
576
+ as $$
577
+ declare
578
+ w public.booking_waitlist;
579
+ r jsonb;
580
+ begin
581
+ select * into w from public.booking_waitlist where token_hash = p_hash and status = 'offered' and offered_until > p_now;
582
+ if not found then
583
+ return null;
584
+ end if;
585
+ r := public.bookings_join(w.session, w.series, w.account, w.places, p_status, w.customer_name, w.customer_email, w.customer_phone, null, w.member, p_booking_hash,
586
+ p_next_reminder, p_hold_until, p_max, p_min_start, p_now, w.id);
587
+ if r ? 'refused' then
588
+ return r;
589
+ end if;
590
+ update public.booking_waitlist set status = 'booked', offered_until = null, booking = (r ->> 'id')::uuid, updated_at = p_now where id = w.id and status = 'offered';
591
+ if not found then
592
+ raise exception using errcode = '40001', message = 'bookings: the offer was taken or withdrawn meanwhile';
593
+ end if;
594
+ return r;
595
+ end;
596
+ $$;
597
+
598
+ -- Marks whether one of the account's bookings came (p_came null clears the
599
+ -- mark). p_session says which date, for a series booking. False when the
600
+ -- booking isn't the account's.
601
+ create function public.bookings_mark(p_booking uuid, p_account text, p_session uuid, p_came boolean, p_now timestamptz)
602
+ returns boolean
603
+ language plpgsql
604
+ security invoker
605
+ set search_path = ''
606
+ as $$
607
+ declare
608
+ v_session uuid := coalesce(p_session, '00000000-0000-0000-0000-000000000000');
609
+ begin
610
+ perform 1 from public.bookings b where b.id = p_booking and b.account = p_account
611
+ and (p_session is null or b.session = p_session or exists (select 1 from public.booking_sessions s where s.id = p_session and s.series = b.series));
612
+ if not found then
613
+ return false;
614
+ end if;
615
+ if p_came is null then
616
+ delete from public.booking_attendance where booking = p_booking and session = v_session;
617
+ else
618
+ insert into public.booking_attendance (booking, session, came, marked_at) values (p_booking, v_session, p_came, p_now)
619
+ on conflict (booking, session) do update set came = excluded.came, marked_at = excluded.marked_at;
620
+ end if;
621
+ return true;
622
+ end;
623
+ $$;
624
+
625
+ -- Everyone booked on one of the account's sessions (its own bookings and its
626
+ -- series'), with whether each came (null: not marked), by name.
627
+ create function public.bookings_roll(p_session uuid, p_account text, p_now timestamptz)
628
+ returns jsonb
629
+ language sql
630
+ stable
631
+ security invoker
632
+ set search_path = ''
633
+ as $$
634
+ select coalesce(jsonb_agg(public.bookings_row(b) || jsonb_build_object('came',
635
+ (select a.came from public.booking_attendance a where a.booking = b.id and a.session in (s.id, '00000000-0000-0000-0000-000000000000') order by (a.session = s.id) desc limit 1))
636
+ order by lower(b.customer_name), b.id), '[]'::jsonb)
637
+ from public.booking_sessions s
638
+ join public.bookings b on b.status in ('pending', 'confirmed') and (b.session = s.id or (s.series is not null and b.series = s.series))
639
+ where s.id = p_session and s.account = p_account;
640
+ $$;
641
+
642
+ -- The cron's minimum check: sessions that start by p_until with fewer places
643
+ -- taken than they need to run, each answered once, for the owner to decide.
644
+ create function public.bookings_sessions_short(p_now timestamptz, p_until timestamptz, p_limit integer)
645
+ returns jsonb
646
+ language plpgsql
647
+ security invoker
648
+ set search_path = ''
649
+ as $$
650
+ declare
651
+ v jsonb;
652
+ begin
653
+ with c as (
654
+ select s.id from public.booking_sessions s
655
+ where s.status = 'open' and s.min_places is not null and s.min_asked_at is null and s.starts_at > p_now and s.starts_at <= p_until
656
+ and public.bookings_session_taken(s, p_now, null) < s.min_places
657
+ order by s.starts_at, s.id limit p_limit
658
+ for update skip locked
659
+ ), u as (
660
+ update public.booking_sessions s set min_asked_at = p_now from c where s.id = c.id returning s.*
661
+ )
662
+ select coalesce(jsonb_agg(public.bookings_session_row(u, p_now) order by u.starts_at, u.id), '[]'::jsonb) into v from u;
663
+ return v;
664
+ end;
665
+ $$;
666
+
667
+ -- The daily clean-up, now also: who came (with the booking), sessions p_days
668
+ -- after they end once no booking is left on them, and waiting list entries
669
+ -- with their session or 30 days after they were settled.
670
+ create or replace function public.bookings_cleanup(p_now timestamptz, p_days integer)
671
+ returns jsonb
672
+ language plpgsql
673
+ security invoker
674
+ set search_path = ''
675
+ as $$
676
+ declare
677
+ n integer;
678
+ n_sessions integer;
679
+ n_waits integer;
680
+ begin
681
+ delete from public.bookings where block_end < p_now - make_interval(days => p_days);
682
+ get diagnostics n = row_count;
683
+ delete from public.booking_waitlist where status in ('booked', 'expired', 'left') and updated_at < p_now - interval '30 days';
684
+ get diagnostics n_waits = row_count;
685
+ delete from public.booking_sessions s
686
+ where s.ends_at < p_now - make_interval(days => p_days) and not exists (select 1 from public.bookings b where b.session = s.id);
687
+ get diagnostics n_sessions = row_count;
688
+ return jsonb_build_object('bookings', n, 'sessions', n_sessions, 'waits', n_waits);
689
+ end;
690
+ $$;
691
+
692
+ ${grants}
693
+ grant select, insert, update, delete on public.booking_sessions, public.booking_waitlist, public.booking_attendance to service_role;
694
+ `,
695
+ down: `${CLEANUP_BEFORE}
696
+ ${drops}
697
+ ${ROW(2)}
698
+ drop table public.booking_attendance;
699
+ drop table public.booking_waitlist;
700
+ drop index public.bookings_series;
701
+ drop index public.bookings_session;
702
+ alter table public.bookings drop constraint bookings_session_or_series;
703
+ alter table public.bookings drop column series;
704
+ alter table public.bookings drop column session;
705
+ drop table public.booking_sessions;
706
+ `,
707
+ };