@ordinatio/scheduling 0.3.0 → 0.4.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/dist/index.js CHANGED
@@ -30,10 +30,17 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
+ BRAND_FIELDS: () => BRAND_FIELDS,
33
34
  BlockedTargetError: () => BlockedTargetError,
34
35
  DEFAULT_BACKOFF_SECONDS: () => DEFAULT_BACKOFF_SECONDS,
36
+ DEFAULT_OFFER_MINUTES: () => DEFAULT_OFFER_MINUTES,
37
+ ERASED_EMAIL: () => ERASED_EMAIL,
38
+ ERASED_NAME: () => ERASED_NAME,
35
39
  MAX_ENDPOINTS_PER_ORGANIZATION: () => MAX_ENDPOINTS_PER_ORGANIZATION,
40
+ MAX_WAITING_PER_TYPE_DAY: () => MAX_WAITING_PER_TYPE_DAY,
41
+ OPERATORS_BY_TYPE: () => OPERATORS_BY_TYPE,
36
42
  RECURRING_MAX_OCCURRENCES: () => RECURRING_MAX_OCCURRENCES,
43
+ ROUTING_LIMITS: () => LIMITS,
37
44
  SCHEDULING_ERRORS: () => SCHEDULING_ERRORS,
38
45
  SIGNATURE_HEADER: () => SIGNATURE_HEADER,
39
46
  SchedulingNotFoundError: () => SchedulingNotFoundError,
@@ -46,7 +53,9 @@ __export(index_exports, {
46
53
  addTimeBlock: () => addTimeBlock,
47
54
  appointmentWebhookData: () => appointmentWebhookData,
48
55
  archiveCalendar: () => archiveCalendar,
56
+ beginWaitlistAccept: () => beginWaitlistAccept,
49
57
  bookAppointment: () => bookAppointment,
58
+ brandTemplateFields: () => brandTemplateFields,
50
59
  buildJitsiUrl: () => buildJitsiUrl,
51
60
  buildNotificationContext: () => buildNotificationContext,
52
61
  buildOccurrenceStartTime: () => buildOccurrenceStartTime,
@@ -54,25 +63,33 @@ __export(index_exports, {
54
63
  calculateCancellationFee: () => calculateCancellationFee,
55
64
  cancelAppointment: () => cancelAppointment,
56
65
  cancelPendingNotifications: () => cancelPendingNotifications,
66
+ checkAnswers: () => checkAnswers,
57
67
  checkAuthContract: () => checkAuthContract,
58
68
  checkCalendarSyncContract: () => checkCalendarSyncContract,
59
69
  checkClockContract: () => checkClockContract,
60
70
  checkNotificationContract: () => checkNotificationContract,
61
71
  checkPaymentContract: () => checkPaymentContract,
62
72
  checkWebhookUrl: () => checkWebhookUrl,
73
+ completeWaitlistAccept: () => completeWaitlistAccept,
63
74
  createAppointmentType: () => createAppointmentType,
64
75
  createCalendar: () => createCalendar,
65
76
  createInMemoryAdapters: () => createInMemoryAdapters,
66
77
  createNodeTransport: () => createNodeTransport,
67
78
  createNotificationTemplate: () => createNotificationTemplate,
79
+ createRoutingForm: () => createRoutingForm,
68
80
  createWebhookEndpoint: () => createWebhookEndpoint,
81
+ deleteBrand: () => deleteBrand,
69
82
  deleteCalendar: () => deleteCalendar,
70
83
  deleteNotificationTemplate: () => deleteNotificationTemplate,
84
+ deleteRoutingForm: () => deleteRoutingForm,
71
85
  deleteWebhookEndpoint: () => deleteWebhookEndpoint,
72
86
  deliverDueWebhooks: () => deliverDueWebhooks,
73
87
  enqueueAppointmentWebhook: () => enqueueAppointmentWebhook,
74
88
  enqueueReminderSent: () => enqueueReminderSent,
75
89
  enqueueWebhookEvent: () => enqueueWebhookEvent,
90
+ eraseSubject: () => eraseSubject,
91
+ expireWaitlistOffers: () => expireWaitlistOffers,
92
+ exportSubject: () => exportSubject,
76
93
  generateOccurrenceDates: () => generateOccurrenceDates,
77
94
  generateWebhookSecret: () => generateWebhookSecret,
78
95
  getAppointment: () => getAppointment,
@@ -82,42 +99,73 @@ __export(index_exports, {
82
99
  getAvailableDates: () => getAvailableDates,
83
100
  getAvailableSlots: () => getAvailableSlots,
84
101
  getBookingAnalytics: () => getBookingAnalytics,
102
+ getBrand: () => getBrand,
85
103
  getCalendar: () => getCalendar,
86
104
  getGroupCapacity: () => getGroupCapacity,
87
105
  getGroupSessions: () => getGroupSessions,
88
106
  getNotificationTemplate: () => getNotificationTemplate,
107
+ getPublicBrand: () => getPublicBrand,
108
+ getPublicRoutingForm: () => getPublicRoutingForm,
109
+ getRoutingForm: () => getRoutingForm,
89
110
  getTeamAvailableSlots: () => getTeamAvailableSlots,
90
111
  getUserDayAppointments: () => getUserDayAppointments,
112
+ getWaitlistOffer: () => getWaitlistOffer,
91
113
  isPrivateAddress: () => isPrivateAddress,
92
114
  isSlotAvailable: () => isSlotAvailable,
93
115
  isVirtualMeeting: () => isVirtualMeeting,
116
+ joinWaitlist: () => joinWaitlist,
117
+ leaveWaitlist: () => leaveWaitlist,
94
118
  listAppointmentTypes: () => listAppointmentTypes,
95
119
  listAppointments: () => listAppointments,
96
120
  listAvailabilityRules: () => listAvailabilityRules,
97
121
  listCalendars: () => listCalendars,
98
122
  listNotificationTemplates: () => listNotificationTemplates,
123
+ listPrivacyRequests: () => listPrivacyRequests,
124
+ listRoutingForms: () => listRoutingForms,
125
+ listWaitlist: () => listWaitlist,
99
126
  listWebhookDeliveries: () => listWebhookDeliveries,
100
127
  listWebhookEndpoints: () => listWebhookEndpoints,
128
+ localDay: () => localDay,
101
129
  localToUTC: () => localToUTC,
102
130
  markNoShow: () => markNoShow,
131
+ matchingRules: () => matchingRules,
132
+ offerFreedSlot: () => offerFreedSlot,
133
+ parseSubject: () => parseSubject,
103
134
  parseTimeLocal: () => parseTimeLocal,
135
+ previewErase: () => previewErase,
104
136
  processPendingNotifications: () => processPendingNotifications,
105
137
  queueImmediateNotification: () => queueImmediateNotification,
106
138
  queueStaffNotification: () => queueStaffNotification,
139
+ releaseWaitlistAccept: () => releaseWaitlistAccept,
107
140
  removeDateOverride: () => removeDateOverride,
141
+ removeWaitlistEntry: () => removeWaitlistEntry,
108
142
  renderTemplate: () => renderTemplate,
109
143
  rescheduleAppointment: () => rescheduleAppointment,
144
+ resolveDestination: () => resolveDestination,
110
145
  resolveLocation: () => resolveLocation,
146
+ resolveSubject: () => resolveSubject,
111
147
  retryWebhookDelivery: () => retryWebhookDelivery,
148
+ routeClient: () => routeClient,
149
+ saveBrand: () => saveBrand,
112
150
  schedError: () => schedError,
113
151
  scheduleNotifications: () => scheduleNotifications,
114
152
  selectCalendarForBooking: () => selectCalendarForBooking,
115
153
  sendTestWebhook: () => sendTestWebhook,
154
+ senderIdentity: () => senderIdentity,
116
155
  setWeeklyAvailability: () => setWeeklyAvailability,
156
+ settleBookedAccept: () => settleBookedAccept,
117
157
  signWebhook: () => signWebhook,
158
+ subjectHashes: () => subjectHashes,
159
+ testRoutingForm: () => testRoutingForm,
160
+ toPublicBrand: () => toPublicBrand,
161
+ tryOfferFreedSlot: () => tryOfferFreedSlot,
118
162
  updateAppointmentType: () => updateAppointmentType,
119
163
  updateCalendar: () => updateCalendar,
120
164
  updateNotificationTemplate: () => updateNotificationTemplate,
165
+ updateRoutingForm: () => updateRoutingForm,
166
+ validateBrand: () => validateBrand,
167
+ validateRoutingDestinations: () => validateRoutingDestinations,
168
+ validateRoutingStructure: () => validateRoutingStructure,
121
169
  verifyWebhookSignature: () => verifyWebhookSignature,
122
170
  withCalendarVisibility: () => withCalendarVisibility
123
171
  });
@@ -1051,7 +1099,7 @@ var WEBHOOK_ERRORS = {
1051
1099
  description: "The webhook event list is empty or names an event that does not exist",
1052
1100
  diagnosis: [
1053
1101
  'Send at least one event name, or "*" for every event',
1054
- "Valid names: appointment.booked, appointment.rescheduled, appointment.cancelled, appointment.no_show, reminder.sent"
1102
+ "Valid names: appointment.booked, appointment.rescheduled, appointment.cancelled, appointment.no_show, reminder.sent, waitlist.offered"
1055
1103
  ]
1056
1104
  },
1057
1105
  SCHED_1002: {
@@ -1113,6 +1161,153 @@ var WEBHOOK_ERRORS = {
1113
1161
  }
1114
1162
  };
1115
1163
 
1164
+ // src/errors/registry-waitlist.ts
1165
+ function entry(code, fn, description, diagnosis, severity = "warning", recoverable = true) {
1166
+ return { code, file: "waitlist/", function: fn, severity, recoverable, description, diagnosis };
1167
+ }
1168
+ var WAITLIST_ERRORS = {
1169
+ SCHED_1100: entry(
1170
+ "SCHED_1100",
1171
+ "joinWaitlist",
1172
+ "The appointment type or calendar for this waitlist request was not found",
1173
+ ["Check the type id and, if given, the calendar id", "The calendar must be one that offers the type", "An inactive type has no waitlist"]
1174
+ ),
1175
+ SCHED_1101: entry(
1176
+ "SCHED_1101",
1177
+ "joinWaitlist",
1178
+ "The waitlist day is invalid, in the past, or too far ahead",
1179
+ ["Send the day as YYYY-MM-DD", "The day must be today or later, and within the next 90 days"]
1180
+ ),
1181
+ SCHED_1102: entry(
1182
+ "SCHED_1102",
1183
+ "joinWaitlist",
1184
+ "The waitlist time is invalid or not on the chosen day",
1185
+ ["Send the time as an ISO date-time on the chosen day, in the future"]
1186
+ ),
1187
+ SCHED_1103: entry(
1188
+ "SCHED_1103",
1189
+ "joinWaitlist",
1190
+ "That time or day still has open slots, so the client should book instead of waiting",
1191
+ ["Look up the open slots for the day", "Join the waitlist only for a slot or day that is full"]
1192
+ ),
1193
+ SCHED_1104: entry(
1194
+ "SCHED_1104",
1195
+ "joinWaitlist",
1196
+ "This email is already waiting for that day",
1197
+ ["The client is already on the list for this type and day", "They can leave with their link and join again"]
1198
+ ),
1199
+ SCHED_1105: entry(
1200
+ "SCHED_1105",
1201
+ "joinWaitlist",
1202
+ "A waitlist is not available for a type that needs payment",
1203
+ ["Payment cannot be taken when an offer is accepted", "Use a free type, or let clients book as slots open"]
1204
+ ),
1205
+ SCHED_1106: entry(
1206
+ "SCHED_1106",
1207
+ "getWaitlistOffer",
1208
+ "No open offer for this link",
1209
+ ["The link may be wrong, already used, or the entry may have left the list", "An offer can be accepted once"]
1210
+ ),
1211
+ SCHED_1107: entry(
1212
+ "SCHED_1107",
1213
+ "beginWaitlistAccept",
1214
+ "The offer has expired",
1215
+ ["The time limit ran out; the slot may have gone to the next person", "Join the waitlist again to wait for another slot"]
1216
+ ),
1217
+ SCHED_1108: entry(
1218
+ "SCHED_1108",
1219
+ "joinWaitlist",
1220
+ "The waitlist for that day is full",
1221
+ ["Too many people are already waiting for this type and day"]
1222
+ ),
1223
+ SCHED_1109: entry(
1224
+ "SCHED_1109",
1225
+ "offerFreedSlot",
1226
+ "A waitlist offer could not be made; the cancellation itself was saved",
1227
+ ["Check that the waitlist table exists (run the package migrations)", "Check the database connection"],
1228
+ "error"
1229
+ ),
1230
+ SCHED_1110: entry(
1231
+ "SCHED_1110",
1232
+ "joinWaitlist",
1233
+ "A waitlist is not available for a type with required intake questions",
1234
+ ["An accepted offer books without form answers, so the required questions could not be answered", "Make the questions optional, or let clients book as slots open"]
1235
+ )
1236
+ };
1237
+
1238
+ // src/errors/registry-routing.ts
1239
+ function entry2(code, fn, description, diagnosis, severity = "warning") {
1240
+ return { code, file: "routing/", function: fn, severity, recoverable: true, description, diagnosis };
1241
+ }
1242
+ var ROUTING_ERRORS = {
1243
+ SCHED_1200: entry2(
1244
+ "SCHED_1200",
1245
+ "validateRoutingForm",
1246
+ "The routing form is not valid",
1247
+ ["Read the list of problems in the error context: each names the part of the form and what is wrong", "Every rule must name questions that exist, use an operator that fits the question, and send the client somewhere that is live"]
1248
+ ),
1249
+ SCHED_1201: entry2(
1250
+ "SCHED_1201",
1251
+ "routing form lookup",
1252
+ "The routing form was not found (for the public: no active form with that slug)",
1253
+ ["Check the form address (slug)", "A form that is switched off, or that belongs to another organization, is not found", "With several organizations in one database, name the organization"]
1254
+ ),
1255
+ SCHED_1202: entry2(
1256
+ "SCHED_1202",
1257
+ "createRoutingForm / updateRoutingForm",
1258
+ "Another routing form already uses that slug",
1259
+ ["Choose a different slug", "A slug is unique within the organization and must not be used by another organization in the same database"]
1260
+ ),
1261
+ SCHED_1203: entry2(
1262
+ "SCHED_1203",
1263
+ "routeClient",
1264
+ "The answers do not fit the form",
1265
+ ["Answer every required question", "Pick an offered option for choice questions, and send a list for checkbox questions", "Send only questions the form asks"]
1266
+ ),
1267
+ SCHED_1204: entry2(
1268
+ "SCHED_1204",
1269
+ "createRoutingForm",
1270
+ "The organization already has the maximum number of routing forms",
1271
+ ["Remove a form that is no longer used, then add the new one"]
1272
+ )
1273
+ };
1274
+
1275
+ // src/errors/registry-privacy.ts
1276
+ function entry3(code, fn, description, diagnosis) {
1277
+ return { code, file: "privacy/", function: fn, severity: "warning", recoverable: true, description, diagnosis };
1278
+ }
1279
+ var PRIVACY_ERRORS = {
1280
+ SCHED_1300: entry3(
1281
+ "SCHED_1300",
1282
+ "parseSubject",
1283
+ "Say whose data this is: a valid email address, a client id, or both",
1284
+ ["Send `email` (one address) and/or `clientId`", "An address must be a single address with no spaces, at most 254 characters"]
1285
+ ),
1286
+ SCHED_1301: entry3(
1287
+ "SCHED_1301",
1288
+ "eraseSubject",
1289
+ "This person still has upcoming bookings or an open waitlist offer, so their data cannot be erased yet",
1290
+ ["Cancel or complete the upcoming bookings, and remove the waitlist entries that hold or are taking an offer", "Run the erase preview to see how many of each remain", "Then ask again"]
1291
+ )
1292
+ };
1293
+
1294
+ // src/errors/registry-brand.ts
1295
+ var BRAND_ERRORS = {
1296
+ SCHED_1400: {
1297
+ code: "SCHED_1400",
1298
+ file: "brand/",
1299
+ function: "validateBrand",
1300
+ severity: "warning",
1301
+ recoverable: true,
1302
+ description: "The brand settings are not valid",
1303
+ diagnosis: [
1304
+ "Read the list of problems in the error context: each names the field and what is wrong",
1305
+ "Colours are hex values such as #1a2b3c; the logo is an https address; email addresses are single plain addresses",
1306
+ "A sending address is accepted only for a domain the host has confirmed it may send from"
1307
+ ]
1308
+ }
1309
+ };
1310
+
1116
1311
  // src/errors/registry.ts
1117
1312
  var SCHEDULING_ERRORS = {
1118
1313
  ...CALENDARS_AVAILABILITY_ERRORS,
@@ -1123,7 +1318,11 @@ var SCHEDULING_ERRORS = {
1123
1318
  ...RECURRING_MISC_ERRORS,
1124
1319
  ...PUBLIC_DIRECTORY_ERRORS,
1125
1320
  ...GROUP_SCOPE_ERRORS,
1126
- ...WEBHOOK_ERRORS
1321
+ ...WEBHOOK_ERRORS,
1322
+ ...WAITLIST_ERRORS,
1323
+ ...ROUTING_ERRORS,
1324
+ ...PRIVACY_ERRORS,
1325
+ ...BRAND_ERRORS
1127
1326
  };
1128
1327
 
1129
1328
  // src/errors/diagnostic-error.ts
@@ -2213,9 +2412,7 @@ async function bookAppointment(db, input, callbacks) {
2213
2412
  clientName: input.clientName,
2214
2413
  clientEmail: input.clientEmail,
2215
2414
  clientPhone: input.clientPhone ?? null,
2216
- // ALFRED-246 (system-1701's .autocode/modules/alfred/debt.md): the public booking
2217
- // route passes this through from caller-supplied, unauthenticated input with no
2218
- // existence/ownership check — a real, disclosed, not-yet-fixed gap.
2415
+ // Not verified here: a caller that takes this from unauthenticated input must check it first.
2219
2416
  clientId: input.clientId ?? null,
2220
2417
  intakeResponses: input.intakeResponses,
2221
2418
  staffNotes: input.staffNotes ?? null,
@@ -2318,13 +2515,13 @@ function renderTemplate(template, context, channel = "EMAIL") {
2318
2515
  for (const [key, value] of Object.entries(context)) {
2319
2516
  if (typeof value === "string") {
2320
2517
  const safeValue = channel === "SMS" ? value : escapeHtml(value);
2321
- result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), safeValue);
2518
+ result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), () => safeValue);
2322
2519
  }
2323
2520
  }
2324
2521
  if (context.customFields) {
2325
2522
  for (const [key, value] of Object.entries(context.customFields)) {
2326
2523
  const safeValue = channel === "SMS" ? value : escapeHtml(value);
2327
- result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), safeValue);
2524
+ result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), () => safeValue);
2328
2525
  }
