@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.
- package/CHANGELOG.md +16 -0
- package/README.md +64 -1
- package/dist/bookings.d.ts +50 -5
- package/dist/bookings.js +110 -28
- package/dist/cli.js +16 -8
- package/dist/config.d.ts +2 -0
- package/dist/config.js +81 -3
- package/dist/errors.d.ts +10 -0
- package/dist/ical.d.ts +10 -0
- package/dist/ical.js +14 -0
- package/dist/index.d.ts +8 -6
- package/dist/index.js +8 -4
- package/dist/migration-resources.d.ts +6 -0
- package/dist/migration-resources.js +198 -0
- package/dist/migration-sessions.d.ts +4 -0
- package/dist/migration-sessions.js +707 -0
- package/dist/migration.d.ts +12 -0
- package/dist/migration.js +13 -0
- package/dist/session-ui.d.ts +136 -0
- package/dist/session-ui.js +247 -0
- package/dist/sessions.d.ts +97 -0
- package/dist/sessions.js +426 -0
- package/dist/slots.d.ts +20 -1
- package/dist/slots.js +89 -3
- package/dist/styles.js +33 -0
- package/dist/time.d.ts +8 -0
- package/dist/time.js +20 -0
- package/dist/types.d.ts +128 -3
- package/dist/ui.d.ts +33 -3
- package/dist/ui.js +44 -21
- package/dist/words.d.ts +1 -1
- package/dist/words.js +170 -0
- package/package.json +2 -2
package/dist/config.js
CHANGED
|
@@ -12,6 +12,7 @@ const TOP = [
|
|
|
12
12
|
"hours",
|
|
13
13
|
"closed",
|
|
14
14
|
"services",
|
|
15
|
+
"resources",
|
|
15
16
|
"calendar",
|
|
16
17
|
"notice",
|
|
17
18
|
"ahead_days",
|
|
@@ -24,9 +25,16 @@ const TOP = [
|
|
|
24
25
|
"feed",
|
|
25
26
|
"max_per_customer",
|
|
26
27
|
"retention_days",
|
|
28
|
+
"waitlist",
|
|
29
|
+
"run_check",
|
|
27
30
|
"plans",
|
|
28
31
|
];
|
|
29
|
-
const SERVICE = ["title", "minutes", "buffer", "capacity", "places", "every", "hours"];
|
|
32
|
+
const SERVICE = ["title", "minutes", "buffer", "capacity", "places", "every", "hours", "needs", "sessions"];
|
|
33
|
+
const RESOURCE = ["title", "kind", "hours"];
|
|
34
|
+
/** The most groups a service can need, and the most resources in one. */
|
|
35
|
+
export const MAX_NEEDS = 3;
|
|
36
|
+
const MAX_ANY = 20;
|
|
37
|
+
const MAX_RESOURCES = 100;
|
|
30
38
|
const THIRTY_DAYS = 30 * 1440;
|
|
31
39
|
/** The most reminders a booking can have. */
|
|
32
40
|
export const MAX_REMINDERS = 3;
|
|
@@ -57,6 +65,36 @@ function hoursProblems(v, at) {
|
|
|
57
65
|
}
|
|
58
66
|
return p;
|
|
59
67
|
}
|
|
68
|
+
function needsProblems(v, at, config) {
|
|
69
|
+
if (config.calendar !== "resources")
|
|
70
|
+
return [`${at}: a service needs resources only with "calendar": "resources"`];
|
|
71
|
+
if (!Array.isArray(v) || v.length === 0 || v.length > MAX_NEEDS)
|
|
72
|
+
return [`${at} must be a list of 1 to ${MAX_NEEDS} groups, each { "any": ["dr-lee", "dr-ng"] }`];
|
|
73
|
+
const known = isObj(config.resources) ? config.resources : {};
|
|
74
|
+
const p = [];
|
|
75
|
+
const seen = new Set();
|
|
76
|
+
let choose = 0;
|
|
77
|
+
v.forEach((g, i) => {
|
|
78
|
+
const here = `${at}[${i}]`;
|
|
79
|
+
if (!isObj(g) || Object.keys(g).some((k) => k !== "any" && k !== "choose") || !Array.isArray(g.any) || g.any.length === 0 || g.any.length > MAX_ANY || (g.choose !== undefined && typeof g.choose !== "boolean")) {
|
|
80
|
+
p.push(`${here} must be { "any": [1 to ${MAX_ANY} resources], "choose": true | false }`);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if (g.choose)
|
|
84
|
+
choose++;
|
|
85
|
+
for (const r of g.any) {
|
|
86
|
+
if (typeof r !== "string" || !Object.hasOwn(known, r))
|
|
87
|
+
p.push(`${here}: ${String(r)} isn't in resources`);
|
|
88
|
+
else if (seen.has(r))
|
|
89
|
+
p.push(`${here}: ${r} is listed twice (a resource is in one group of a service at most)`);
|
|
90
|
+
else
|
|
91
|
+
seen.add(r);
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
if (choose > 1)
|
|
95
|
+
p.push(`${at}: the customer can choose in one group at most`);
|
|
96
|
+
return p;
|
|
97
|
+
}
|
|
60
98
|
function durationProblem(v, at, max, example, zero = false) {
|
|
61
99
|
if (v === undefined)
|
|
62
100
|
return [];
|
|
@@ -107,10 +145,46 @@ export function bookingProblems(value, where = "bookings.json") {
|
|
|
107
145
|
p.push(`${at}.every must be a whole number of minutes from 5 to 720`);
|
|
108
146
|
if (s.hours !== undefined)
|
|
109
147
|
p.push(...hoursProblems(s.hours, `${at}.hours`));
|
|
148
|
+
if (s.needs !== undefined)
|
|
149
|
+
p.push(...needsProblems(s.needs, `${at}.needs`, value));
|
|
150
|
+
if (s.sessions !== undefined && typeof s.sessions !== "boolean")
|
|
151
|
+
p.push(`${at}.sessions must be true or false`);
|
|
152
|
+
if (s.sessions === true)
|
|
153
|
+
for (const k of ["hours", "every", "buffer", "needs"])
|
|
154
|
+
if (s[k] !== undefined)
|
|
155
|
+
p.push(`${at}.${k}: a service booked by sessions has no ${k} (each session has its own time)`);
|
|
110
156
|
}
|
|
111
157
|
}
|
|
112
|
-
if (value.calendar !== undefined && value.calendar !== "shared" && value.calendar !== "per_service")
|
|
113
|
-
p.push("calendar must be shared or
|
|
158
|
+
if (value.calendar !== undefined && value.calendar !== "shared" && value.calendar !== "per_service" && value.calendar !== "resources")
|
|
159
|
+
p.push("calendar must be shared, per_service or resources");
|
|
160
|
+
if (value.resources !== undefined) {
|
|
161
|
+
if (value.calendar !== "resources")
|
|
162
|
+
p.push('resources need "calendar": "resources"');
|
|
163
|
+
if (!isObj(value.resources) || Object.keys(value.resources).length === 0 || Object.keys(value.resources).length > MAX_RESOURCES)
|
|
164
|
+
p.push(`resources must name 1 to ${MAX_RESOURCES} people, rooms or things`);
|
|
165
|
+
else {
|
|
166
|
+
for (const [name, r] of Object.entries(value.resources)) {
|
|
167
|
+
const at = `resources.${name}`;
|
|
168
|
+
if (!NAME.test(name))
|
|
169
|
+
p.push(`${at}: a resource's name is lower case letters, digits and dashes`);
|
|
170
|
+
if (!isObj(r)) {
|
|
171
|
+
p.push(`${at}: not an object`);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
for (const k of Object.keys(r))
|
|
175
|
+
if (!RESOURCE.includes(k))
|
|
176
|
+
p.push(`${at}.${k} isn't a resource setting`);
|
|
177
|
+
if (typeof r.title !== "string" || !r.title.trim() || r.title.length > 80)
|
|
178
|
+
p.push(`${at}.title must be text up to 80 characters`);
|
|
179
|
+
if (r.kind !== undefined && r.kind !== "person" && r.kind !== "room" && r.kind !== "thing")
|
|
180
|
+
p.push(`${at}.kind must be person, room or thing`);
|
|
181
|
+
if (r.hours !== undefined)
|
|
182
|
+
p.push(...hoursProblems(r.hours, `${at}.hours`));
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
else if (value.calendar === "resources")
|
|
187
|
+
p.push('"calendar": "resources" needs resources');
|
|
114
188
|
p.push(...durationProblem(value.notice, "notice", THIRTY_DAYS, "2h", true));
|
|
115
189
|
if (value.ahead_days !== undefined && !whole(value.ahead_days, 1, 365))
|
|
116
190
|
p.push("ahead_days must be a whole number from 1 to 365");
|
|
@@ -144,6 +218,10 @@ export function bookingProblems(value, where = "bookings.json") {
|
|
|
144
218
|
p.push("max_per_customer must be a whole number from 1 to 20");
|
|
145
219
|
if (value.retention_days !== undefined && !whole(value.retention_days, 1, 730))
|
|
146
220
|
p.push("retention_days must be a whole number from 1 to 730");
|
|
221
|
+
if (value.waitlist !== undefined && (!isObj(value.waitlist) || Object.keys(value.waitlist).some((k) => k !== "offer") || durationProblem(value.waitlist.offer, "offer", 7 * 1440, "12h").length > 0)) {
|
|
222
|
+
p.push('waitlist must be { "offer": a length such as "12h" } (up to 7 days)');
|
|
223
|
+
}
|
|
224
|
+
p.push(...durationProblem(value.run_check, "run_check", 30 * 1440, "2d"));
|
|
147
225
|
if (value.plans !== undefined) {
|
|
148
226
|
const pl = value.plans;
|
|
149
227
|
if (!isObj(pl) || Object.keys(pl).some((k) => k !== "feature") || (pl.feature !== undefined && (typeof pl.feature !== "string" || !/^[a-z][a-z0-9_]{0,39}$/.test(pl.feature)))) {
|
package/dist/errors.d.ts
CHANGED
|
@@ -15,6 +15,16 @@ export type BookingsErrorCode =
|
|
|
15
15
|
| "too_late"
|
|
16
16
|
/** No such booking, or it has ended. */
|
|
17
17
|
| "unknown_booking"
|
|
18
|
+
/** No such session, or it isn't this account's. */
|
|
19
|
+
| "unknown_session"
|
|
20
|
+
/** A place is free, but people are waiting for it: join the waiting list. */
|
|
21
|
+
| "waitlist"
|
|
22
|
+
/** There is room and nobody is waiting: book instead of waiting. */
|
|
23
|
+
| "not_full"
|
|
24
|
+
/** This email is already on the waiting list for it. */
|
|
25
|
+
| "already_waiting"
|
|
26
|
+
/** A session can't have fewer places than are already taken. */
|
|
27
|
+
| "too_small"
|
|
18
28
|
/** The account's plan doesn't include bookings. Nothing was written. */
|
|
19
29
|
| "not_allowed"
|
|
20
30
|
/** The database refused or failed. */
|
package/dist/ical.d.ts
CHANGED
|
@@ -9,5 +9,15 @@ export interface EventText {
|
|
|
9
9
|
}
|
|
10
10
|
/** One booking as a calendar file. A cancelled or declined booking is METHOD:CANCEL, so a calendar app that has it takes it off. */
|
|
11
11
|
export declare function bookingIcs(b: Booking, t: EventText, now?: Date): string;
|
|
12
|
+
/** One date of a series booking, for its calendar file. */
|
|
13
|
+
export interface SeriesDate {
|
|
14
|
+
id: string;
|
|
15
|
+
starts_at: string;
|
|
16
|
+
ends_at: string;
|
|
17
|
+
sequence: number;
|
|
18
|
+
text: EventText;
|
|
19
|
+
}
|
|
20
|
+
/** A series booking (a term) as a calendar file: one event for each date. */
|
|
21
|
+
export declare function seriesIcs(b: Booking, dates: readonly SeriesDate[], now?: Date): string;
|
|
12
22
|
/** The owner's feed: every pending and confirmed booking given, as tentative and confirmed events. */
|
|
13
23
|
export declare function feedIcs(name: string, bookings: readonly Booking[], summary: (b: Booking) => string, now?: Date): string;
|
package/dist/ical.js
CHANGED
|
@@ -55,6 +55,20 @@ export function bookingIcs(b, t, now = new Date()) {
|
|
|
55
55
|
"END:VCALENDAR",
|
|
56
56
|
]);
|
|
57
57
|
}
|
|
58
|
+
/** A series booking (a term) as a calendar file: one event for each date. */
|
|
59
|
+
export function seriesIcs(b, dates, now = new Date()) {
|
|
60
|
+
const cancel = b.status === "cancelled" || b.status === "declined";
|
|
61
|
+
const stamp = utc(now.toISOString());
|
|
62
|
+
return wrap([
|
|
63
|
+
"BEGIN:VCALENDAR",
|
|
64
|
+
"VERSION:2.0",
|
|
65
|
+
"PRODID:-//Workbench//workbench-bookings//EN",
|
|
66
|
+
"CALSCALE:GREGORIAN",
|
|
67
|
+
`METHOD:${cancel ? "CANCEL" : "PUBLISH"}`,
|
|
68
|
+
...dates.flatMap((d) => vevent({ ...b, id: `${b.id}-${d.id}`, starts_at: d.starts_at, ends_at: d.ends_at, sequence: b.sequence + d.sequence }, d.text, stamp, cancel)),
|
|
69
|
+
"END:VCALENDAR",
|
|
70
|
+
]);
|
|
71
|
+
}
|
|
58
72
|
/** The owner's feed: every pending and confirmed booking given, as tentative and confirmed events. */
|
|
59
73
|
export function feedIcs(name, bookings, summary, now = new Date()) {
|
|
60
74
|
const stamp = utc(now.toISOString());
|
package/dist/index.d.ts
CHANGED
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
export { createBookings, customerOf, nextReminder, type AccountSettings, type BookRequest, type Bookings, type BookingsClient, type BookingsMailer, type BookingsOptions, type BookingsPlans, type Business } from "./bookings.ts";
|
|
2
|
-
export { bookingProblems, checkBookingConfig, MAX_REMINDERS } from "./config.ts";
|
|
3
|
-
export { openSlots, offered, type SlotQuery } from "./slots.ts";
|
|
4
|
-
export { bookingIcs, feedIcs, type EventText } from "./ical.ts";
|
|
5
|
-
export {
|
|
2
|
+
export { bookingProblems, checkBookingConfig, MAX_NEEDS, MAX_REMINDERS } from "./config.ts";
|
|
3
|
+
export { candidates, openSlots, offered, working, type SlotQuery } from "./slots.ts";
|
|
4
|
+
export { bookingIcs, feedIcs, seriesIcs, type EventText, type SeriesDate } from "./ical.ts";
|
|
5
|
+
export { type SeriesBookRequest, type SessionBookRequest, type SessionBookings, type SessionMethods, type WaitRequest } from "./sessions.ts";
|
|
6
|
+
export { ownerSessionAction, renderRoll, renderSessionAdmin, renderSessionEditor, renderSessionForm, renderSessionList, renderWaitPage, sessionAction, type RollOptions, type SessionActionResult, type SessionAdminOptions, type SessionEditorOptions, type SessionFormOptions, type SessionListOptions, type WaitPageOptions, } from "./session-ui.ts";
|
|
7
|
+
export { bookingsMigration, bookingsMigrations } from "./migration.ts";
|
|
6
8
|
export { STARTER_BOOKINGS } from "./starters.ts";
|
|
7
|
-
export { bookingAction, ownerBookingAction, renderBookingDone, renderBookingForm, renderBookingList, renderBookingManage, renderMyBookings, renderSlotPicker, type ActionResult, type DoneOptions, type FormField, type FormOptions, type ListOptions, type ManageOptions, type MineOptions, type PickerOptions, } from "./ui.ts";
|
|
9
|
+
export { bookingAction, ownerBookingAction, renderBookingDone, renderBookingForm, renderBookingList, renderBookingManage, renderMyBookings, renderSlotPicker, type ActionResult, type DoneOptions, type FormField, type FormOptions, type ListOptions, type ManageOptions, type MineOptions, type PickerChoice, type PickerOptions, } from "./ui.ts";
|
|
8
10
|
export { whenText, type Words } from "./format.ts";
|
|
9
11
|
export { BOOKING_WORDS, BOOKING_WORD_KEYS, type BookingWordKey } from "./words.ts";
|
|
10
12
|
export { BOOKING_STYLES } from "./styles.ts";
|
|
11
13
|
export { BookingsError, type BookingsErrorCode } from "./errors.ts";
|
|
12
14
|
export { BOOKING_STATUSES, WEEKDAYS } from "./types.ts";
|
|
13
|
-
export type { Booking, BookingConfig, BookingConfig as BookingSettings, BookingService, BookingStatus, Busy, CalendarMode, ConfirmMode, Customer, Duration, Slot, SlotDay, TickResult, Weekday, WeekHours } from "./types.ts";
|
|
15
|
+
export type { Booking, BookingConfig, BookingConfig as BookingSettings, BookingResource, BookingService, BookingStatus, Busy, CalendarMode, ConfirmMode, Customer, Duration, ResourceTimes, RollEntry, ServiceNeed, Session, SessionInput, Slot, SlotDay, TickResult, WaitEntry, Weekday, WeekHours } from "./types.ts";
|
package/dist/index.js
CHANGED
|
@@ -5,12 +5,16 @@
|
|
|
5
5
|
// for each booking, a list in the app and a calendar feed. A store in the
|
|
6
6
|
// app's own database (bookingsMigration), a settings file
|
|
7
7
|
// (workbench/bookings.json), and tick() from the app's cron every 15 minutes.
|
|
8
|
+
// Services with "sessions": true are booked by dated sessions the owner makes
|
|
9
|
+
// (a departure, a workshop, a term), with a waiting list and attendance.
|
|
8
10
|
// No AI.
|
|
9
11
|
export { createBookings, customerOf, nextReminder } from "./bookings.js";
|
|
10
|
-
export { bookingProblems, checkBookingConfig, MAX_REMINDERS } from "./config.js";
|
|
11
|
-
export { openSlots, offered } from "./slots.js";
|
|
12
|
-
export { bookingIcs, feedIcs } from "./ical.js";
|
|
13
|
-
export {
|
|
12
|
+
export { bookingProblems, checkBookingConfig, MAX_NEEDS, MAX_REMINDERS } from "./config.js";
|
|
13
|
+
export { candidates, openSlots, offered, working } from "./slots.js";
|
|
14
|
+
export { bookingIcs, feedIcs, seriesIcs } from "./ical.js";
|
|
15
|
+
export {} from "./sessions.js";
|
|
16
|
+
export { ownerSessionAction, renderRoll, renderSessionAdmin, renderSessionEditor, renderSessionForm, renderSessionList, renderWaitPage, sessionAction, } from "./session-ui.js";
|
|
17
|
+
export { bookingsMigration, bookingsMigrations } from "./migration.js";
|
|
14
18
|
export { STARTER_BOOKINGS } from "./starters.js";
|
|
15
19
|
export { bookingAction, ownerBookingAction, renderBookingDone, renderBookingForm, renderBookingList, renderBookingManage, renderMyBookings, renderSlotPicker, } from "./ui.js";
|
|
16
20
|
export { whenText } from "./format.js";
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// The bookings tables' second migration (docs/capabilities/20-capacity-calendar.md):
|
|
2
|
+
// named resources. A booking of a service that needs resources (a practitioner
|
|
3
|
+
// and a room) holds one from each group, in bookings.resources, and
|
|
4
|
+
// bookings_take picks them under the account's lock, so two people can't take
|
|
5
|
+
// the same person or the same room for overlapping times.
|
|
6
|
+
//
|
|
7
|
+
// It only adds: a column with a default, an index, two new functions, and the
|
|
8
|
+
// two read functions (bookings_row, bookings_busy) replaced so they also
|
|
9
|
+
// answer the resources. The first migration's bookings_book and bookings_move
|
|
10
|
+
// stay as they are for services that need no resources, and for a Worker still
|
|
11
|
+
// running 0.2 while this is applied. The down file reverses only this file.
|
|
12
|
+
//
|
|
13
|
+
// Which resources work at the time (their hours, a roster's shifts, leave) is
|
|
14
|
+
// decided by the package before the call: p_needs lists, for each group, only
|
|
15
|
+
// the resources that work then. The database decides who is already booked.
|
|
16
|
+
/** bookings_row at each migration: 1 as the first left it, 2 with resources, 3 with session and series too. */
|
|
17
|
+
export const ROW = (level) => `create or replace function public.bookings_row(b public.bookings)
|
|
18
|
+
returns jsonb
|
|
19
|
+
language sql
|
|
20
|
+
immutable
|
|
21
|
+
security invoker
|
|
22
|
+
set search_path = ''
|
|
23
|
+
as $$
|
|
24
|
+
select jsonb_build_object('id', b.id, 'account', b.account, 'service', b.service, 'starts_at', b.starts_at, 'ends_at', b.ends_at,
|
|
25
|
+
'status', b.status, 'places', b.places, 'member', b.member, 'customer', jsonb_build_object('name', b.customer_name, 'email', b.customer_email, 'phone', b.customer_phone, 'note', b.note),
|
|
26
|
+
'sequence', b.sequence, 'reason', b.reason, 'created_at', b.created_at, 'updated_at', b.updated_at${level >= 2 ? ", 'resources', to_jsonb(b.resources)" : ""}${level >= 3 ? ", 'session', b.session, 'series', b.series" : ""});
|
|
27
|
+
$$;
|
|
28
|
+
`;
|
|
29
|
+
const BUSY = (resources) => `create or replace function public.bookings_busy(p_account text, p_from timestamptz, p_to timestamptz)
|
|
30
|
+
returns jsonb
|
|
31
|
+
language sql
|
|
32
|
+
stable
|
|
33
|
+
security invoker
|
|
34
|
+
set search_path = ''
|
|
35
|
+
as $$
|
|
36
|
+
select coalesce(jsonb_agg(jsonb_build_object('service', b.service, 'starts_at', b.starts_at, 'block_end', b.block_end, 'places', b.places${resources ? ", 'resources', to_jsonb(b.resources)" : ""}) order by b.starts_at), '[]'::jsonb)
|
|
37
|
+
from public.bookings b
|
|
38
|
+
where b.account = p_account and b.status in ('pending', 'confirmed') and b.starts_at < p_to and b.block_end > p_from;
|
|
39
|
+
$$;
|
|
40
|
+
`;
|
|
41
|
+
const TAKE = "text, text, timestamptz, timestamptz, timestamptz, integer, integer, jsonb, text, text, text, text, text, text, text, timestamptz, timestamptz, integer, timestamptz";
|
|
42
|
+
const RETIME = "uuid, timestamptz, timestamptz, timestamptz, integer, jsonb, timestamptz, timestamptz";
|
|
43
|
+
const PICK = "text, text, timestamptz, timestamptz, integer, integer, jsonb, uuid";
|
|
44
|
+
export const bookingsResourcesMigration = {
|
|
45
|
+
up: `alter table public.bookings add column resources text[] not null default '{}' check (cardinality(resources) <= 3);
|
|
46
|
+
|
|
47
|
+
comment on column public.bookings.resources is 'The resources the booking holds (workbench/bookings.json, resources), one from each group its service needs. Empty for a service that needs none.';
|
|
48
|
+
|
|
49
|
+
create index bookings_resources on public.bookings using gin (resources) where status in ('pending', 'confirmed');
|
|
50
|
+
|
|
51
|
+
${ROW(2)}
|
|
52
|
+
${BUSY(true)}
|
|
53
|
+
-- Picks the resources for p_places of p_service at p_start, with the account's
|
|
54
|
+
-- lock already held. p_needs is a list of groups, each a list of the resources
|
|
55
|
+
-- that work at that time. People booked into the same start with the same
|
|
56
|
+
-- resources are one sitting (a class): the booking joins the fullest sitting
|
|
57
|
+
-- that has room and fits p_needs. Otherwise a new sitting opens: each group
|
|
58
|
+
-- gives its free resource with the fewest bookings within 12 hours, then the
|
|
59
|
+
-- first listed. Answers the resources, or null when nothing fits. p_except
|
|
60
|
+
-- leaves out the booking being moved.
|
|
61
|
+
create function public.bookings_pick(p_account text, p_service text, p_start timestamptz, p_block_end timestamptz, p_capacity integer, p_places integer, p_needs jsonb, p_except uuid)
|
|
62
|
+
returns text[]
|
|
63
|
+
language plpgsql
|
|
64
|
+
stable
|
|
65
|
+
security invoker
|
|
66
|
+
set search_path = ''
|
|
67
|
+
as $$
|
|
68
|
+
declare
|
|
69
|
+
v_res text[];
|
|
70
|
+
v_group jsonb;
|
|
71
|
+
v_pick text;
|
|
72
|
+
begin
|
|
73
|
+
if jsonb_typeof(p_needs) is distinct from 'array' or jsonb_array_length(p_needs) not between 1 and 3 then
|
|
74
|
+
raise exception using errcode = '22023', message = 'bookings: needs is 1 to 3 groups';
|
|
75
|
+
end if;
|
|
76
|
+
select s.resources into v_res
|
|
77
|
+
from (select (select array_agg(r order by r) from unnest(b.resources) r) as resources, sum(b.places) as taken
|
|
78
|
+
from public.bookings b
|
|
79
|
+
where b.account = p_account and b.service = p_service and b.starts_at = p_start and b.status in ('pending', 'confirmed')
|
|
80
|
+
and b.id is distinct from p_except and cardinality(b.resources) > 0
|
|
81
|
+
group by 1) s
|
|
82
|
+
where s.taken + p_places <= p_capacity
|
|
83
|
+
and not exists (select 1 from jsonb_array_elements(p_needs) g
|
|
84
|
+
where not exists (select 1 from jsonb_array_elements_text(g.value) c where c.value = any(s.resources)))
|
|
85
|
+
order by s.taken desc, s.resources
|
|
86
|
+
limit 1;
|
|
87
|
+
if v_res is not null then
|
|
88
|
+
return v_res;
|
|
89
|
+
end if;
|
|
90
|
+
v_res := '{}';
|
|
91
|
+
for v_group in select value from jsonb_array_elements(p_needs) loop
|
|
92
|
+
select c.value into v_pick
|
|
93
|
+
from jsonb_array_elements_text(v_group) with ordinality c(value, ord)
|
|
94
|
+
where c.value <> all(v_res)
|
|
95
|
+
and not exists (select 1 from public.bookings x
|
|
96
|
+
where x.account = p_account and x.status in ('pending', 'confirmed') and x.id is distinct from p_except
|
|
97
|
+
and x.resources @> array[c.value] and x.starts_at < p_block_end and x.block_end > p_start)
|
|
98
|
+
order by (select count(*) from public.bookings y
|
|
99
|
+
where y.account = p_account and y.status in ('pending', 'confirmed') and y.resources @> array[c.value]
|
|
100
|
+
and y.starts_at >= p_start - interval '12 hours' and y.starts_at < p_start + interval '12 hours'), c.ord
|
|
101
|
+
limit 1;
|
|
102
|
+
if v_pick is null then
|
|
103
|
+
return null;
|
|
104
|
+
end if;
|
|
105
|
+
v_res := v_res || v_pick;
|
|
106
|
+
end loop;
|
|
107
|
+
return v_res;
|
|
108
|
+
end;
|
|
109
|
+
$$;
|
|
110
|
+
|
|
111
|
+
-- Books a time for a service that needs resources, if one of each is still
|
|
112
|
+
-- free, under the account's lock. Answers the booking, or
|
|
113
|
+
-- { "refused": "taken" | "too_many" }.
|
|
114
|
+
create function public.bookings_take(p_account text, p_service text, p_start timestamptz, p_end timestamptz, p_block_end timestamptz, p_capacity integer, p_places integer, p_needs jsonb,
|
|
115
|
+
p_status text, p_name text, p_email text, p_phone text, p_note text, p_member text, p_hash text, p_next_reminder timestamptz, p_hold_until timestamptz, p_max integer, p_now timestamptz)
|
|
116
|
+
returns jsonb
|
|
117
|
+
language plpgsql
|
|
118
|
+
security invoker
|
|
119
|
+
set search_path = ''
|
|
120
|
+
as $$
|
|
121
|
+
declare
|
|
122
|
+
b public.bookings;
|
|
123
|
+
v_res text[];
|
|
124
|
+
begin
|
|
125
|
+
if p_status not in ('pending', 'confirmed') then
|
|
126
|
+
raise exception using errcode = '22023', message = 'bookings: a new booking is pending or confirmed';
|
|
127
|
+
end if;
|
|
128
|
+
if p_places is null or p_places < 1 or p_places > p_capacity then
|
|
129
|
+
raise exception using errcode = '22023', message = 'bookings: places is 1 to the capacity';
|
|
130
|
+
end if;
|
|
131
|
+
perform pg_advisory_xact_lock(hashtext('workbench-bookings:' || p_account));
|
|
132
|
+
if (select count(*) from public.bookings
|
|
133
|
+
where account = p_account and lower(customer_email) = lower(p_email) and status in ('pending', 'confirmed') and ends_at > p_now) >= p_max then
|
|
134
|
+
return jsonb_build_object('refused', 'too_many');
|
|
135
|
+
end if;
|
|
136
|
+
v_res := public.bookings_pick(p_account, p_service, p_start, p_block_end, p_capacity, p_places, p_needs, null);
|
|
137
|
+
if v_res is null then
|
|
138
|
+
return jsonb_build_object('refused', 'taken');
|
|
139
|
+
end if;
|
|
140
|
+
insert into public.bookings (account, service, starts_at, ends_at, block_end, status, places, resources, customer_name, customer_email, customer_phone, note, member, token_hash,
|
|
141
|
+
next_reminder_at, hold_until, created_at, updated_at)
|
|
142
|
+
values (p_account, p_service, p_start, p_end, p_block_end, p_status, p_places, v_res, p_name, p_email, p_phone, p_note, p_member, p_hash,
|
|
143
|
+
case when p_status = 'confirmed' then p_next_reminder end, case when p_status = 'pending' then p_hold_until end, p_now, p_now)
|
|
144
|
+
returning * into b;
|
|
145
|
+
return public.bookings_row(b);
|
|
146
|
+
end;
|
|
147
|
+
$$;
|
|
148
|
+
|
|
149
|
+
-- Moves a booking that holds resources to a new time, picking again from
|
|
150
|
+
-- p_needs (the package keeps the customer's chosen person by listing only
|
|
151
|
+
-- them). Answers the booking, null when it has ended, or { "refused": "taken" }.
|
|
152
|
+
create function public.bookings_retime(p_id uuid, p_start timestamptz, p_end timestamptz, p_block_end timestamptz, p_capacity integer, p_needs jsonb, p_next_reminder timestamptz, p_now timestamptz)
|
|
153
|
+
returns jsonb
|
|
154
|
+
language plpgsql
|
|
155
|
+
security invoker
|
|
156
|
+
set search_path = ''
|
|
157
|
+
as $$
|
|
158
|
+
declare
|
|
159
|
+
b public.bookings;
|
|
160
|
+
v_res text[];
|
|
161
|
+
begin
|
|
162
|
+
select * into b from public.bookings where id = p_id;
|
|
163
|
+
if not found or b.status not in ('pending', 'confirmed') then
|
|
164
|
+
return null;
|
|
165
|
+
end if;
|
|
166
|
+
perform pg_advisory_xact_lock(hashtext('workbench-bookings:' || b.account));
|
|
167
|
+
v_res := public.bookings_pick(b.account, b.service, p_start, p_block_end, p_capacity, b.places, p_needs, p_id);
|
|
168
|
+
if v_res is null then
|
|
169
|
+
return jsonb_build_object('refused', 'taken');
|
|
170
|
+
end if;
|
|
171
|
+
update public.bookings
|
|
172
|
+
set starts_at = p_start, ends_at = p_end, block_end = p_block_end, resources = v_res, sequence = sequence + 1, reminders_sent = 0,
|
|
173
|
+
next_reminder_at = case when status = 'confirmed' then p_next_reminder end, claim = null, claimed_until = null, updated_at = p_now
|
|
174
|
+
where id = p_id and status in ('pending', 'confirmed')
|
|
175
|
+
returning * into b;
|
|
176
|
+
if not found then
|
|
177
|
+
return null;
|
|
178
|
+
end if;
|
|
179
|
+
return public.bookings_row(b);
|
|
180
|
+
end;
|
|
181
|
+
$$;
|
|
182
|
+
|
|
183
|
+
revoke execute on function public.bookings_pick(${PICK}) from public, anon, authenticated;
|
|
184
|
+
revoke execute on function public.bookings_take(${TAKE}) from public, anon, authenticated;
|
|
185
|
+
revoke execute on function public.bookings_retime(${RETIME}) from public, anon, authenticated;
|
|
186
|
+
grant execute on function public.bookings_pick(${PICK}) to service_role;
|
|
187
|
+
grant execute on function public.bookings_take(${TAKE}) to service_role;
|
|
188
|
+
grant execute on function public.bookings_retime(${RETIME}) to service_role;
|
|
189
|
+
`,
|
|
190
|
+
down: `drop function public.bookings_retime(${RETIME});
|
|
191
|
+
drop function public.bookings_take(${TAKE});
|
|
192
|
+
drop function public.bookings_pick(${PICK});
|
|
193
|
+
${ROW(1)}
|
|
194
|
+
${BUSY(false)}
|
|
195
|
+
drop index public.bookings_resources;
|
|
196
|
+
alter table public.bookings drop column resources;
|
|
197
|
+
`,
|
|
198
|
+
};
|