@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.mjs CHANGED
@@ -926,7 +926,7 @@ var WEBHOOK_ERRORS = {
926
926
  description: "The webhook event list is empty or names an event that does not exist",
927
927
  diagnosis: [
928
928
  'Send at least one event name, or "*" for every event',
929
- "Valid names: appointment.booked, appointment.rescheduled, appointment.cancelled, appointment.no_show, reminder.sent"
929
+ "Valid names: appointment.booked, appointment.rescheduled, appointment.cancelled, appointment.no_show, reminder.sent, waitlist.offered"
930
930
  ]
931
931
  },
932
932
  SCHED_1002: {
@@ -988,6 +988,153 @@ var WEBHOOK_ERRORS = {
988
988
  }
989
989
  };
990
990
 
991
+ // src/errors/registry-waitlist.ts
992
+ function entry(code, fn, description, diagnosis, severity = "warning", recoverable = true) {
993
+ return { code, file: "waitlist/", function: fn, severity, recoverable, description, diagnosis };
994
+ }
995
+ var WAITLIST_ERRORS = {
996
+ SCHED_1100: entry(
997
+ "SCHED_1100",
998
+ "joinWaitlist",
999
+ "The appointment type or calendar for this waitlist request was not found",
1000
+ ["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"]
1001
+ ),
1002
+ SCHED_1101: entry(
1003
+ "SCHED_1101",
1004
+ "joinWaitlist",
1005
+ "The waitlist day is invalid, in the past, or too far ahead",
1006
+ ["Send the day as YYYY-MM-DD", "The day must be today or later, and within the next 90 days"]
1007
+ ),
1008
+ SCHED_1102: entry(
1009
+ "SCHED_1102",
1010
+ "joinWaitlist",
1011
+ "The waitlist time is invalid or not on the chosen day",
1012
+ ["Send the time as an ISO date-time on the chosen day, in the future"]
1013
+ ),
1014
+ SCHED_1103: entry(
1015
+ "SCHED_1103",
1016
+ "joinWaitlist",
1017
+ "That time or day still has open slots, so the client should book instead of waiting",
1018
+ ["Look up the open slots for the day", "Join the waitlist only for a slot or day that is full"]
1019
+ ),
1020
+ SCHED_1104: entry(
1021
+ "SCHED_1104",
1022
+ "joinWaitlist",
1023
+ "This email is already waiting for that day",
1024
+ ["The client is already on the list for this type and day", "They can leave with their link and join again"]
1025
+ ),
1026
+ SCHED_1105: entry(
1027
+ "SCHED_1105",
1028
+ "joinWaitlist",
1029
+ "A waitlist is not available for a type that needs payment",
1030
+ ["Payment cannot be taken when an offer is accepted", "Use a free type, or let clients book as slots open"]
1031
+ ),
1032
+ SCHED_1106: entry(
1033
+ "SCHED_1106",
1034
+ "getWaitlistOffer",
1035
+ "No open offer for this link",
1036
+ ["The link may be wrong, already used, or the entry may have left the list", "An offer can be accepted once"]
1037
+ ),
1038
+ SCHED_1107: entry(
1039
+ "SCHED_1107",
1040
+ "beginWaitlistAccept",
1041
+ "The offer has expired",
1042
+ ["The time limit ran out; the slot may have gone to the next person", "Join the waitlist again to wait for another slot"]
1043
+ ),
1044
+ SCHED_1108: entry(
1045
+ "SCHED_1108",
1046
+ "joinWaitlist",
1047
+ "The waitlist for that day is full",
1048
+ ["Too many people are already waiting for this type and day"]
1049
+ ),
1050
+ SCHED_1109: entry(
1051
+ "SCHED_1109",
1052
+ "offerFreedSlot",
1053
+ "A waitlist offer could not be made; the cancellation itself was saved",
1054
+ ["Check that the waitlist table exists (run the package migrations)", "Check the database connection"],
1055
+ "error"
1056
+ ),
1057
+ SCHED_1110: entry(
1058
+ "SCHED_1110",
1059
+ "joinWaitlist",
1060
+ "A waitlist is not available for a type with required intake questions",
1061
+ ["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"]
1062
+ )
1063
+ };
1064
+
1065
+ // src/errors/registry-routing.ts
1066
+ function entry2(code, fn, description, diagnosis, severity = "warning") {
1067
+ return { code, file: "routing/", function: fn, severity, recoverable: true, description, diagnosis };
1068
+ }
1069
+ var ROUTING_ERRORS = {
1070
+ SCHED_1200: entry2(
1071
+ "SCHED_1200",
1072
+ "validateRoutingForm",
1073
+ "The routing form is not valid",
1074
+ ["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"]
1075
+ ),
1076
+ SCHED_1201: entry2(
1077
+ "SCHED_1201",
1078
+ "routing form lookup",
1079
+ "The routing form was not found (for the public: no active form with that slug)",
1080
+ ["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"]
1081
+ ),
1082
+ SCHED_1202: entry2(
1083
+ "SCHED_1202",
1084
+ "createRoutingForm / updateRoutingForm",
1085
+ "Another routing form already uses that slug",
1086
+ ["Choose a different slug", "A slug is unique within the organization and must not be used by another organization in the same database"]
1087
+ ),
1088
+ SCHED_1203: entry2(
1089
+ "SCHED_1203",
1090
+ "routeClient",
1091
+ "The answers do not fit the form",
1092
+ ["Answer every required question", "Pick an offered option for choice questions, and send a list for checkbox questions", "Send only questions the form asks"]
1093
+ ),
1094
+ SCHED_1204: entry2(
1095
+ "SCHED_1204",
1096
+ "createRoutingForm",
1097
+ "The organization already has the maximum number of routing forms",
1098
+ ["Remove a form that is no longer used, then add the new one"]
1099
+ )
1100
+ };
1101
+
1102
+ // src/errors/registry-privacy.ts
1103
+ function entry3(code, fn, description, diagnosis) {
1104
+ return { code, file: "privacy/", function: fn, severity: "warning", recoverable: true, description, diagnosis };
1105
+ }
1106
+ var PRIVACY_ERRORS = {
1107
+ SCHED_1300: entry3(
1108
+ "SCHED_1300",
1109
+ "parseSubject",
1110
+ "Say whose data this is: a valid email address, a client id, or both",
1111
+ ["Send `email` (one address) and/or `clientId`", "An address must be a single address with no spaces, at most 254 characters"]
1112
+ ),
1113
+ SCHED_1301: entry3(
1114
+ "SCHED_1301",
1115
+ "eraseSubject",
1116
+ "This person still has upcoming bookings or an open waitlist offer, so their data cannot be erased yet",
1117
+ ["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"]
1118
+ )
1119
+ };
1120
+
1121
+ // src/errors/registry-brand.ts
1122
+ var BRAND_ERRORS = {
1123
+ SCHED_1400: {
1124
+ code: "SCHED_1400",
1125
+ file: "brand/",
1126
+ function: "validateBrand",
1127
+ severity: "warning",
1128
+ recoverable: true,
1129
+ description: "The brand settings are not valid",
1130
+ diagnosis: [
1131
+ "Read the list of problems in the error context: each names the field and what is wrong",
1132
+ "Colours are hex values such as #1a2b3c; the logo is an https address; email addresses are single plain addresses",
1133
+ "A sending address is accepted only for a domain the host has confirmed it may send from"
1134
+ ]
1135
+ }
1136
+ };
1137
+
991
1138
  // src/errors/registry.ts
992
1139
  var SCHEDULING_ERRORS = {
993
1140
  ...CALENDARS_AVAILABILITY_ERRORS,
@@ -998,7 +1145,11 @@ var SCHEDULING_ERRORS = {
998
1145
  ...RECURRING_MISC_ERRORS,
999
1146
  ...PUBLIC_DIRECTORY_ERRORS,
1000
1147
  ...GROUP_SCOPE_ERRORS,
1001
- ...WEBHOOK_ERRORS
1148
+ ...WEBHOOK_ERRORS,
1149
+ ...WAITLIST_ERRORS,
1150
+ ...ROUTING_ERRORS,
1151
+ ...PRIVACY_ERRORS,
1152
+ ...BRAND_ERRORS
1002
1153
  };
1003
1154
 
1004
1155
  // src/errors/diagnostic-error.ts
@@ -2088,9 +2239,7 @@ async function bookAppointment(db, input, callbacks) {
2088
2239
  clientName: input.clientName,
2089
2240
  clientEmail: input.clientEmail,
2090
2241
  clientPhone: input.clientPhone ?? null,
2091
- // ALFRED-246 (system-1701's .autocode/modules/alfred/debt.md): the public booking
2092
- // route passes this through from caller-supplied, unauthenticated input with no
2093
- // existence/ownership check — a real, disclosed, not-yet-fixed gap.
2242
+ // Not verified here: a caller that takes this from unauthenticated input must check it first.
2094
2243
  clientId: input.clientId ?? null,
2095
2244
  intakeResponses: input.intakeResponses,
2096
2245
  staffNotes: input.staffNotes ?? null,
@@ -2193,13 +2342,13 @@ function renderTemplate(template, context, channel = "EMAIL") {
2193
2342
  for (const [key, value] of Object.entries(context)) {
2194
2343
  if (typeof value === "string") {
2195
2344
  const safeValue = channel === "SMS" ? value : escapeHtml(value);
2196
- result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), safeValue);
2345
+ result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), () => safeValue);
2197
2346
  }
2198
2347
  }
2199
2348
  if (context.customFields) {
2200
2349
  for (const [key, value] of Object.entries(context.customFields)) {
2201
2350
  const safeValue = channel === "SMS" ? value : escapeHtml(value);
2202
- result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), safeValue);
2351
+ result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), () => safeValue);
2203
2352
  }
2204
2353
  }
2205
2354
  if (channel === "SMS") {
@@ -2252,6 +2401,196 @@ function buildNotificationContext(appointment, baseUrl) {
2252
2401
  };
2253
2402
  }
2254
2403
 