2329
2526
  }
2330
2527
  if (channel === "SMS") {
@@ -2377,6 +2574,196 @@ function buildNotificationContext(appointment, baseUrl) {
2377
2574
  };
2378
2575
  }
2379
2576
 
2577
+ // src/brand/sender.ts
2578
+ var NOT_IN_A_SENDER_NAME = /[<>",;@\\]/g;
2579
+ function senderIdentity(brand) {
2580
+ if (!brand) return null;
2581
+ const fallbackName = brand.displayName.replace(/[\u0000-\u001f\u007f]/g, " ").replace(NOT_IN_A_SENDER_NAME, "").replace(/\s+/g, " ").trim();
2582
+ const name = brand.fromName ?? (fallbackName || void 0);
2583
+ return {
2584
+ ...name ? { name } : {},
2585
+ ...brand.fromEmail ? { email: brand.fromEmail } : {},
2586
+ ...brand.replyToEmail ? { replyTo: brand.replyToEmail } : {}
2587
+ };
2588
+ }
2589
+ function brandTemplateFields(brand) {
2590
+ return {
2591
+ brandName: brand?.displayName ?? "",
2592
+ brandLogoUrl: brand?.logoUrl ?? "",
2593
+ brandColor: brand?.primaryColor ?? "",
2594
+ brandFooter: brand?.footerText ?? ""
2595
+ };
2596
+ }
2597
+ function toPublicBrand(brand) {
2598
+ return {
2599
+ displayName: brand.displayName,
2600
+ logoUrl: brand.logoUrl,
2601
+ primaryColor: brand.primaryColor,
2602
+ accentColor: brand.accentColor,
2603
+ backgroundColor: brand.backgroundColor,
2604
+ textColor: brand.textColor,
2605
+ fontFamily: brand.fontFamily,
2606
+ footerText: brand.footerText
2607
+ };
2608
+ }
2609
+
2610
+ // src/brand/types.ts
2611
+ var BRAND_FIELDS = [
2612
+ "displayName",
2613
+ "logoUrl",
2614
+ "primaryColor",
2615
+ "accentColor",
2616
+ "backgroundColor",
2617
+ "textColor",
2618
+ "fontFamily",
2619
+ "footerText",
2620
+ "replyToEmail",
2621
+ "fromName",
2622
+ "fromEmail"
2623
+ ];
2624
+
2625
+ // src/brand/validate.ts
2626
+ var HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
2627
+ var FONT = /^[A-Za-z0-9 ,-]{1,100}$/;
2628
+ var EMAIL = /^[^\s@<>,;"'()[\]\\]+@[^\s@<>,;"'()[\]\\]+\.[^\s@<>,;"'()[\]\\]+$/;
2629
+ var CONTROL = /[\u0000-\u001f\u007f]/;
2630
+ var COLOR_FIELDS = ["primaryColor", "accentColor", "backgroundColor", "textColor"];
2631
+ function text(value, path, max, problems, required = false) {
2632
+ if (value === void 0 || value === null || value === "") {
2633
+ if (required) problems.push({ path, message: "Required" });
2634
+ return null;
2635
+ }
2636
+ if (typeof value !== "string") {
2637
+ problems.push({ path, message: "Must be text" });
2638
+ return null;
2639
+ }
2640
+ const trimmed = value.trim();
2641
+ if (trimmed.length === 0) {
2642
+ if (required) problems.push({ path, message: "Required" });
2643
+ return null;
2644
+ }
2645
+ if (trimmed.length > max) problems.push({ path, message: `At most ${max} characters` });
2646
+ else if (CONTROL.test(trimmed)) problems.push({ path, message: "Must not contain control characters" });
2647
+ else return trimmed;
2648
+ return null;
2649
+ }
2650
+ function email(value, path, problems) {
2651
+ const raw = text(value, path, 254, problems);
2652
+ if (raw === null) return null;
2653
+ if (!EMAIL.test(raw)) {
2654
+ problems.push({ path, message: "Must be a single email address" });
2655
+ return null;
2656
+ }
2657
+ return raw.toLowerCase();
2658
+ }
2659
+ function logo(value, problems) {
2660
+ const raw = text(value, "logoUrl", 500, problems);
2661
+ if (raw === null) return null;
2662
+ try {
2663
+ const url = new URL(raw);
2664
+ if (url.protocol === "https:" && !url.username && !url.password && url.hostname) return raw;
2665
+ } catch {
2666
+ }
2667
+ problems.push({ path: "logoUrl", message: "Must be an https address without a user name or password" });
2668
+ return null;
2669
+ }
2670
+ async function validateBrand(input, options) {
2671
+ const problems = [];
2672
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
2673
+ throw new SchedulingValidationError("The brand settings are not valid", "SCHED_1400", { errors: [{ path: "", message: "Must be an object" }] });
2674
+ }
2675
+ const given = input;
2676
+ for (const key of Object.keys(given)) if (!BRAND_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
2677
+ const out = {
2678
+ displayName: text(given.displayName, "displayName", 100, problems, true) ?? "",
2679
+ logoUrl: logo(given.logoUrl, problems),
2680
+ primaryColor: null,
2681
+ accentColor: null,
2682
+ backgroundColor: null,
2683
+ textColor: null,
2684
+ fontFamily: null,
2685
+ footerText: text(given.footerText, "footerText", 300, problems),
2686
+ replyToEmail: email(given.replyToEmail, "replyToEmail", problems),
2687
+ fromName: text(given.fromName, "fromName", 100, problems),
2688
+ fromEmail: email(given.fromEmail, "fromEmail", problems)
2689
+ };
2690
+ for (const field of COLOR_FIELDS) {
2691
+ const raw = text(given[field], field, 7, problems);
2692
+ if (raw === null) continue;
2693
+ if (HEX.test(raw)) out[field] = raw.toLowerCase();
2694
+ else problems.push({ path: field, message: "Must be a hex colour such as #1a2b3c" });
2695
+ }
2696
+ const font = text(given.fontFamily, "fontFamily", 100, problems);
2697
+ if (font !== null) {
2698
+ if (FONT.test(font)) out.fontFamily = font;
2699
+ else problems.push({ path: "fontFamily", message: "Letters, digits, spaces, commas and dashes only" });
2700
+ }
2701
+ if (out.fromName !== null && /[<>",;@\\]/.test(out.fromName)) {
2702
+ problems.push({ path: "fromName", message: "Must not contain quotes, angle brackets, commas, semicolons, @ or backslashes" });
2703
+ out.fromName = null;
2704
+ }
2705
+ if (out.fromEmail !== null && !problems.some((p) => p.path === "fromEmail")) {
2706
+ const domain = out.fromEmail.slice(out.fromEmail.lastIndexOf("@") + 1);
2707
+ let verified = false;
2708
+ try {
2709
+ verified = options.isSendingDomainVerified ? await options.isSendingDomainVerified(domain) : false;
2710
+ } catch (error) {
2711
+ console.error("[brand] the sending-domain check failed:", error);
2712
+ verified = false;
2713
+ }
2714
+ if (!verified) problems.push({ path: "fromEmail", message: `Sending from ${domain} is not confirmed for this server` });
2715
+ }
2716
+ if (problems.length > 0) throw new SchedulingValidationError("The brand settings are not valid", "SCHED_1400", { errors: problems });
2717
+ return out;
2718
+ }
2719
+
2720
+ // src/brand/crud.ts
2721
+ var SELECT = {
2722
+ displayName: true,
2723
+ logoUrl: true,
2724
+ primaryColor: true,
2725
+ accentColor: true,
2726
+ backgroundColor: true,
2727
+ textColor: true,
2728
+ fontFamily: true,
2729
+ footerText: true,
2730
+ replyToEmail: true,
2731
+ fromName: true,
2732
+ fromEmail: true,
2733
+ updatedAt: true
2734
+ };
2735
+ async function getBrand(db, organizationId) {
2736
+ return db.organizationBrand.findUnique({ where: { organizationId }, select: SELECT });
2737
+ }
2738
+ async function getPublicBrand(db, organizationId) {
2739
+ if (organizationId) {
2740
+ const brand = await getBrand(db, organizationId);
2741
+ return brand ? toPublicBrand(brand) : null;
2742
+ }
2743
+ const all = await db.organizationBrand.findMany({ take: 2, select: SELECT });
2744
+ return all.length === 1 ? toPublicBrand(all[0]) : null;
2745
+ }
2746
+ async function saveBrand(db, organizationId, input, options) {
2747
+ const fields = await validateBrand(input, options);
2748
+ return db.organizationBrand.upsert({
2749
+ where: { organizationId },
2750
+ create: { organizationId, ...fields },
2751
+ update: { ...fields },
2752
+ select: SELECT
2753
+ });
2754
+ }
2755
+ async function deleteBrand(db, organizationId) {
2756
+ const { count } = await db.organizationBrand.deleteMany({ where: { organizationId } });
2757
+ return count > 0;
2758
+ }
2759
+
2760
+ // src/notifications/brand-context.ts
2761
+ async function withBrandFields(db, organizationId, context, enabled) {
2762
+ if (!enabled) return context;
2763
+ const brand = organizationId ? await getBrand(db, organizationId) : null;
2764
+ return { ...context, customFields: { ...context.customFields, ...brandTemplateFields(brand) } };
2765
+ }
2766
+
2380
2767
  // src/notifications/process-pending-notifications.ts
2381
2768
  var import_crypto = require("crypto");
2382
2769
  var import_client6 = require("@prisma/client");
@@ -2388,7 +2775,8 @@ var WEBHOOK_EVENT_TYPES = [
2388
2775
  "appointment.rescheduled",
2389
2776
  "appointment.cancelled",
2390
2777
  "appointment.no_show",
2391
- "reminder.sent"
2778
+ "reminder.sent",
2779
+ "waitlist.offered"
2392
2780
  ];
2393
2781
  var WEBHOOK_TEST_EVENT = "webhook.test";
2394
2782
  var ALL_EVENTS = "*";
@@ -2535,8 +2923,10 @@ async function processPendingNotifications(db, sender, options) {
2535
2923
  `;
2536
2924
  if (claimed.length === 0) return { sent: 0, failed: 0, deadLettered: 0, skipped: 0 };
2537
2925
  const pending = await db.scheduledNotification.findMany({
2538
- where: { id: { in: claimed.map((c) => c.id) } }
2926
+ where: { id: { in: claimed.map((c) => c.id) } },
2927
+ ...options?.brand ? { include: { appointment: { select: { calendar: { select: { organizationId: true } } } } } } : {}
2539
2928
  });
2929
+ const senders = options?.brand ? await loadSenders(db, pending) : null;
2540
2930
  let sent = 0;
2541
2931
  let failed = 0;
2542
2932
  let deadLettered = 0;
@@ -2548,7 +2938,10 @@ async function processPendingNotifications(db, sender, options) {
2548
2938
  notification.recipient,
2549
2939
  notification.subject || "",
2550
2940
  notification.body,
2551
- { trigger: notification.trigger }
2941
+ {
2942
+ trigger: notification.trigger,
2943
+ ...senderFor(senders, notification)
2944
+ }
2552
2945
  );
2553
2946
  if (result?.skipped) {
2554
2947
  await db.scheduledNotification.update({
@@ -2602,6 +2995,22 @@ async function processPendingNotifications(db, sender, options) {
2602
2995
  }
2603
2996
  return { sent, failed, deadLettered, skipped };
2604
2997
  }
2998
+ async function loadSenders(db, rows) {
2999
+ const ids = [...new Set(rows.map((row) => row.appointment?.calendar?.organizationId).filter((id) => Boolean(id)))];
3000
+ const senders = /* @__PURE__ */ new Map();
3001
+ if (ids.length === 0) return senders;
3002
+ const brands = await db.organizationBrand.findMany({ where: { organizationId: { in: ids } } });
3003
+ for (const brand of brands) {
3004
+ const identity = senderIdentity(brand);
3005
+ if (identity) senders.set(brand.organizationId, identity);
3006
+ }
3007
+ return senders;
3008
+ }
3009
+ function senderFor(senders, row) {
3010
+ const organizationId = row.appointment?.calendar?.organizationId;
3011
+ const from = senders && organizationId ? senders.get(organizationId) : void 0;
3012
+ return from ? { from } : {};
3013
+ }
2605
3014
 
2606
3015
  // src/notifications/engine.ts
2607
3016
  async function scheduleNotifications(db, appointmentId, baseUrl, options) {
@@ -2621,10 +3030,10 @@ async function scheduleNotifications(db, appointmentId, baseUrl, options) {
2621
3030
  }
2622
3031
  });
2623
3032
  if (!appointment) return;
2624
- const context = buildNotificationContext({
3033
+ const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
2625
3034
  ...appointment,
2626
3035
  intakeResponses: appointment.intakeResponses
2627
- }, baseUrl);
3036
+ }, baseUrl), options?.brand);
2628
3037
  const now = /* @__PURE__ */ new Date();
2629
3038
  const startTime = new Date(appointment.startTime);
2630
3039
  const templates = await db.notificationTemplate.findMany({
@@ -2697,7 +3106,7 @@ async function cancelPendingNotifications(db, appointmentId) {
2697
3106
  data: { status: "CANCELLED" }
2698
3107
  });
2699
3108
  }
2700
- async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
3109
+ async function queueImmediateNotification(db, appointmentId, trigger, baseUrl, options) {
2701
3110
  const appointment = await db.appointment.findUnique({
2702
3111
  where: { id: appointmentId },
2703
3112
  include: {
@@ -2706,10 +3115,10 @@ async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
2706
3115
  }
2707
3116
  });
2708
3117
  if (!appointment) return;
2709
- const context = buildNotificationContext({
3118
+ const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
2710
3119
  ...appointment,
2711
3120
  intakeResponses: appointment.intakeResponses
2712
- }, baseUrl);
3121
+ }, baseUrl), options?.brand);
2713
3122
  const templates = await db.notificationTemplate.findMany({
2714
3123
  where: { trigger, isActive: true, recipientType: "CLIENT", organizationId: appointment.calendar.organizationId ?? "" }
2715
3124
  });
@@ -2735,7 +3144,7 @@ async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
2735
3144
  await db.scheduledNotification.createMany({ data: notifications });
2736
3145
  }
2737
3146
  }
2738
- async function queueStaffNotification(db, appointmentId, trigger, baseUrl) {
3147
+ async function queueStaffNotification(db, appointmentId, trigger, baseUrl, options) {
2739
3148
  const appointment = await db.appointment.findUnique({
2740
3149
  where: { id: appointmentId },
2741
3150
  include: {
@@ -2750,10 +3159,10 @@ async function queueStaffNotification(db, appointmentId, trigger, baseUrl) {
2750
3159
  where: { trigger, recipientType: "STAFF", isActive: true, organizationId: appointment.calendar.organizationId ?? "" }
2751
3160
  });
2752
3161
  if (staffTemplates.length === 0) return;
2753
- const context = buildNotificationContext({
3162
+ const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
2754
3163
  ...appointment,
2755
3164
  intakeResponses: appointment.intakeResponses
2756
- }, baseUrl);
3165
+ }, baseUrl), options?.brand);
2757
3166
  const now = /* @__PURE__ */ new Date();
2758
3167
  const notifications = staffTemplates.map((template) => ({
2759
3168
  appointmentId: appointment.id,
@@ -3700,7 +4109,7 @@ function adaptersToCallbacks(adapters, passThrough = {}) {
3700
4109
  return {
3701
4110
  ...passThrough,
3702
4111
  sendNotification: async (channel, to, subject, body, context) => {
3703
- const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger });
4112
+ const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger, ...context?.from ? { from: context.from } : {} });
3704
4113
  if (result.status === "SKIPPED") return { skipped: true, reason: result.reason };
3705
4114
  return void 0;
3706
4115
  },
@@ -3748,10 +4157,10 @@ async function checkNotificationContract(adapter) {
3748
4157
  const result = await adapter.send({ channel: "EMAIL", to: "contract@example.com", subject: "Contract", body: "Body" });
3749
4158
  if (result.status !== "SENT" && result.status !== "SKIPPED") failures.push("send() must return status SENT or SKIPPED");
3750
4159
  });
3751
- for (const blank of ["", " "]) {
3752
- await guarded(`send to an empty recipient (${JSON.stringify(blank)})`, failures, async () => {
3753
- const result = await adapter.send({ channel: "SMS", to: blank, subject: "", body: "Body" }).catch(() => null);
3754
- if (result?.status === "SENT") failures.push(`send() must not report SENT for an empty recipient (${JSON.stringify(blank)})`);
4160
+ for (const blank2 of ["", " "]) {
4161
+ await guarded(`send to an empty recipient (${JSON.stringify(blank2)})`, failures, async () => {
4162
+ const result = await adapter.send({ channel: "SMS", to: blank2, subject: "", body: "Body" }).catch(() => null);
4163
+ if (result?.status === "SENT") failures.push(`send() must not report SENT for an empty recipient (${JSON.stringify(blank2)})`);
3755
4164
  });
3756
4165
  }
3757
4166
  return failures;
@@ -3771,7 +4180,7 @@ async function checkPaymentContract(adapter, options = {}) {
3771
4180
  if (!await refused(() => adapter.charge({ ...request, amount: 0 }))) failures.push("a charge of 0 must not succeed");
3772
4181
  });
3773
4182
  await guarded("verify of an unknown payment", failures, async () => {
3774
- const paid = await adapter.verify("contract-unknown-payment").then((check) => check.paid, () => false);
4183
+ const paid = await adapter.verify("contract-unknown-payment").then((check2) => check2.paid, () => false);
3775
4184
  if (paid) failures.push("verify() must report an unknown payment as not paid");
3776
4185
  });
3777
4186
  await guarded("refund of an unknown payment", failures, async () => {
@@ -3787,10 +4196,10 @@ async function checkPaymentContract(adapter, options = {}) {
3787
4196
  failures.push("a valid charge must succeed and return a paymentId");
3788
4197
  return;
3789
4198
  }
3790
- const check = await adapter.verify(charge.paymentId);
3791
- if (!check.paid) failures.push("verify() must report a charged payment as paid");
3792
- if (check.amount !== void 0 && check.amount !== request.amount) failures.push("verify() must report the amount that was charged");
3793
- if (check.metadata?.contract !== "metadata-round-trip") failures.push("verify() must return the metadata the charge was made with");
4199
+ const check2 = await adapter.verify(charge.paymentId);
4200
+ if (!check2.paid) failures.push("verify() must report a charged payment as paid");
4201
+ if (check2.amount !== void 0 && check2.amount !== request.amount) failures.push("verify() must report the amount that was charged");
4202
+ if (check2.metadata?.contract !== "metadata-round-trip") failures.push("verify() must return the metadata the charge was made with");
3794
4203
  const first = await adapter.refund(charge.paymentId);
3795
4204
  if (!first.success) failures.push("the first refund of a paid payment must succeed");
3796
4205
  if (first.amount !== void 0 && first.amount !== request.amount) failures.push("a full refund must report the amount it refunded");
@@ -4059,7 +4468,7 @@ function buildRecurringSlots(firstDate, frequency, occurrences, startTimeLocal,
4059
4468
 
4060
4469
  // src/appointments/meeting.ts
4061
4470
  function buildJitsiUrl(appointmentId) {
4062
- return `https://meet.jit.si/s1701-${appointmentId}`;
4471
+ return `https://meet.jit.si/ordinatio-${appointmentId}`;
4063
4472
  }
4064
4473
  function isVirtualMeeting(locationType) {
4065
4474
  return locationType === "VIRTUAL";
@@ -4175,13 +4584,13 @@ function isPrivateV4(ip) {
4175
4584
  return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 0 && c === 0 || a === 192 && b === 168 || a === 198 && (b === 18 || b === 19) || a >= 224;
4176
4585
  }
4177
4586
  function v6Groups(ip) {
4178
- let text = ip.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0];
4179
- const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(text);
4587
+ let text2 = ip.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0];
4588
+ const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(text2);
4180
4589
  if (tail) {
4181
4590
  const [a, b, c, d] = v4Parts(tail[1]);
4182
- text = text.slice(0, -tail[1].length) + (a << 8 | b).toString(16) + ":" + (c << 8 | d).toString(16);
4591
+ text2 = text2.slice(0, -tail[1].length) + (a << 8 | b).toString(16) + ":" + (c << 8 | d).toString(16);
4183
4592
  }
4184
- const halves = text.split("::");
4593
+ const halves = text2.split("::");
4185
4594
  if (halves.length > 2) return null;
4186
4595
  const head = halves[0] ? halves[0].split(":") : [];
4187
4596
  const rest = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
@@ -4521,12 +4930,1211 @@ async function retryWebhookDelivery(db, organizationId, deliveryId, now = /* @__
4521
4930
  });
4522
4931
  if (updated.count === 0) throw new SchedulingNotFoundError("Delivery not found or not in the dead-letter list", "SCHED_1004", { deliveryId });
4523
4932
  }
4933
+
4934
+ // src/waitlist/join.ts
4935
+ var import_node_crypto5 = require("crypto");
4936
+
4937
+ // src/waitlist/day.ts
4938
+ var MAX_DAYS_AHEAD = 90;
4939
+ function isDayString(value) {
4940
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
4941
+ const parsed = /* @__PURE__ */ new Date(`${value}T00:00:00Z`);
4942
+ return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
4943
+ }
4944
+ function localDay(instant, timeZone) {
4945
+ return new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).format(instant);
4946
+ }
4947
+ function daysBetween(from, to) {
4948
+ return Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 864e5);
4949
+ }
4950
+
4951
+ // src/waitlist/view.ts
4952
+ var VIEW_SELECT = {
4953
+ id: true,
4954
+ typeId: true,
4955
+ calendarId: true,
4956
+ day: true,
4957
+ slotStart: true,
4958
+ clientName: true,
4959
+ clientEmail: true,
4960
+ clientPhone: true,
4961
+ status: true,
4962
+ offerSlotStart: true,
4963
+ offerExpiresAt: true,
4964
+ createdAt: true
4965
+ };
4966
+ var LIVE_STATUSES = ["WAITING", "OFFERED", "ACCEPTING"];
4967
+
4968
+ // src/waitlist/join.ts
4969
+ var MAX_WAITING_PER_TYPE_DAY = 50;
4970
+ async function joinWaitlist(db, input, now = /* @__PURE__ */ new Date()) {
4971
+ const orgScope = [{ organizationId: input.organizationId }, { organizationId: null }];
4972
+ const type = await db.appointmentType.findFirst({
4973
+ where: { id: input.typeId, isActive: true, OR: orgScope },
4974
+ select: { id: true, duration: true, requiresPayment: true, intakeForm: true, calendars: { select: { calendarId: true } } }
4975
+ });
4976
+ if (!type) throw new SchedulingNotFoundError("Appointment type not found", "SCHED_1100", { typeId: input.typeId });
4977
+ if (type.requiresPayment) {
4978
+ throw new SchedulingValidationError("A waitlist is not available for a type that needs payment", "SCHED_1105", { typeId: input.typeId });
4979
+ }
4980
+ const intakeForm = Array.isArray(type.intakeForm) ? type.intakeForm : [];
4981
+ if (intakeForm.some((field) => field.required)) {
4982
+ throw new SchedulingValidationError("A waitlist is not available for a type with required questions", "SCHED_1110", { typeId: input.typeId });
4983
+ }
4984
+ const linked = type.calendars.map((c) => c.calendarId);
4985
+ if (input.calendarId && !linked.includes(input.calendarId)) {
4986
+ throw new SchedulingNotFoundError("Calendar not found for this type", "SCHED_1100", { calendarId: input.calendarId });
4987
+ }
4988
+ const calendars = await db.schedulingCalendar.findMany({
4989
+ where: { id: { in: input.calendarId ? [input.calendarId] : linked }, OR: orgScope },
4990
+ select: { id: true, timezone: true }
4991
+ });
4992
+ if (calendars.length === 0) throw new SchedulingNotFoundError("Calendar not found for this type", "SCHED_1100", { typeId: input.typeId });
4993
+ const timezone = calendars[0].timezone;
4994
+ if (!isDayString(input.day)) throw new SchedulingValidationError("The day must be YYYY-MM-DD", "SCHED_1101", { day: input.day });
4995
+ const ahead = daysBetween(localDay(now, timezone), input.day);
4996
+ if (ahead < 0 || ahead > MAX_DAYS_AHEAD) {
4997
+ throw new SchedulingValidationError(`The day must be within the next ${MAX_DAYS_AHEAD} days`, "SCHED_1101", { day: input.day });
4998
+ }
4999
+ if (input.slotStart) {
5000
+ if (Number.isNaN(input.slotStart.getTime()) || input.slotStart <= now || localDay(input.slotStart, timezone) !== input.day) {
5001
+ throw new SchedulingValidationError("The time must be in the future, on the chosen day", "SCHED_1102", { day: input.day });
5002
+ }
5003
+ }
5004
+ const open = [];
5005
+ for (const calendar of calendars) {
5006
+ const result = await getAvailableSlots(db, {
5007
+ calendarId: calendar.id,
5008
+ date: /* @__PURE__ */ new Date(`${input.day}T12:00:00Z`),
5009
+ localDate: input.day,
5010
+ duration: type.duration,
5011
+ timezone: calendar.timezone
5012
+ });
5013
+ for (const slot of result.slots) if (slot.available) open.push(slot.start);
5014
+ }
5015
+ const stillOpen = input.slotStart ? open.some((start) => start.getTime() === input.slotStart.getTime()) : open.length > 0;
5016
+ if (stillOpen) {
5017
+ throw new SchedulingValidationError("That time is open: book it instead of waiting", "SCHED_1103", { day: input.day });
5018
+ }
5019
+ const email2 = input.clientEmail.trim();
5020
+ const duplicate = await db.waitlistEntry.findFirst({
5021
+ where: {
5022
+ organizationId: input.organizationId,
5023
+ typeId: type.id,
5024
+ day: input.day,
5025
+ slotStart: input.slotStart ?? null,
5026
+ clientEmail: { equals: email2, mode: "insensitive" },
5027
+ status: { in: LIVE_STATUSES }
5028
+ },
5029
+ select: { id: true }
5030
+ });
5031
+ if (duplicate) throw new SchedulingValidationError("This email is already waiting for that day", "SCHED_1104", { day: input.day });
5032
+ const waiting = await db.waitlistEntry.count({ where: { organizationId: input.organizationId, typeId: type.id, day: input.day, status: "WAITING" } });
5033
+ if (waiting >= MAX_WAITING_PER_TYPE_DAY) {
5034
+ throw new SchedulingValidationError("The waitlist for that day is full", "SCHED_1108", { day: input.day });
5035
+ }
5036
+ const token = (0, import_node_crypto5.randomBytes)(24).toString("base64url");
5037
+ const entry4 = await db.waitlistEntry.create({
5038
+ data: {
5039
+ organizationId: input.organizationId,
5040
+ typeId: type.id,
5041
+ calendarId: input.calendarId ?? null,
5042
+ day: input.day,
5043
+ slotStart: input.slotStart ?? null,
5044
+ timezone,
5045
+ clientName: input.clientName.trim(),
5046
+ clientEmail: email2,
5047
+ clientPhone: input.clientPhone?.trim() || null,
5048
+ token
5049
+ },
5050
+ select: VIEW_SELECT
5051
+ });
5052
+ return { entry: entry4, token };
5053
+ }
5054
+
5055
+ // src/waitlist/accept.ts
5056
+ var ENTRY_SELECT = {
5057
+ id: true,
5058
+ organizationId: true,
5059
+ typeId: true,
5060
+ status: true,
5061
+ offerCalendarId: true,
5062
+ offerSlotStart: true,
5063
+ offerExpiresAt: true,
5064
+ clientName: true,
5065
+ clientEmail: true,
5066
+ clientPhone: true,
5067
+ timezone: true,
5068
+ type: { select: { name: true } }
5069
+ };
5070
+ async function loadOffer(db, token) {
5071
+ const entry4 = await db.waitlistEntry.findUnique({ where: { token }, select: ENTRY_SELECT });
5072
+ if (!entry4 || !entry4.offerCalendarId || !entry4.offerSlotStart || !entry4.offerExpiresAt) {
5073
+ throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
5074
+ }
5075
+ const calendar = await db.schedulingCalendar.findUnique({ where: { id: entry4.offerCalendarId }, select: { name: true } });
5076
+ return {
5077
+ status: entry4.status,
5078
+ details: {
5079
+ entryId: entry4.id,
5080
+ organizationId: entry4.organizationId,
5081
+ typeId: entry4.typeId,
5082
+ typeName: entry4.type.name,
5083
+ calendarId: entry4.offerCalendarId,
5084
+ calendarName: calendar?.name ?? "",
5085
+ startTime: entry4.offerSlotStart,
5086
+ timezone: entry4.timezone,
5087
+ expiresAt: entry4.offerExpiresAt,
5088
+ clientName: entry4.clientName,
5089
+ clientEmail: entry4.clientEmail,
5090
+ clientPhone: entry4.clientPhone
5091
+ }
5092
+ };
5093
+ }
5094
+ async function getWaitlistOffer(db, token, now = /* @__PURE__ */ new Date()) {
5095
+ const { details, status } = await loadOffer(db, token);
5096
+ if (status !== "OFFERED") throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
5097
+ if (details.expiresAt <= now) throw new SchedulingValidationError("The offer has expired", "SCHED_1107");
5098
+ return details;
5099
+ }
5100
+ async function beginWaitlistAccept(db, token, now = /* @__PURE__ */ new Date()) {
5101
+ const claimed = await db.waitlistEntry.updateMany({
5102
+ where: { token, status: "OFFERED", offerExpiresAt: { gt: now } },
5103
+ data: { status: "ACCEPTING", acceptingAt: now }
5104
+ });
5105
+ if (claimed.count === 0) {
5106
+ await getWaitlistOffer(db, token, now);
5107
+ throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
5108
+ }
5109
+ return (await loadOffer(db, token)).details;
5110
+ }
5111
+ async function completeWaitlistAccept(db, entryId, appointmentId) {
5112
+ await db.waitlistEntry.updateMany({
5113
+ where: { id: entryId, status: "ACCEPTING" },
5114
+ data: { status: "BOOKED", bookedAppointmentId: appointmentId }
5115
+ });
5116
+ }
5117
+ async function releaseWaitlistAccept(db, entryId, outcome = "BACK_IN_LINE") {
5118
+ const where = { id: entryId, status: "ACCEPTING" };
5119
+ if (outcome === "KEEP_OFFER") {
5120
+ await db.waitlistEntry.updateMany({ where, data: { status: "OFFERED", acceptingAt: null } });
5121
+ return null;
5122
+ }
5123
+ if (outcome === "BACK_IN_LINE") {
5124
+ await db.waitlistEntry.updateMany({
5125
+ where,
5126
+ data: { status: "WAITING", offerCalendarId: null, offerSlotStart: null, offerExpiresAt: null, offeredAt: null, acceptingAt: null }
5127
+ });
5128
+ return null;
5129
+ }
5130
+ const row = await db.waitlistEntry.findFirst({ where, select: { organizationId: true, offerCalendarId: true, offerSlotStart: true } });
5131
+ const ended = await db.waitlistEntry.updateMany({ where, data: { status: "EXPIRED", acceptingAt: null } });
5132
+ return row && ended.count > 0 && row.offerCalendarId && row.offerSlotStart ? { organizationId: row.organizationId, calendarId: row.offerCalendarId, startTime: row.offerSlotStart } : null;
5133
+ }
5134
+ async function findBookingForOffer(db, entry4) {
5135
+ if (!entry4.offerCalendarId || !entry4.offerSlotStart) return null;
5136
+ return db.appointment.findFirst({
5137
+ where: {
5138
+ calendarId: entry4.offerCalendarId,
5139
+ startTime: entry4.offerSlotStart,
5140
+ clientEmail: { equals: entry4.clientEmail, mode: "insensitive" },
5141
+ status: { in: ["PENDING", "CONFIRMED"] }
5142
+ },
5143
+ select: { id: true }
5144
+ });
5145
+ }
5146
+ async function settleBookedAccept(db, entryId) {
5147
+ const entry4 = await db.waitlistEntry.findFirst({
5148
+ where: { id: entryId, status: "ACCEPTING" },
5149
+ select: { offerCalendarId: true, offerSlotStart: true, clientEmail: true }
5150
+ });
5151
+ const found = entry4 ? await findBookingForOffer(db, entry4) : null;
5152
+ if (!found) return null;
5153
+ await db.waitlistEntry.updateMany({
5154
+ where: { id: entryId, status: "ACCEPTING" },
5155
+ data: { status: "BOOKED", bookedAppointmentId: found.id, acceptingAt: null }
5156
+ });
5157
+ return db.appointment.findUnique({
5158
+ where: { id: found.id },
5159
+ select: { id: true, status: true, startTime: true, endTime: true, manageToken: true, clientName: true, clientEmail: true }
5160
+ });
5161
+ }
5162
+
5163
+ // src/waitlist/offer.ts
5164
+ var DEFAULT_OFFER_MINUTES = 30;
5165
+ var CANDIDATES_PER_SLOT = 25;
5166
+ function isUniqueViolation(error) {
5167
+ return typeof error === "object" && error !== null && error.code === "P2002";
5168
+ }
5169
+ async function offerFreedSlot(db, input) {
5170
+ const now = input.now ?? /* @__PURE__ */ new Date();
5171
+ if (input.startTime <= now) return null;
5172
+ const calendar = await db.schedulingCalendar.findUnique({
5173
+ where: { id: input.calendarId },
5174
+ select: { name: true, timezone: true, organizationId: true }
5175
+ });
5176
+ if (!calendar || calendar.organizationId !== null && calendar.organizationId !== input.organizationId) return null;
5177
+ await db.waitlistEntry.updateMany({
5178
+ where: {
5179
+ organizationId: input.organizationId,
5180
+ status: "OFFERED",
5181
+ offerCalendarId: input.calendarId,
5182
+ offerSlotStart: input.startTime,
5183
+ offerExpiresAt: { lte: now }
5184
+ },
5185
+ data: { status: "EXPIRED" }
5186
+ });
5187
+ const candidates = await db.waitlistEntry.findMany({
5188
+ where: {
5189
+ organizationId: input.organizationId,
5190
+ status: "WAITING",
5191
+ day: localDay(input.startTime, calendar.timezone),
5192
+ // Only people whose type runs on this calendar, so earlier people it cannot fit never crowd out later ones that it can.
5193
+ type: { isActive: true, calendars: { some: { calendarId: input.calendarId } } },
5194
+ AND: [
5195
+ { OR: [{ calendarId: null }, { calendarId: input.calendarId }] },
5196
+ { OR: [{ slotStart: null }, { slotStart: input.startTime }] }
5197
+ ]
5198
+ },
5199
+ orderBy: { createdAt: "asc" },
5200
+ take: CANDIDATES_PER_SLOT,
5201
+ select: { ...VIEW_SELECT, token: true, timezone: true }
5202
+ });
5203
+ const expiresAt = new Date(Math.min(now.getTime() + (input.offerMinutes ?? DEFAULT_OFFER_MINUTES) * 6e4, input.startTime.getTime()));
5204
+ for (const candidate of candidates) {
5205
+ const type = await db.appointmentType.findFirst({
5206
+ where: { id: candidate.typeId, isActive: true, calendars: { some: { calendarId: input.calendarId } } },
5207
+ select: { name: true, duration: true }
5208
+ });
5209
+ if (!type || !await isSlotAvailable(db, input.calendarId, input.startTime, type.duration)) continue;
5210
+ let claimed;
5211
+ try {
5212
+ claimed = await db.waitlistEntry.updateMany({
5213
+ where: { id: candidate.id, status: "WAITING" },
5214
+ data: { status: "OFFERED", offerCalendarId: input.calendarId, offerSlotStart: input.startTime, offerExpiresAt: expiresAt, offeredAt: now }
5215
+ });
5216
+ } catch (error) {
5217
+ if (isUniqueViolation(error)) return null;
5218
+ throw error;
5219
+ }
5220
+ if (claimed.count === 0) continue;
5221
+ const { token, timezone, ...view2 } = candidate;
5222
+ return {
5223
+ entry: { ...view2, status: "OFFERED", offerSlotStart: input.startTime, offerExpiresAt: expiresAt },
5224
+ token,
5225
+ calendarId: input.calendarId,
5226
+ calendarName: calendar.name,
5227
+ typeName: type.name,
5228
+ startTime: input.startTime,
5229
+ timezone,
5230
+ expiresAt
5231
+ };
5232
+ }
5233
+ return null;
5234
+ }
5235
+ async function tryOfferFreedSlot(db, input) {
5236
+ try {
5237
+ return await offerFreedSlot(db, input);
5238
+ } catch (error) {
5239
+ const diagnostic = schedError("SCHED_1109", { organizationId: input.organizationId, calendarId: input.calendarId, error });
5240
+ console.error(`[waitlist] ${diagnostic.ref} could not offer a freed slot:`, error);
5241
+ return null;
5242
+ }
5243
+ }
5244
+ async function expireWaitlistOffers(db, options = {}) {
5245
+ const now = options.now ?? /* @__PURE__ */ new Date();
5246
+ const stuckBefore = new Date(now.getTime() - (options.acceptTimeoutMs ?? 5 * 6e4));
5247
+ const rows = await db.$queryRaw`
5248
+ UPDATE "WaitlistEntry" SET status = 'EXPIRED'
5249
+ WHERE status = 'OFFERED' AND "offerExpiresAt" <= ${now}
5250
+ RETURNING "organizationId", "offerCalendarId", "offerSlotStart"
5251
+ `;
5252
+ const lapsed = rows.map((r) => ({ organizationId: r.organizationId, calendarId: r.offerCalendarId, startTime: r.offerSlotStart }));
5253
+ const stuck = await db.waitlistEntry.findMany({
5254
+ where: { status: "ACCEPTING", acceptingAt: { lte: stuckBefore } },
5255
+ take: 100,
5256
+ select: { id: true, organizationId: true, offerCalendarId: true, offerSlotStart: true, clientEmail: true }
5257
+ });
5258
+ let released = 0;
5259
+ let booked = 0;
5260
+ for (const entry4 of stuck) {
5261
+ const appointment = await findBookingForOffer(db, entry4);
5262
+ if (appointment) {
5263
+ const done = await db.waitlistEntry.updateMany({
5264
+ where: { id: entry4.id, status: "ACCEPTING" },
5265
+ data: { status: "BOOKED", bookedAppointmentId: appointment.id, acceptingAt: null }
5266
+ });
5267
+ booked += done.count;
5268
+ continue;
5269
+ }
5270
+ const back = await db.waitlistEntry.updateMany({
5271
+ where: { id: entry4.id, status: "ACCEPTING" },
5272
+ data: { status: "WAITING", offerCalendarId: null, offerSlotStart: null, offerExpiresAt: null, offeredAt: null, acceptingAt: null }
5273
+ });
5274
+ if (back.count > 0) {
5275
+ released++;
5276
+ if (entry4.offerCalendarId && entry4.offerSlotStart) {
5277
+ lapsed.push({ organizationId: entry4.organizationId, calendarId: entry4.offerCalendarId, startTime: entry4.offerSlotStart });
5278
+ }
5279
+ }
5280
+ }
5281
+ return { lapsed, released, booked };
5282
+ }
5283
+
5284
+ // src/waitlist/manage.ts
5285
+ var OFFER_FIELDS = { organizationId: true, status: true, offerCalendarId: true, offerSlotStart: true };
5286
+ function freedSlot(row) {
5287
+ return row.status === "OFFERED" && row.offerCalendarId && row.offerSlotStart ? { organizationId: row.organizationId, calendarId: row.offerCalendarId, startTime: row.offerSlotStart } : null;
5288
+ }
5289
+ async function listWaitlist(db, input) {
5290
+ const where = { organizationId: input.organizationId, ...input.status ? { status: input.status } : {} };
5291
+ const [entries, total] = await Promise.all([
5292
+ db.waitlistEntry.findMany({
5293
+ where,
5294
+ orderBy: { createdAt: "asc" },
5295
+ take: Math.min(input.limit ?? 50, 200),
5296
+ skip: input.offset ?? 0,
5297
+ select: VIEW_SELECT
5298
+ }),
5299
+ db.waitlistEntry.count({ where })
5300
+ ]);
5301
+ return { entries, total };
5302
+ }
5303
+ async function removeWaitlistEntry(db, organizationId, entryId) {
5304
+ const where = { id: entryId, organizationId, status: { in: ["WAITING", "OFFERED", "EXPIRED", "BOOKED"] } };
5305
+ const row = await db.waitlistEntry.findFirst({ where, select: OFFER_FIELDS });
5306
+ const removed = row ? await db.waitlistEntry.deleteMany({ where: { ...where, status: row.status } }) : { count: 0 };
5307
+ if (!row || removed.count === 0) throw new SchedulingNotFoundError("Waitlist entry not found", "SCHED_1106", { entryId });
5308
+ return freedSlot(row);
5309
+ }
5310
+ async function leaveWaitlist(db, token) {
5311
+ const where = { token, status: { in: ["WAITING", "OFFERED"] } };
5312
+ const row = await db.waitlistEntry.findFirst({ where, select: OFFER_FIELDS });
5313
+ const removed = row ? await db.waitlistEntry.deleteMany({ where: { ...where, status: row.status } }) : { count: 0 };
5314
+ if (!row || removed.count === 0) throw new SchedulingNotFoundError("No waitlist entry for this link", "SCHED_1106");
5315
+ return freedSlot(row);
5316
+ }
5317
+
5318
+ // src/routing/types.ts
5319
+ var LIMITS = {
5320
+ questions: 20,
5321
+ rules: 50,
5322
+ conditionsPerRule: 10,
5323
+ options: 50,
5324
+ label: 200,
5325
+ option: 100,
5326
+ message: 500,
5327
+ textAnswer: 1e3,
5328
+ problems: 50,
5329
+ formsPerOrganization: 50
5330
+ };
5331
+
5332
+ // src/routing/validate-structure.ts
5333
+ var ID = /^[A-Za-z][A-Za-z0-9_-]{0,39}$/;
5334
+ var QUESTION_TYPES = ["select", "radio", "checkbox", "text", "number"];
5335
+ var NO_VALUE = ["is_answered", "is_empty"];
5336
+ var OPERATORS_BY_TYPE = {
5337
+ select: ["equals", "not_equals", "in", "is_answered", "is_empty"],
5338
+ radio: ["equals", "not_equals", "in", "is_answered", "is_empty"],
5339
+ checkbox: ["contains", "not_contains", "is_answered", "is_empty"],
5340
+ text: ["equals", "not_equals", "contains", "not_contains", "is_answered", "is_empty"],
5341
+ number: ["equals", "not_equals", "gt", "gte", "lt", "lte", "is_answered", "is_empty"]
5342
+ };
5343
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5344
+ var isText = (value, max) => typeof value === "string" && value.trim().length > 0 && value.length <= max && !value.includes("\0");
5345
+ function checkQuestions(input, problems) {
5346
+ if (!Array.isArray(input) || input.length === 0) {
5347
+ problems.push({ path: "questions", message: "Add at least one question" });
5348
+ return [];
5349
+ }
5350
+ if (input.length > LIMITS.questions) problems.push({ path: "questions", message: `At most ${LIMITS.questions} questions` });
5351
+ const seen = /* @__PURE__ */ new Set();
5352
+ const questions = [];
5353
+ input.slice(0, LIMITS.questions).forEach((raw, i) => {
5354
+ const at = `questions[${i}]`;
5355
+ if (!isObject(raw)) return void problems.push({ path: at, message: "A question must be an object" });
5356
+ const { id, label, type, required, options } = raw;
5357
+ if (typeof id !== "string" || !ID.test(id)) problems.push({ path: `${at}.id`, message: "The id must start with a letter and use only letters, numbers, - and _ (40 characters at most)" });
5358
+ else if (seen.has(id)) problems.push({ path: `${at}.id`, message: `Another question already uses the id "${id}"` });
5359
+ else seen.add(id);
5360
+ if (!isText(label, LIMITS.label)) problems.push({ path: `${at}.label`, message: `A label of 1 to ${LIMITS.label} characters is required` });
5361
+ if (!QUESTION_TYPES.includes(type)) problems.push({ path: `${at}.type`, message: `The type must be one of ${QUESTION_TYPES.join(", ")}` });
5362
+ if (required !== void 0 && typeof required !== "boolean") problems.push({ path: `${at}.required`, message: "required must be true or false" });
5363
+ const choice = type === "select" || type === "radio" || type === "checkbox";
5364
+ let cleanOptions;
5365
+ if (choice) {
5366
+ if (!Array.isArray(options) || options.length < 2 || options.length > LIMITS.options) {
5367
+ problems.push({ path: `${at}.options`, message: `A choice question needs 2 to ${LIMITS.options} options` });
5368
+ } else if (!options.every((o) => isText(o, LIMITS.option))) {
5369
+ problems.push({ path: `${at}.options`, message: `Each option must be 1 to ${LIMITS.option} characters` });
5370
+ } else if (new Set(options).size !== options.length) {
5371
+ problems.push({ path: `${at}.options`, message: "Options must all be different" });
5372
+ } else cleanOptions = options;
5373
+ } else if (options !== void 0) {
5374
+ problems.push({ path: `${at}.options`, message: "Only choice questions have options" });
5375
+ }
5376
+ if (typeof id === "string" && typeof label === "string" && QUESTION_TYPES.includes(type)) {
5377
+ questions.push({ id, label: label.trim(), type, required: required === true, ...cleanOptions ? { options: cleanOptions } : {} });
5378
+ }
5379
+ });
5380
+ return questions;
5381
+ }
5382
+ function checkValue(question, condition, at, problems) {
5383
+ const { operator, value } = condition;
5384
+ if (NO_VALUE.includes(operator)) {
5385
+ if (value !== void 0) problems.push({ path: `${at}.value`, message: `${String(operator)} takes no value` });
5386
+ return void 0;
5387
+ }
5388
+ if (value === void 0) {
5389
+ problems.push({ path: `${at}.value`, message: "A value is required" });
5390
+ return void 0;
5391
+ }
5392
+ if (question.type === "number") {
5393
+ if (typeof value !== "number" || !Number.isFinite(value)) problems.push({ path: `${at}.value`, message: "The value must be a number" });
5394
+ else return value;
5395
+ return void 0;
5396
+ }
5397
+ if (question.type === "text") {
5398
+ if (!isText(value, LIMITS.option * 2)) problems.push({ path: `${at}.value`, message: "The value must be a text of 1 to 200 characters" });
5399
+ else return value;
5400
+ return void 0;
5401
+ }
5402
+ const options = question.options ?? [];
5403
+ if (operator === "in") {
5404
+ if (!Array.isArray(value) || value.length === 0 || !value.every((v) => typeof v === "string" && options.includes(v))) {
5405
+ problems.push({ path: `${at}.value`, message: "The value must be a list of this question's options" });
5406
+ return void 0;
5407
+ }
5408
+ return value;
5409
+ }
5410
+ if (typeof value !== "string" || !options.includes(value)) {
5411
+ problems.push({ path: `${at}.value`, message: "The value must be one of this question's options" });
5412
+ return void 0;
5413
+ }
5414
+ return value;
5415
+ }
5416
+ function checkDestination(raw, at, problems) {
5417
+ if (!isObject(raw)) {
5418
+ problems.push({ path: at, message: "Say where to send the client" });
5419
+ return null;
5420
+ }
5421
+ const { typeId, calendarId } = raw;
5422
+ const okType = typeId === void 0 || typeof typeId === "string" && typeId.length > 0 && typeId.length <= 100;
5423
+ const okCalendar = calendarId === void 0 || typeof calendarId === "string" && calendarId.length > 0 && calendarId.length <= 100;
5424
+ if (!okType || !okCalendar) {
5425
+ problems.push({ path: at, message: "typeId and calendarId must be ids" });
5426
+ return null;
5427
+ }
5428
+ if (typeId === void 0 && calendarId === void 0) {
5429
+ problems.push({ path: at, message: "Name an appointment type, a calendar, or both" });
5430
+ return null;
5431
+ }
5432
+ return { ...typeId !== void 0 ? { typeId } : {}, ...calendarId !== void 0 ? { calendarId } : {} };
5433
+ }
5434
+ function checkRules(input, questions, problems) {
5435
+ if (!Array.isArray(input) || input.length === 0) {
5436
+ problems.push({ path: "rules", message: "Add at least one rule" });
5437
+ return [];
5438
+ }
5439
+ if (input.length > LIMITS.rules) problems.push({ path: "rules", message: `At most ${LIMITS.rules} rules` });
5440
+ const byId = new Map(questions.map((q) => [q.id, q]));
5441
+ const written = new Set(input.flatMap((r) => isObject(r) && typeof r.id === "string" ? [r.id] : []));
5442
+ const seen = /* @__PURE__ */ new Set();
5443
+ const rules = [];
5444
+ input.slice(0, LIMITS.rules).forEach((raw, i) => {
5445
+ const at = `rules[${i}]`;
5446
+ if (!isObject(raw)) return void problems.push({ path: at, message: "A rule must be an object" });
5447
+ let id = typeof raw.id === "string" && ID.test(raw.id) ? raw.id : null;
5448
+ if (raw.id !== void 0 && id === null) problems.push({ path: `${at}.id`, message: "The id must start with a letter and use only letters, numbers, - and _" });
5449
+ if (id === null) {
5450
+ id = `rule_${i + 1}`;
5451
+ while (written.has(id)) id = `${id}_auto`;
5452
+ }
5453
+ if (seen.has(id)) problems.push({ path: `${at}.id`, message: `Another rule already uses the id "${id}"` });
5454
+ seen.add(id);
5455
+ if (raw.label !== void 0 && !isText(raw.label, LIMITS.label)) problems.push({ path: `${at}.label`, message: `A label must be 1 to ${LIMITS.label} characters` });
5456
+ const match = raw.match === void 0 ? "all" : raw.match;
5457
+ if (match !== "all" && match !== "any") problems.push({ path: `${at}.match`, message: 'match must be "all" or "any"' });
5458
+ const conditions = [];
5459
+ if (!Array.isArray(raw.conditions) || raw.conditions.length === 0 || raw.conditions.length > LIMITS.conditionsPerRule) {
5460
+ problems.push({ path: `${at}.conditions`, message: `A rule needs 1 to ${LIMITS.conditionsPerRule} conditions` });
5461
+ } else {
5462
+ raw.conditions.forEach((c, j) => {
5463
+ const cat = `${at}.conditions[${j}]`;
5464
+ if (!isObject(c)) return void problems.push({ path: cat, message: "A condition must be an object" });
5465
+ const question = typeof c.questionId === "string" ? byId.get(c.questionId) : void 0;
5466
+ if (!question) return void problems.push({ path: `${cat}.questionId`, message: "This names a question the form does not have" });
5467
+ if (!OPERATORS_BY_TYPE[question.type].includes(c.operator)) {
5468
+ return void problems.push({ path: `${cat}.operator`, message: `A ${question.type} question allows: ${OPERATORS_BY_TYPE[question.type].join(", ")}` });
5469
+ }
5470
+ const value = checkValue(question, c, cat, problems);
5471
+ conditions.push({ questionId: question.id, operator: c.operator, ...value !== void 0 ? { value } : {} });
5472
+ });
5473
+ }
5474
+ const destination = checkDestination(raw.destination, `${at}.destination`, problems);
5475
+ if (destination && (match === "all" || match === "any")) {
5476
+ rules.push({ id, ...typeof raw.label === "string" ? { label: raw.label.trim() } : {}, match, conditions, destination });
5477
+ }
5478
+ });
5479
+ return rules;
5480
+ }
5481
+ function checkFallback(raw, problems) {
5482
+ if (!isObject(raw)) {
5483
+ problems.push({ path: "fallback", message: "Say what happens when no rule matches" });
5484
+ return null;
5485
+ }
5486
+ if (raw.kind === "MESSAGE") {
5487
+ if (!isText(raw.message, LIMITS.message)) {
5488
+ problems.push({ path: "fallback.message", message: `A message of 1 to ${LIMITS.message} characters is required` });
5489
+ return null;
5490
+ }
5491
+ return { kind: "MESSAGE", message: raw.message.trim() };
5492
+ }
5493
+ if (raw.kind === "DESTINATION") {
5494
+ const destination = checkDestination(raw.destination, "fallback.destination", problems);
5495
+ return destination ? { kind: "DESTINATION", destination } : null;
5496
+ }
5497
+ problems.push({ path: "fallback.kind", message: 'kind must be "DESTINATION" or "MESSAGE"' });
5498
+ return null;
5499
+ }
5500
+ function validateRoutingStructure(input) {
5501
+ const problems = [];
5502
+ if (!isObject(input)) return { ok: false, problems: [{ path: "", message: "A routing form must be an object" }] };
5503
+ const questions = checkQuestions(input.questions, problems);
5504
+ const rules = checkRules(input.rules, questions, problems);
5505
+ const fallback = checkFallback(input.fallback, problems);
5506
+ if (problems.length > 0 || !fallback) return { ok: false, problems: problems.slice(0, LIMITS.problems) };
5507
+ return { ok: true, value: { questions, rules, fallback } };
5508
+ }
5509
+
5510
+ // src/routing/validate-destinations.ts
5511
+ function placesOf(definition) {
5512
+ const places = definition.rules.map((rule, i) => ({ path: `rules[${i}].destination`, destination: rule.destination }));
5513
+ if (definition.fallback.kind === "DESTINATION") places.push({ path: "fallback.destination", destination: definition.fallback.destination });
5514
+ return places;
5515
+ }
5516
+ async function validateRoutingDestinations(db, organizationId, definition) {
5517
+ const places = placesOf(definition);
5518
+ const typeIds = [...new Set(places.flatMap((p) => p.destination.typeId ? [p.destination.typeId] : []))];
5519
+ const calendarIds = [...new Set(places.flatMap((p) => p.destination.calendarId ? [p.destination.calendarId] : []))];
5520
+ const scope = [{ organizationId }, { organizationId: null }];
5521
+ const [types, calendars] = await Promise.all([
5522
+ typeIds.length ? db.appointmentType.findMany({ where: { id: { in: typeIds }, isActive: true, OR: scope }, select: { id: true } }) : [],
5523
+ calendarIds.length ? db.schedulingCalendar.findMany({ where: { id: { in: calendarIds }, isActive: true, OR: scope }, select: { id: true } }) : []
5524
+ ]);
5525
+ const liveTypes = new Set(types.map((t) => t.id));
5526
+ const liveCalendars = new Set(calendars.map((c) => c.id));
5527
+ const problems = [];
5528
+ const pairs = [];
5529
+ for (const { path, destination } of places) {
5530
+ const typeOk = !destination.typeId || liveTypes.has(destination.typeId);
5531
+ const calendarOk = !destination.calendarId || liveCalendars.has(destination.calendarId);
5532
+ if (!typeOk) problems.push({ path: `${path}.typeId`, message: "This appointment type does not exist here or is switched off" });
5533
+ if (!calendarOk) problems.push({ path: `${path}.calendarId`, message: "This calendar does not exist here or is switched off" });
5534
+ if (typeOk && calendarOk && destination.typeId && destination.calendarId) pairs.push({ path, destination });
5535
+ }
5536
+ if (pairs.length > 0) {
5537
+ const links = await db.appointmentTypeCalendar.findMany({
5538
+ where: { OR: pairs.map((p) => ({ appointmentTypeId: p.destination.typeId, calendarId: p.destination.calendarId })) },
5539
+ select: { appointmentTypeId: true, calendarId: true }
5540
+ });
5541
+ const linked = new Set(links.map((l) => `${l.appointmentTypeId}:${l.calendarId}`));
5542
+ for (const { path, destination } of pairs) {
5543
+ if (!linked.has(`${destination.typeId}:${destination.calendarId}`)) {
5544
+ problems.push({ path, message: "This appointment type is not offered on this calendar" });
5545
+ }
5546
+ }
5547
+ }
5548
+ return problems;
5549
+ }
5550
+
5551
+ // src/routing/evaluate.ts
5552
+ var blank = (value) => value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0;
5553
+ function checkAnswers(questions, input) {
5554
+ const problems = [];
5555
+ const raw = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {};
5556
+ if (input !== void 0 && raw !== input) problems.push({ path: "answers", message: "Answers must be an object keyed by question id" });
5557
+ const known = new Set(questions.map((q) => q.id));
5558
+ for (const key of Object.keys(raw)) if (!known.has(key)) problems.push({ path: `answers.${key}`, message: "The form does not ask this question" });
5559
+ const answers = /* @__PURE__ */ Object.create(null);
5560
+ for (const q of questions) {
5561
+ const at = `answers.${q.id}`;
5562
+ const value = Object.prototype.hasOwnProperty.call(raw, q.id) ? raw[q.id] : void 0;
5563
+ if (blank(value)) {
5564
+ if (q.required) problems.push({ path: at, message: "This question needs an answer" });
5565
+ continue;
5566
+ }
5567
+ if (q.type === "select" || q.type === "radio") {
5568
+ if (typeof value !== "string" || !q.options?.includes(value)) problems.push({ path: at, message: "Pick one of the offered options" });
5569
+ else answers[q.id] = value;
5570
+ } else if (q.type === "checkbox") {
5571
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string" && q.options?.includes(v)) || new Set(value).size !== value.length) {
5572
+ problems.push({ path: at, message: "Send a list of offered options, each once" });
5573
+ } else answers[q.id] = value;
5574
+ } else if (q.type === "number") {
5575
+ if (typeof value !== "number" || !Number.isFinite(value)) problems.push({ path: at, message: "The answer must be a number" });
5576
+ else answers[q.id] = value;
5577
+ } else if (typeof value !== "string" || value.length > LIMITS.textAnswer) {
5578
+ problems.push({ path: at, message: `The answer must be a text of at most ${LIMITS.textAnswer} characters` });
5579
+ } else answers[q.id] = value;
5580
+ }
5581
+ return problems.length > 0 ? { ok: false, problems: problems.slice(0, LIMITS.problems) } : { ok: true, answers };
5582
+ }
5583
+ function holds(condition, answers) {
5584
+ const answer = answers[condition.questionId];
5585
+ const { operator, value } = condition;
5586
+ if (operator === "is_empty") return blank(answer);
5587
+ if (operator === "is_answered") return !blank(answer);
5588
+ if (blank(answer)) return false;
5589
+ if (typeof answer === "number") {
5590
+ if (typeof value !== "number") return false;
5591
+ return { equals: answer === value, not_equals: answer !== value, gt: answer > value, gte: answer >= value, lt: answer < value, lte: answer <= value }[operator] ?? false;
5592
+ }
5593
+ if (Array.isArray(answer)) {
5594
+ if (typeof value !== "string") return false;
5595
+ return operator === "contains" ? answer.includes(value) : operator === "not_contains" ? !answer.includes(value) : false;
5596
+ }
5597
+ if (operator === "in") return Array.isArray(value) && value.includes(answer);
5598
+ if (typeof value !== "string") return false;
5599
+ const a = answer;
5600
+ switch (operator) {
5601
+ case "equals":
5602
+ return a === value;
5603
+ case "not_equals":
5604
+ return a !== value;
5605
+ case "contains":
5606
+ return a.toLowerCase().includes(value.toLowerCase());
5607
+ case "not_contains":
5608
+ return !a.toLowerCase().includes(value.toLowerCase());
5609
+ default:
5610
+ return false;
5611
+ }
5612
+ }
5613
+ function matchingRules(definition, answers) {
5614
+ return definition.rules.filter(
5615
+ (rule) => rule.match === "any" ? rule.conditions.some((c) => holds(c, answers)) : rule.conditions.every((c) => holds(c, answers))
5616
+ );
5617
+ }
5618
+
5619
+ // src/routing/crud.ts
5620
+ var SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
5621
+ var FULL = { id: true, name: true, slug: true, description: true, isActive: true, questions: true, rules: true, fallback: true, createdAt: true, updatedAt: true };
5622
+ function invalid(problems) {
5623
+ return new SchedulingValidationError("The routing form has problems", "SCHED_1200", { errors: problems });
5624
+ }
5625
+ function view(row) {
5626
+ return { ...row, questions: row.questions, rules: row.rules, fallback: row.fallback };
5627
+ }
5628
+ async function check(db, organizationId, input, options) {
5629
+ const problems = [];
5630
+ const name = typeof input.name === "string" ? input.name.trim() : "";
5631
+ if (name.length < 1 || name.length > 100 || name.includes("\0")) problems.push({ path: "name", message: "A name of 1 to 100 characters is required" });
5632
+ if (typeof input.slug !== "string" || !SLUG.test(input.slug) || input.slug.length > 60) {
5633
+ problems.push({ path: "slug", message: "The slug must be lower-case words joined by dashes, 60 characters at most" });
5634
+ } else {
5635
+ const taken = await db.routingForm.count({ where: { slug: input.slug, organizationId: { not: organizationId } } });
5636
+ if (taken > 0) problems.push({ path: "slug", message: "That slug is already in use; choose another" });
5637
+ }
5638
+ const description = typeof input.description === "string" ? input.description.trim() || null : null;
5639
+ if (description && (description.length > 500 || description.includes("\0"))) problems.push({ path: "description", message: "The description is at most 500 characters" });
5640
+ const structure = validateRoutingStructure({ questions: input.questions, rules: input.rules, fallback: input.fallback });
5641
+ if (!structure.ok) problems.push(...structure.problems);
5642
+ else if (options.checkDestinations) problems.push(...await validateRoutingDestinations(db, organizationId, structure.value));
5643
+ if (problems.length > 0 || !structure.ok) throw invalid(problems.slice(0, LIMITS.problems));
5644
+ return { definition: structure.value, name, slug: input.slug, description };
5645
+ }
5646
+ async function createRoutingForm(db, organizationId, input) {
5647
+ const { definition, name, slug, description } = await check(db, organizationId, input, { checkDestinations: true });
5648
+ const existing = await db.routingForm.count({ where: { organizationId } });
5649
+ if (existing >= LIMITS.formsPerOrganization) {
5650
+ throw new SchedulingValidationError(`An organization can have at most ${LIMITS.formsPerOrganization} routing forms`, "SCHED_1204", { organizationId });
5651
+ }
5652
+ try {
5653
+ const row = await db.routingForm.create({
5654
+ data: {
5655
+ organizationId,
5656
+ name,
5657
+ slug,
5658
+ description,
5659
+ isActive: input.isActive ?? true,
5660
+ questions: definition.questions,
5661
+ rules: definition.rules,
5662
+ fallback: definition.fallback
5663
+ },
5664
+ select: FULL
5665
+ });
5666
+ return view(row);
5667
+ } catch (error) {
5668
+ if (error.code === "P2002") throw new SchedulingValidationError("That slug is already used by another form", "SCHED_1202", { slug });
5669
+ throw error;
5670
+ }
5671
+ }
5672
+ async function getRoutingForm(db, organizationId, id) {
5673
+ const row = await db.routingForm.findFirst({ where: { id, organizationId }, select: FULL });
5674
+ if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
5675
+ return view(row);
5676
+ }
5677
+ async function listRoutingForms(db, organizationId) {
5678
+ return db.routingForm.findMany({
5679
+ where: { organizationId },
5680
+ orderBy: { name: "asc" },
5681
+ select: { id: true, name: true, slug: true, description: true, isActive: true, updatedAt: true }
5682
+ });
5683
+ }
5684
+ async function updateRoutingForm(db, organizationId, id, patch) {
5685
+ const current = await getRoutingForm(db, organizationId, id);
5686
+ const merged = {
5687
+ name: patch.name ?? current.name,
5688
+ slug: patch.slug ?? current.slug,
5689
+ description: patch.description === void 0 ? current.description : patch.description,
5690
+ isActive: patch.isActive ?? current.isActive,
5691
+ questions: patch.questions ?? current.questions,
5692
+ rules: patch.rules ?? current.rules,
5693
+ fallback: patch.fallback ?? current.fallback
5694
+ };
5695
+ const changesRouting = patch.questions !== void 0 || patch.rules !== void 0 || patch.fallback !== void 0;
5696
+ const { definition, name, slug, description } = await check(db, organizationId, merged, { checkDestinations: changesRouting });
5697
+ try {
5698
+ const updated = await db.routingForm.updateMany({
5699
+ where: { id, organizationId },
5700
+ data: {
5701
+ name,
5702
+ slug,
5703
+ description,
5704
+ isActive: merged.isActive,
5705
+ questions: definition.questions,
5706
+ rules: definition.rules,
5707
+ fallback: definition.fallback
5708
+ }
5709
+ });
5710
+ if (updated.count === 0) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
5711
+ } catch (error) {
5712
+ if (error.code === "P2002") throw new SchedulingValidationError("That slug is already used by another form", "SCHED_1202", { slug });
5713
+ throw error;
5714
+ }
5715
+ return getRoutingForm(db, organizationId, id);
5716
+ }
5717
+ async function deleteRoutingForm(db, organizationId, id) {
5718
+ const removed = await db.routingForm.deleteMany({ where: { id, organizationId } });
5719
+ if (removed.count === 0) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
5720
+ }
5721
+
5722
+ // src/routing/route.ts
5723
+ var UNAVAILABLE = "Online booking is not available for this choice right now. Please contact us to book.";
5724
+ async function findForm(db, organizationId, slug) {
5725
+ const select = { organizationId: true, name: true, slug: true, description: true, questions: true, rules: true, fallback: true };
5726
+ if (organizationId) return db.routingForm.findFirst({ where: { organizationId, slug, isActive: true }, select });
5727
+ const found = await db.routingForm.findMany({ where: { slug, isActive: true }, take: 2, select });
5728
+ return found.length === 1 ? found[0] : null;
5729
+ }
5730
+ async function load(db, organizationId, slug) {
5731
+ const row = await findForm(db, organizationId, slug);
5732
+ if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { slug });
5733
+ return row;
5734
+ }
5735
+ async function getPublicRoutingForm(db, input) {
5736
+ const row = await load(db, input.organizationId, input.slug);
5737
+ return { name: row.name, slug: row.slug, description: row.description, questions: row.questions };
5738
+ }
5739
+ async function resolveDestination(db, organizationId, destination) {
5740
+ const scope = [{ organizationId }, { organizationId: null }];
5741
+ const [type, calendar] = await Promise.all([
5742
+ destination.typeId ? db.appointmentType.findFirst({ where: { id: destination.typeId, isActive: true, OR: scope }, select: { id: true, slug: true, name: true } }) : null,
5743
+ destination.calendarId ? db.schedulingCalendar.findFirst({ where: { id: destination.calendarId, isActive: true, OR: scope }, select: { id: true, slug: true, name: true } }) : null
5744
+ ]);
5745
+ if (destination.typeId && !type || destination.calendarId && !calendar) return null;
5746
+ if (type && calendar) {
5747
+ const link = await db.appointmentTypeCalendar.findUnique({
5748
+ where: { appointmentTypeId_calendarId: { appointmentTypeId: type.id, calendarId: calendar.id } },
5749
+ select: { calendarId: true }
5750
+ });
5751
+ if (!link) return null;
5752
+ }
5753
+ return {
5754
+ typeId: type?.id ?? null,
5755
+ typeSlug: type?.slug ?? null,
5756
+ typeName: type?.name ?? null,
5757
+ calendarId: calendar?.id ?? null,
5758
+ calendarSlug: calendar?.slug ?? null,
5759
+ calendarName: calendar?.name ?? null
5760
+ };
5761
+ }
5762
+ async function decide(db, organizationId, definition, answers) {
5763
+ const checked = checkAnswers(definition.questions, answers);
5764
+ if (!checked.ok) throw new SchedulingValidationError("The answers do not fit the form", "SCHED_1203", { errors: checked.problems });
5765
+ for (const rule of matchingRules(definition, checked.answers)) {
5766
+ const destination = await resolveDestination(db, organizationId, rule.destination);
5767
+ if (destination) return { destination, message: null, matchedRuleId: rule.id, usedFallback: false };
5768
+ }
5769
+ if (definition.fallback.kind === "DESTINATION") {
5770
+ const destination = await resolveDestination(db, organizationId, definition.fallback.destination);
5771
+ return { destination, message: destination ? null : UNAVAILABLE, matchedRuleId: null, usedFallback: true };
5772
+ }
5773
+ return { destination: null, message: definition.fallback.message, matchedRuleId: null, usedFallback: true };
5774
+ }
5775
+ async function routeClient(db, input) {
5776
+ const row = await load(db, input.organizationId, input.slug);
5777
+ return decide(db, row.organizationId, row, input.answers);
5778
+ }
5779
+ async function testRoutingForm(db, input) {
5780
+ const row = await db.routingForm.findFirst({
5781
+ where: { id: input.id, organizationId: input.organizationId },
5782
+ select: { questions: true, rules: true, fallback: true }
5783
+ });
5784
+ if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id: input.id });
5785
+ const definition = row;
5786
+ const outcome = await decide(db, input.organizationId, definition, input.answers);
5787
+ const checked = checkAnswers(definition.questions, input.answers);
5788
+ const allMatchedRuleIds = checked.ok ? matchingRules(definition, checked.answers).map((r) => r.id) : [];
5789
+ return { ...outcome, allMatchedRuleIds };
5790
+ }
5791
+
5792
+ // src/privacy/subject.ts
5793
+ var import_node_crypto6 = require("crypto");
5794
+ var EMAIL2 = /^[^\s@]+@[^\s@]+$/;
5795
+ function invalid2(reason) {
5796
+ return new SchedulingValidationError(`Say whose data this is: ${reason}`, "SCHED_1300", { reason });
5797
+ }
5798
+ function parseSubject(input) {
5799
+ let email2 = null;
5800
+ let clientId = null;
5801
+ if (input.email !== void 0 && input.email !== null) {
5802
+ if (typeof input.email !== "string") throw invalid2("the email must be text");
5803
+ const trimmed = input.email.trim().toLowerCase();
5804
+ if (trimmed.length > 254 || !EMAIL2.test(trimmed)) throw invalid2("the email is not a single valid address");
5805
+ email2 = trimmed;
5806
+ }
5807
+ if (input.clientId !== void 0 && input.clientId !== null) {
5808
+ if (typeof input.clientId !== "string") throw invalid2("the client id must be text");
5809
+ const trimmed = input.clientId.trim();
5810
+ if (trimmed.length < 1 || trimmed.length > 200) throw invalid2("the client id must be 1 to 200 characters");
5811
+ clientId = trimmed;
5812
+ }
5813
+ if (!email2 && !clientId) throw invalid2("send an email address, a client id, or both");
5814
+ return { email: email2, clientId };
5815
+ }
5816
+ function subjectHashes(organizationId, subject) {
5817
+ const identifiers = [...subject.emails, ...subject.clientId ? [`client:${subject.clientId}`] : []];
5818
+ return identifiers.map((identifier) => (0, import_node_crypto6.createHash)("sha256").update(`${organizationId}
5819
+ ${identifier}`).digest("hex"));
5820
+ }
5821
+ async function resolveSubject(db, organizationId, parsed) {
5822
+ const emails = new Set(parsed.email ? [parsed.email] : []);
5823
+ if (parsed.clientId) {
5824
+ const [bookings, series] = await Promise.all([
5825
+ db.appointment.findMany({ where: { clientId: parsed.clientId, calendar: { organizationId } }, select: { clientEmail: true } }),
5826
+ db.recurringSeries.findMany({ where: { clientId: parsed.clientId, organizationId }, select: { clientEmail: true } })
5827
+ ]);
5828
+ for (const row of [...bookings, ...series]) emails.add(row.clientEmail.trim().toLowerCase());
5829
+ }
5830
+ return { emails: [...emails], clientId: parsed.clientId };
5831
+ }
5832
+
5833
+ // src/privacy/audit.ts
5834
+ async function recordPrivacyRequest(db, input) {
5835
+ await db.dataSubjectRequest.create({
5836
+ data: {
5837
+ organizationId: input.organizationId,
5838
+ kind: input.kind,
5839
+ subjectHashes: subjectHashes(input.organizationId, input.subject),
5840
+ requestedBy: input.requestedBy,
5841
+ counts: { ...input.counts },
5842
+ createdAt: input.now
5843
+ }
5844
+ });
5845
+ }
5846
+ async function listPrivacyRequests(db, input) {
5847
+ const where = { organizationId: input.organizationId };
5848
+ const [requests, total] = await Promise.all([
5849
+ db.dataSubjectRequest.findMany({
5850
+ where,
5851
+ orderBy: { createdAt: "desc" },
5852
+ take: Math.min(input.limit ?? 50, 200),
5853
+ skip: input.offset ?? 0,
5854
+ select: { id: true, kind: true, requestedBy: true, counts: true, createdAt: true }
5855
+ }),
5856
+ db.dataSubjectRequest.count({ where })
5857
+ ]);
5858
+ return { requests, total };
5859
+ }
5860
+
5861
+ // src/privacy/collect.ts
5862
+ var APPOINTMENT = {
5863
+ id: true,
5864
+ startTime: true,
5865
+ endTime: true,
5866
+ duration: true,
5867
+ timezone: true,
5868
+ status: true,
5869
+ isGroup: true,
5870
+ clientName: true,
5871
+ clientEmail: true,
5872
+ clientPhone: true,
5873
+ clientId: true,
5874
+ cancelledAt: true,
5875
+ cancelledBy: true,
5876
+ cancelReason: true,
5877
+ rescheduledFrom: true,
5878
+ rescheduleCount: true,
5879
+ intakeResponses: true,
5880
+ notes: true,
5881
+ staffNotes: true,
5882
+ location: true,
5883
+ meetingUrl: true,
5884
+ paymentStatus: true,
5885
+ paymentAmount: true,
5886
+ depositAmount: true,
5887
+ tipAmount: true,
5888
+ paymentProvider: true,
5889
+ paymentId: true,
5890
+ balancePaymentId: true,
5891
+ couponCode: true,
5892
+ discountAmount: true,
5893
+ cancellationFeeAmount: true,
5894
+ refundAmount: true,
5895
+ refundStatus: true,
5896
+ recurringId: true,
5897
+ recurringIndex: true,
5898
+ packagePurchaseId: true,
5899
+ createdAt: true,
5900
+ updatedAt: true,
5901
+ calendar: { select: { name: true } },
5902
+ type: { select: { name: true } }
5903
+ };
5904
+ var NOTIFICATION = {
5905
+ id: true,
5906
+ appointmentId: true,
5907
+ channel: true,
5908
+ trigger: true,
5909
+ recipient: true,
5910
+ subject: true,
5911
+ body: true,
5912
+ status: true,
5913
+ scheduledFor: true,
5914
+ sentAt: true,
5915
+ createdAt: true
5916
+ };
5917
+ var WAITLIST = {
5918
+ id: true,
5919
+ typeId: true,
5920
+ calendarId: true,
5921
+ day: true,
5922
+ slotStart: true,
5923
+ timezone: true,
5924
+ clientName: true,
5925
+ clientEmail: true,
5926
+ clientPhone: true,
5927
+ status: true,
5928
+ offerSlotStart: true,
5929
+ offerExpiresAt: true,
5930
+ offeredAt: true,
5931
+ bookedAppointmentId: true,
5932
+ createdAt: true
5933
+ };
5934
+ var PURCHASE = {
5935
+ id: true,
5936
+ packageId: true,
5937
+ clientEmail: true,
5938
+ clientName: true,
5939
+ sessionsTotal: true,
5940
+ sessionsUsed: true,
5941
+ expiresAt: true,
5942
+ purchasedAt: true,
5943
+ status: true,
5944
+ paymentId: true,
5945
+ notes: true,
5946
+ pricePaidCents: true,
5947
+ createdAt: true
5948
+ };
5949
+ var SERIES = {
5950
+ id: true,
5951
+ calendarId: true,
5952
+ typeId: true,
5953
+ frequency: true,
5954
+ occurrences: true,
5955
+ startTimeLocal: true,
5956
+ durationMins: true,
5957
+ timezone: true,
5958
+ endsAt: true,
5959
+ clientEmail: true,
5960
+ clientName: true,
5961
+ clientPhone: true,
5962
+ clientId: true,
5963
+ notes: true,
5964
+ status: true,
5965
+ createdAt: true
5966
+ };
5967
+ var DELIVERY = { id: true, eventId: true, eventType: true, body: true, status: true, createdAt: true };
5968
+ var emailIs = (field, emails) => emails.map((email2) => ({ [field]: { equals: email2, mode: "insensitive" } }));
5969
+ var escape = (text2) => text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5970
+ function mentions(body, emails, ids) {
5971
+ const lower = body.toLowerCase();
5972
+ const whole = emails.some((email2) => new RegExp(`(?<![a-z0-9._%+-])${escape(email2.toLowerCase())}(?![a-z0-9_-]|\\.[a-z0-9])`).test(lower));
5973
+ return whole || ids.some((id) => body.includes(`"${id}"`));
5974
+ }
5975
+ async function collectSubjectRows(db, organizationId, subject) {
5976
+ const person = (field) => [...emailIs(field, subject.emails), ...subject.clientId ? [{ clientId: subject.clientId }] : []];
5977
+ const byEmail = emailIs("clientEmail", subject.emails);
5978
+ const none = subject.emails.length === 0 && !subject.clientId;
5979
+ const appointments = none ? [] : await db.appointment.findMany({
5980
+ where: { calendar: { organizationId }, OR: person("clientEmail") },
5981
+ orderBy: { startTime: "asc" },
5982
+ select: APPOINTMENT
5983
+ });
5984
+ const appointmentIds = appointments.map((row) => row.id);
5985
+ const [notifications, waitlistEntries, packagePurchases, recurringSeries] = await Promise.all([
5986
+ appointmentIds.length ? db.scheduledNotification.findMany({ where: { appointmentId: { in: appointmentIds } }, orderBy: { createdAt: "asc" }, select: NOTIFICATION }) : [],
5987
+ byEmail.length ? db.waitlistEntry.findMany({ where: { organizationId, OR: byEmail }, orderBy: { createdAt: "asc" }, select: WAITLIST }) : [],
5988
+ byEmail.length ? db.packagePurchase.findMany({ where: { organizationId, OR: byEmail }, orderBy: { createdAt: "asc" }, select: PURCHASE }) : [],
5989
+ none ? [] : db.recurringSeries.findMany({ where: { organizationId, OR: person("clientEmail") }, orderBy: { createdAt: "asc" }, select: SERIES })
5990
+ ]);
5991
+ const terms = [...subject.emails, ...appointmentIds.map((id) => `"${id}"`), ...waitlistEntries.map((row) => `"${row.id}"`)];
5992
+ const deliveries = /* @__PURE__ */ new Map();
5993
+ for (let start = 0; start < terms.length; start += 40) {
5994
+ const chunk = terms.slice(start, start + 40);
5995
+ const rows = await db.webhookDelivery.findMany({
5996
+ where: { organizationId, OR: chunk.map((term) => ({ body: { contains: term, mode: "insensitive" } })) },
5997
+ orderBy: { createdAt: "asc" },
5998
+ select: DELIVERY
5999
+ });
6000
+ for (const row of rows) if (mentions(row.body, subject.emails, [...appointmentIds, ...waitlistEntries.map((entry4) => entry4.id)])) deliveries.set(row.id, row);
6001
+ }
6002
+ return { appointments, notifications, waitlistEntries, packagePurchases, recurringSeries, webhookDeliveries: [...deliveries.values()] };
6003
+ }
6004
+ function countRows(rows) {
6005
+ return {
6006
+ appointments: rows.appointments.length,
6007
+ notifications: rows.notifications.length,
6008
+ waitlistEntries: rows.waitlistEntries.length,
6009
+ packagePurchases: rows.packagePurchases.length,
6010
+ recurringSeries: rows.recurringSeries.length,
6011
+ webhookDeliveries: rows.webhookDeliveries.length
6012
+ };
6013
+ }
6014
+
6015
+ // src/privacy/export.ts
6016
+ function withoutOfferToken(body) {
6017
+ try {
6018
+ const parsed = JSON.parse(body);
6019
+ if (parsed?.data?.offer && "token" in parsed.data.offer) {
6020
+ delete parsed.data.offer.token;
6021
+ return JSON.stringify(parsed);
6022
+ }
6023
+ } catch {
6024
+ }
6025
+ return body;
6026
+ }
6027
+ function withoutLinks(body) {
6028
+ return body.replace(/\/appt\/[A-Za-z0-9_-]+/g, "/appt/[removed]").replace(/([?&]token=)[A-Za-z0-9_-]+/g, "$1[removed]");
6029
+ }
6030
+ async function exportSubject(db, input) {
6031
+ const parsed = parseSubject(input);
6032
+ const now = input.now ?? /* @__PURE__ */ new Date();
6033
+ const subject = await resolveSubject(db, input.organizationId, parsed);
6034
+ const rows = await collectSubjectRows(db, input.organizationId, subject);
6035
+ const counts = countRows(rows);
6036
+ await recordPrivacyRequest(db, { organizationId: input.organizationId, kind: "EXPORT", subject, requestedBy: input.requestedBy, counts, now });
6037
+ return {
6038
+ format: "ordinatio-scheduling-subject-export",
6039
+ version: 1,
6040
+ exportedAt: now.toISOString(),
6041
+ organizationId: input.organizationId,
6042
+ subject,
6043
+ counts,
6044
+ appointments: rows.appointments.map(({ calendar, type, ...rest }) => ({ ...rest, calendarName: calendar.name, typeName: type.name })),
6045
+ notifications: rows.notifications.map((row) => ({ ...row, body: withoutLinks(row.body) })),
6046
+ waitlistEntries: rows.waitlistEntries,
6047
+ packagePurchases: rows.packagePurchases,
6048
+ recurringSeries: rows.recurringSeries,
6049
+ webhookDeliveries: rows.webhookDeliveries.map((row) => ({ ...row, body: withoutOfferToken(row.body) }))
6050
+ };
6051
+ }
6052
+
6053
+ // src/privacy/erase.ts
6054
+ var import_node_crypto7 = require("crypto");
6055
+ var import_client9 = require("@prisma/client");
6056
+ var ERASED_NAME = "Erased client";
6057
+ var ERASED_EMAIL = "erased@erased.invalid";
6058
+ var LIVE_BOOKING = ["PENDING", "CONFIRMED"];
6059
+ var LIVE_OFFER = ["OFFERED", "ACCEPTING"];
6060
+ function blockersOf(rows, now) {
6061
+ return {
6062
+ upcomingAppointments: rows.appointments.filter((row) => LIVE_BOOKING.includes(row.status) && row.endTime > now).length,
6063
+ liveWaitlistEntries: rows.waitlistEntries.filter((row) => LIVE_OFFER.includes(row.status)).length
6064
+ };
6065
+ }
6066
+ function warningsOf(rows) {
6067
+ const unused = rows.packagePurchases.filter((row) => row.status === "ACTIVE").reduce((sum, row) => sum + Math.max(0, row.sessionsTotal - row.sessionsUsed), 0);
6068
+ return unused > 0 ? [`An active package still has ${unused} unused sessions; after erasure it can no longer be matched to this person`] : [];
6069
+ }
6070
+ var blocked = (blockers) => blockers.upcomingAppointments + blockers.liveWaitlistEntries > 0;
6071
+ async function previewErase(db, input) {
6072
+ const subject = await resolveSubject(db, input.organizationId, parseSubject(input));
6073
+ const rows = await collectSubjectRows(db, input.organizationId, subject);
6074
+ const blockers = blockersOf(rows, input.now ?? /* @__PURE__ */ new Date());
6075
+ return { counts: countRows(rows), blockers, canErase: !blocked(blockers), warnings: warningsOf(rows) };
6076
+ }
6077
+ async function eraseSubject(db, input) {
6078
+ const parsed = parseSubject(input);
6079
+ const now = input.now ?? /* @__PURE__ */ new Date();
6080
+ const { organizationId } = input;
6081
+ return withTransaction(db, async (tx) => {
6082
+ const subject = await resolveSubject(tx, organizationId, parsed);
6083
+ const rows = await collectSubjectRows(tx, organizationId, subject);
6084
+ const blockers = blockersOf(rows, now);
6085
+ if (blocked(blockers)) {
6086
+ throw new SchedulingValidationError("This person still has upcoming bookings or an open waitlist offer", "SCHED_1301", { blockers });
6087
+ }
6088
+ for (const { id } of rows.appointments) {
6089
+ await tx.appointment.update({
6090
+ where: { id },
6091
+ data: {
6092
+ clientName: ERASED_NAME,
6093
+ clientEmail: ERASED_EMAIL,
6094
+ clientPhone: null,
6095
+ clientId: null,
6096
+ intakeResponses: import_client9.Prisma.DbNull,
6097
+ notes: null,
6098
+ staffNotes: null,
6099
+ cancelReason: null,
6100
+ manageToken: `erased_${(0, import_node_crypto7.randomUUID)()}`
6101
+ }
6102
+ });
6103
+ }
6104
+ const idsOf = (list) => list.map((row) => row.id);
6105
+ if (rows.notifications.length) await tx.scheduledNotification.deleteMany({ where: { id: { in: idsOf(rows.notifications) } } });
6106
+ if (rows.waitlistEntries.length) await tx.waitlistEntry.deleteMany({ where: { organizationId, id: { in: idsOf(rows.waitlistEntries) } } });
6107
+ if (rows.webhookDeliveries.length) await tx.webhookDelivery.deleteMany({ where: { organizationId, id: { in: idsOf(rows.webhookDeliveries) } } });
6108
+ if (rows.packagePurchases.length) {
6109
+ await tx.packagePurchase.updateMany({
6110
+ where: { organizationId, id: { in: idsOf(rows.packagePurchases) } },
6111
+ data: { clientEmail: ERASED_EMAIL, clientName: null, notes: null }
6112
+ });
6113
+ }
6114
+ if (rows.recurringSeries.length) {
6115
+ await tx.recurringSeries.updateMany({
6116
+ where: { organizationId, id: { in: idsOf(rows.recurringSeries) } },
6117
+ data: { clientEmail: ERASED_EMAIL, clientName: ERASED_NAME, clientPhone: null, clientId: null, notes: null }
6118
+ });
6119
+ }
6120
+ const counts = countRows(rows);
6121
+ await recordPrivacyRequest(tx, { organizationId, kind: "ERASE", subject, requestedBy: input.requestedBy, counts, now });
6122
+ return { counts };
6123
+ }, { timeout: 12e4 });
6124
+ }
4524
6125
  // Annotate the CommonJS export names for ESM import in node:
4525
6126
  0 && (module.exports = {
6127
+ BRAND_FIELDS,
4526
6128
  BlockedTargetError,
4527
6129
  DEFAULT_BACKOFF_SECONDS,
6130
+ DEFAULT_OFFER_MINUTES,
6131
+ ERASED_EMAIL,
6132
+ ERASED_NAME,
4528
6133
  MAX_ENDPOINTS_PER_ORGANIZATION,
6134
+ MAX_WAITING_PER_TYPE_DAY,
6135
+ OPERATORS_BY_TYPE,
4529
6136
  RECURRING_MAX_OCCURRENCES,
6137
+ ROUTING_LIMITS,
4530
6138
  SCHEDULING_ERRORS,
4531
6139
  SIGNATURE_HEADER,
4532
6140
  SchedulingNotFoundError,
@@ -4539,7 +6147,9 @@ async function retryWebhookDelivery(db, organizationId, deliveryId, now = /* @__
4539
6147
  addTimeBlock,
4540
6148
  appointmentWebhookData,
4541
6149
  archiveCalendar,
6150
+ beginWaitlistAccept,
4542
6151
  bookAppointment,
6152
+ brandTemplateFields,
4543
6153
  buildJitsiUrl,
4544
6154
  buildNotificationContext,
4545
6155
  buildOccurrenceStartTime,
@@ -4547,25 +6157,33 @@ async function retryWebhookDelivery(db, organizationId, deliveryId, now = /* @__
4547
6157
  calculateCancellationFee,
4548
6158
  cancelAppointment,
4549
6159
  cancelPendingNotifications,
6160
+ checkAnswers,
4550
6161
  checkAuthContract,
4551
6162
  checkCalendarSyncContract,
4552
6163
  checkClockContract,
4553
6164
  checkNotificationContract,
4554
6165
  checkPaymentContract,
4555
6166
  checkWebhookUrl,
6167
+ completeWaitlistAccept,
4556
6168
  createAppointmentType,
4557
6169
  createCalendar,
4558
6170
  createInMemoryAdapters,
4559
6171
  createNodeTransport,
4560
6172
  createNotificationTemplate,
6173
+ createRoutingForm,
4561
6174
  createWebhookEndpoint,
6175
+ deleteBrand,
4562
6176
  deleteCalendar,
4563
6177
  deleteNotificationTemplate,
6178
+ deleteRoutingForm,
4564
6179
  deleteWebhookEndpoint,
4565
6180
  deliverDueWebhooks,
4566
6181
  enqueueAppointmentWebhook,
4567
6182
  enqueueReminderSent,
4568
6183
  enqueueWebhookEvent,
6184
+ eraseSubject,
6185
+ expireWaitlistOffers,
6186
+ exportSubject,
4569
6187
  generateOccurrenceDates,
4570
6188
  generateWebhookSecret,
4571
6189
  getAppointment,
@@ -4575,42 +6193,73 @@ async function retryWebhookDelivery(db, organizationId, deliveryId, now = /* @__
4575
6193
  getAvailableDates,
4576
6194
  getAvailableSlots,
4577
6195
  getBookingAnalytics,
6196
+ getBrand,
4578
6197
  getCalendar,
4579
6198
  getGroupCapacity,
4580
6199
  getGroupSessions,
4581
6200
  getNotificationTemplate,
6201
+ getPublicBrand,
6202
+ getPublicRoutingForm,
6203
+ getRoutingForm,
4582
6204
  getTeamAvailableSlots,
4583
6205
  getUserDayAppointments,
6206
+ getWaitlistOffer,
4584
6207
  isPrivateAddress,
4585
6208
  isSlotAvailable,
4586
6209
  isVirtualMeeting,
6210
+ joinWaitlist,
6211
+ leaveWaitlist,
4587
6212
  listAppointmentTypes,
4588
6213
  listAppointments,
4589
6214
  listAvailabilityRules,
4590
6215
  listCalendars,
4591
6216
  listNotificationTemplates,
6217
+ listPrivacyRequests,
6218
+ listRoutingForms,
6219
+ listWaitlist,
4592
6220
  listWebhookDeliveries,
4593
6221
  listWebhookEndpoints,
6222
+ localDay,
4594
6223
  localToUTC,
4595
6224
  markNoShow,
6225
+ matchingRules,
6226
+ offerFreedSlot,
6227
+ parseSubject,
4596
6228
  parseTimeLocal,
6229
+ previewErase,
4597
6230
  processPendingNotifications,
4598
6231
  queueImmediateNotification,
4599
6232
  queueStaffNotification,
6233
+ releaseWaitlistAccept,
4600
6234
  removeDateOverride,
6235
+ removeWaitlistEntry,
4601
6236
  renderTemplate,
4602
6237
  rescheduleAppointment,
6238
+ resolveDestination,
4603
6239
  resolveLocation,
6240
+ resolveSubject,
4604
6241
  retryWebhookDelivery,
6242
+ routeClient,
6243
+ saveBrand,
4605
6244
  schedError,
4606
6245
  scheduleNotifications,
4607
6246
  selectCalendarForBooking,
4608
6247
  sendTestWebhook,
6248
+ senderIdentity,
4609
6249
  setWeeklyAvailability,
6250
+ settleBookedAccept,
4610
6251
  signWebhook,
6252
+ subjectHashes,
6253
+ testRoutingForm,
6254
+ toPublicBrand,
6255
+ tryOfferFreedSlot,
4611
6256
  updateAppointmentType,
4612
6257
  updateCalendar,
4613
6258
  updateNotificationTemplate,
6259
+ updateRoutingForm,
6260
+ validateBrand,
6261
+ validateRoutingDestinations,
6262
+ validateRoutingStructure,
4614
6263
  verifyWebhookSignature,
4615
6264
  withCalendarVisibility
4616
6265
  });