2404
+ // src/brand/sender.ts
2405
+ var NOT_IN_A_SENDER_NAME = /[<>",;@\\]/g;
2406
+ function senderIdentity(brand) {
2407
+ if (!brand) return null;
2408
+ const fallbackName = brand.displayName.replace(/[\u0000-\u001f\u007f]/g, " ").replace(NOT_IN_A_SENDER_NAME, "").replace(/\s+/g, " ").trim();
2409
+ const name = brand.fromName ?? (fallbackName || void 0);
2410
+ return {
2411
+ ...name ? { name } : {},
2412
+ ...brand.fromEmail ? { email: brand.fromEmail } : {},
2413
+ ...brand.replyToEmail ? { replyTo: brand.replyToEmail } : {}
2414
+ };
2415
+ }
2416
+ function brandTemplateFields(brand) {
2417
+ return {
2418
+ brandName: brand?.displayName ?? "",
2419
+ brandLogoUrl: brand?.logoUrl ?? "",
2420
+ brandColor: brand?.primaryColor ?? "",
2421
+ brandFooter: brand?.footerText ?? ""
2422
+ };
2423
+ }
2424
+ function toPublicBrand(brand) {
2425
+ return {
2426
+ displayName: brand.displayName,
2427
+ logoUrl: brand.logoUrl,
2428
+ primaryColor: brand.primaryColor,
2429
+ accentColor: brand.accentColor,
2430
+ backgroundColor: brand.backgroundColor,
2431
+ textColor: brand.textColor,
2432
+ fontFamily: brand.fontFamily,
2433
+ footerText: brand.footerText
2434
+ };
2435
+ }
2436
+
2437
+ // src/brand/types.ts
2438
+ var BRAND_FIELDS = [
2439
+ "displayName",
2440
+ "logoUrl",
2441
+ "primaryColor",
2442
+ "accentColor",
2443
+ "backgroundColor",
2444
+ "textColor",
2445
+ "fontFamily",
2446
+ "footerText",
2447
+ "replyToEmail",
2448
+ "fromName",
2449
+ "fromEmail"
2450
+ ];
2451
+
2452
+ // src/brand/validate.ts
2453
+ var HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
2454
+ var FONT = /^[A-Za-z0-9 ,-]{1,100}$/;
2455
+ var EMAIL = /^[^\s@<>,;"'()[\]\\]+@[^\s@<>,;"'()[\]\\]+\.[^\s@<>,;"'()[\]\\]+$/;
2456
+ var CONTROL = /[\u0000-\u001f\u007f]/;
2457
+ var COLOR_FIELDS = ["primaryColor", "accentColor", "backgroundColor", "textColor"];
2458
+ function text(value, path, max, problems, required = false) {
2459
+ if (value === void 0 || value === null || value === "") {
2460
+ if (required) problems.push({ path, message: "Required" });
2461
+ return null;
2462
+ }
2463
+ if (typeof value !== "string") {
2464
+ problems.push({ path, message: "Must be text" });
2465
+ return null;
2466
+ }
2467
+ const trimmed = value.trim();
2468
+ if (trimmed.length === 0) {
2469
+ if (required) problems.push({ path, message: "Required" });
2470
+ return null;
2471
+ }
2472
+ if (trimmed.length > max) problems.push({ path, message: `At most ${max} characters` });
2473
+ else if (CONTROL.test(trimmed)) problems.push({ path, message: "Must not contain control characters" });
2474
+ else return trimmed;
2475
+ return null;
2476
+ }
2477
+ function email(value, path, problems) {
2478
+ const raw = text(value, path, 254, problems);
2479
+ if (raw === null) return null;
2480
+ if (!EMAIL.test(raw)) {
2481
+ problems.push({ path, message: "Must be a single email address" });
2482
+ return null;
2483
+ }
2484
+ return raw.toLowerCase();
2485
+ }
2486
+ function logo(value, problems) {
2487
+ const raw = text(value, "logoUrl", 500, problems);
2488
+ if (raw === null) return null;
2489
+ try {
2490
+ const url = new URL(raw);
2491
+ if (url.protocol === "https:" && !url.username && !url.password && url.hostname) return raw;
2492
+ } catch {
2493
+ }
2494
+ problems.push({ path: "logoUrl", message: "Must be an https address without a user name or password" });
2495
+ return null;
2496
+ }
2497
+ async function validateBrand(input, options) {
2498
+ const problems = [];
2499
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
2500
+ throw new SchedulingValidationError("The brand settings are not valid", "SCHED_1400", { errors: [{ path: "", message: "Must be an object" }] });
2501
+ }
2502
+ const given = input;
2503
+ for (const key of Object.keys(given)) if (!BRAND_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
2504
+ const out = {
2505
+ displayName: text(given.displayName, "displayName", 100, problems, true) ?? "",
2506
+ logoUrl: logo(given.logoUrl, problems),
2507
+ primaryColor: null,
2508
+ accentColor: null,
2509
+ backgroundColor: null,
2510
+ textColor: null,
2511
+ fontFamily: null,
2512
+ footerText: text(given.footerText, "footerText", 300, problems),
2513
+ replyToEmail: email(given.replyToEmail, "replyToEmail", problems),
2514
+ fromName: text(given.fromName, "fromName", 100, problems),
2515
+ fromEmail: email(given.fromEmail, "fromEmail", problems)
2516
+ };
2517
+ for (const field of COLOR_FIELDS) {
2518
+ const raw = text(given[field], field, 7, problems);
2519
+ if (raw === null) continue;
2520
+ if (HEX.test(raw)) out[field] = raw.toLowerCase();
2521
+ else problems.push({ path: field, message: "Must be a hex colour such as #1a2b3c" });
2522
+ }
2523
+ const font = text(given.fontFamily, "fontFamily", 100, problems);
2524
+ if (font !== null) {
2525
+ if (FONT.test(font)) out.fontFamily = font;
2526
+ else problems.push({ path: "fontFamily", message: "Letters, digits, spaces, commas and dashes only" });
2527
+ }
2528
+ if (out.fromName !== null && /[<>",;@\\]/.test(out.fromName)) {
2529
+ problems.push({ path: "fromName", message: "Must not contain quotes, angle brackets, commas, semicolons, @ or backslashes" });
2530
+ out.fromName = null;
2531
+ }
2532
+ if (out.fromEmail !== null && !problems.some((p) => p.path === "fromEmail")) {
2533
+ const domain = out.fromEmail.slice(out.fromEmail.lastIndexOf("@") + 1);
2534
+ let verified = false;
2535
+ try {
2536
+ verified = options.isSendingDomainVerified ? await options.isSendingDomainVerified(domain) : false;
2537
+ } catch (error) {
2538
+ console.error("[brand] the sending-domain check failed:", error);
2539
+ verified = false;
2540
+ }
2541
+ if (!verified) problems.push({ path: "fromEmail", message: `Sending from ${domain} is not confirmed for this server` });
2542
+ }
2543
+ if (problems.length > 0) throw new SchedulingValidationError("The brand settings are not valid", "SCHED_1400", { errors: problems });
2544
+ return out;
2545
+ }
2546
+
2547
+ // src/brand/crud.ts
2548
+ var SELECT = {
2549
+ displayName: true,
2550
+ logoUrl: true,
2551
+ primaryColor: true,
2552
+ accentColor: true,
2553
+ backgroundColor: true,
2554
+ textColor: true,
2555
+ fontFamily: true,
2556
+ footerText: true,
2557
+ replyToEmail: true,
2558
+ fromName: true,
2559
+ fromEmail: true,
2560
+ updatedAt: true
2561
+ };
2562
+ async function getBrand(db, organizationId) {
2563
+ return db.organizationBrand.findUnique({ where: { organizationId }, select: SELECT });
2564
+ }
2565
+ async function getPublicBrand(db, organizationId) {
2566
+ if (organizationId) {
2567
+ const brand = await getBrand(db, organizationId);
2568
+ return brand ? toPublicBrand(brand) : null;
2569
+ }
2570
+ const all = await db.organizationBrand.findMany({ take: 2, select: SELECT });
2571
+ return all.length === 1 ? toPublicBrand(all[0]) : null;
2572
+ }
2573
+ async function saveBrand(db, organizationId, input, options) {
2574
+ const fields = await validateBrand(input, options);
2575
+ return db.organizationBrand.upsert({
2576
+ where: { organizationId },
2577
+ create: { organizationId, ...fields },
2578
+ update: { ...fields },
2579
+ select: SELECT
2580
+ });
2581
+ }
2582
+ async function deleteBrand(db, organizationId) {
2583
+ const { count } = await db.organizationBrand.deleteMany({ where: { organizationId } });
2584
+ return count > 0;
2585
+ }
2586
+
2587
+ // src/notifications/brand-context.ts
2588
+ async function withBrandFields(db, organizationId, context, enabled) {
2589
+ if (!enabled) return context;
2590
+ const brand = organizationId ? await getBrand(db, organizationId) : null;
2591
+ return { ...context, customFields: { ...context.customFields, ...brandTemplateFields(brand) } };
2592
+ }
2593
+
2255
2594
  // src/notifications/process-pending-notifications.ts
2256
2595
  import { randomUUID as randomUUID2 } from "crypto";
2257
2596
  import { Prisma as Prisma6 } from "@prisma/client";
@@ -2263,7 +2602,8 @@ var WEBHOOK_EVENT_TYPES = [
2263
2602
  "appointment.rescheduled",
2264
2603
  "appointment.cancelled",
2265
2604
  "appointment.no_show",
2266
- "reminder.sent"
2605
+ "reminder.sent",
2606
+ "waitlist.offered"
2267
2607
  ];
2268
2608
  var WEBHOOK_TEST_EVENT = "webhook.test";
2269
2609
  var ALL_EVENTS = "*";
@@ -2410,8 +2750,10 @@ async function processPendingNotifications(db, sender, options) {
2410
2750
  `;
2411
2751
  if (claimed.length === 0) return { sent: 0, failed: 0, deadLettered: 0, skipped: 0 };
2412
2752
  const pending = await db.scheduledNotification.findMany({
2413
- where: { id: { in: claimed.map((c) => c.id) } }
2753
+ where: { id: { in: claimed.map((c) => c.id) } },
2754
+ ...options?.brand ? { include: { appointment: { select: { calendar: { select: { organizationId: true } } } } } } : {}
2414
2755
  });
2756
+ const senders = options?.brand ? await loadSenders(db, pending) : null;
2415
2757
  let sent = 0;
2416
2758
  let failed = 0;
2417
2759
  let deadLettered = 0;
@@ -2423,7 +2765,10 @@ async function processPendingNotifications(db, sender, options) {
2423
2765
  notification.recipient,
2424
2766
  notification.subject || "",
2425
2767
  notification.body,
2426
- { trigger: notification.trigger }
2768
+ {
2769
+ trigger: notification.trigger,
2770
+ ...senderFor(senders, notification)
2771
+ }
2427
2772
  );
2428
2773
  if (result?.skipped) {
2429
2774
  await db.scheduledNotification.update({
@@ -2477,6 +2822,22 @@ async function processPendingNotifications(db, sender, options) {
2477
2822
  }
2478
2823
  return { sent, failed, deadLettered, skipped };
2479
2824
  }
2825
+ async function loadSenders(db, rows) {
2826
+ const ids = [...new Set(rows.map((row) => row.appointment?.calendar?.organizationId).filter((id) => Boolean(id)))];
2827
+ const senders = /* @__PURE__ */ new Map();
2828
+ if (ids.length === 0) return senders;
2829
+ const brands = await db.organizationBrand.findMany({ where: { organizationId: { in: ids } } });
2830
+ for (const brand of brands) {
2831
+ const identity = senderIdentity(brand);
2832
+ if (identity) senders.set(brand.organizationId, identity);
2833
+ }
2834
+ return senders;
2835
+ }
2836
+ function senderFor(senders, row) {
2837
+ const organizationId = row.appointment?.calendar?.organizationId;
2838
+ const from = senders && organizationId ? senders.get(organizationId) : void 0;
2839
+ return from ? { from } : {};
2840
+ }
2480
2841
 
2481
2842
  // src/notifications/engine.ts
2482
2843
  async function scheduleNotifications(db, appointmentId, baseUrl, options) {
@@ -2496,10 +2857,10 @@ async function scheduleNotifications(db, appointmentId, baseUrl, options) {
2496
2857
  }
2497
2858
  });
2498
2859
  if (!appointment) return;
2499
- const context = buildNotificationContext({
2860
+ const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
2500
2861
  ...appointment,
2501
2862
  intakeResponses: appointment.intakeResponses
2502
- }, baseUrl);
2863
+ }, baseUrl), options?.brand);
2503
2864
  const now = /* @__PURE__ */ new Date();
2504
2865
  const startTime = new Date(appointment.startTime);
2505
2866
  const templates = await db.notificationTemplate.findMany({
@@ -2572,7 +2933,7 @@ async function cancelPendingNotifications(db, appointmentId) {
2572
2933
  data: { status: "CANCELLED" }
2573
2934
  });
2574
2935
  }
2575
- async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
2936
+ async function queueImmediateNotification(db, appointmentId, trigger, baseUrl, options) {
2576
2937
  const appointment = await db.appointment.findUnique({
2577
2938
  where: { id: appointmentId },
2578
2939
  include: {
@@ -2581,10 +2942,10 @@ async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
2581
2942
  }
2582
2943
  });
2583
2944
  if (!appointment) return;
2584
- const context = buildNotificationContext({
2945
+ const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
2585
2946
  ...appointment,
2586
2947
  intakeResponses: appointment.intakeResponses
2587
- }, baseUrl);
2948
+ }, baseUrl), options?.brand);
2588
2949
  const templates = await db.notificationTemplate.findMany({
2589
2950
  where: { trigger, isActive: true, recipientType: "CLIENT", organizationId: appointment.calendar.organizationId ?? "" }
2590
2951
  });
@@ -2610,7 +2971,7 @@ async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
2610
2971
  await db.scheduledNotification.createMany({ data: notifications });
2611
2972
  }
2612
2973
  }
2613
- async function queueStaffNotification(db, appointmentId, trigger, baseUrl) {
2974
+ async function queueStaffNotification(db, appointmentId, trigger, baseUrl, options) {
2614
2975
  const appointment = await db.appointment.findUnique({
2615
2976
  where: { id: appointmentId },
2616
2977
  include: {
@@ -2625,10 +2986,10 @@ async function queueStaffNotification(db, appointmentId, trigger, baseUrl) {
2625
2986
  where: { trigger, recipientType: "STAFF", isActive: true, organizationId: appointment.calendar.organizationId ?? "" }
2626
2987
  });
2627
2988
  if (staffTemplates.length === 0) return;
2628
- const context = buildNotificationContext({
2989
+ const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
2629
2990
  ...appointment,
2630
2991
  intakeResponses: appointment.intakeResponses
2631
- }, baseUrl);
2992
+ }, baseUrl), options?.brand);
2632
2993
  const now = /* @__PURE__ */ new Date();
2633
2994
  const notifications = staffTemplates.map((template) => ({
2634
2995
  appointmentId: appointment.id,
@@ -3575,7 +3936,7 @@ function adaptersToCallbacks(adapters, passThrough = {}) {
3575
3936
  return {
3576
3937
  ...passThrough,
3577
3938
  sendNotification: async (channel, to, subject, body, context) => {
3578
- const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger });
3939
+ const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger, ...context?.from ? { from: context.from } : {} });
3579
3940
  if (result.status === "SKIPPED") return { skipped: true, reason: result.reason };
3580
3941
  return void 0;
3581
3942
  },
@@ -3623,10 +3984,10 @@ async function checkNotificationContract(adapter) {
3623
3984
  const result = await adapter.send({ channel: "EMAIL", to: "contract@example.com", subject: "Contract", body: "Body" });
3624
3985
  if (result.status !== "SENT" && result.status !== "SKIPPED") failures.push("send() must return status SENT or SKIPPED");
3625
3986
  });
3626
- for (const blank of ["", " "]) {
3627
- await guarded(`send to an empty recipient (${JSON.stringify(blank)})`, failures, async () => {
3628
- const result = await adapter.send({ channel: "SMS", to: blank, subject: "", body: "Body" }).catch(() => null);
3629
- if (result?.status === "SENT") failures.push(`send() must not report SENT for an empty recipient (${JSON.stringify(blank)})`);
3987
+ for (const blank2 of ["", " "]) {
3988
+ await guarded(`send to an empty recipient (${JSON.stringify(blank2)})`, failures, async () => {
3989
+ const result = await adapter.send({ channel: "SMS", to: blank2, subject: "", body: "Body" }).catch(() => null);
3990
+ if (result?.status === "SENT") failures.push(`send() must not report SENT for an empty recipient (${JSON.stringify(blank2)})`);
3630
3991
  });
3631
3992
  }
3632
3993
  return failures;
@@ -3646,7 +4007,7 @@ async function checkPaymentContract(adapter, options = {}) {
3646
4007
  if (!await refused(() => adapter.charge({ ...request, amount: 0 }))) failures.push("a charge of 0 must not succeed");
3647
4008
  });
3648
4009
  await guarded("verify of an unknown payment", failures, async () => {
3649
- const paid = await adapter.verify("contract-unknown-payment").then((check) => check.paid, () => false);
4010
+ const paid = await adapter.verify("contract-unknown-payment").then((check2) => check2.paid, () => false);
3650
4011
  if (paid) failures.push("verify() must report an unknown payment as not paid");
3651
4012
  });
3652
4013
  await guarded("refund of an unknown payment", failures, async () => {
@@ -3662,10 +4023,10 @@ async function checkPaymentContract(adapter, options = {}) {
3662
4023
  failures.push("a valid charge must succeed and return a paymentId");
3663
4024
  return;
3664
4025
  }
3665
- const check = await adapter.verify(charge.paymentId);
3666
- if (!check.paid) failures.push("verify() must report a charged payment as paid");
3667
- if (check.amount !== void 0 && check.amount !== request.amount) failures.push("verify() must report the amount that was charged");
3668
- if (check.metadata?.contract !== "metadata-round-trip") failures.push("verify() must return the metadata the charge was made with");
4026
+ const check2 = await adapter.verify(charge.paymentId);
4027
+ if (!check2.paid) failures.push("verify() must report a charged payment as paid");
4028
+ if (check2.amount !== void 0 && check2.amount !== request.amount) failures.push("verify() must report the amount that was charged");
4029
+ if (check2.metadata?.contract !== "metadata-round-trip") failures.push("verify() must return the metadata the charge was made with");
3669
4030
  const first = await adapter.refund(charge.paymentId);
3670
4031
  if (!first.success) failures.push("the first refund of a paid payment must succeed");
3671
4032
  if (first.amount !== void 0 && first.amount !== request.amount) failures.push("a full refund must report the amount it refunded");
@@ -3934,7 +4295,7 @@ function buildRecurringSlots(firstDate, frequency, occurrences, startTimeLocal,
3934
4295
 
3935
4296
  // src/appointments/meeting.ts
3936
4297
  function buildJitsiUrl(appointmentId) {
3937
- return `https://meet.jit.si/s1701-${appointmentId}`;
4298
+ return `https://meet.jit.si/ordinatio-${appointmentId}`;
3938
4299
  }
3939
4300
  function isVirtualMeeting(locationType) {
3940
4301
  return locationType === "VIRTUAL";
@@ -4050,13 +4411,13 @@ function isPrivateV4(ip) {
4050
4411
  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;
4051
4412
  }
4052
4413
  function v6Groups(ip) {
4053
- let text = ip.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0];
4054
- const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(text);
4414
+ let text2 = ip.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0];
4415
+ const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(text2);
4055
4416
  if (tail) {
4056
4417
  const [a, b, c, d] = v4Parts(tail[1]);
4057
- text = text.slice(0, -tail[1].length) + (a << 8 | b).toString(16) + ":" + (c << 8 | d).toString(16);
4418
+ text2 = text2.slice(0, -tail[1].length) + (a << 8 | b).toString(16) + ":" + (c << 8 | d).toString(16);
4058
4419
  }
4059
- const halves = text.split("::");
4420
+ const halves = text2.split("::");
4060
4421
  if (halves.length > 2) return null;
4061
4422
  const head = halves[0] ? halves[0].split(":") : [];
4062
4423
  const rest = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
@@ -4396,11 +4757,1210 @@ async function retryWebhookDelivery(db, organizationId, deliveryId, now = /* @__
4396
4757
  });
4397
4758
  if (updated.count === 0) throw new SchedulingNotFoundError("Delivery not found or not in the dead-letter list", "SCHED_1004", { deliveryId });
4398
4759
  }
4760
+
4761
+ // src/waitlist/join.ts
4762
+ import { randomBytes as randomBytes2 } from "crypto";
4763
+
4764
+ // src/waitlist/day.ts
4765
+ var MAX_DAYS_AHEAD = 90;
4766
+ function isDayString(value) {
4767
+ if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
4768
+ const parsed = /* @__PURE__ */ new Date(`${value}T00:00:00Z`);
4769
+ return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
4770
+ }
4771
+ function localDay(instant, timeZone) {
4772
+ return new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).format(instant);
4773
+ }
4774
+ function daysBetween(from, to) {
4775
+ return Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 864e5);
4776
+ }
4777
+
4778
+ // src/waitlist/view.ts
4779
+ var VIEW_SELECT = {
4780
+ id: true,
4781
+ typeId: true,
4782
+ calendarId: true,
4783
+ day: true,
4784
+ slotStart: true,
4785
+ clientName: true,
4786
+ clientEmail: true,
4787
+ clientPhone: true,
4788
+ status: true,
4789
+ offerSlotStart: true,
4790
+ offerExpiresAt: true,
4791
+ createdAt: true
4792
+ };
4793
+ var LIVE_STATUSES = ["WAITING", "OFFERED", "ACCEPTING"];
4794
+
4795
+ // src/waitlist/join.ts
4796
+ var MAX_WAITING_PER_TYPE_DAY = 50;
4797
+ async function joinWaitlist(db, input, now = /* @__PURE__ */ new Date()) {
4798
+ const orgScope = [{ organizationId: input.organizationId }, { organizationId: null }];
4799
+ const type = await db.appointmentType.findFirst({
4800
+ where: { id: input.typeId, isActive: true, OR: orgScope },
4801
+ select: { id: true, duration: true, requiresPayment: true, intakeForm: true, calendars: { select: { calendarId: true } } }
4802
+ });
4803
+ if (!type) throw new SchedulingNotFoundError("Appointment type not found", "SCHED_1100", { typeId: input.typeId });
4804
+ if (type.requiresPayment) {
4805
+ throw new SchedulingValidationError("A waitlist is not available for a type that needs payment", "SCHED_1105", { typeId: input.typeId });
4806
+ }
4807
+ const intakeForm = Array.isArray(type.intakeForm) ? type.intakeForm : [];
4808
+ if (intakeForm.some((field) => field.required)) {
4809
+ throw new SchedulingValidationError("A waitlist is not available for a type with required questions", "SCHED_1110", { typeId: input.typeId });
4810
+ }
4811
+ const linked = type.calendars.map((c) => c.calendarId);
4812
+ if (input.calendarId && !linked.includes(input.calendarId)) {
4813
+ throw new SchedulingNotFoundError("Calendar not found for this type", "SCHED_1100", { calendarId: input.calendarId });
4814
+ }
4815
+ const calendars = await db.schedulingCalendar.findMany({
4816
+ where: { id: { in: input.calendarId ? [input.calendarId] : linked }, OR: orgScope },
4817
+ select: { id: true, timezone: true }
4818
+ });
4819
+ if (calendars.length === 0) throw new SchedulingNotFoundError("Calendar not found for this type", "SCHED_1100", { typeId: input.typeId });
4820
+ const timezone = calendars[0].timezone;
4821
+ if (!isDayString(input.day)) throw new SchedulingValidationError("The day must be YYYY-MM-DD", "SCHED_1101", { day: input.day });
4822
+ const ahead = daysBetween(localDay(now, timezone), input.day);
4823
+ if (ahead < 0 || ahead > MAX_DAYS_AHEAD) {
4824
+ throw new SchedulingValidationError(`The day must be within the next ${MAX_DAYS_AHEAD} days`, "SCHED_1101", { day: input.day });
4825
+ }
4826
+ if (input.slotStart) {
4827
+ if (Number.isNaN(input.slotStart.getTime()) || input.slotStart <= now || localDay(input.slotStart, timezone) !== input.day) {
4828
+ throw new SchedulingValidationError("The time must be in the future, on the chosen day", "SCHED_1102", { day: input.day });
4829
+ }
4830
+ }
4831
+ const open = [];
4832
+ for (const calendar of calendars) {
4833
+ const result = await getAvailableSlots(db, {
4834
+ calendarId: calendar.id,
4835
+ date: /* @__PURE__ */ new Date(`${input.day}T12:00:00Z`),
4836
+ localDate: input.day,
4837
+ duration: type.duration,
4838
+ timezone: calendar.timezone
4839
+ });
4840
+ for (const slot of result.slots) if (slot.available) open.push(slot.start);
4841
+ }
4842
+ const stillOpen = input.slotStart ? open.some((start) => start.getTime() === input.slotStart.getTime()) : open.length > 0;
4843
+ if (stillOpen) {
4844
+ throw new SchedulingValidationError("That time is open: book it instead of waiting", "SCHED_1103", { day: input.day });
4845
+ }
4846
+ const email2 = input.clientEmail.trim();
4847
+ const duplicate = await db.waitlistEntry.findFirst({
4848
+ where: {
4849
+ organizationId: input.organizationId,
4850
+ typeId: type.id,
4851
+ day: input.day,
4852
+ slotStart: input.slotStart ?? null,
4853
+ clientEmail: { equals: email2, mode: "insensitive" },
4854
+ status: { in: LIVE_STATUSES }
4855
+ },
4856
+ select: { id: true }
4857
+ });
4858
+ if (duplicate) throw new SchedulingValidationError("This email is already waiting for that day", "SCHED_1104", { day: input.day });
4859
+ const waiting = await db.waitlistEntry.count({ where: { organizationId: input.organizationId, typeId: type.id, day: input.day, status: "WAITING" } });
4860
+ if (waiting >= MAX_WAITING_PER_TYPE_DAY) {
4861
+ throw new SchedulingValidationError("The waitlist for that day is full", "SCHED_1108", { day: input.day });
4862
+ }
4863
+ const token = randomBytes2(24).toString("base64url");
4864
+ const entry4 = await db.waitlistEntry.create({
4865
+ data: {
4866
+ organizationId: input.organizationId,
4867
+ typeId: type.id,
4868
+ calendarId: input.calendarId ?? null,
4869
+ day: input.day,
4870
+ slotStart: input.slotStart ?? null,
4871
+ timezone,
4872
+ clientName: input.clientName.trim(),
4873
+ clientEmail: email2,
4874
+ clientPhone: input.clientPhone?.trim() || null,
4875
+ token
4876
+ },
4877
+ select: VIEW_SELECT
4878
+ });
4879
+ return { entry: entry4, token };
4880
+ }
4881
+
4882
+ // src/waitlist/accept.ts
4883
+ var ENTRY_SELECT = {
4884
+ id: true,
4885
+ organizationId: true,
4886
+ typeId: true,
4887
+ status: true,
4888
+ offerCalendarId: true,
4889
+ offerSlotStart: true,
4890
+ offerExpiresAt: true,
4891
+ clientName: true,
4892
+ clientEmail: true,
4893
+ clientPhone: true,
4894
+ timezone: true,
4895
+ type: { select: { name: true } }
4896
+ };
4897
+ async function loadOffer(db, token) {
4898
+ const entry4 = await db.waitlistEntry.findUnique({ where: { token }, select: ENTRY_SELECT });
4899
+ if (!entry4 || !entry4.offerCalendarId || !entry4.offerSlotStart || !entry4.offerExpiresAt) {
4900
+ throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
4901
+ }
4902
+ const calendar = await db.schedulingCalendar.findUnique({ where: { id: entry4.offerCalendarId }, select: { name: true } });
4903
+ return {
4904
+ status: entry4.status,
4905
+ details: {
4906
+ entryId: entry4.id,
4907
+ organizationId: entry4.organizationId,
4908
+ typeId: entry4.typeId,
4909
+ typeName: entry4.type.name,
4910
+ calendarId: entry4.offerCalendarId,
4911
+ calendarName: calendar?.name ?? "",
4912
+ startTime: entry4.offerSlotStart,
4913
+ timezone: entry4.timezone,
4914
+ expiresAt: entry4.offerExpiresAt,
4915
+ clientName: entry4.clientName,
4916
+ clientEmail: entry4.clientEmail,
4917
+ clientPhone: entry4.clientPhone
4918
+ }
4919
+ };
4920
+ }
4921
+ async function getWaitlistOffer(db, token, now = /* @__PURE__ */ new Date()) {
4922
+ const { details, status } = await loadOffer(db, token);
4923
+ if (status !== "OFFERED") throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
4924
+ if (details.expiresAt <= now) throw new SchedulingValidationError("The offer has expired", "SCHED_1107");
4925
+ return details;
4926
+ }
4927
+ async function beginWaitlistAccept(db, token, now = /* @__PURE__ */ new Date()) {
4928
+ const claimed = await db.waitlistEntry.updateMany({
4929
+ where: { token, status: "OFFERED", offerExpiresAt: { gt: now } },
4930
+ data: { status: "ACCEPTING", acceptingAt: now }
4931
+ });
4932
+ if (claimed.count === 0) {
4933
+ await getWaitlistOffer(db, token, now);
4934
+ throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
4935
+ }
4936
+ return (await loadOffer(db, token)).details;
4937
+ }
4938
+ async function completeWaitlistAccept(db, entryId, appointmentId) {
4939
+ await db.waitlistEntry.updateMany({
4940
+ where: { id: entryId, status: "ACCEPTING" },
4941
+ data: { status: "BOOKED", bookedAppointmentId: appointmentId }
4942
+ });
4943
+ }
4944
+ async function releaseWaitlistAccept(db, entryId, outcome = "BACK_IN_LINE") {
4945
+ const where = { id: entryId, status: "ACCEPTING" };
4946
+ if (outcome === "KEEP_OFFER") {
4947
+ await db.waitlistEntry.updateMany({ where, data: { status: "OFFERED", acceptingAt: null } });
4948
+ return null;
4949
+ }
4950
+ if (outcome === "BACK_IN_LINE") {
4951
+ await db.waitlistEntry.updateMany({
4952
+ where,
4953
+ data: { status: "WAITING", offerCalendarId: null, offerSlotStart: null, offerExpiresAt: null, offeredAt: null, acceptingAt: null }
4954
+ });
4955
+ return null;
4956
+ }
4957
+ const row = await db.waitlistEntry.findFirst({ where, select: { organizationId: true, offerCalendarId: true, offerSlotStart: true } });
4958
+ const ended = await db.waitlistEntry.updateMany({ where, data: { status: "EXPIRED", acceptingAt: null } });
4959
+ return row && ended.count > 0 && row.offerCalendarId && row.offerSlotStart ? { organizationId: row.organizationId, calendarId: row.offerCalendarId, startTime: row.offerSlotStart } : null;
4960
+ }
4961
+ async function findBookingForOffer(db, entry4) {
4962
+ if (!entry4.offerCalendarId || !entry4.offerSlotStart) return null;
4963
+ return db.appointment.findFirst({
4964
+ where: {
4965
+ calendarId: entry4.offerCalendarId,
4966
+ startTime: entry4.offerSlotStart,
4967
+ clientEmail: { equals: entry4.clientEmail, mode: "insensitive" },
4968
+ status: { in: ["PENDING", "CONFIRMED"] }
4969
+ },
4970
+ select: { id: true }
4971
+ });
4972
+ }
4973
+ async function settleBookedAccept(db, entryId) {
4974
+ const entry4 = await db.waitlistEntry.findFirst({
4975
+ where: { id: entryId, status: "ACCEPTING" },
4976
+ select: { offerCalendarId: true, offerSlotStart: true, clientEmail: true }
4977
+ });
4978
+ const found = entry4 ? await findBookingForOffer(db, entry4) : null;
4979
+ if (!found) return null;
4980
+ await db.waitlistEntry.updateMany({
4981
+ where: { id: entryId, status: "ACCEPTING" },
4982
+ data: { status: "BOOKED", bookedAppointmentId: found.id, acceptingAt: null }
4983
+ });
4984
+ return db.appointment.findUnique({
4985
+ where: { id: found.id },
4986
+ select: { id: true, status: true, startTime: true, endTime: true, manageToken: true, clientName: true, clientEmail: true }
4987
+ });
4988
+ }
4989
+
4990
+ // src/waitlist/offer.ts
4991
+ var DEFAULT_OFFER_MINUTES = 30;
4992
+ var CANDIDATES_PER_SLOT = 25;
4993
+ function isUniqueViolation(error) {
4994
+ return typeof error === "object" && error !== null && error.code === "P2002";
4995
+ }
4996
+ async function offerFreedSlot(db, input) {
4997
+ const now = input.now ?? /* @__PURE__ */ new Date();
4998
+ if (input.startTime <= now) return null;
4999
+ const calendar = await db.schedulingCalendar.findUnique({
5000
+ where: { id: input.calendarId },
5001
+ select: { name: true, timezone: true, organizationId: true }
5002
+ });
5003
+ if (!calendar || calendar.organizationId !== null && calendar.organizationId !== input.organizationId) return null;
5004
+ await db.waitlistEntry.updateMany({
5005
+ where: {
5006
+ organizationId: input.organizationId,
5007
+ status: "OFFERED",
5008
+ offerCalendarId: input.calendarId,
5009
+ offerSlotStart: input.startTime,
5010
+ offerExpiresAt: { lte: now }
5011
+ },
5012
+ data: { status: "EXPIRED" }
5013
+ });
5014
+ const candidates = await db.waitlistEntry.findMany({
5015
+ where: {
5016
+ organizationId: input.organizationId,
5017
+ status: "WAITING",
5018
+ day: localDay(input.startTime, calendar.timezone),
5019
+ // Only people whose type runs on this calendar, so earlier people it cannot fit never crowd out later ones that it can.
5020
+ type: { isActive: true, calendars: { some: { calendarId: input.calendarId } } },
5021
+ AND: [
5022
+ { OR: [{ calendarId: null }, { calendarId: input.calendarId }] },
5023
+ { OR: [{ slotStart: null }, { slotStart: input.startTime }] }
5024
+ ]
5025
+ },
5026
+ orderBy: { createdAt: "asc" },
5027
+ take: CANDIDATES_PER_SLOT,
5028
+ select: { ...VIEW_SELECT, token: true, timezone: true }
5029
+ });
5030
+ const expiresAt = new Date(Math.min(now.getTime() + (input.offerMinutes ?? DEFAULT_OFFER_MINUTES) * 6e4, input.startTime.getTime()));
5031
+ for (const candidate of candidates) {
5032
+ const type = await db.appointmentType.findFirst({
5033
+ where: { id: candidate.typeId, isActive: true, calendars: { some: { calendarId: input.calendarId } } },
5034
+ select: { name: true, duration: true }
5035
+ });
5036
+ if (!type || !await isSlotAvailable(db, input.calendarId, input.startTime, type.duration)) continue;
5037
+ let claimed;
5038
+ try {
5039
+ claimed = await db.waitlistEntry.updateMany({
5040
+ where: { id: candidate.id, status: "WAITING" },
5041
+ data: { status: "OFFERED", offerCalendarId: input.calendarId, offerSlotStart: input.startTime, offerExpiresAt: expiresAt, offeredAt: now }
5042
+ });
5043
+ } catch (error) {
5044
+ if (isUniqueViolation(error)) return null;
5045
+ throw error;
5046
+ }
5047
+ if (claimed.count === 0) continue;
5048
+ const { token, timezone, ...view2 } = candidate;
5049
+ return {
5050
+ entry: { ...view2, status: "OFFERED", offerSlotStart: input.startTime, offerExpiresAt: expiresAt },
5051
+ token,
5052
+ calendarId: input.calendarId,
5053
+ calendarName: calendar.name,
5054
+ typeName: type.name,
5055
+ startTime: input.startTime,
5056
+ timezone,
5057
+ expiresAt
5058
+ };
5059
+ }
5060
+ return null;
5061
+ }
5062
+ async function tryOfferFreedSlot(db, input) {
5063
+ try {
5064
+ return await offerFreedSlot(db, input);
5065
+ } catch (error) {
5066
+ const diagnostic = schedError("SCHED_1109", { organizationId: input.organizationId, calendarId: input.calendarId, error });
5067
+ console.error(`[waitlist] ${diagnostic.ref} could not offer a freed slot:`, error);
5068
+ return null;
5069
+ }
5070
+ }
5071
+ async function expireWaitlistOffers(db, options = {}) {
5072
+ const now = options.now ?? /* @__PURE__ */ new Date();
5073
+ const stuckBefore = new Date(now.getTime() - (options.acceptTimeoutMs ?? 5 * 6e4));
5074
+ const rows = await db.$queryRaw`
5075
+ UPDATE "WaitlistEntry" SET status = 'EXPIRED'
5076
+ WHERE status = 'OFFERED' AND "offerExpiresAt" <= ${now}
5077
+ RETURNING "organizationId", "offerCalendarId", "offerSlotStart"
5078
+ `;
5079
+ const lapsed = rows.map((r) => ({ organizationId: r.organizationId, calendarId: r.offerCalendarId, startTime: r.offerSlotStart }));
5080
+ const stuck = await db.waitlistEntry.findMany({
5081
+ where: { status: "ACCEPTING", acceptingAt: { lte: stuckBefore } },
5082
+ take: 100,
5083
+ select: { id: true, organizationId: true, offerCalendarId: true, offerSlotStart: true, clientEmail: true }
5084
+ });
5085
+ let released = 0;
5086
+ let booked = 0;
5087
+ for (const entry4 of stuck) {
5088
+ const appointment = await findBookingForOffer(db, entry4);
5089
+ if (appointment) {
5090
+ const done = await db.waitlistEntry.updateMany({
5091
+ where: { id: entry4.id, status: "ACCEPTING" },
5092
+ data: { status: "BOOKED", bookedAppointmentId: appointment.id, acceptingAt: null }
5093
+ });
5094
+ booked += done.count;
5095
+ continue;
5096
+ }
5097
+ const back = await db.waitlistEntry.updateMany({
5098
+ where: { id: entry4.id, status: "ACCEPTING" },
5099
+ data: { status: "WAITING", offerCalendarId: null, offerSlotStart: null, offerExpiresAt: null, offeredAt: null, acceptingAt: null }
5100
+ });
5101
+ if (back.count > 0) {
5102
+ released++;
5103
+ if (entry4.offerCalendarId && entry4.offerSlotStart) {
5104
+ lapsed.push({ organizationId: entry4.organizationId, calendarId: entry4.offerCalendarId, startTime: entry4.offerSlotStart });
5105
+ }
5106
+ }
5107
+ }
5108
+ return { lapsed, released, booked };
5109
+ }
5110
+
5111
+ // src/waitlist/manage.ts
5112
+ var OFFER_FIELDS = { organizationId: true, status: true, offerCalendarId: true, offerSlotStart: true };
5113
+ function freedSlot(row) {
5114
+ return row.status === "OFFERED" && row.offerCalendarId && row.offerSlotStart ? { organizationId: row.organizationId, calendarId: row.offerCalendarId, startTime: row.offerSlotStart } : null;
5115
+ }
5116
+ async function listWaitlist(db, input) {
5117
+ const where = { organizationId: input.organizationId, ...input.status ? { status: input.status } : {} };
5118
+ const [entries, total] = await Promise.all([
5119
+ db.waitlistEntry.findMany({
5120
+ where,
5121
+ orderBy: { createdAt: "asc" },
5122
+ take: Math.min(input.limit ?? 50, 200),
5123
+ skip: input.offset ?? 0,
5124
+ select: VIEW_SELECT
5125
+ }),
5126
+ db.waitlistEntry.count({ where })
5127
+ ]);
5128
+ return { entries, total };
5129
+ }
5130
+ async function removeWaitlistEntry(db, organizationId, entryId) {
5131
+ const where = { id: entryId, organizationId, status: { in: ["WAITING", "OFFERED", "EXPIRED", "BOOKED"] } };
5132
+ const row = await db.waitlistEntry.findFirst({ where, select: OFFER_FIELDS });
5133
+ const removed = row ? await db.waitlistEntry.deleteMany({ where: { ...where, status: row.status } }) : { count: 0 };
5134
+ if (!row || removed.count === 0) throw new SchedulingNotFoundError("Waitlist entry not found", "SCHED_1106", { entryId });
5135
+ return freedSlot(row);
5136
+ }
5137
+ async function leaveWaitlist(db, token) {
5138
+ const where = { token, status: { in: ["WAITING", "OFFERED"] } };
5139
+ const row = await db.waitlistEntry.findFirst({ where, select: OFFER_FIELDS });
5140
+ const removed = row ? await db.waitlistEntry.deleteMany({ where: { ...where, status: row.status } }) : { count: 0 };
5141
+ if (!row || removed.count === 0) throw new SchedulingNotFoundError("No waitlist entry for this link", "SCHED_1106");
5142
+ return freedSlot(row);
5143
+ }
5144
+
5145
+ // src/routing/types.ts
5146
+ var LIMITS = {
5147
+ questions: 20,
5148
+ rules: 50,
5149
+ conditionsPerRule: 10,
5150
+ options: 50,
5151
+ label: 200,
5152
+ option: 100,
5153
+ message: 500,
5154
+ textAnswer: 1e3,
5155
+ problems: 50,
5156
+ formsPerOrganization: 50
5157
+ };
5158
+
5159
+ // src/routing/validate-structure.ts
5160
+ var ID = /^[A-Za-z][A-Za-z0-9_-]{0,39}$/;
5161
+ var QUESTION_TYPES = ["select", "radio", "checkbox", "text", "number"];
5162
+ var NO_VALUE = ["is_answered", "is_empty"];
5163
+ var OPERATORS_BY_TYPE = {
5164
+ select: ["equals", "not_equals", "in", "is_answered", "is_empty"],
5165
+ radio: ["equals", "not_equals", "in", "is_answered", "is_empty"],
5166
+ checkbox: ["contains", "not_contains", "is_answered", "is_empty"],
5167
+ text: ["equals", "not_equals", "contains", "not_contains", "is_answered", "is_empty"],
5168
+ number: ["equals", "not_equals", "gt", "gte", "lt", "lte", "is_answered", "is_empty"]
5169
+ };
5170
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5171
+ var isText = (value, max) => typeof value === "string" && value.trim().length > 0 && value.length <= max && !value.includes("\0");
5172
+ function checkQuestions(input, problems) {
5173
+ if (!Array.isArray(input) || input.length === 0) {
5174
+ problems.push({ path: "questions", message: "Add at least one question" });
5175
+ return [];
5176
+ }
5177
+ if (input.length > LIMITS.questions) problems.push({ path: "questions", message: `At most ${LIMITS.questions} questions` });
5178
+ const seen = /* @__PURE__ */ new Set();
5179
+ const questions = [];
5180
+ input.slice(0, LIMITS.questions).forEach((raw, i) => {
5181
+ const at = `questions[${i}]`;
5182
+ if (!isObject(raw)) return void problems.push({ path: at, message: "A question must be an object" });
5183
+ const { id, label, type, required, options } = raw;
5184
+ 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)" });
5185
+ else if (seen.has(id)) problems.push({ path: `${at}.id`, message: `Another question already uses the id "${id}"` });
5186
+ else seen.add(id);
5187
+ if (!isText(label, LIMITS.label)) problems.push({ path: `${at}.label`, message: `A label of 1 to ${LIMITS.label} characters is required` });
5188
+ if (!QUESTION_TYPES.includes(type)) problems.push({ path: `${at}.type`, message: `The type must be one of ${QUESTION_TYPES.join(", ")}` });
5189
+ if (required !== void 0 && typeof required !== "boolean") problems.push({ path: `${at}.required`, message: "required must be true or false" });
5190
+ const choice = type === "select" || type === "radio" || type === "checkbox";
5191
+ let cleanOptions;
5192
+ if (choice) {
5193
+ if (!Array.isArray(options) || options.length < 2 || options.length > LIMITS.options) {
5194
+ problems.push({ path: `${at}.options`, message: `A choice question needs 2 to ${LIMITS.options} options` });
5195
+ } else if (!options.every((o) => isText(o, LIMITS.option))) {
5196
+ problems.push({ path: `${at}.options`, message: `Each option must be 1 to ${LIMITS.option} characters` });
5197
+ } else if (new Set(options).size !== options.length) {
5198
+ problems.push({ path: `${at}.options`, message: "Options must all be different" });
5199
+ } else cleanOptions = options;
5200
+ } else if (options !== void 0) {
5201
+ problems.push({ path: `${at}.options`, message: "Only choice questions have options" });
5202
+ }
5203
+ if (typeof id === "string" && typeof label === "string" && QUESTION_TYPES.includes(type)) {
5204
+ questions.push({ id, label: label.trim(), type, required: required === true, ...cleanOptions ? { options: cleanOptions } : {} });
5205
+ }
5206
+ });
5207
+ return questions;
5208
+ }
5209
+ function checkValue(question, condition, at, problems) {
5210
+ const { operator, value } = condition;
5211
+ if (NO_VALUE.includes(operator)) {
5212
+ if (value !== void 0) problems.push({ path: `${at}.value`, message: `${String(operator)} takes no value` });
5213
+ return void 0;
5214
+ }
5215
+ if (value === void 0) {
5216
+ problems.push({ path: `${at}.value`, message: "A value is required" });
5217
+ return void 0;
5218
+ }
5219
+ if (question.type === "number") {
5220
+ if (typeof value !== "number" || !Number.isFinite(value)) problems.push({ path: `${at}.value`, message: "The value must be a number" });
5221
+ else return value;
5222
+ return void 0;
5223
+ }
5224
+ if (question.type === "text") {
5225
+ if (!isText(value, LIMITS.option * 2)) problems.push({ path: `${at}.value`, message: "The value must be a text of 1 to 200 characters" });
5226
+ else return value;
5227
+ return void 0;
5228
+ }
5229
+ const options = question.options ?? [];
5230
+ if (operator === "in") {
5231
+ if (!Array.isArray(value) || value.length === 0 || !value.every((v) => typeof v === "string" && options.includes(v))) {
5232
+ problems.push({ path: `${at}.value`, message: "The value must be a list of this question's options" });
5233
+ return void 0;
5234
+ }
5235
+ return value;
5236
+ }
5237
+ if (typeof value !== "string" || !options.includes(value)) {
5238
+ problems.push({ path: `${at}.value`, message: "The value must be one of this question's options" });
5239
+ return void 0;
5240
+ }
5241
+ return value;
5242
+ }
5243
+ function checkDestination(raw, at, problems) {
5244
+ if (!isObject(raw)) {
5245
+ problems.push({ path: at, message: "Say where to send the client" });
5246
+ return null;
5247
+ }
5248
+ const { typeId, calendarId } = raw;
5249
+ const okType = typeId === void 0 || typeof typeId === "string" && typeId.length > 0 && typeId.length <= 100;
5250
+ const okCalendar = calendarId === void 0 || typeof calendarId === "string" && calendarId.length > 0 && calendarId.length <= 100;
5251
+ if (!okType || !okCalendar) {
5252
+ problems.push({ path: at, message: "typeId and calendarId must be ids" });
5253
+ return null;
5254
+ }
5255
+ if (typeId === void 0 && calendarId === void 0) {
5256
+ problems.push({ path: at, message: "Name an appointment type, a calendar, or both" });
5257
+ return null;
5258
+ }
5259
+ return { ...typeId !== void 0 ? { typeId } : {}, ...calendarId !== void 0 ? { calendarId } : {} };
5260
+ }
5261
+ function checkRules(input, questions, problems) {
5262
+ if (!Array.isArray(input) || input.length === 0) {
5263
+ problems.push({ path: "rules", message: "Add at least one rule" });
5264
+ return [];
5265
+ }
5266
+ if (input.length > LIMITS.rules) problems.push({ path: "rules", message: `At most ${LIMITS.rules} rules` });
5267
+ const byId = new Map(questions.map((q) => [q.id, q]));
5268
+ const written = new Set(input.flatMap((r) => isObject(r) && typeof r.id === "string" ? [r.id] : []));
5269
+ const seen = /* @__PURE__ */ new Set();
5270
+ const rules = [];
5271
+ input.slice(0, LIMITS.rules).forEach((raw, i) => {
5272
+ const at = `rules[${i}]`;
5273
+ if (!isObject(raw)) return void problems.push({ path: at, message: "A rule must be an object" });
5274
+ let id = typeof raw.id === "string" && ID.test(raw.id) ? raw.id : null;
5275
+ 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 _" });
5276
+ if (id === null) {
5277
+ id = `rule_${i + 1}`;
5278
+ while (written.has(id)) id = `${id}_auto`;
5279
+ }
5280
+ if (seen.has(id)) problems.push({ path: `${at}.id`, message: `Another rule already uses the id "${id}"` });
5281
+ seen.add(id);
5282
+ 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` });
5283
+ const match = raw.match === void 0 ? "all" : raw.match;
5284
+ if (match !== "all" && match !== "any") problems.push({ path: `${at}.match`, message: 'match must be "all" or "any"' });
5285
+ const conditions = [];
5286
+ if (!Array.isArray(raw.conditions) || raw.conditions.length === 0 || raw.conditions.length > LIMITS.conditionsPerRule) {
5287
+ problems.push({ path: `${at}.conditions`, message: `A rule needs 1 to ${LIMITS.conditionsPerRule} conditions` });
5288
+ } else {
5289
+ raw.conditions.forEach((c, j) => {
5290
+ const cat = `${at}.conditions[${j}]`;
5291
+ if (!isObject(c)) return void problems.push({ path: cat, message: "A condition must be an object" });
5292
+ const question = typeof c.questionId === "string" ? byId.get(c.questionId) : void 0;
5293
+ if (!question) return void problems.push({ path: `${cat}.questionId`, message: "This names a question the form does not have" });
5294
+ if (!OPERATORS_BY_TYPE[question.type].includes(c.operator)) {
5295
+ return void problems.push({ path: `${cat}.operator`, message: `A ${question.type} question allows: ${OPERATORS_BY_TYPE[question.type].join(", ")}` });
5296
+ }
5297
+ const value = checkValue(question, c, cat, problems);
5298
+ conditions.push({ questionId: question.id, operator: c.operator, ...value !== void 0 ? { value } : {} });
5299
+ });
5300
+ }
5301
+ const destination = checkDestination(raw.destination, `${at}.destination`, problems);
5302
+ if (destination && (match === "all" || match === "any")) {
5303
+ rules.push({ id, ...typeof raw.label === "string" ? { label: raw.label.trim() } : {}, match, conditions, destination });
5304
+ }
5305
+ });
5306
+ return rules;
5307
+ }
5308
+ function checkFallback(raw, problems) {
5309
+ if (!isObject(raw)) {
5310
+ problems.push({ path: "fallback", message: "Say what happens when no rule matches" });
5311
+ return null;
5312
+ }
5313
+ if (raw.kind === "MESSAGE") {
5314
+ if (!isText(raw.message, LIMITS.message)) {
5315
+ problems.push({ path: "fallback.message", message: `A message of 1 to ${LIMITS.message} characters is required` });
5316
+ return null;
5317
+ }
5318
+ return { kind: "MESSAGE", message: raw.message.trim() };
5319
+ }
5320
+ if (raw.kind === "DESTINATION") {
5321
+ const destination = checkDestination(raw.destination, "fallback.destination", problems);
5322
+ return destination ? { kind: "DESTINATION", destination } : null;
5323
+ }
5324
+ problems.push({ path: "fallback.kind", message: 'kind must be "DESTINATION" or "MESSAGE"' });
5325
+ return null;
5326
+ }
5327
+ function validateRoutingStructure(input) {
5328
+ const problems = [];
5329
+ if (!isObject(input)) return { ok: false, problems: [{ path: "", message: "A routing form must be an object" }] };
5330
+ const questions = checkQuestions(input.questions, problems);
5331
+ const rules = checkRules(input.rules, questions, problems);
5332
+ const fallback = checkFallback(input.fallback, problems);
5333
+ if (problems.length > 0 || !fallback) return { ok: false, problems: problems.slice(0, LIMITS.problems) };
5334
+ return { ok: true, value: { questions, rules, fallback } };
5335
+ }
5336
+
5337
+ // src/routing/validate-destinations.ts
5338
+ function placesOf(definition) {
5339
+ const places = definition.rules.map((rule, i) => ({ path: `rules[${i}].destination`, destination: rule.destination }));
5340
+ if (definition.fallback.kind === "DESTINATION") places.push({ path: "fallback.destination", destination: definition.fallback.destination });
5341
+ return places;
5342
+ }
5343
+ async function validateRoutingDestinations(db, organizationId, definition) {
5344
+ const places = placesOf(definition);
5345
+ const typeIds = [...new Set(places.flatMap((p) => p.destination.typeId ? [p.destination.typeId] : []))];
5346
+ const calendarIds = [...new Set(places.flatMap((p) => p.destination.calendarId ? [p.destination.calendarId] : []))];
5347
+ const scope = [{ organizationId }, { organizationId: null }];
5348
+ const [types, calendars] = await Promise.all([
5349
+ typeIds.length ? db.appointmentType.findMany({ where: { id: { in: typeIds }, isActive: true, OR: scope }, select: { id: true } }) : [],
5350
+ calendarIds.length ? db.schedulingCalendar.findMany({ where: { id: { in: calendarIds }, isActive: true, OR: scope }, select: { id: true } }) : []
5351
+ ]);
5352
+ const liveTypes = new Set(types.map((t) => t.id));
5353
+ const liveCalendars = new Set(calendars.map((c) => c.id));
5354
+ const problems = [];
5355
+ const pairs = [];
5356
+ for (const { path, destination } of places) {
5357
+ const typeOk = !destination.typeId || liveTypes.has(destination.typeId);
5358
+ const calendarOk = !destination.calendarId || liveCalendars.has(destination.calendarId);
5359
+ if (!typeOk) problems.push({ path: `${path}.typeId`, message: "This appointment type does not exist here or is switched off" });
5360
+ if (!calendarOk) problems.push({ path: `${path}.calendarId`, message: "This calendar does not exist here or is switched off" });
5361
+ if (typeOk && calendarOk && destination.typeId && destination.calendarId) pairs.push({ path, destination });
5362
+ }
5363
+ if (pairs.length > 0) {
5364
+ const links = await db.appointmentTypeCalendar.findMany({
5365
+ where: { OR: pairs.map((p) => ({ appointmentTypeId: p.destination.typeId, calendarId: p.destination.calendarId })) },
5366
+ select: { appointmentTypeId: true, calendarId: true }
5367
+ });
5368
+ const linked = new Set(links.map((l) => `${l.appointmentTypeId}:${l.calendarId}`));
5369
+ for (const { path, destination } of pairs) {
5370
+ if (!linked.has(`${destination.typeId}:${destination.calendarId}`)) {
5371
+ problems.push({ path, message: "This appointment type is not offered on this calendar" });
5372
+ }
5373
+ }
5374
+ }
5375
+ return problems;
5376
+ }
5377
+
5378
+ // src/routing/evaluate.ts
5379
+ var blank = (value) => value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0;
5380
+ function checkAnswers(questions, input) {
5381
+ const problems = [];
5382
+ const raw = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {};
5383
+ if (input !== void 0 && raw !== input) problems.push({ path: "answers", message: "Answers must be an object keyed by question id" });
5384
+ const known = new Set(questions.map((q) => q.id));
5385
+ for (const key of Object.keys(raw)) if (!known.has(key)) problems.push({ path: `answers.${key}`, message: "The form does not ask this question" });
5386
+ const answers = /* @__PURE__ */ Object.create(null);
5387
+ for (const q of questions) {
5388
+ const at = `answers.${q.id}`;
5389
+ const value = Object.prototype.hasOwnProperty.call(raw, q.id) ? raw[q.id] : void 0;
5390
+ if (blank(value)) {
5391
+ if (q.required) problems.push({ path: at, message: "This question needs an answer" });
5392
+ continue;
5393
+ }
5394
+ if (q.type === "select" || q.type === "radio") {
5395
+ if (typeof value !== "string" || !q.options?.includes(value)) problems.push({ path: at, message: "Pick one of the offered options" });
5396
+ else answers[q.id] = value;
5397
+ } else if (q.type === "checkbox") {
5398
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string" && q.options?.includes(v)) || new Set(value).size !== value.length) {
5399
+ problems.push({ path: at, message: "Send a list of offered options, each once" });
5400
+ } else answers[q.id] = value;
5401
+ } else if (q.type === "number") {
5402
+ if (typeof value !== "number" || !Number.isFinite(value)) problems.push({ path: at, message: "The answer must be a number" });
5403
+ else answers[q.id] = value;
5404
+ } else if (typeof value !== "string" || value.length > LIMITS.textAnswer) {
5405
+ problems.push({ path: at, message: `The answer must be a text of at most ${LIMITS.textAnswer} characters` });
5406
+ } else answers[q.id] = value;
5407
+ }
5408
+ return problems.length > 0 ? { ok: false, problems: problems.slice(0, LIMITS.problems) } : { ok: true, answers };
5409
+ }
5410
+ function holds(condition, answers) {
5411
+ const answer = answers[condition.questionId];
5412
+ const { operator, value } = condition;
5413
+ if (operator === "is_empty") return blank(answer);
5414
+ if (operator === "is_answered") return !blank(answer);
5415
+ if (blank(answer)) return false;
5416
+ if (typeof answer === "number") {
5417
+ if (typeof value !== "number") return false;
5418
+ return { equals: answer === value, not_equals: answer !== value, gt: answer > value, gte: answer >= value, lt: answer < value, lte: answer <= value }[operator] ?? false;
5419
+ }
5420
+ if (Array.isArray(answer)) {
5421
+ if (typeof value !== "string") return false;
5422
+ return operator === "contains" ? answer.includes(value) : operator === "not_contains" ? !answer.includes(value) : false;
5423
+ }
5424
+ if (operator === "in") return Array.isArray(value) && value.includes(answer);
5425
+ if (typeof value !== "string") return false;
5426
+ const a = answer;
5427
+ switch (operator) {
5428
+ case "equals":
5429
+ return a === value;
5430
+ case "not_equals":
5431
+ return a !== value;
5432
+ case "contains":
5433
+ return a.toLowerCase().includes(value.toLowerCase());
5434
+ case "not_contains":
5435
+ return !a.toLowerCase().includes(value.toLowerCase());
5436
+ default:
5437
+ return false;
5438
+ }
5439
+ }
5440
+ function matchingRules(definition, answers) {
5441
+ return definition.rules.filter(
5442
+ (rule) => rule.match === "any" ? rule.conditions.some((c) => holds(c, answers)) : rule.conditions.every((c) => holds(c, answers))
5443
+ );
5444
+ }
5445
+
5446
+ // src/routing/crud.ts
5447
+ var SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
5448
+ var FULL = { id: true, name: true, slug: true, description: true, isActive: true, questions: true, rules: true, fallback: true, createdAt: true, updatedAt: true };
5449
+ function invalid(problems) {
5450
+ return new SchedulingValidationError("The routing form has problems", "SCHED_1200", { errors: problems });
5451
+ }
5452
+ function view(row) {
5453
+ return { ...row, questions: row.questions, rules: row.rules, fallback: row.fallback };
5454
+ }
5455
+ async function check(db, organizationId, input, options) {
5456
+ const problems = [];
5457
+ const name = typeof input.name === "string" ? input.name.trim() : "";
5458
+ if (name.length < 1 || name.length > 100 || name.includes("\0")) problems.push({ path: "name", message: "A name of 1 to 100 characters is required" });
5459
+ if (typeof input.slug !== "string" || !SLUG.test(input.slug) || input.slug.length > 60) {
5460
+ problems.push({ path: "slug", message: "The slug must be lower-case words joined by dashes, 60 characters at most" });
5461
+ } else {
5462
+ const taken = await db.routingForm.count({ where: { slug: input.slug, organizationId: { not: organizationId } } });
5463
+ if (taken > 0) problems.push({ path: "slug", message: "That slug is already in use; choose another" });
5464
+ }
5465
+ const description = typeof input.description === "string" ? input.description.trim() || null : null;
5466
+ if (description && (description.length > 500 || description.includes("\0"))) problems.push({ path: "description", message: "The description is at most 500 characters" });
5467
+ const structure = validateRoutingStructure({ questions: input.questions, rules: input.rules, fallback: input.fallback });
5468
+ if (!structure.ok) problems.push(...structure.problems);
5469
+ else if (options.checkDestinations) problems.push(...await validateRoutingDestinations(db, organizationId, structure.value));
5470
+ if (problems.length > 0 || !structure.ok) throw invalid(problems.slice(0, LIMITS.problems));
5471
+ return { definition: structure.value, name, slug: input.slug, description };
5472
+ }
5473
+ async function createRoutingForm(db, organizationId, input) {
5474
+ const { definition, name, slug, description } = await check(db, organizationId, input, { checkDestinations: true });
5475
+ const existing = await db.routingForm.count({ where: { organizationId } });
5476
+ if (existing >= LIMITS.formsPerOrganization) {
5477
+ throw new SchedulingValidationError(`An organization can have at most ${LIMITS.formsPerOrganization} routing forms`, "SCHED_1204", { organizationId });
5478
+ }
5479
+ try {
5480
+ const row = await db.routingForm.create({
5481
+ data: {
5482
+ organizationId,
5483
+ name,
5484
+ slug,
5485
+ description,
5486
+ isActive: input.isActive ?? true,
5487
+ questions: definition.questions,
5488
+ rules: definition.rules,
5489
+ fallback: definition.fallback
5490
+ },
5491
+ select: FULL
5492
+ });
5493
+ return view(row);
5494
+ } catch (error) {
5495
+ if (error.code === "P2002") throw new SchedulingValidationError("That slug is already used by another form", "SCHED_1202", { slug });
5496
+ throw error;
5497
+ }
5498
+ }
5499
+ async function getRoutingForm(db, organizationId, id) {
5500
+ const row = await db.routingForm.findFirst({ where: { id, organizationId }, select: FULL });
5501
+ if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
5502
+ return view(row);
5503
+ }
5504
+ async function listRoutingForms(db, organizationId) {
5505
+ return db.routingForm.findMany({
5506
+ where: { organizationId },
5507
+ orderBy: { name: "asc" },
5508
+ select: { id: true, name: true, slug: true, description: true, isActive: true, updatedAt: true }
5509
+ });
5510
+ }
5511
+ async function updateRoutingForm(db, organizationId, id, patch) {
5512
+ const current = await getRoutingForm(db, organizationId, id);
5513
+ const merged = {
5514
+ name: patch.name ?? current.name,
5515
+ slug: patch.slug ?? current.slug,
5516
+ description: patch.description === void 0 ? current.description : patch.description,
5517
+ isActive: patch.isActive ?? current.isActive,
5518
+ questions: patch.questions ?? current.questions,
5519
+ rules: patch.rules ?? current.rules,
5520
+ fallback: patch.fallback ?? current.fallback
5521
+ };
5522
+ const changesRouting = patch.questions !== void 0 || patch.rules !== void 0 || patch.fallback !== void 0;
5523
+ const { definition, name, slug, description } = await check(db, organizationId, merged, { checkDestinations: changesRouting });
5524
+ try {
5525
+ const updated = await db.routingForm.updateMany({
5526
+ where: { id, organizationId },
5527
+ data: {
5528
+ name,
5529
+ slug,
5530
+ description,
5531
+ isActive: merged.isActive,
5532
+ questions: definition.questions,
5533
+ rules: definition.rules,
5534
+ fallback: definition.fallback
5535
+ }
5536
+ });
5537
+ if (updated.count === 0) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
5538
+ } catch (error) {
5539
+ if (error.code === "P2002") throw new SchedulingValidationError("That slug is already used by another form", "SCHED_1202", { slug });
5540
+ throw error;
5541
+ }
5542
+ return getRoutingForm(db, organizationId, id);
5543
+ }
5544
+ async function deleteRoutingForm(db, organizationId, id) {
5545
+ const removed = await db.routingForm.deleteMany({ where: { id, organizationId } });
5546
+ if (removed.count === 0) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
5547
+ }
5548
+
5549
+ // src/routing/route.ts
5550
+ var UNAVAILABLE = "Online booking is not available for this choice right now. Please contact us to book.";
5551
+ async function findForm(db, organizationId, slug) {
5552
+ const select = { organizationId: true, name: true, slug: true, description: true, questions: true, rules: true, fallback: true };
5553
+ if (organizationId) return db.routingForm.findFirst({ where: { organizationId, slug, isActive: true }, select });
5554
+ const found = await db.routingForm.findMany({ where: { slug, isActive: true }, take: 2, select });
5555
+ return found.length === 1 ? found[0] : null;
5556
+ }
5557
+ async function load(db, organizationId, slug) {
5558
+ const row = await findForm(db, organizationId, slug);
5559
+ if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { slug });
5560
+ return row;
5561
+ }
5562
+ async function getPublicRoutingForm(db, input) {
5563
+ const row = await load(db, input.organizationId, input.slug);
5564
+ return { name: row.name, slug: row.slug, description: row.description, questions: row.questions };
5565
+ }
5566
+ async function resolveDestination(db, organizationId, destination) {
5567
+ const scope = [{ organizationId }, { organizationId: null }];
5568
+ const [type, calendar] = await Promise.all([
5569
+ destination.typeId ? db.appointmentType.findFirst({ where: { id: destination.typeId, isActive: true, OR: scope }, select: { id: true, slug: true, name: true } }) : null,
5570
+ destination.calendarId ? db.schedulingCalendar.findFirst({ where: { id: destination.calendarId, isActive: true, OR: scope }, select: { id: true, slug: true, name: true } }) : null
5571
+ ]);
5572
+ if (destination.typeId && !type || destination.calendarId && !calendar) return null;
5573
+ if (type && calendar) {
5574
+ const link = await db.appointmentTypeCalendar.findUnique({
5575
+ where: { appointmentTypeId_calendarId: { appointmentTypeId: type.id, calendarId: calendar.id } },
5576
+ select: { calendarId: true }
5577
+ });
5578
+ if (!link) return null;
5579
+ }
5580
+ return {
5581
+ typeId: type?.id ?? null,
5582
+ typeSlug: type?.slug ?? null,
5583
+ typeName: type?.name ?? null,
5584
+ calendarId: calendar?.id ?? null,
5585
+ calendarSlug: calendar?.slug ?? null,
5586
+ calendarName: calendar?.name ?? null
5587
+ };
5588
+ }
5589
+ async function decide(db, organizationId, definition, answers) {
5590
+ const checked = checkAnswers(definition.questions, answers);
5591
+ if (!checked.ok) throw new SchedulingValidationError("The answers do not fit the form", "SCHED_1203", { errors: checked.problems });
5592
+ for (const rule of matchingRules(definition, checked.answers)) {
5593
+ const destination = await resolveDestination(db, organizationId, rule.destination);
5594
+ if (destination) return { destination, message: null, matchedRuleId: rule.id, usedFallback: false };
5595
+ }
5596
+ if (definition.fallback.kind === "DESTINATION") {
5597
+ const destination = await resolveDestination(db, organizationId, definition.fallback.destination);
5598
+ return { destination, message: destination ? null : UNAVAILABLE, matchedRuleId: null, usedFallback: true };
5599
+ }
5600
+ return { destination: null, message: definition.fallback.message, matchedRuleId: null, usedFallback: true };
5601
+ }
5602
+ async function routeClient(db, input) {
5603
+ const row = await load(db, input.organizationId, input.slug);
5604
+ return decide(db, row.organizationId, row, input.answers);
5605
+ }
5606
+ async function testRoutingForm(db, input) {
5607
+ const row = await db.routingForm.findFirst({
5608
+ where: { id: input.id, organizationId: input.organizationId },
5609
+ select: { questions: true, rules: true, fallback: true }
5610
+ });
5611
+ if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id: input.id });
5612
+ const definition = row;
5613
+ const outcome = await decide(db, input.organizationId, definition, input.answers);
5614
+ const checked = checkAnswers(definition.questions, input.answers);
5615
+ const allMatchedRuleIds = checked.ok ? matchingRules(definition, checked.answers).map((r) => r.id) : [];
5616
+ return { ...outcome, allMatchedRuleIds };
5617
+ }
5618
+
5619
+ // src/privacy/subject.ts
5620
+ import { createHash } from "crypto";
5621
+ var EMAIL2 = /^[^\s@]+@[^\s@]+$/;
5622
+ function invalid2(reason) {
5623
+ return new SchedulingValidationError(`Say whose data this is: ${reason}`, "SCHED_1300", { reason });
5624
+ }
5625
+ function parseSubject(input) {
5626
+ let email2 = null;
5627
+ let clientId = null;
5628
+ if (input.email !== void 0 && input.email !== null) {
5629
+ if (typeof input.email !== "string") throw invalid2("the email must be text");
5630
+ const trimmed = input.email.trim().toLowerCase();
5631
+ if (trimmed.length > 254 || !EMAIL2.test(trimmed)) throw invalid2("the email is not a single valid address");
5632
+ email2 = trimmed;
5633
+ }
5634
+ if (input.clientId !== void 0 && input.clientId !== null) {
5635
+ if (typeof input.clientId !== "string") throw invalid2("the client id must be text");
5636
+ const trimmed = input.clientId.trim();
5637
+ if (trimmed.length < 1 || trimmed.length > 200) throw invalid2("the client id must be 1 to 200 characters");
5638
+ clientId = trimmed;
5639
+ }
5640
+ if (!email2 && !clientId) throw invalid2("send an email address, a client id, or both");
5641
+ return { email: email2, clientId };
5642
+ }
5643
+ function subjectHashes(organizationId, subject) {
5644
+ const identifiers = [...subject.emails, ...subject.clientId ? [`client:${subject.clientId}`] : []];
5645
+ return identifiers.map((identifier) => createHash("sha256").update(`${organizationId}
5646
+ ${identifier}`).digest("hex"));
5647
+ }
5648
+ async function resolveSubject(db, organizationId, parsed) {
5649
+ const emails = new Set(parsed.email ? [parsed.email] : []);
5650
+ if (parsed.clientId) {
5651
+ const [bookings, series] = await Promise.all([
5652
+ db.appointment.findMany({ where: { clientId: parsed.clientId, calendar: { organizationId } }, select: { clientEmail: true } }),
5653
+ db.recurringSeries.findMany({ where: { clientId: parsed.clientId, organizationId }, select: { clientEmail: true } })
5654
+ ]);
5655
+ for (const row of [...bookings, ...series]) emails.add(row.clientEmail.trim().toLowerCase());
5656
+ }
5657
+ return { emails: [...emails], clientId: parsed.clientId };
5658
+ }
5659
+
5660
+ // src/privacy/audit.ts
5661
+ async function recordPrivacyRequest(db, input) {
5662
+ await db.dataSubjectRequest.create({
5663
+ data: {
5664
+ organizationId: input.organizationId,
5665
+ kind: input.kind,
5666
+ subjectHashes: subjectHashes(input.organizationId, input.subject),
5667
+ requestedBy: input.requestedBy,
5668
+ counts: { ...input.counts },
5669
+ createdAt: input.now
5670
+ }
5671
+ });
5672
+ }
5673
+ async function listPrivacyRequests(db, input) {
5674
+ const where = { organizationId: input.organizationId };
5675
+ const [requests, total] = await Promise.all([
5676
+ db.dataSubjectRequest.findMany({
5677
+ where,
5678
+ orderBy: { createdAt: "desc" },
5679
+ take: Math.min(input.limit ?? 50, 200),
5680
+ skip: input.offset ?? 0,
5681
+ select: { id: true, kind: true, requestedBy: true, counts: true, createdAt: true }
5682
+ }),
5683
+ db.dataSubjectRequest.count({ where })
5684
+ ]);
5685
+ return { requests, total };
5686
+ }
5687
+
5688
+ // src/privacy/collect.ts
5689
+ var APPOINTMENT = {
5690
+ id: true,
5691
+ startTime: true,
5692
+ endTime: true,
5693
+ duration: true,
5694
+ timezone: true,
5695
+ status: true,
5696
+ isGroup: true,
5697
+ clientName: true,
5698
+ clientEmail: true,
5699
+ clientPhone: true,
5700
+ clientId: true,
5701
+ cancelledAt: true,
5702
+ cancelledBy: true,
5703
+ cancelReason: true,
5704
+ rescheduledFrom: true,
5705
+ rescheduleCount: true,
5706
+ intakeResponses: true,
5707
+ notes: true,
5708
+ staffNotes: true,
5709
+ location: true,
5710
+ meetingUrl: true,
5711
+ paymentStatus: true,
5712
+ paymentAmount: true,
5713
+ depositAmount: true,
5714
+ tipAmount: true,
5715
+ paymentProvider: true,
5716
+ paymentId: true,
5717
+ balancePaymentId: true,
5718
+ couponCode: true,
5719
+ discountAmount: true,
5720
+ cancellationFeeAmount: true,
5721
+ refundAmount: true,
5722
+ refundStatus: true,
5723
+ recurringId: true,
5724
+ recurringIndex: true,
5725
+ packagePurchaseId: true,
5726
+ createdAt: true,
5727
+ updatedAt: true,
5728
+ calendar: { select: { name: true } },
5729
+ type: { select: { name: true } }
5730
+ };
5731
+ var NOTIFICATION = {
5732
+ id: true,
5733
+ appointmentId: true,
5734
+ channel: true,
5735
+ trigger: true,
5736
+ recipient: true,
5737
+ subject: true,
5738
+ body: true,
5739
+ status: true,
5740
+ scheduledFor: true,
5741
+ sentAt: true,
5742
+ createdAt: true
5743
+ };
5744
+ var WAITLIST = {
5745
+ id: true,
5746
+ typeId: true,
5747
+ calendarId: true,
5748
+ day: true,
5749
+ slotStart: true,
5750
+ timezone: true,
5751
+ clientName: true,
5752
+ clientEmail: true,
5753
+ clientPhone: true,
5754
+ status: true,
5755
+ offerSlotStart: true,
5756
+ offerExpiresAt: true,
5757
+ offeredAt: true,
5758
+ bookedAppointmentId: true,
5759
+ createdAt: true
5760
+ };
5761
+ var PURCHASE = {
5762
+ id: true,
5763
+ packageId: true,
5764
+ clientEmail: true,
5765
+ clientName: true,
5766
+ sessionsTotal: true,
5767
+ sessionsUsed: true,
5768
+ expiresAt: true,
5769
+ purchasedAt: true,
5770
+ status: true,
5771
+ paymentId: true,
5772
+ notes: true,
5773
+ pricePaidCents: true,
5774
+ createdAt: true
5775
+ };
5776
+ var SERIES = {
5777
+ id: true,
5778
+ calendarId: true,
5779
+ typeId: true,
5780
+ frequency: true,
5781
+ occurrences: true,
5782
+ startTimeLocal: true,
5783
+ durationMins: true,
5784
+ timezone: true,
5785
+ endsAt: true,
5786
+ clientEmail: true,
5787
+ clientName: true,
5788
+ clientPhone: true,
5789
+ clientId: true,
5790
+ notes: true,
5791
+ status: true,
5792
+ createdAt: true
5793
+ };
5794
+ var DELIVERY = { id: true, eventId: true, eventType: true, body: true, status: true, createdAt: true };
5795
+ var emailIs = (field, emails) => emails.map((email2) => ({ [field]: { equals: email2, mode: "insensitive" } }));
5796
+ var escape = (text2) => text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5797
+ function mentions(body, emails, ids) {
5798
+ const lower = body.toLowerCase();
5799
+ const whole = emails.some((email2) => new RegExp(`(?<![a-z0-9._%+-])${escape(email2.toLowerCase())}(?![a-z0-9_-]|\\.[a-z0-9])`).test(lower));
5800
+ return whole || ids.some((id) => body.includes(`"${id}"`));
5801
+ }
5802
+ async function collectSubjectRows(db, organizationId, subject) {
5803
+ const person = (field) => [...emailIs(field, subject.emails), ...subject.clientId ? [{ clientId: subject.clientId }] : []];
5804
+ const byEmail = emailIs("clientEmail", subject.emails);
5805
+ const none = subject.emails.length === 0 && !subject.clientId;
5806
+ const appointments = none ? [] : await db.appointment.findMany({
5807
+ where: { calendar: { organizationId }, OR: person("clientEmail") },
5808
+ orderBy: { startTime: "asc" },
5809
+ select: APPOINTMENT
5810
+ });
5811
+ const appointmentIds = appointments.map((row) => row.id);
5812
+ const [notifications, waitlistEntries, packagePurchases, recurringSeries] = await Promise.all([
5813
+ appointmentIds.length ? db.scheduledNotification.findMany({ where: { appointmentId: { in: appointmentIds } }, orderBy: { createdAt: "asc" }, select: NOTIFICATION }) : [],
5814
+ byEmail.length ? db.waitlistEntry.findMany({ where: { organizationId, OR: byEmail }, orderBy: { createdAt: "asc" }, select: WAITLIST }) : [],
5815
+ byEmail.length ? db.packagePurchase.findMany({ where: { organizationId, OR: byEmail }, orderBy: { createdAt: "asc" }, select: PURCHASE }) : [],
5816
+ none ? [] : db.recurringSeries.findMany({ where: { organizationId, OR: person("clientEmail") }, orderBy: { createdAt: "asc" }, select: SERIES })
5817
+ ]);
5818
+ const terms = [...subject.emails, ...appointmentIds.map((id) => `"${id}"`), ...waitlistEntries.map((row) => `"${row.id}"`)];
5819
+ const deliveries = /* @__PURE__ */ new Map();
5820
+ for (let start = 0; start < terms.length; start += 40) {
5821
+ const chunk = terms.slice(start, start + 40);
5822
+ const rows = await db.webhookDelivery.findMany({
5823
+ where: { organizationId, OR: chunk.map((term) => ({ body: { contains: term, mode: "insensitive" } })) },
5824
+ orderBy: { createdAt: "asc" },
5825
+ select: DELIVERY
5826
+ });
5827
+ for (const row of rows) if (mentions(row.body, subject.emails, [...appointmentIds, ...waitlistEntries.map((entry4) => entry4.id)])) deliveries.set(row.id, row);
5828
+ }
5829
+ return { appointments, notifications, waitlistEntries, packagePurchases, recurringSeries, webhookDeliveries: [...deliveries.values()] };
5830
+ }
5831
+ function countRows(rows) {
5832
+ return {
5833
+ appointments: rows.appointments.length,
5834
+ notifications: rows.notifications.length,
5835
+ waitlistEntries: rows.waitlistEntries.length,
5836
+ packagePurchases: rows.packagePurchases.length,
5837
+ recurringSeries: rows.recurringSeries.length,
5838
+ webhookDeliveries: rows.webhookDeliveries.length
5839
+ };
5840
+ }
5841
+
5842
+ // src/privacy/export.ts
5843
+ function withoutOfferToken(body) {
5844
+ try {
5845
+ const parsed = JSON.parse(body);
5846
+ if (parsed?.data?.offer && "token" in parsed.data.offer) {
5847
+ delete parsed.data.offer.token;
5848
+ return JSON.stringify(parsed);
5849
+ }
5850
+ } catch {
5851
+ }
5852
+ return body;
5853
+ }
5854
+ function withoutLinks(body) {
5855
+ return body.replace(/\/appt\/[A-Za-z0-9_-]+/g, "/appt/[removed]").replace(/([?&]token=)[A-Za-z0-9_-]+/g, "$1[removed]");
5856
+ }
5857
+ async function exportSubject(db, input) {
5858
+ const parsed = parseSubject(input);
5859
+ const now = input.now ?? /* @__PURE__ */ new Date();
5860
+ const subject = await resolveSubject(db, input.organizationId, parsed);
5861
+ const rows = await collectSubjectRows(db, input.organizationId, subject);
5862
+ const counts = countRows(rows);
5863
+ await recordPrivacyRequest(db, { organizationId: input.organizationId, kind: "EXPORT", subject, requestedBy: input.requestedBy, counts, now });
5864
+ return {
5865
+ format: "ordinatio-scheduling-subject-export",
5866
+ version: 1,
5867
+ exportedAt: now.toISOString(),
5868
+ organizationId: input.organizationId,
5869
+ subject,
5870
+ counts,
5871
+ appointments: rows.appointments.map(({ calendar, type, ...rest }) => ({ ...rest, calendarName: calendar.name, typeName: type.name })),
5872
+ notifications: rows.notifications.map((row) => ({ ...row, body: withoutLinks(row.body) })),
5873
+ waitlistEntries: rows.waitlistEntries,
5874
+ packagePurchases: rows.packagePurchases,
5875
+ recurringSeries: rows.recurringSeries,
5876
+ webhookDeliveries: rows.webhookDeliveries.map((row) => ({ ...row, body: withoutOfferToken(row.body) }))
5877
+ };
5878
+ }
5879
+
5880
+ // src/privacy/erase.ts
5881
+ import { randomUUID as randomUUID5 } from "crypto";
5882
+ import { Prisma as Prisma9 } from "@prisma/client";
5883
+ var ERASED_NAME = "Erased client";
5884
+ var ERASED_EMAIL = "erased@erased.invalid";
5885
+ var LIVE_BOOKING = ["PENDING", "CONFIRMED"];
5886
+ var LIVE_OFFER = ["OFFERED", "ACCEPTING"];
5887
+ function blockersOf(rows, now) {
5888
+ return {
5889
+ upcomingAppointments: rows.appointments.filter((row) => LIVE_BOOKING.includes(row.status) && row.endTime > now).length,
5890
+ liveWaitlistEntries: rows.waitlistEntries.filter((row) => LIVE_OFFER.includes(row.status)).length
5891
+ };
5892
+ }
5893
+ function warningsOf(rows) {
5894
+ const unused = rows.packagePurchases.filter((row) => row.status === "ACTIVE").reduce((sum, row) => sum + Math.max(0, row.sessionsTotal - row.sessionsUsed), 0);
5895
+ return unused > 0 ? [`An active package still has ${unused} unused sessions; after erasure it can no longer be matched to this person`] : [];
5896
+ }
5897
+ var blocked = (blockers) => blockers.upcomingAppointments + blockers.liveWaitlistEntries > 0;
5898
+ async function previewErase(db, input) {
5899
+ const subject = await resolveSubject(db, input.organizationId, parseSubject(input));
5900
+ const rows = await collectSubjectRows(db, input.organizationId, subject);
5901
+ const blockers = blockersOf(rows, input.now ?? /* @__PURE__ */ new Date());
5902
+ return { counts: countRows(rows), blockers, canErase: !blocked(blockers), warnings: warningsOf(rows) };
5903
+ }
5904
+ async function eraseSubject(db, input) {
5905
+ const parsed = parseSubject(input);
5906
+ const now = input.now ?? /* @__PURE__ */ new Date();
5907
+ const { organizationId } = input;
5908
+ return withTransaction(db, async (tx) => {
5909
+ const subject = await resolveSubject(tx, organizationId, parsed);
5910
+ const rows = await collectSubjectRows(tx, organizationId, subject);
5911
+ const blockers = blockersOf(rows, now);
5912
+ if (blocked(blockers)) {
5913
+ throw new SchedulingValidationError("This person still has upcoming bookings or an open waitlist offer", "SCHED_1301", { blockers });
5914
+ }
5915
+ for (const { id } of rows.appointments) {
5916
+ await tx.appointment.update({
5917
+ where: { id },
5918
+ data: {
5919
+ clientName: ERASED_NAME,
5920
+ clientEmail: ERASED_EMAIL,
5921
+ clientPhone: null,
5922
+ clientId: null,
5923
+ intakeResponses: Prisma9.DbNull,
5924
+ notes: null,
5925
+ staffNotes: null,
5926
+ cancelReason: null,
5927
+ manageToken: `erased_${randomUUID5()}`
5928
+ }
5929
+ });
5930
+ }
5931
+ const idsOf = (list) => list.map((row) => row.id);
5932
+ if (rows.notifications.length) await tx.scheduledNotification.deleteMany({ where: { id: { in: idsOf(rows.notifications) } } });
5933
+ if (rows.waitlistEntries.length) await tx.waitlistEntry.deleteMany({ where: { organizationId, id: { in: idsOf(rows.waitlistEntries) } } });
5934
+ if (rows.webhookDeliveries.length) await tx.webhookDelivery.deleteMany({ where: { organizationId, id: { in: idsOf(rows.webhookDeliveries) } } });
5935
+ if (rows.packagePurchases.length) {
5936
+ await tx.packagePurchase.updateMany({
5937
+ where: { organizationId, id: { in: idsOf(rows.packagePurchases) } },
5938
+ data: { clientEmail: ERASED_EMAIL, clientName: null, notes: null }
5939
+ });
5940
+ }
5941
+ if (rows.recurringSeries.length) {
5942
+ await tx.recurringSeries.updateMany({
5943
+ where: { organizationId, id: { in: idsOf(rows.recurringSeries) } },
5944
+ data: { clientEmail: ERASED_EMAIL, clientName: ERASED_NAME, clientPhone: null, clientId: null, notes: null }
5945
+ });
5946
+ }
5947
+ const counts = countRows(rows);
5948
+ await recordPrivacyRequest(tx, { organizationId, kind: "ERASE", subject, requestedBy: input.requestedBy, counts, now });
5949
+ return { counts };
5950
+ }, { timeout: 12e4 });
5951
+ }
4399
5952
  export {
5953
+ BRAND_FIELDS,
4400
5954
  BlockedTargetError,
4401
5955
  DEFAULT_BACKOFF_SECONDS,
5956
+ DEFAULT_OFFER_MINUTES,
5957
+ ERASED_EMAIL,
5958
+ ERASED_NAME,
4402
5959
  MAX_ENDPOINTS_PER_ORGANIZATION,
5960
+ MAX_WAITING_PER_TYPE_DAY,
5961
+ OPERATORS_BY_TYPE,
4403
5962
  RECURRING_MAX_OCCURRENCES,
5963
+ LIMITS as ROUTING_LIMITS,
4404
5964
  SCHEDULING_ERRORS,
4405
5965
  SIGNATURE_HEADER,
4406
5966
  SchedulingNotFoundError,
@@ -4413,7 +5973,9 @@ export {
4413
5973
  addTimeBlock,
4414
5974
  appointmentWebhookData,
4415
5975
  archiveCalendar,
5976
+ beginWaitlistAccept,
4416
5977
  bookAppointment,
5978
+ brandTemplateFields,
4417
5979
  buildJitsiUrl,
4418
5980
  buildNotificationContext,
4419
5981
  buildOccurrenceStartTime,
@@ -4421,25 +5983,33 @@ export {
4421
5983
  calculateCancellationFee,
4422
5984
  cancelAppointment,
4423
5985
  cancelPendingNotifications,
5986
+ checkAnswers,
4424
5987
  checkAuthContract,
4425
5988
  checkCalendarSyncContract,
4426
5989
  checkClockContract,
4427
5990
  checkNotificationContract,
4428
5991
  checkPaymentContract,
4429
5992
  checkWebhookUrl,
5993
+ completeWaitlistAccept,
4430
5994
  createAppointmentType,
4431
5995
  createCalendar,
4432
5996
  createInMemoryAdapters,
4433
5997
  createNodeTransport,
4434
5998
  createNotificationTemplate,
5999
+ createRoutingForm,
4435
6000
  createWebhookEndpoint,
6001
+ deleteBrand,
4436
6002
  deleteCalendar,
4437
6003
  deleteNotificationTemplate,
6004
+ deleteRoutingForm,
4438
6005
  deleteWebhookEndpoint,
4439
6006
  deliverDueWebhooks,
4440
6007
  enqueueAppointmentWebhook,
4441
6008
  enqueueReminderSent,
4442
6009
  enqueueWebhookEvent,
6010
+ eraseSubject,
6011
+ expireWaitlistOffers,
6012
+ exportSubject,
4443
6013
  generateOccurrenceDates,
4444
6014
  generateWebhookSecret,
4445
6015
  getAppointment,
@@ -4449,42 +6019,73 @@ export {
4449
6019
  getAvailableDates,
4450
6020
  getAvailableSlots,
4451
6021
  getBookingAnalytics,
6022
+ getBrand,
4452
6023
  getCalendar,
4453
6024
  getGroupCapacity,
4454
6025
  getGroupSessions,
4455
6026
  getNotificationTemplate,
6027
+ getPublicBrand,
6028
+ getPublicRoutingForm,
6029
+ getRoutingForm,
4456
6030
  getTeamAvailableSlots,
4457
6031
  getUserDayAppointments,
6032
+ getWaitlistOffer,
4458
6033
  isPrivateAddress,
4459
6034
  isSlotAvailable,
4460
6035
  isVirtualMeeting,
6036
+ joinWaitlist,
6037
+ leaveWaitlist,
4461
6038
  listAppointmentTypes,
4462
6039
  listAppointments,
4463
6040
  listAvailabilityRules,
4464
6041
  listCalendars,
4465
6042
  listNotificationTemplates,
6043
+ listPrivacyRequests,
6044
+ listRoutingForms,
6045
+ listWaitlist,
4466
6046
  listWebhookDeliveries,
4467
6047
  listWebhookEndpoints,
6048
+ localDay,
4468
6049
  localToUTC,
4469
6050
  markNoShow,
6051
+ matchingRules,
6052
+ offerFreedSlot,
6053
+ parseSubject,
4470
6054
  parseTimeLocal,
6055
+ previewErase,
4471
6056
  processPendingNotifications,
4472
6057
  queueImmediateNotification,
4473
6058
  queueStaffNotification,
6059
+ releaseWaitlistAccept,
4474
6060
  removeDateOverride,
6061
+ removeWaitlistEntry,
4475
6062
  renderTemplate,
4476
6063
  rescheduleAppointment,
6064
+ resolveDestination,
4477
6065
  resolveLocation,
6066
+ resolveSubject,
4478
6067
  retryWebhookDelivery,
6068
+ routeClient,
6069
+ saveBrand,
4479
6070
  schedError,
4480
6071
  scheduleNotifications,
4481
6072
  selectCalendarForBooking,
4482
6073
  sendTestWebhook,
6074
+ senderIdentity,
4483
6075
  setWeeklyAvailability,
6076
+ settleBookedAccept,
4484
6077
  signWebhook,
6078
+ subjectHashes,
6079
+ testRoutingForm,
6080
+ toPublicBrand,
6081
+ tryOfferFreedSlot,
4485
6082
  updateAppointmentType,
4486
6083
  updateCalendar,
4487
6084
  updateNotificationTemplate,
6085
+ updateRoutingForm,
6086
+ validateBrand,
6087
+ validateRoutingDestinations,
6088
+ validateRoutingStructure,
4488
6089
  verifyWebhookSignature,
4489
6090
  withCalendarVisibility
4490
6091
  };