@ordinatio/scheduling-api 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -39,6 +39,7 @@ __export(index_exports, {
39
39
  BalanceRequestInProgressError: () => BalanceRequestInProgressError,
40
40
  BookingPageConfigSchema: () => BookingPageConfigSchema,
41
41
  BookingPageThemeSchema: () => BookingPageThemeSchema,
42
+ BrandSchema: () => BrandSchema,
42
43
  CancelRecurringScopeSchema: () => CancelRecurringScopeSchema,
43
44
  CancelRecurringSeriesSchema: () => CancelRecurringSeriesSchema,
44
45
  CreateAppointmentCategorySchema: () => CreateAppointmentCategorySchema,
@@ -49,6 +50,7 @@ __export(index_exports, {
49
50
  CreateNotificationTemplateSchema: () => CreateNotificationTemplateSchema,
50
51
  CreatePackagePurchaseSchema: () => CreatePackagePurchaseSchema,
51
52
  CreateRecurringSeriesSchema: () => CreateRecurringSeriesSchema,
53
+ CreateRoutingFormSchema: () => CreateRoutingFormSchema,
52
54
  CreateServicePackageSchema: () => CreateServicePackageSchema,
53
55
  CreateWebhookEndpointSchema: () => CreateWebhookEndpointSchema,
54
56
  DEFAULT_CANCELLATION_POLICY: () => DEFAULT_CANCELLATION_POLICY,
@@ -57,13 +59,17 @@ __export(index_exports, {
57
59
  NotificationChannelSchema: () => NotificationChannelSchema,
58
60
  NotificationTriggerSchema: () => NotificationTriggerSchema,
59
61
  OrgCancellationPolicySchema: () => OrgCancellationPolicySchema,
62
+ PrivacyEraseSchema: () => PrivacyEraseSchema,
63
+ PrivacySubjectSchema: () => PrivacySubjectSchema,
60
64
  RETRYABLE_REFUND_STATUSES: () => RETRYABLE_REFUND_STATUSES,
61
65
  RecurringFrequencySchema: () => RecurringFrequencySchema,
62
66
  RefundOutcomePersistenceError: () => RefundOutcomePersistenceError,
67
+ RouteClientSchema: () => RouteClientSchema,
63
68
  SLOT_GRANULARITY_DEFAULT: () => SLOT_GRANULARITY_DEFAULT,
64
69
  SLOT_GRANULARITY_OPTIONS: () => SLOT_GRANULARITY_OPTIONS,
65
70
  TERMINAL_SUCCESS_STATUSES: () => TERMINAL_SUCCESS_STATUSES,
66
71
  TOKEN_TTL_DAYS: () => TOKEN_TTL_DAYS,
72
+ TestRoutingFormSchema: () => TestRoutingFormSchema,
67
73
  UnverifiedPaymentError: () => UnverifiedPaymentError,
68
74
  UpdateAppointmentCategorySchema: () => UpdateAppointmentCategorySchema,
69
75
  UpdateAppointmentTypeSchema: () => UpdateAppointmentTypeSchema,
@@ -72,6 +78,7 @@ __export(index_exports, {
72
78
  UpdateCouponCodeSchema: () => UpdateCouponCodeSchema,
73
79
  UpdateNotificationTemplateSchema: () => UpdateNotificationTemplateSchema,
74
80
  UpdatePackagePurchaseSchema: () => UpdatePackagePurchaseSchema,
81
+ UpdateRoutingFormSchema: () => UpdateRoutingFormSchema,
75
82
  UpdateServicePackageSchema: () => UpdateServicePackageSchema,
76
83
  attemptLegRefund: () => attemptLegRefund,
77
84
  createBalanceIntent: () => createBalanceIntent,
@@ -101,6 +108,9 @@ __export(index_exports, {
101
108
  });
102
109
  module.exports = __toCommonJS(index_exports);
103
110
 
111
+ // src/create-api.ts
112
+ var engine = __toESM(require("@ordinatio/scheduling"));
113
+
104
114
  // src/cors.ts
105
115
  function defaultCorsHeaders() {
106
116
  return {
@@ -322,8 +332,87 @@ function withWebhooks(inner, host) {
322
332
  };
323
333
  }
324
334
 
335
+ // src/waitlist/announce-offer.ts
336
+ var import_scheduling2 = require("@ordinatio/scheduling");
337
+ async function offerAndAnnounce(host, settings, db, slot) {
338
+ const offer = await (0, import_scheduling2.tryOfferFreedSlot)(db, { ...slot, offerMinutes: settings.offerMinutes });
339
+ if (!offer) return false;
340
+ const details = {
341
+ organizationId: slot.organizationId,
342
+ token: offer.token,
343
+ clientName: offer.entry.clientName,
344
+ clientEmail: offer.entry.clientEmail,
345
+ clientPhone: offer.entry.clientPhone,
346
+ typeName: offer.typeName,
347
+ calendarName: offer.calendarName,
348
+ startTime: offer.startTime,
349
+ timezone: offer.timezone,
350
+ expiresAt: offer.expiresAt
351
+ };
352
+ if (settings.notify) {
353
+ try {
354
+ await settings.notify(details);
355
+ } catch (error) {
356
+ console.error("[waitlist] the host could not send the offer; it stays open until it expires:", error);
357
+ }
358
+ }
359
+ if (host.webhooks) {
360
+ try {
361
+ await (0, import_scheduling2.enqueueWebhookEvent)(db, {
362
+ organizationId: slot.organizationId,
363
+ type: "waitlist.offered",
364
+ // Each offering has its own id, so offering the same slot to the same person again still reaches subscribers.
365
+ eventId: `waitlist_offer_${offer.entry.id}_${offer.startTime.getTime()}_${offer.expiresAt.getTime()}`,
366
+ data: {
367
+ offer: {
368
+ entryId: offer.entry.id,
369
+ token: offer.token,
370
+ clientName: details.clientName,
371
+ clientEmail: details.clientEmail,
372
+ clientPhone: details.clientPhone,
373
+ typeName: details.typeName,
374
+ calendarName: details.calendarName,
375
+ calendarId: offer.calendarId,
376
+ startTime: offer.startTime.toISOString(),
377
+ expiresAt: offer.expiresAt.toISOString()
378
+ }
379
+ }
380
+ });
381
+ } catch (error) {
382
+ console.error("[waitlist] could not queue the waitlist.offered webhook:", error);
383
+ }
384
+ }
385
+ return true;
386
+ }
387
+
388
+ // src/waitlist/waitlist-events.ts
389
+ var FREED_BY = /* @__PURE__ */ new Set(["appointment.cancelled", "appointment.rejected", "appointment.updated"]);
390
+ function withWaitlist(inner, host) {
391
+ return {
392
+ async emit(organizationId, type, data) {
393
+ const appointmentId = data.appointmentId;
394
+ if (host.waitlist && FREED_BY.has(type) && typeof appointmentId === "string") {
395
+ try {
396
+ const db = await host.tenantDb(organizationId, "waitlist");
397
+ const appointment = db ? await db.appointment.findUnique({
398
+ where: { id: appointmentId },
399
+ select: { calendarId: true, startTime: true, rescheduledFrom: true, status: true, calendar: { select: { organizationId: true } } }
400
+ }) : null;
401
+ if (db && appointment && (appointment.calendar.organizationId ?? organizationId) === organizationId) {
402
+ const freed = type === "appointment.updated" ? appointment.rescheduledFrom : appointment.status === "CANCELLED" ? appointment.startTime : null;
403
+ if (freed) await offerAndAnnounce(host, host.waitlist, db, { organizationId, calendarId: appointment.calendarId, startTime: freed });
404
+ }
405
+ } catch (error) {
406
+ console.error("[scheduling-api] could not offer a freed slot to the waitlist:", error);
407
+ }
408
+ }
409
+ await inner.emit(organizationId, type, data);
410
+ }
411
+ };
412
+ }
413
+
325
414
  // src/handlers/manage-cancel.ts
326
- var import_scheduling5 = require("@ordinatio/scheduling");
415
+ var import_scheduling6 = require("@ordinatio/scheduling");
327
416
 
328
417
  // src/client-address.ts
329
418
  function forwardedAddress(request) {
@@ -334,7 +423,7 @@ function clientAddress(request) {
334
423
  }
335
424
 
336
425
  // src/error-guards.ts
337
- var import_scheduling2 = require("@ordinatio/scheduling");
426
+ var import_scheduling3 = require("@ordinatio/scheduling");
338
427
  function getErrorCode(error) {
339
428
  if (typeof error === "object" && error !== null && "code" in error) {
340
429
  const code = error.code;
@@ -361,20 +450,20 @@ function getErrorMessage(error, fallback) {
361
450
  return fallback;
362
451
  }
363
452
  function schedErrorStatus(code) {
364
- return import_scheduling2.SCHEDULING_ERRORS[code]?.httpStatus ?? 400;
453
+ return import_scheduling3.SCHEDULING_ERRORS[code]?.httpStatus ?? 400;
365
454
  }
366
455
 
367
456
  // src/manage/cancel-via-token.ts
368
- var import_scheduling4 = require("@ordinatio/scheduling");
457
+ var import_scheduling5 = require("@ordinatio/scheduling");
369
458
 
370
459
  // src/calendar-sync.ts
371
- var import_scheduling3 = require("@ordinatio/scheduling");
460
+ var import_scheduling4 = require("@ordinatio/scheduling");
372
461
  async function runWithoutBlocking(code, appointmentId, step, recordFailure) {
373
462
  try {
374
463
  await step();
375
464
  return { queued: true };
376
465
  } catch (error) {
377
- const diagnostic = (0, import_scheduling3.schedError)(code, { error, appointmentId });
466
+ const diagnostic = (0, import_scheduling4.schedError)(code, { error, appointmentId });
378
467
  console.error("[calendar-sync]", diagnostic.ref, error instanceof Error ? error.message : error);
379
468
  try {
380
469
  await recordFailure?.(diagnostic.ref);
@@ -394,7 +483,7 @@ function runCalendarRemoveWithoutBlocking(sync, ref, recordFailure) {
394
483
  // src/manage/cancel-via-token.ts
395
484
  async function cancelViaToken(host, db, organizationId, appointment) {
396
485
  const hasPayment = !!(appointment.paymentId && (appointment.paymentStatus === "PAID" || appointment.paymentStatus === "DEPOSIT_PAID"));
397
- await (0, import_scheduling4.cancelAppointment)(db, {
486
+ await (0, import_scheduling5.cancelAppointment)(db, {
398
487
  appointmentId: appointment.id,
399
488
  cancelledBy: "client",
400
489
  reason: "Cancelled via self-service link"
@@ -405,7 +494,7 @@ async function cancelViaToken(host, db, organizationId, appointment) {
405
494
  data: { refundStatus: hasPayment ? "PENDING_REVIEW" : "NO_PAYMENT" }
406
495
  });
407
496
  } catch (refundStatusError) {
408
- const diagnostic = (0, import_scheduling4.schedError)("SCHED_602", {
497
+ const diagnostic = (0, import_scheduling5.schedError)("SCHED_602", {
409
498
  error: refundStatusError,
410
499
  appointmentId: appointment.id,
411
500
  context: "refundStatus write failed after cancellation already committed",
@@ -450,9 +539,9 @@ async function cancelViaToken(host, db, organizationId, appointment) {
450
539
  const baseUrl = host.appUrl();
451
540
  if (baseUrl) {
452
541
  try {
453
- await (0, import_scheduling4.queueStaffNotification)(db, appointment.id, "CANCELLATION", baseUrl);
542
+ await (0, import_scheduling5.queueStaffNotification)(db, appointment.id, "CANCELLATION", baseUrl, { brand: Boolean(host.brand) });
454
543
  } catch (staffError) {
455
- const diagnostic = (0, import_scheduling4.schedError)("SCHED_607", { error: staffError, appointmentId: appointment.id });
544
+ const diagnostic = (0, import_scheduling5.schedError)("SCHED_607", { error: staffError, appointmentId: appointment.id });
456
545
  console.error("[DELETE /manage]", diagnostic.ref, staffError instanceof Error ? staffError.message : staffError);
457
546
  }
458
547
  }
@@ -526,14 +615,14 @@ async function cancelManagedAppointment(request, { host }) {
526
615
  { status: 409 }
527
616
  );
528
617
  }
529
- const diagnostic = (0, import_scheduling5.schedError)("SCHED_602", { error, token: token ?? "unknown", appointmentId });
618
+ const diagnostic = (0, import_scheduling6.schedError)("SCHED_602", { error, token: token ?? "unknown", appointmentId });
530
619
  console.error("[DELETE /manage]", diagnostic.ref, error instanceof Error ? error.message : error);
531
620
  return Response.json({ error: "Failed to cancel", ref: diagnostic.ref }, { status: 500 });
532
621
  }
533
622
  }
534
623
 
535
624
  // src/handlers/manage-get.ts
536
- var import_scheduling6 = require("@ordinatio/scheduling");
625
+ var import_scheduling7 = require("@ordinatio/scheduling");
537
626
  async function getManagedAppointment(request, { host }) {
538
627
  let token = null;
539
628
  try {
@@ -567,24 +656,24 @@ async function getManagedAppointment(request, { host }) {
567
656
  staffName: appointment.calendar.staffName,
568
657
  calendarId: appointment.calendarId,
569
658
  allowReschedule: appointment.type.allowReschedule,
570
- location: (0, import_scheduling6.resolveLocation)(appointment),
659
+ location: (0, import_scheduling7.resolveLocation)(appointment),
571
660
  meetingUrl: appointment.meetingUrl ?? null,
572
661
  theme: appointment.calendar.theme ?? null
573
662
  });
574
663
  } catch (error) {
575
- const diagnostic = (0, import_scheduling6.schedError)("SCHED_601", { error, token: token ?? "unknown" });
664
+ const diagnostic = (0, import_scheduling7.schedError)("SCHED_601", { error, token: token ?? "unknown" });
576
665
  console.error("[GET /manage]", diagnostic.ref, error instanceof Error ? error.message : error);
577
666
  return Response.json({ error: "Failed to fetch appointment", ref: diagnostic.ref }, { status: 500 });
578
667
  }
579
668
  }
580
669
 
581
670
  // src/handlers/manage-reschedule.ts
582
- var import_scheduling8 = require("@ordinatio/scheduling");
671
+ var import_scheduling9 = require("@ordinatio/scheduling");
583
672
 
584
673
  // src/manage/reschedule-via-token.ts
585
- var import_scheduling7 = require("@ordinatio/scheduling");
674
+ var import_scheduling8 = require("@ordinatio/scheduling");
586
675
  async function rescheduleViaToken(host, db, organizationId, appointment, newTime) {
587
- const result = await (0, import_scheduling7.rescheduleAppointment)(db, {
676
+ const result = await (0, import_scheduling8.rescheduleAppointment)(db, {
588
677
  appointmentId: appointment.id,
589
678
  newStartTime: newTime,
590
679
  reason: "Rescheduled via self-service link"
@@ -609,21 +698,21 @@ async function rescheduleViaToken(host, db, organizationId, appointment, newTime
609
698
  );
610
699
  const baseUrl = host.appUrl() ?? void 0;
611
700
  if (baseUrl) {
612
- await (0, import_scheduling7.queueImmediateNotification)(db, appointment.id, "RESCHEDULE", baseUrl);
701
+ await (0, import_scheduling8.queueImmediateNotification)(db, appointment.id, "RESCHEDULE", baseUrl, { brand: Boolean(host.brand) });
613
702
  } else {
614
703
  console.warn("[manage] no appUrl \u2014 RESCHEDULE notification skipped");
615
704
  }
616
705
  try {
617
- await (0, import_scheduling7.scheduleNotifications)(db, appointment.id, baseUrl, { excludeTriggers: ["CONFIRMATION"] });
706
+ await (0, import_scheduling8.scheduleNotifications)(db, appointment.id, baseUrl, { excludeTriggers: ["CONFIRMATION"], brand: Boolean(host.brand) });
618
707
  } catch (error) {
619
- const diagnostic = (0, import_scheduling7.schedError)("SCHED_604", { error, appointmentId: appointment.id });
708
+ const diagnostic = (0, import_scheduling8.schedError)("SCHED_604", { error, appointmentId: appointment.id });
620
709
  console.error("[PATCH /manage] scheduleNotifications failed (non-blocking):", diagnostic.ref, error instanceof Error ? error.message : error);
621
710
  }
622
711
  if (baseUrl) {
623
712
  try {
624
- await (0, import_scheduling7.queueStaffNotification)(db, appointment.id, "RESCHEDULE", baseUrl);
713
+ await (0, import_scheduling8.queueStaffNotification)(db, appointment.id, "RESCHEDULE", baseUrl, { brand: Boolean(host.brand) });
625
714
  } catch (staffError) {
626
- const diagnostic = (0, import_scheduling7.schedError)("SCHED_607", { error: staffError, appointmentId: appointment.id });
715
+ const diagnostic = (0, import_scheduling8.schedError)("SCHED_607", { error: staffError, appointmentId: appointment.id });
627
716
  console.error("[PATCH /manage]", diagnostic.ref, staffError instanceof Error ? staffError.message : staffError);
628
717
  }
629
718
  }
@@ -682,7 +771,7 @@ async function rescheduleManagedAppointment(request, { host }) {
682
771
  if (target instanceof Response) return target;
683
772
  return await rescheduleViaToken(host, target.db, target.organizationId, appointment, newTime);
684
773
  } catch (error) {
685
- if (error instanceof import_scheduling8.SchedulingValidationError) {
774
+ if (error instanceof import_scheduling9.SchedulingValidationError) {
686
775
  return Response.json({ error: error.message, ref: error.ref }, { status: 400 });
687
776
  }
688
777
  const code = getErrorCode(error);
@@ -701,14 +790,14 @@ async function rescheduleManagedAppointment(request, { host }) {
701
790
  console.error("[PATCH /manage]", ref, "SCHED_306", error);
702
791
  return Response.json({ error: "Appointment status prevents rescheduling", ...ref && { ref } }, { status: 400 });
703
792
  }
704
- const diagnostic = (0, import_scheduling8.schedError)("SCHED_603", { error, token: token ?? "unknown", appointmentId });
793
+ const diagnostic = (0, import_scheduling9.schedError)("SCHED_603", { error, token: token ?? "unknown", appointmentId });
705
794
  console.error("[PATCH /manage]", diagnostic.ref, error instanceof Error ? error.message : error);
706
795
  return Response.json({ error: "Failed to reschedule", ref: diagnostic.ref }, { status: 500 });
707
796
  }
708
797
  }
709
798
 
710
799
  // src/handlers/capacity.ts
711
- var import_scheduling9 = require("@ordinatio/scheduling");
800
+ var import_scheduling10 = require("@ordinatio/scheduling");
712
801
 
713
802
  // src/respond.ts
714
803
  var WIDGET_CACHE_HEADERS = {
@@ -755,7 +844,7 @@ async function getCapacity(request, { host }) {
755
844
  select: { isGroup: true }
756
845
  });
757
846
  if (!type || !type.isGroup) return corsJson(cors, NOT_FOUND, { status: 404 });
758
- return corsJson(cors, await (0, import_scheduling9.getGroupCapacity)(db, { typeId, calendarId, startTime }));
847
+ return corsJson(cors, await (0, import_scheduling10.getGroupCapacity)(db, { typeId, calendarId, startTime }));
759
848
  } catch (error) {
760
849
  console.error("[group-capacity] unexpected error:", error instanceof Error ? error.message : error);
761
850
  return corsJson(cors, { error: "Failed to fetch capacity" }, { status: 500 });
@@ -763,7 +852,7 @@ async function getCapacity(request, { host }) {
763
852
  }
764
853
 
765
854
  // src/handlers/payment-intent.ts
766
- var import_scheduling10 = require("@ordinatio/scheduling");
855
+ var import_scheduling11 = require("@ordinatio/scheduling");
767
856
  var import_zod = require("zod");
768
857
 
769
858
  // src/payments/create-payment-intent.ts
@@ -879,7 +968,7 @@ async function createPaymentIntentRoute(request, { host }) {
879
968
  if (!result.ok) return corsJson(cors, { error: result.error }, { status: result.status });
880
969
  return corsJson(cors, result.body, { status: result.status });
881
970
  } catch (error) {
882
- const err = (0, import_scheduling10.schedError)("SCHED_407", {
971
+ const err = (0, import_scheduling11.schedError)("SCHED_407", {
883
972
  typeId,
884
973
  calendarId,
885
974
  error: error instanceof Error ? error.message : String(error)
@@ -890,7 +979,7 @@ async function createPaymentIntentRoute(request, { host }) {
890
979
  }
891
980
 
892
981
  // src/handlers/appointment-cancel.ts
893
- var import_scheduling12 = require("@ordinatio/scheduling");
982
+ var import_scheduling13 = require("@ordinatio/scheduling");
894
983
 
895
984
  // src/appointments/owned-appointment.ts
896
985
  async function verifyAppointmentOwnership(db, appointmentId, organizationId) {
@@ -943,7 +1032,7 @@ async function writeRefundStatusAfterCancel(host, db, input) {
943
1032
  }
944
1033
 
945
1034
  // src/staff/require-staff.ts
946
- var import_scheduling11 = require("@ordinatio/scheduling");
1035
+ var import_scheduling12 = require("@ordinatio/scheduling");
947
1036
  async function requireAdminStaff(host, request, options) {
948
1037
  const staff = await host.staff.resolve(request);
949
1038
  if (!staff) return Response.json({ error: "Unauthorized" }, { status: 401 });
@@ -952,7 +1041,7 @@ async function requireAdminStaff(host, request, options) {
952
1041
  if (limited) return limited;
953
1042
  }
954
1043
  if (!staff.isAdmin && !options.allowAnyRole) {
955
- const err = (0, import_scheduling11.schedError)("SCHED_900", { userId: staff.userId, role: staff.role });
1044
+ const err = (0, import_scheduling12.schedError)("SCHED_900", { userId: staff.userId, role: staff.role });
956
1045
  return Response.json({ error: "Forbidden", ref: err.ref }, { status: 403 });
957
1046
  }
958
1047
  if (!staff.schedulingEnabled && !options.ignoreSchedulingSwitch) {
@@ -988,7 +1077,7 @@ async function cancelByStaff(request, { host, params }) {
988
1077
  const appointment = await verifyAppointmentOwnership(db, id, organizationId);
989
1078
  if (!appointment) return Response.json({ error: "Appointment not found" }, { status: 404 });
990
1079
  const hasPayment = hasPendingPayment(appointment.paymentId, appointment.paymentStatus);
991
- const result = await (0, import_scheduling12.cancelAppointment)(db, { appointmentId: id, cancelledBy: "staff", reason });
1080
+ const result = await (0, import_scheduling13.cancelAppointment)(db, { appointmentId: id, cancelledBy: "staff", reason });
992
1081
  await writeRefundStatusAfterCancel(host, db, { appointmentId: id, hasPayment, clientName: appointment.clientName });
993
1082
  if (hasPayment) {
994
1083
  await host.activity.log(db, {
@@ -1008,7 +1097,7 @@ async function cancelByStaff(request, { host, params }) {
1008
1097
  const baseUrl = host.appUrl();
1009
1098
  if (baseUrl) {
1010
1099
  try {
1011
- await (0, import_scheduling12.queueStaffNotification)(db, id, "CANCELLATION", baseUrl);
1100
+ await (0, import_scheduling13.queueStaffNotification)(db, id, "CANCELLATION", baseUrl, { brand: Boolean(host.brand) });
1012
1101
  } catch (error) {
1013
1102
  await host.activity.log(db, {
1014
1103
  action: "scheduling.staff_notification_failed",
@@ -1035,7 +1124,7 @@ async function cancelByStaff(request, { host, params }) {
1035
1124
  });
1036
1125
  return Response.json(result);
1037
1126
  } catch (error) {
1038
- if (error instanceof import_scheduling12.SchedulingNotFoundError) {
1127
+ if (error instanceof import_scheduling13.SchedulingNotFoundError) {
1039
1128
  return Response.json({ error: error.message, ref: error.ref }, { status: 404 });
1040
1129
  }
1041
1130
  const ref = getErrorRef(error);
@@ -1240,7 +1329,7 @@ function finishOutlookConnection(request, { host }) {
1240
1329
  }
1241
1330
 
1242
1331
  // src/handlers/appointment-cancel-sync.ts
1243
- var import_scheduling13 = require("@ordinatio/scheduling");
1332
+ var import_scheduling14 = require("@ordinatio/scheduling");
1244
1333
  var import_zod2 = require("zod");
1245
1334
  var Schema2 = import_zod2.z.object({
1246
1335
  source: import_zod2.z.enum(["google", "outlook"]),
@@ -1283,13 +1372,13 @@ async function cancelFromCalendarSync(request, { host, params }) {
1283
1372
  return Response.json({ error: "Appointment not available for sync" }, { status: 503 });
1284
1373
  }
1285
1374
  try {
1286
- await (0, import_scheduling13.cancelAppointment)(db, {
1375
+ await (0, import_scheduling14.cancelAppointment)(db, {
1287
1376
  appointmentId: id,
1288
1377
  cancelledBy: "system",
1289
1378
  reason: reason ?? `Cancelled via ${source === "google" ? "Google" : "Outlook"} Calendar`
1290
1379
  });
1291
1380
  } catch (error) {
1292
- if (error instanceof import_scheduling13.SchedulingNotFoundError) {
1381
+ if (error instanceof import_scheduling14.SchedulingNotFoundError) {
1293
1382
  return Response.json({ error: "Appointment not found", ref: error.ref }, { status: 404 });
1294
1383
  }
1295
1384
  const ref = getErrorRef(error);
@@ -1323,7 +1412,7 @@ async function cancelFromCalendarSync(request, { host, params }) {
1323
1412
  await host.workerCommands.queue(source === "google" ? "delete-from-outlook" : "delete-from-google", { appointmentId: id });
1324
1413
  const baseUrl = host.appUrl();
1325
1414
  if (baseUrl) {
1326
- await (0, import_scheduling13.queueImmediateNotification)(db, id, "CANCELLATION", baseUrl).catch(
1415
+ await (0, import_scheduling14.queueImmediateNotification)(db, id, "CANCELLATION", baseUrl, { brand: Boolean(host.brand) }).catch(
1327
1416
  (err) => console.warn("[cancel-sync] Failed to queue cancellation notification:", id, err instanceof Error ? err.message : err)
1328
1417
  );
1329
1418
  }
@@ -1336,10 +1425,10 @@ async function cancelFromCalendarSync(request, { host, params }) {
1336
1425
  }
1337
1426
 
1338
1427
  // src/handlers/appointment-approve.ts
1339
- var import_scheduling14 = require("@ordinatio/scheduling");
1428
+ var import_scheduling15 = require("@ordinatio/scheduling");
1340
1429
  async function rejectAppointment(host, db, organizationId, appointment, reason) {
1341
1430
  const { id } = appointment;
1342
- const result = await (0, import_scheduling14.cancelAppointment)(db, {
1431
+ const result = await (0, import_scheduling15.cancelAppointment)(db, {
1343
1432
  appointmentId: id,
1344
1433
  cancelledBy: "staff",
1345
1434
  reason: reason || "Appointment request rejected"
@@ -1421,10 +1510,10 @@ async function approveOrReject(request, { host, params }) {
1421
1510
  if (confirmed.count === 0) {
1422
1511
  return Response.json({ error: "Appointment was already processed by a concurrent request" }, { status: 409 });
1423
1512
  }
1424
- await (0, import_scheduling14.cancelPendingNotifications)(db, id);
1513
+ await (0, import_scheduling15.cancelPendingNotifications)(db, id);
1425
1514
  const baseUrl = host.appUrl();
1426
1515
  if (!baseUrl) throw new Error("NEXT_PUBLIC_APP_URL is required");
1427
- await (0, import_scheduling14.scheduleNotifications)(db, id, baseUrl);
1516
+ await (0, import_scheduling15.scheduleNotifications)(db, id, baseUrl, { brand: Boolean(host.brand) });
1428
1517
  await host.availabilityCache.invalidate(appointment.calendarId);
1429
1518
  await host.events.emit(organizationId, "appointment.confirmed", { appointmentId: id });
1430
1519
  await host.activity.log(db, {
@@ -1432,7 +1521,7 @@ async function approveOrReject(request, { host, params }) {
1432
1521
  description: `approved ${appointment.clientName}'s appointment`,
1433
1522
  metadata: { appointmentId: id, clientName: appointment.clientName }
1434
1523
  });
1435
- const confirmedAppointment = await (0, import_scheduling14.getAppointment)(db, id);
1524
+ const confirmedAppointment = await (0, import_scheduling15.getAppointment)(db, id);
1436
1525
  return Response.json({ success: true, status: "CONFIRMED", appointment: confirmedAppointment });
1437
1526
  } catch (error) {
1438
1527
  if (getErrorCode(error) === "SCHED_306") {
@@ -1445,7 +1534,7 @@ async function approveOrReject(request, { host, params }) {
1445
1534
  }
1446
1535
 
1447
1536
  // src/handlers/appointment-reschedule.ts
1448
- var import_scheduling15 = require("@ordinatio/scheduling");
1537
+ var import_scheduling16 = require("@ordinatio/scheduling");
1449
1538
  var RESCHEDULE_BLOCKER_CODES = ["SCHED_301", "SCHED_307", "SCHED_309", "SCHED_802"];
1450
1539
  async function rescheduleByStaff(request, { host, params }) {
1451
1540
  try {
@@ -1473,21 +1562,21 @@ async function rescheduleByStaff(request, { host, params }) {
1473
1562
  if (newTime < /* @__PURE__ */ new Date()) {
1474
1563
  return Response.json({ error: "Cannot reschedule to a past time" }, { status: 400 });
1475
1564
  }
1476
- const result = await (0, import_scheduling15.rescheduleAppointment)(db, {
1565
+ const result = await (0, import_scheduling16.rescheduleAppointment)(db, {
1477
1566
  appointmentId: id,
1478
1567
  newStartTime: newTime,
1479
1568
  reason: "Rescheduled via calendar drag"
1480
1569
  });
1481
1570
  const baseUrl = host.appUrl();
1482
1571
  if (!baseUrl) throw new Error("NEXT_PUBLIC_APP_URL is required");
1483
- await (0, import_scheduling15.queueImmediateNotification)(db, id, "RESCHEDULE", baseUrl);
1572
+ await (0, import_scheduling16.queueImmediateNotification)(db, id, "RESCHEDULE", baseUrl, { brand: Boolean(host.brand) });
1484
1573
  try {
1485
- await (0, import_scheduling15.scheduleNotifications)(db, id, baseUrl, { excludeTriggers: ["CONFIRMATION"] });
1574
+ await (0, import_scheduling16.scheduleNotifications)(db, id, baseUrl, { excludeTriggers: ["CONFIRMATION"], brand: Boolean(host.brand) });
1486
1575
  } catch (error) {
1487
1576
  console.warn("[reschedule] scheduleNotifications failed:", error instanceof Error ? error.message : error);
1488
1577
  }
1489
1578
  try {
1490
- await (0, import_scheduling15.queueStaffNotification)(db, id, "RESCHEDULE", baseUrl);
1579
+ await (0, import_scheduling16.queueStaffNotification)(db, id, "RESCHEDULE", baseUrl, { brand: Boolean(host.brand) });
1491
1580
  } catch (error) {
1492
1581
  await host.activity.log(db, {
1493
1582
  action: "scheduling.staff_notification_failed",
@@ -1525,8 +1614,8 @@ async function rescheduleByStaff(request, { host, params }) {
1525
1614
  });
1526
1615
  return Response.json(result);
1527
1616
  } catch (error) {
1528
- if (error instanceof import_scheduling15.SchedulingValidationError) return Response.json({ error: error.message }, { status: 400 });
1529
- if (error instanceof import_scheduling15.SchedulingNotFoundError) return Response.json({ error: error.message }, { status: 404 });
1617
+ if (error instanceof import_scheduling16.SchedulingValidationError) return Response.json({ error: error.message }, { status: 400 });
1618
+ if (error instanceof import_scheduling16.SchedulingNotFoundError) return Response.json({ error: error.message }, { status: 404 });
1530
1619
  const errorCode = getErrorCode(error) ?? "";
1531
1620
  const status = errorCode === "SCHED_306" ? 400 : RESCHEDULE_BLOCKER_CODES.includes(errorCode) ? 409 : 500;
1532
1621
  return Response.json({ error: getErrorMessage(error, "Failed to reschedule") }, { status });
@@ -1534,7 +1623,7 @@ async function rescheduleByStaff(request, { host, params }) {
1534
1623
  }
1535
1624
 
1536
1625
  // src/handlers/appointment-reassign.ts
1537
- var import_scheduling16 = require("@ordinatio/scheduling");
1626
+ var import_scheduling17 = require("@ordinatio/scheduling");
1538
1627
  var import_zod3 = require("zod");
1539
1628
  var REASSIGNABLE_STATUSES = ["PENDING", "CONFIRMED"];
1540
1629
  var REASSIGN_MAX_ATTEMPTS = 2;
@@ -1585,7 +1674,7 @@ async function reassignAppointment(request, { host, params }) {
1585
1674
  if (!current || !REASSIGNABLE_STATUSES.includes(current.status)) {
1586
1675
  return { outcome: "statusChanged", currentStatus: current?.status ?? "unknown" };
1587
1676
  }
1588
- const available = await (0, import_scheduling16.isSlotAvailable)(txDb, calendarId, current.startTime, current.duration, id);
1677
+ const available = await (0, import_scheduling17.isSlotAvailable)(txDb, calendarId, current.startTime, current.duration, id);
1589
1678
  if (!available) return { outcome: "conflict" };
1590
1679
  const updated2 = await tx.appointment.update({
1591
1680
  where: { id, status: { in: [...REASSIGNABLE_STATUSES] } },
@@ -1611,14 +1700,14 @@ async function reassignAppointment(request, { host, params }) {
1611
1700
  };
1612
1701
  const result = await attemptReassign();
1613
1702
  if (result.outcome === "statusChanged") {
1614
- const diagnostic = (0, import_scheduling16.schedError)("SCHED_309", { appointmentId: id, calendarId, currentStatus: result.currentStatus });
1703
+ const diagnostic = (0, import_scheduling17.schedError)("SCHED_309", { appointmentId: id, calendarId, currentStatus: result.currentStatus });
1615
1704
  return Response.json(
1616
1705
  { error: "Appointment status changed before the reassignment could commit", ref: diagnostic.ref },
1617
1706
  { status: 409 }
1618
1707
  );
1619
1708
  }
1620
1709
  if (result.outcome === "conflict") {
1621
- const diagnostic = (0, import_scheduling16.schedError)("SCHED_301", { appointmentId: id, calendarId });
1710
+ const diagnostic = (0, import_scheduling17.schedError)("SCHED_301", { appointmentId: id, calendarId });
1622
1711
  return Response.json(
1623
1712
  { error: "Target calendar is not available at this appointment's time", ref: diagnostic.ref },
1624
1713
  { status: 409 }
@@ -1753,10 +1842,10 @@ async function listNotifications(request, { host, params }) {
1753
1842
  noRateLimit: true
1754
1843
  });
1755
1844
  if (staff instanceof Response) return staff;
1756
- const { db } = staff;
1845
+ const { db, organizationId } = staff;
1757
1846
  const { id } = params;
1758
1847
  if (!await staff.canSeeAppointment(id)) return NOT_FOUND3();
1759
- const appointment = await db.appointment.findUnique({ where: { id }, select: { id: true } });
1848
+ const appointment = await verifyAppointmentOwnership(db, id, organizationId);
1760
1849
  if (!appointment) return NOT_FOUND3();
1761
1850
  const notifications = await db.scheduledNotification.findMany({
1762
1851
  where: { appointmentId: id },
@@ -1781,7 +1870,7 @@ async function listNotifications(request, { host, params }) {
1781
1870
  }
1782
1871
 
1783
1872
  // src/handlers/appointment-no-show.ts
1784
- var import_scheduling17 = require("@ordinatio/scheduling");
1873
+ var import_scheduling18 = require("@ordinatio/scheduling");
1785
1874
  async function markAppointmentNoShow(request, { host, params }) {
1786
1875
  try {
1787
1876
  const staff = await requireAdminStaff(host, request, {
@@ -1798,7 +1887,7 @@ async function markAppointmentNoShow(request, { host, params }) {
1798
1887
  }
1799
1888
  const appointment = await verifyAppointmentOwnership(db, id, organizationId);
1800
1889
  if (!appointment) return Response.json({ error: "Appointment not found" }, { status: 404 });
1801
- const result = await (0, import_scheduling17.markNoShow)(db, { appointmentId: id });
1890
+ const result = await (0, import_scheduling18.markNoShow)(db, { appointmentId: id });
1802
1891
  await host.events.emit(organizationId, "appointment.no_show", { appointmentId: id });
1803
1892
  await host.activity.log(db, {
1804
1893
  action: "scheduling.appointment_no_show",
@@ -1807,7 +1896,7 @@ async function markAppointmentNoShow(request, { host, params }) {
1807
1896
  });
1808
1897
  return Response.json(result);
1809
1898
  } catch (error) {
1810
- if (error instanceof import_scheduling17.SchedulingNotFoundError) {
1899
+ if (error instanceof import_scheduling18.SchedulingNotFoundError) {
1811
1900
  return Response.json({ error: error.message, ref: error.ref }, { status: 404 });
1812
1901
  }
1813
1902
  const ref = getErrorRef(error);
@@ -1817,7 +1906,7 @@ async function markAppointmentNoShow(request, { host, params }) {
1817
1906
  }
1818
1907
 
1819
1908
  // src/handlers/appointment-collect-balance.ts
1820
- var import_scheduling20 = require("@ordinatio/scheduling");
1909
+ var import_scheduling21 = require("@ordinatio/scheduling");
1821
1910
 
1822
1911
  // src/payments/balance/eligibility.ts
1823
1912
  var BALANCE_BLOCKED_APPOINTMENT_STATUS = "CANCELLED";
@@ -1913,7 +2002,7 @@ function resolveBalanceEligibility(appointment, organizationId) {
1913
2002
  }
1914
2003
 
1915
2004
  // src/payments/balance/record-intent.ts
1916
- var import_scheduling18 = require("@ordinatio/scheduling");
2005
+ var import_scheduling19 = require("@ordinatio/scheduling");
1917
2006
  var BALANCE_OUTCOME_TRACE = {
1918
2007
  cancelled: {
1919
2008
  action: "scheduling.balance_intent_cancelled",
@@ -1956,7 +2045,7 @@ async function recordBalanceIntent(db, payments, target) {
1956
2045
  data: { balancePaymentId: intentId }
1957
2046
  });
1958
2047
  } catch (writeError) {
1959
- const diagnostic = (0, import_scheduling18.schedError)("SCHED_605", {
2048
+ const diagnostic = (0, import_scheduling19.schedError)("SCHED_605", {
1960
2049
  error: writeError,
1961
2050
  appointmentId,
1962
2051
  paymentIntentId: intentId,
@@ -1978,7 +2067,7 @@ async function recordBalanceIntent(db, payments, target) {
1978
2067
  select: { balancePaymentId: true, status: true, refundStatus: true, paymentStatus: true }
1979
2068
  });
1980
2069
  } catch (rereadError) {
1981
- const diagnostic = (0, import_scheduling18.schedError)("SCHED_605", {
2070
+ const diagnostic = (0, import_scheduling19.schedError)("SCHED_605", {
1982
2071
  error: rereadError,
1983
2072
  appointmentId,
1984
2073
  paymentIntentId: intentId,
@@ -1995,7 +2084,7 @@ async function recordBalanceIntent(db, payments, target) {
1995
2084
  const stillEligible = current !== null && !isBalanceBlockedByStatus(current.status) && !hasBalanceRefundStarted(current.refundStatus);
1996
2085
  if (current?.balancePaymentId === intentId) {
1997
2086
  if (stillEligible) return { ok: true };
1998
- const diagnostic = (0, import_scheduling18.schedError)("SCHED_605", {
2087
+ const diagnostic = (0, import_scheduling19.schedError)("SCHED_605", {
1999
2088
  appointmentId,
2000
2089
  paymentIntentId: intentId,
2001
2090
  status: current.status,
@@ -2037,7 +2126,7 @@ async function recordBalanceIntent(db, payments, target) {
2037
2126
  outcome = "cancel-failed";
2038
2127
  }
2039
2128
  if (outcome !== cancelledOutcome) {
2040
- const diagnostic = (0, import_scheduling18.schedError)("SCHED_605", {
2129
+ const diagnostic = (0, import_scheduling19.schedError)("SCHED_605", {
2041
2130
  error: cancelError,
2042
2131
  appointmentId,
2043
2132
  paymentIntentId: intentId,
@@ -2085,7 +2174,7 @@ async function recordBalanceIntent(db, payments, target) {
2085
2174
  }
2086
2175
 
2087
2176
  // src/payments/balance/create-intent.ts
2088
- var import_scheduling19 = require("@ordinatio/scheduling");
2177
+ var import_scheduling20 = require("@ordinatio/scheduling");
2089
2178
 
2090
2179
  // src/payments/unverified-payment-error.ts
2091
2180
  var UnverifiedPaymentError = class extends Error {
@@ -2131,7 +2220,7 @@ async function createBalanceIntent(payments, input, appointmentId) {
2131
2220
  });
2132
2221
  } catch (error) {
2133
2222
  if (error instanceof UnverifiedPaymentError) {
2134
- const diagnostic2 = (0, import_scheduling19.schedError)("SCHED_605", {
2223
+ const diagnostic2 = (0, import_scheduling20.schedError)("SCHED_605", {
2135
2224
  error,
2136
2225
  appointmentId,
2137
2226
  paymentIntentId: error.paymentId,
@@ -2151,7 +2240,7 @@ async function createBalanceIntent(payments, input, appointmentId) {
2151
2240
  return { paymentId: result.paymentId, clientSecret: result.clientSecret ?? null };
2152
2241
  }
2153
2242
  if (result.code === "IN_PROGRESS") {
2154
- const diagnostic2 = (0, import_scheduling19.schedError)("SCHED_605", {
2243
+ const diagnostic2 = (0, import_scheduling20.schedError)("SCHED_605", {
2155
2244
  error: result.error,
2156
2245
  appointmentId,
2157
2246
  key,
@@ -2161,7 +2250,7 @@ async function createBalanceIntent(payments, input, appointmentId) {
2161
2250
  throw new BalanceRequestInProgressError(diagnostic2.ref);
2162
2251
  }
2163
2252
  if (result.code === "KEY_REUSED") {
2164
- const diagnostic2 = (0, import_scheduling19.schedError)("SCHED_605", {
2253
+ const diagnostic2 = (0, import_scheduling20.schedError)("SCHED_605", {
2165
2254
  error: result.error,
2166
2255
  appointmentId,
2167
2256
  abandonedKey: key,
@@ -2177,7 +2266,7 @@ async function createBalanceIntent(payments, input, appointmentId) {
2177
2266
  if (result.code === "CANCELED") continue;
2178
2267
  throw new Error(result.error ?? "The payment provider did not create the balance payment");
2179
2268
  }
2180
- const diagnostic = (0, import_scheduling19.schedError)("SCHED_605", {
2269
+ const diagnostic = (0, import_scheduling20.schedError)("SCHED_605", {
2181
2270
  appointmentId,
2182
2271
  phase: "balance-key-generations-exhausted",
2183
2272
  generations: MAX_KEY_GENERATIONS2
@@ -2269,7 +2358,7 @@ async function collectAppointmentBalance(request, { host, params }) {
2269
2358
  if (error instanceof BalanceRequestInProgressError || error instanceof BalanceIntentGenerationsExhaustedError) {
2270
2359
  return Response.json({ error: error.message, ref: error.ref }, { status: 409 });
2271
2360
  }
2272
- const diagnostic = (0, import_scheduling20.schedError)("SCHED_605", { error, appointmentId });
2361
+ const diagnostic = (0, import_scheduling21.schedError)("SCHED_605", { error, appointmentId });
2273
2362
  console.error("[POST /collect-balance]", diagnostic.ref, error instanceof Error ? error.message : error);
2274
2363
  return Response.json({ error: "Failed to create balance payment", ref: diagnostic.ref }, { status: 500 });
2275
2364
  }
@@ -2279,7 +2368,7 @@ async function collectAppointmentBalance(request, { host, params }) {
2279
2368
  var import_zod6 = require("zod");
2280
2369
 
2281
2370
  // src/payments/refund/refund-status.ts
2282
- var import_scheduling21 = require("@ordinatio/scheduling");
2371
+ var import_scheduling22 = require("@ordinatio/scheduling");
2283
2372
  var REFUND_STATUS_BUCKET = {
2284
2373
  PENDING_REVIEW: "retryable",
2285
2374
  REFUND_FAILED: "retryable",
@@ -2301,7 +2390,7 @@ var CREDIT_REFUSED_NEXT_STEP = "Retry the refund to resolve the remaining balanc
2301
2390
  var CREDIT_REFUSED_NO_AMOUNT_NEXT_STEP = "Check the refunded amount in Stripe, then retry the refund or resolve this manually before issuing a credit.";
2302
2391
  function checkCreditGuard(action, refundAmount, refundStatus) {
2303
2392
  if (refundStatus == null) {
2304
- const diagnostic = (0, import_scheduling21.schedError)("SCHED_610", {
2393
+ const diagnostic = (0, import_scheduling22.schedError)("SCHED_610", {
2305
2394
  action,
2306
2395
  refundAmount,
2307
2396
  error: "checkCreditGuard was called without a refundStatus"
@@ -2347,10 +2436,10 @@ function checkCreditGuard(action, refundAmount, refundStatus) {
2347
2436
  }
2348
2437
 
2349
2438
  // src/money.ts
2350
- var import_scheduling22 = require("@ordinatio/scheduling");
2439
+ var import_scheduling23 = require("@ordinatio/scheduling");
2351
2440
  function decimalToCents(value, field = "unknown") {
2352
2441
  if (value === null || value === void 0) {
2353
- throw new import_scheduling22.SchedulingValidationError(
2442
+ throw new import_scheduling23.SchedulingValidationError(
2354
2443
  `Could not convert ${field} to cents \u2014 value is ${value}`,
2355
2444
  "SCHED_406",
2356
2445
  { field, value }
@@ -2358,7 +2447,7 @@ function decimalToCents(value, field = "unknown") {
2358
2447
  }
2359
2448
  const cents = Math.round(Number(value) * 100);
2360
2449
  if (!Number.isFinite(cents)) {
2361
- throw new import_scheduling22.SchedulingValidationError(
2450
+ throw new import_scheduling23.SchedulingValidationError(
2362
2451
  `Could not convert ${field} to cents \u2014 value is not numeric`,
2363
2452
  "SCHED_406",
2364
2453
  { field, value }
@@ -2369,7 +2458,7 @@ function decimalToCents(value, field = "unknown") {
2369
2458
 
2370
2459
  // src/payments/refund/refund-leg.ts
2371
2460
  var import_node_crypto2 = require("crypto");
2372
- var import_scheduling23 = require("@ordinatio/scheduling");
2461
+ var import_scheduling24 = require("@ordinatio/scheduling");
2373
2462
  async function attemptLegRefund(payments, paymentIntentId, idempotencyKeySuffix, appointmentId, errorCode, logLabel) {
2374
2463
  const baseKey = `refund:${appointmentId}:${idempotencyKeySuffix}`;
2375
2464
  let idempotencyKey = baseKey;
@@ -2402,7 +2491,7 @@ async function attemptLegRefund(payments, paymentIntentId, idempotencyKeySuffix,
2402
2491
  return { succeeded: true, amountCents: null };
2403
2492
  }
2404
2493
  if (result.code === "IN_PROGRESS") {
2405
- const inFlight = (0, import_scheduling23.schedError)(errorCode, { error: result.error, appointmentId, paymentIntentId, kind: "idempotency_key_in_use" });
2494
+ const inFlight = (0, import_scheduling24.schedError)(errorCode, { error: result.error, appointmentId, paymentIntentId, kind: "idempotency_key_in_use" });
2406
2495
  console.warn(
2407
2496
  `[resolve-refund] ${logLabel} leg is already being refunded by another in-flight request (idempotency key in use) \u2014 its outcome is unknown, so this leg is recorded as retryable:`,
2408
2497
  inFlight.ref,
@@ -2428,7 +2517,7 @@ async function attemptLegRefund(payments, paymentIntentId, idempotencyKeySuffix,
2428
2517
  }
2429
2518
  }
2430
2519
  function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempotencyKey, retriedAfterReplay, failure3) {
2431
- const diagnostic = (0, import_scheduling23.schedError)(errorCode, { error: failure3.error, appointmentId, paymentIntentId });
2520
+ const diagnostic = (0, import_scheduling24.schedError)(errorCode, { error: failure3.error, appointmentId, paymentIntentId });
2432
2521
  console.error(
2433
2522
  `[resolve-refund] ${logLabel} refund failed${retriedAfterReplay ? " (after a fresh-key re-attempt)" : ""} \u2014 manual refund may be required:`,
2434
2523
  diagnostic.ref,
@@ -2442,7 +2531,7 @@ function failedLeg(errorCode, logLabel, appointmentId, paymentIntentId, idempote
2442
2531
  }
2443
2532
 
2444
2533
  // src/payments/refund/persist-refund-outcome.ts
2445
- var import_scheduling24 = require("@ordinatio/scheduling");
2534
+ var import_scheduling25 = require("@ordinatio/scheduling");
2446
2535
  var WEBHOOK_RACE_OUTCOMES = ["REFUNDED", "PARTIAL_REFUND"];
2447
2536
  var SUCCESS_RANK = {
2448
2537
  REFUND_FAILED: 0,
@@ -2487,7 +2576,7 @@ async function persistRefundOutcome(db, id, refundOutcome, refundAmount, legs) {
2487
2576
  });
2488
2577
  } catch (writeErr) {
2489
2578
  const dbMessage = writeErr instanceof Error ? writeErr.message : String(writeErr);
2490
- const diagnostic = (0, import_scheduling24.schedError)("SCHED_610", {
2579
+ const diagnostic = (0, import_scheduling25.schedError)("SCHED_610", {
2491
2580
  error: writeErr,
2492
2581
  dbMessage,
2493
2582
  appointmentId: id,
@@ -2511,7 +2600,7 @@ async function persistRefundOutcome(db, id, refundOutcome, refundAmount, legs) {
2511
2600
  }
2512
2601
  if (writeResult.count === 0) {
2513
2602
  const buildLostRaceError = () => {
2514
- const diagnostic = (0, import_scheduling24.schedError)("SCHED_610", {
2603
+ const diagnostic = (0, import_scheduling25.schedError)("SCHED_610", {
2515
2604
  appointmentId: id,
2516
2605
  phase: "persist-cas-lost-race",
2517
2606
  refundOutcome,
@@ -2550,7 +2639,7 @@ async function persistRefundOutcome(db, id, refundOutcome, refundAmount, legs) {
2550
2639
  if (reconcileResult.count === 0) {
2551
2640
  throw buildLostRaceError();
2552
2641
  }
2553
- const reconcileDiagnostic = (0, import_scheduling24.schedError)("SCHED_610", {
2642
+ const reconcileDiagnostic = (0, import_scheduling25.schedError)("SCHED_610", {
2554
2643
  appointmentId: id,
2555
2644
  phase: "persist-cas-reconciled",
2556
2645
  refundOutcome,
@@ -2649,7 +2738,7 @@ async function executeRefundLegs(db, id, preClaimSnapshot, payments) {
2649
2738
  }
2650
2739
 
2651
2740
  // src/payments/refund/refund-housekeeping.ts
2652
- var import_scheduling25 = require("@ordinatio/scheduling");
2741
+ var import_scheduling26 = require("@ordinatio/scheduling");
2653
2742
  async function runHousekeeping(db, activity, appointment, id, action, newRefundStatus, userId) {
2654
2743
  const isTerminalSuccess = TERMINAL_SUCCESS_STATUSES.includes(newRefundStatus);
2655
2744
  try {
@@ -2665,7 +2754,7 @@ async function runHousekeeping(db, activity, appointment, id, action, newRefundS
2665
2754
  });
2666
2755
  return void 0;
2667
2756
  } catch (err) {
2668
- const diagnostic = (0, import_scheduling25.schedError)("SCHED_606", { error: err, appointmentId: id, phase: "housekeeping" });
2757
+ const diagnostic = (0, import_scheduling26.schedError)("SCHED_606", { error: err, appointmentId: id, phase: "housekeeping" });
2669
2758
  console.error(
2670
2759
  isTerminalSuccess ? "[resolve-refund] Sticky-activity resolution or audit log failed after a successful refund/credit:" : "[resolve-refund] Sticky-activity resolution or audit log failed after a non-terminal refund outcome (REFUND_FAILED/PARTIAL_REFUND):",
2671
2760
  diagnostic.ref,
@@ -2750,9 +2839,9 @@ async function evaluatePreClaimState(input) {
2750
2839
  }
2751
2840
 
2752
2841
  // src/payments/refund/refund-failure-response.ts
2753
- var import_scheduling26 = require("@ordinatio/scheduling");
2842
+ var import_scheduling27 = require("@ordinatio/scheduling");
2754
2843
  function refundFailureResponse({ error, id, stripeMayHaveMoved }) {
2755
- const diagnostic = (0, import_scheduling26.schedError)("SCHED_610", { error, appointmentId: id, stripeMayHaveMoved });
2844
+ const diagnostic = (0, import_scheduling27.schedError)("SCHED_610", { error, appointmentId: id, stripeMayHaveMoved });
2756
2845
  console.error("[POST /resolve-refund]", diagnostic.ref, error instanceof Error ? error.message : error);
2757
2846
  if (!stripeMayHaveMoved) {
2758
2847
  return Response.json({ error: "Failed to resolve refund", ref: diagnostic.ref }, { status: 500 });
@@ -3229,6 +3318,57 @@ var CreateWebhookEndpointSchema = import_zod11.z.object({
3229
3318
  description: optionalString(200, "Description")
3230
3319
  });
3231
3320
 
3321
+ // src/schemas/routing.schema.ts
3322
+ var import_zod12 = require("zod");
3323
+ var bounded = {
3324
+ name: import_zod12.z.string().max(200),
3325
+ slug: import_zod12.z.string().max(100),
3326
+ description: import_zod12.z.string().max(1e3).nullable().optional(),
3327
+ isActive: import_zod12.z.boolean().optional(),
3328
+ questions: import_zod12.z.array(import_zod12.z.unknown()).max(30),
3329
+ rules: import_zod12.z.array(import_zod12.z.unknown()).max(60),
3330
+ fallback: import_zod12.z.unknown()
3331
+ };
3332
+ var CreateRoutingFormSchema = import_zod12.z.object({
3333
+ ...bounded,
3334
+ fallback: import_zod12.z.record(import_zod12.z.string(), import_zod12.z.unknown())
3335
+ });
3336
+ var UpdateRoutingFormSchema = import_zod12.z.object({ ...bounded, fallback: import_zod12.z.record(import_zod12.z.string(), import_zod12.z.unknown()) }).partial().refine((value) => Object.keys(value).length > 0, { message: "Send at least one field to change" });
3337
+ var RouteClientSchema = import_zod12.z.object({
3338
+ slug: import_zod12.z.string().min(1).max(100),
3339
+ orgSlug: import_zod12.z.string().min(1).max(100).optional(),
3340
+ answers: import_zod12.z.record(import_zod12.z.string(), import_zod12.z.unknown())
3341
+ });
3342
+ var TestRoutingFormSchema = import_zod12.z.object({ answers: import_zod12.z.record(import_zod12.z.string(), import_zod12.z.unknown()) });
3343
+
3344
+ // src/schemas/privacy.schema.ts
3345
+ var import_zod13 = require("zod");
3346
+ var subject = {
3347
+ email: import_zod13.z.string().max(320).optional(),
3348
+ clientId: import_zod13.z.string().max(200).optional()
3349
+ };
3350
+ var namesSomeone = (value) => Boolean(value.email?.trim() || value.clientId?.trim());
3351
+ var namesSomeoneMessage = { message: "Send an email address, a client id, or both" };
3352
+ var PrivacySubjectSchema = import_zod13.z.object(subject).strict().refine(namesSomeone, namesSomeoneMessage);
3353
+ var PrivacyEraseSchema = import_zod13.z.object({ ...subject, confirm: import_zod13.z.boolean().optional() }).strict().refine(namesSomeone, namesSomeoneMessage);
3354
+
3355
+ // src/schemas/brand.schema.ts
3356
+ var import_zod14 = require("zod");
3357
+ var optionalText = (max) => import_zod14.z.string().max(max).nullable().optional();
3358
+ var BrandSchema = import_zod14.z.object({
3359
+ displayName: import_zod14.z.string().max(200),
3360
+ logoUrl: optionalText(1e3),
3361
+ primaryColor: optionalText(20),
3362
+ accentColor: optionalText(20),
3363
+ backgroundColor: optionalText(20),
3364
+ textColor: optionalText(20),
3365
+ fontFamily: optionalText(200),
3366
+ footerText: optionalText(1e3),
3367
+ replyToEmail: optionalText(400),
3368
+ fromName: optionalText(200),
3369
+ fromEmail: optionalText(400)
3370
+ }).strict();
3371
+
3232
3372
  // src/pagination.ts
3233
3373
  var DEFAULT_LIMIT = 50;
3234
3374
  var MAX_LIMIT = 200;
@@ -3250,12 +3390,12 @@ function parsePagination(request, maxLimit = MAX_LIMIT, defaultLimit = DEFAULT_L
3250
3390
  }
3251
3391
 
3252
3392
  // src/validation.ts
3253
- var import_zod12 = require("zod");
3393
+ var import_zod15 = require("zod");
3254
3394
  async function parseBody(request, schema) {
3255
3395
  try {
3256
3396
  return { success: true, data: schema.parse(await request.json()) };
3257
3397
  } catch (error) {
3258
- if (error instanceof import_zod12.ZodError) {
3398
+ if (error instanceof import_zod15.ZodError) {
3259
3399
  const details = error.issues.map((issue) => ({ field: issue.path.join("."), message: issue.message }));
3260
3400
  return { success: false, response: Response.json({ error: "Validation failed", details }, { status: 400 }) };
3261
3401
  }
@@ -3269,7 +3409,7 @@ function validateData(data, schema) {
3269
3409
  try {
3270
3410
  return { success: true, data: schema.parse(data) };
3271
3411
  } catch (error) {
3272
- if (error instanceof import_zod12.ZodError) {
3412
+ if (error instanceof import_zod15.ZodError) {
3273
3413
  return { success: false, errors: error.issues.map((issue) => ({ field: issue.path.join("."), message: issue.message })) };
3274
3414
  }
3275
3415
  return { success: false, errors: [{ field: "", message: "Validation failed" }] };
@@ -3739,7 +3879,7 @@ async function updatePackagePurchase(request, { host, params }) {
3739
3879
  }
3740
3880
 
3741
3881
  // src/handlers/admin-group-sessions.ts
3742
- var import_scheduling27 = require("@ordinatio/scheduling");
3882
+ var import_scheduling28 = require("@ordinatio/scheduling");
3743
3883
  var MAX_RANGE_MS = 366 * 24 * 60 * 60 * 1e3;
3744
3884
  async function listGroupSessions(request, { host }) {
3745
3885
  try {
@@ -3757,29 +3897,29 @@ async function listGroupSessions(request, { host }) {
3757
3897
  return Response.json({ error: "Invalid date format \u2014 use ISO 8601" }, { status: 400 });
3758
3898
  }
3759
3899
  if (startDate >= endDate) {
3760
- const err = (0, import_scheduling27.schedError)("SCHED_310", { startDateStr, endDateStr });
3900
+ const err = (0, import_scheduling28.schedError)("SCHED_310", { startDateStr, endDateStr });
3761
3901
  return Response.json({ error: "startDate must be before endDate", ref: err.ref }, { status: 400 });
3762
3902
  }
3763
3903
  if (endDate.getTime() - startDate.getTime() > MAX_RANGE_MS) {
3764
- const err = (0, import_scheduling27.schedError)("SCHED_312", { startDateStr, endDateStr });
3904
+ const err = (0, import_scheduling28.schedError)("SCHED_312", { startDateStr, endDateStr });
3765
3905
  return Response.json({ error: "Date range exceeds maximum allowed (366 days)", ref: err.ref }, { status: 400 });
3766
3906
  }
3767
3907
  const calendarId = params.get("calendarId") || void 0;
3768
3908
  const visibleCalendarIds = await staff.visibleCalendarIds();
3769
- const { sessions, hasMore } = await (0, import_scheduling27.getGroupSessions)(staff.db, { startDate, endDate, calendarId, visibleCalendarIds });
3909
+ const { sessions, hasMore } = await (0, import_scheduling28.getGroupSessions)(staff.db, { startDate, endDate, calendarId, visibleCalendarIds, organizationId: staff.organizationId });
3770
3910
  return Response.json({ sessions, total: sessions.length, hasMore });
3771
3911
  } catch (error) {
3772
- const err = (0, import_scheduling27.schedError)("SCHED_311", { error });
3912
+ const err = (0, import_scheduling28.schedError)("SCHED_311", { error });
3773
3913
  console.error("[group-sessions]", err.ref, error);
3774
3914
  return Response.json({ error: "Failed to fetch group sessions", ref: err.ref }, { status: 500 });
3775
3915
  }
3776
3916
  }
3777
3917
 
3778
3918
  // src/handlers/admin-recurring.ts
3779
- var import_scheduling30 = require("@ordinatio/scheduling");
3919
+ var import_scheduling31 = require("@ordinatio/scheduling");
3780
3920
 
3781
3921
  // src/recurring/series-side-effects.ts
3782
- var import_scheduling28 = require("@ordinatio/scheduling");
3922
+ var import_scheduling29 = require("@ordinatio/scheduling");
3783
3923
 
3784
3924
  // src/recurring/failure-collector.ts
3785
3925
  function createFailureCollector() {
@@ -3843,7 +3983,7 @@ async function runSeriesSideEffects(host, db, organizationId, seriesId, client)
3843
3983
  const sendConfirmation = async (url, appointmentId) => {
3844
3984
  for (let tryNumber = 1; tryNumber <= 2; tryNumber += 1) {
3845
3985
  try {
3846
- await (0, import_scheduling28.scheduleNotifications)(db, appointmentId, url);
3986
+ await (0, import_scheduling29.scheduleNotifications)(db, appointmentId, url, { brand: Boolean(host.brand) });
3847
3987
  return;
3848
3988
  } catch (error) {
3849
3989
  if (tryNumber === 2) record("Client confirmation", error);
@@ -3855,10 +3995,9 @@ async function runSeriesSideEffects(host, db, organizationId, seriesId, client)
3855
3995
  if (visit === confirmationVisit) {
3856
3996
  await sendConfirmation(baseUrl, visit.id);
3857
3997
  } else {
3858
- await attempt(
3859
- "Client notices",
3860
- () => (0, import_scheduling28.scheduleNotifications)(db, visit.id, baseUrl, { excludeTriggers: ["CONFIRMATION"] })
3861
- );
3998
+ await attempt("Client notices", async () => {
3999
+ await (0, import_scheduling29.scheduleNotifications)(db, visit.id, baseUrl, { excludeTriggers: ["CONFIRMATION"], brand: Boolean(host.brand) });
4000
+ });
3862
4001
  }
3863
4002
  }
3864
4003
  await attempt(
@@ -3877,7 +4016,7 @@ async function runSeriesSideEffects(host, db, organizationId, seriesId, client)
3877
4016
  await Promise.all(visits.slice(from, from + VISITS_PER_GROUP).map(handleVisit));
3878
4017
  }
3879
4018
  if (baseUrl && confirmationVisit) {
3880
- await attempt("Staff alert", () => (0, import_scheduling28.queueStaffNotification)(db, confirmationVisit.id, "CONFIRMATION", baseUrl));
4019
+ await attempt("Staff alert", () => (0, import_scheduling29.queueStaffNotification)(db, confirmationVisit.id, "CONFIRMATION", baseUrl, { brand: Boolean(host.brand) }));
3881
4020
  }
3882
4021
  await attempt("Availability cache", () => host.availabilityCache.invalidate(first.calendarId));
3883
4022
  await attempt(
@@ -3893,11 +4032,11 @@ async function runSeriesSideEffects(host, db, organizationId, seriesId, client)
3893
4032
  }
3894
4033
 
3895
4034
  // src/recurring/validate-timezone.ts
3896
- var import_scheduling29 = require("@ordinatio/scheduling");
4035
+ var import_scheduling30 = require("@ordinatio/scheduling");
3897
4036
  var SUPPORTED_TIMEZONES = new Set(Intl.supportedValuesOf("timeZone"));
3898
4037
  function validateRecurringTimezone(timezone) {
3899
4038
  if (isValidIanaTimezone(timezone)) return null;
3900
- const err = (0, import_scheduling29.schedError)("SCHED_704", { timezone });
4039
+ const err = (0, import_scheduling30.schedError)("SCHED_704", { timezone });
3901
4040
  return Response.json({ error: err.description, ref: err.ref }, { status: 422 });
3902
4041
  }
3903
4042
  function isValidIanaTimezone(timezone) {
@@ -3950,12 +4089,12 @@ async function createRecurringSeries(request, { host }) {
3950
4089
  const validation = await parseBody(request, CreateRecurringSeriesSchema);
3951
4090
  if (!validation.success) return validation.response;
3952
4091
  const input = validation.data;
3953
- if (input.occurrences < 1 || input.occurrences > import_scheduling30.RECURRING_MAX_OCCURRENCES) {
3954
- const err = (0, import_scheduling30.schedError)("SCHED_701", { occurrences: input.occurrences });
4092
+ if (input.occurrences < 1 || input.occurrences > import_scheduling31.RECURRING_MAX_OCCURRENCES) {
4093
+ const err = (0, import_scheduling31.schedError)("SCHED_701", { occurrences: input.occurrences });
3955
4094
  return Response.json({ error: err.description, ref: err.ref }, { status: 422 });
3956
4095
  }
3957
- if (!(0, import_scheduling30.parseTimeLocal)(input.startTimeLocal)) {
3958
- const err = (0, import_scheduling30.schedError)("SCHED_700", { startTimeLocal: input.startTimeLocal });
4096
+ if (!(0, import_scheduling31.parseTimeLocal)(input.startTimeLocal)) {
4097
+ const err = (0, import_scheduling31.schedError)("SCHED_700", { startTimeLocal: input.startTimeLocal });
3959
4098
  return Response.json({ error: err.description, ref: err.ref }, { status: 422 });
3960
4099
  }
3961
4100
  const tzError = validateRecurringTimezone(input.timezone);
@@ -3984,7 +4123,7 @@ async function createRecurringSeries(request, { host }) {
3984
4123
  });
3985
4124
  const firstDate = new Date(input.firstDate);
3986
4125
  const endsAt = input.endsAt ? new Date(input.endsAt) : void 0;
3987
- const slots = (0, import_scheduling30.buildRecurringSlots)(
4126
+ const slots = (0, import_scheduling31.buildRecurringSlots)(
3988
4127
  firstDate,
3989
4128
  input.frequency,
3990
4129
  input.occurrences,
@@ -4065,17 +4204,17 @@ async function createRecurringSeries(request, { host }) {
4065
4204
  }
4066
4205
 
4067
4206
  // src/handlers/admin-recurring-detail.ts
4068
- var import_scheduling32 = require("@ordinatio/scheduling");
4207
+ var import_scheduling33 = require("@ordinatio/scheduling");
4069
4208
 
4070
4209
  // src/recurring/series-cancel-side-effects.ts
4071
- var import_scheduling31 = require("@ordinatio/scheduling");
4210
+ var import_scheduling32 = require("@ordinatio/scheduling");
4072
4211
  var OCCURRENCES_PER_GROUP = 8;
4073
4212
  async function runSeriesCancelSideEffects(host, db, organizationId, seriesId, seriesCalendarId, occurrences) {
4074
4213
  if (occurrences.length === 0) return { failures: [] };
4075
4214
  const { attempt, record, lines } = createFailureCollector();
4076
4215
  const handle = async (occurrence) => {
4077
4216
  const { id } = occurrence;
4078
- await attempt("Pending reminders", () => (0, import_scheduling31.cancelPendingNotifications)(db, id));
4217
+ await attempt("Pending reminders", () => (0, import_scheduling32.cancelPendingNotifications)(db, id));
4079
4218
  const hasPayment = hasPendingPayment(occurrence.paymentId, occurrence.paymentStatus);
4080
4219
  await attempt("Refund review flag", async () => {
4081
4220
  await writeRefundStatusAfterCancel(host, db, { appointmentId: id, hasPayment, clientName: occurrence.clientName });
@@ -4107,7 +4246,7 @@ async function runSeriesCancelSideEffects(host, db, organizationId, seriesId, se
4107
4246
  }
4108
4247
  const baseUrl = host.appUrl()?.trim();
4109
4248
  if (baseUrl) {
4110
- await attempt("Staff notice", () => (0, import_scheduling31.queueStaffNotification)(db, occurrences[0].id, "CANCELLATION", baseUrl));
4249
+ await attempt("Staff notice", () => (0, import_scheduling32.queueStaffNotification)(db, occurrences[0].id, "CANCELLATION", baseUrl, { brand: Boolean(host.brand) }));
4111
4250
  } else {
4112
4251
  record("Staff notice", "skipped because the application address is not set");
4113
4252
  }
@@ -4153,7 +4292,7 @@ async function getRecurringSeries(request, { host, params }) {
4153
4292
  }
4154
4293
  });
4155
4294
  if (!series || !await staff.canSeeCalendar(series.calendar.id)) {
4156
- const err = (0, import_scheduling32.schedError)("SCHED_702", { seriesId: id, organizationId });
4295
+ const err = (0, import_scheduling33.schedError)("SCHED_702", { seriesId: id, organizationId });
4157
4296
  return Response.json({ error: err.description, ref: err.ref }, { status: 404 });
4158
4297
  }
4159
4298
  return Response.json({ series });
@@ -4180,14 +4319,14 @@ async function cancelRecurringSeries(request, { host, params }) {
4180
4319
  select: { id: true, status: true, clientName: true, clientEmail: true, frequency: true, occurrences: true, calendarId: true }
4181
4320
  });
4182
4321
  if (!series) {
4183
- const err = (0, import_scheduling32.schedError)("SCHED_702", { seriesId: id, organizationId });
4322
+ const err = (0, import_scheduling33.schedError)("SCHED_702", { seriesId: id, organizationId });
4184
4323
  return Response.json({ error: err.description, ref: err.ref }, { status: 404 });
4185
4324
  }
4186
4325
  if (!await staff.canSeeCalendar(series.calendarId)) {
4187
4326
  return Response.json({ error: "Calendar not found" }, { status: 404 });
4188
4327
  }
4189
4328
  if ((input.scope === "ONE" || input.scope === "THIS_AND_FOLLOWING") && !input.fromAppointmentId) {
4190
- const err = (0, import_scheduling32.schedError)("SCHED_703", { scope: input.scope });
4329
+ const err = (0, import_scheduling33.schedError)("SCHED_703", { scope: input.scope });
4191
4330
  return Response.json({ error: err.description, ref: err.ref }, { status: 422 });
4192
4331
  }
4193
4332
  const NON_CANCELLABLE_STATUSES = ["CANCELLED", "COMPLETED", "NO_SHOW"];
@@ -4215,7 +4354,7 @@ async function cancelRecurringSeries(request, { host, params }) {
4215
4354
  if (hiddenCalendars) {
4216
4355
  const hidden = await db.appointment.count({ where: { ...open, calendar: { organizationId, NOT: hiddenCalendars } } });
4217
4356
  if (hidden > 0) {
4218
- const err = (0, import_scheduling32.schedError)("SCHED_702", { seriesId: id, organizationId, reason: "open occurrence on a calendar outside the viewer scope" });
4357
+ const err = (0, import_scheduling33.schedError)("SCHED_702", { seriesId: id, organizationId, reason: "open occurrence on a calendar outside the viewer scope" });
4219
4358
  return Response.json({ error: err.description, ref: err.ref }, { status: 404 });
4220
4359
  }
4221
4360
  }
@@ -4248,7 +4387,7 @@ async function cancelRecurringSeries(request, { host, params }) {
4248
4387
  return Response.json({ cancelledCount, newSeriesStatus, ...warnings.length > 0 && { warnings } });
4249
4388
  } catch (error) {
4250
4389
  if (error?.code === "P2025") {
4251
- const err = (0, import_scheduling32.schedError)("SCHED_702", { race: "series vanished between org-scoped pre-check and cancellation transaction" });
4390
+ const err = (0, import_scheduling33.schedError)("SCHED_702", { race: "series vanished between org-scoped pre-check and cancellation transaction" });
4252
4391
  return Response.json({ error: err.description, ref: err.ref }, { status: 404 });
4253
4392
  }
4254
4393
  return Response.json({ error: getErrorMessage(error, "Failed to cancel recurring series") }, { status: 500 });
@@ -4256,7 +4395,7 @@ async function cancelRecurringSeries(request, { host, params }) {
4256
4395
  }
4257
4396
 
4258
4397
  // src/handlers/booking-analytics.ts
4259
- var import_scheduling33 = require("@ordinatio/scheduling");
4398
+ var import_scheduling34 = require("@ordinatio/scheduling");
4260
4399
  async function getAnalytics(request, { host }) {
4261
4400
  try {
4262
4401
  const staff = await host.staff.resolve(request);
@@ -4268,7 +4407,7 @@ async function getAnalytics(request, { host }) {
4268
4407
  const limited = await host.rateLimit(`analytics:${ip}`, "GENERAL");
4269
4408
  if (limited) return limited;
4270
4409
  if (!staff.isAdmin) {
4271
- const err = (0, import_scheduling33.schedError)("SCHED_900", { userId: staff.userId, role: staff.role });
4410
+ const err = (0, import_scheduling34.schedError)("SCHED_900", { userId: staff.userId, role: staff.role });
4272
4411
  return Response.json({ error: "Forbidden", ref: err.ref }, { status: 403 });
4273
4412
  }
4274
4413
  const params = new URL(request.url).searchParams;
@@ -4294,7 +4433,7 @@ async function getAnalytics(request, { host }) {
4294
4433
  }
4295
4434
  }
4296
4435
  const visibleCalendarIds = await staff.visibleCalendarIds();
4297
- const analytics = await (0, import_scheduling33.getBookingAnalytics)(staff.db, { days, calendarId, visibleCalendarIds });
4436
+ const analytics = await (0, import_scheduling34.getBookingAnalytics)(staff.db, { days, calendarId, visibleCalendarIds, organizationId: staff.organizationId });
4298
4437
  return Response.json(analytics);
4299
4438
  } catch (error) {
4300
4439
  const ref = getErrorRef(error);
@@ -4312,6 +4451,36 @@ function escapeHtml(text) {
4312
4451
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
4313
4452
  }
4314
4453
 
4454
+ // src/brand/brand-http.ts
4455
+ var import_scheduling35 = require("@ordinatio/scheduling");
4456
+ var NOT_ENABLED = { error: "Branding is not enabled on this server" };
4457
+ function brandErrorResponse(error, fallback, cors) {
4458
+ const send = (payload, status) => cors ? corsJson(cors, payload, { status }) : Response.json(payload, { status });
4459
+ if (error instanceof import_scheduling35.SchedulingValidationError) {
4460
+ const details = error.context.errors;
4461
+ return send({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, 400);
4462
+ }
4463
+ console.error("[brand]", error);
4464
+ return send({ error: fallback }, 500);
4465
+ }
4466
+ async function requireBrandAdmin(host, request, options) {
4467
+ const staff = await requireAdminStaff(host, request, options);
4468
+ if (staff instanceof Response) return staff;
4469
+ if (!host.brand) return Response.json(NOT_ENABLED, { status: 501 });
4470
+ return staff;
4471
+ }
4472
+ async function businessName(host, db, organizationId) {
4473
+ if (host.brand) {
4474
+ try {
4475
+ const brand = await (0, import_scheduling35.getBrand)(db, organizationId);
4476
+ if (brand) return brand.displayName;
4477
+ } catch (error) {
4478
+ console.error("[brand] could not read the brand for a message:", error);
4479
+ }
4480
+ }
4481
+ return host.appName() || null;
4482
+ }
4483
+
4315
4484
  // src/handlers/appointment-messages.ts
4316
4485
  var NOT_FOUND4 = () => Response.json({ error: "Appointment not found" }, { status: 404 });
4317
4486
  function failure2(label, error, fallback) {
@@ -4352,7 +4521,7 @@ async function sendFollowup(request, { host, params }) {
4352
4521
  { status: 400 }
4353
4522
  );
4354
4523
  }
4355
- const staffName = appointment.calendar.staffName || host.appName() || "Your provider";
4524
+ const staffName = appointment.calendar.staffName || await businessName(host, db, organizationId) || "Your provider";
4356
4525
  const serviceName = appointment.type.name;
4357
4526
  await db.scheduledNotification.deleteMany({
4358
4527
  where: { appointmentId: id, trigger: "FOLLOWUP_MANUAL", status: "PENDING" }
@@ -4423,6 +4592,7 @@ async function sendReminder(request, { host, params }) {
4423
4592
  month: "long",
4424
4593
  day: "numeric"
4425
4594
  }) + " at " + time;
4595
+ const providerName = appointment.calendar.staffName || await businessName(host, db, organizationId);
4426
4596
  await db.scheduledNotification.deleteMany({
4427
4597
  where: { appointmentId: id, trigger: "REMINDER_MANUAL", status: "PENDING" }
4428
4598
  });
@@ -4433,7 +4603,7 @@ async function sendReminder(request, { host, params }) {
4433
4603
  channel: "SMS",
4434
4604
  trigger: "REMINDER_MANUAL",
4435
4605
  recipient: appointment.clientPhone,
4436
- body: `Reminder: Your ${appointment.type.name} with ${appointment.calendar.staffName || host.appName() || "your provider"} is on ${dateTime}.`,
4606
+ body: `Reminder: Your ${appointment.type.name} with ${providerName || "your provider"} is on ${dateTime}.`,
4437
4607
  scheduledFor: /* @__PURE__ */ new Date()
4438
4608
  }
4439
4609
  });
@@ -4454,7 +4624,7 @@ Date: ${dateTime}
4454
4624
 
4455
4625
  We look forward to seeing you!
4456
4626
 
4457
- \u2014 ${escapeHtml(appointment.calendar.staffName || host.appName() || "Your provider")}`,
4627
+ \u2014 ${escapeHtml(providerName || "Your provider")}`,
4458
4628
  scheduledFor: /* @__PURE__ */ new Date()
4459
4629
  }
4460
4630
  });
@@ -4470,7 +4640,7 @@ We look forward to seeing you!
4470
4640
  }
4471
4641
 
4472
4642
  // src/handlers/calendar-ownership.ts
4473
- var import_scheduling34 = require("@ordinatio/scheduling");
4643
+ var import_scheduling36 = require("@ordinatio/scheduling");
4474
4644
  async function getOwnedCalendarForRoute(db, id, organizationId) {
4475
4645
  const calendar = await db.schedulingCalendar.findUnique({
4476
4646
  where: { id },
@@ -4501,7 +4671,7 @@ async function getOwnedCalendarForRoute(db, id, organizationId) {
4501
4671
  async function validateStaffLink(host, userId, organizationId) {
4502
4672
  if (!userId) return null;
4503
4673
  if (await host.staffDirectory.isMember(organizationId, userId)) return null;
4504
- const err = (0, import_scheduling34.schedError)("SCHED_104", { userId, organizationId });
4674
+ const err = (0, import_scheduling36.schedError)("SCHED_104", { userId, organizationId });
4505
4675
  return Response.json({ error: "That staff member is not part of this organization", ref: err.ref }, { status: 400 });
4506
4676
  }
4507
4677
  function buildCalendarUpdateData(input) {
@@ -4634,7 +4804,7 @@ async function createCalendar(request, { host }) {
4634
4804
  }
4635
4805
 
4636
4806
  // src/handlers/admin-calendar-update.ts
4637
- var import_scheduling35 = require("@ordinatio/scheduling");
4807
+ var import_scheduling37 = require("@ordinatio/scheduling");
4638
4808
  var NOT_FOUND5 = () => Response.json({ error: "Calendar not found" }, { status: 404 });
4639
4809
  async function getCalendar(request, { host, params }) {
4640
4810
  try {
@@ -4664,7 +4834,7 @@ async function putCalendar(request, { host, params }) {
4664
4834
  const input = validation.data;
4665
4835
  const linkError = input.userId === void 0 ? null : await validateStaffLink(host, input.userId, organizationId);
4666
4836
  if (linkError) return linkError;
4667
- const { calendar: updated, wasActive } = await (0, import_scheduling35.updateCalendar)(db, id, organizationId, buildCalendarUpdateData(input));
4837
+ const { calendar: updated, wasActive } = await (0, import_scheduling37.updateCalendar)(db, id, organizationId, buildCalendarUpdateData(input));
4668
4838
  if (input.slotGranularityMinutes !== void 0) await host.availabilityCache.invalidate(id);
4669
4839
  if (input.isActive === false && wasActive) {
4670
4840
  await releaseCalendarSlugIfStillInactive(host, db, id, organizationId, existing.slug);
@@ -4689,7 +4859,7 @@ async function deleteCalendar(request, { host, params }) {
4689
4859
  if (!await staff.canSeeCalendar(id)) return NOT_FOUND5();
4690
4860
  const existing = await getOwnedCalendarForRoute(db, id, organizationId);
4691
4861
  if (!existing) return NOT_FOUND5();
4692
- await (0, import_scheduling35.archiveCalendar)(db, id, organizationId);
4862
+ await (0, import_scheduling37.archiveCalendar)(db, id, organizationId);
4693
4863
  await releaseCalendarSlugIfStillInactive(host, db, id, organizationId, existing.slug);
4694
4864
  await bustCalendarCachesOnArchive(host, organizationId, existing.slug, id);
4695
4865
  await host.activity.log(db, {
@@ -4846,7 +5016,7 @@ async function disconnectOutlook(request, { host, params }) {
4846
5016
  }
4847
5017
 
4848
5018
  // src/handlers/admin-calendar-location-recents.ts
4849
- var import_scheduling36 = require("@ordinatio/scheduling");
5019
+ var import_scheduling38 = require("@ordinatio/scheduling");
4850
5020
  async function getLocationRecents(request, { host, params }) {
4851
5021
  try {
4852
5022
  const staff = await requireAdminStaff(host, request, {
@@ -4891,14 +5061,14 @@ async function getLocationRecents(request, { host, params }) {
4891
5061
  }
4892
5062
  return Response.json({ locations });
4893
5063
  } catch (error) {
4894
- const diagnostic = (0, import_scheduling36.schedError)("SCHED_207", { error });
5064
+ const diagnostic = (0, import_scheduling38.schedError)("SCHED_207", { error });
4895
5065
  console.error("[location-recents]", diagnostic.ref, error);
4896
5066
  return Response.json({ error: "Failed to fetch location recents", ref: diagnostic.ref }, { status: 500 });
4897
5067
  }
4898
5068
  }
4899
5069
 
4900
5070
  // src/handlers/admin-availability-rules.ts
4901
- var import_scheduling37 = require("@ordinatio/scheduling");
5071
+ var import_scheduling39 = require("@ordinatio/scheduling");
4902
5072
 
4903
5073
  // src/availability/admin-calendar.ts
4904
5074
  async function verifyCalendar(db, calendarId, organizationId) {
@@ -4963,7 +5133,7 @@ async function listRules(request, { host, params }) {
4963
5133
  const calendar = await requireOwnedVisibleCalendar(staff, calendarId);
4964
5134
  if (calendar instanceof Response) return calendar;
4965
5135
  const { limit, offset } = parsePagination(request, 500, 200);
4966
- const { rules, total, hasMore } = await (0, import_scheduling37.listAvailabilityRules)(staff.db, calendarId, { limit, offset });
5136
+ const { rules, total, hasMore } = await (0, import_scheduling39.listAvailabilityRules)(staff.db, calendarId, { limit, offset });
4967
5137
  return Response.json({ rules, total, hasMore });
4968
5138
  } catch (error) {
4969
5139
  return Response.json({ error: getErrorMessage(error, "Failed to fetch availability") }, { status: 500 });
@@ -4982,7 +5152,7 @@ async function setWeeklyRules(request, { host, params }) {
4982
5152
  if (!Array.isArray(rules)) return Response.json({ error: "rules must be an array" }, { status: 400 });
4983
5153
  const validationError = validateWeeklyRules(rules);
4984
5154
  if (validationError) return Response.json({ error: validationError }, { status: 400 });
4985
- const created = await (0, import_scheduling37.setWeeklyAvailability)(db, calendarId, rules);
5155
+ const created = await (0, import_scheduling39.setWeeklyAvailability)(db, calendarId, rules);
4986
5156
  const activeDays = rules.map((r) => ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"][r.dayOfWeek]).join(", ");
4987
5157
  await host.activity.log(db, {
4988
5158
  action: "scheduling.availability_updated",
@@ -4992,7 +5162,7 @@ async function setWeeklyRules(request, { host, params }) {
4992
5162
  return Response.json(created);
4993
5163
  } catch (error) {
4994
5164
  const msg = getErrorMessage(error, "Failed to update availability");
4995
- if (error instanceof import_scheduling37.SchedulingValidationError) {
5165
+ if (error instanceof import_scheduling39.SchedulingValidationError) {
4996
5166
  console.error("[PUT /admin/availability]", error.ref, error.code, error.context);
4997
5167
  return Response.json({ error: msg, ref: error.ref }, { status: 400 });
4998
5168
  }
@@ -5001,18 +5171,18 @@ async function setWeeklyRules(request, { host, params }) {
5001
5171
  }
5002
5172
 
5003
5173
  // src/handlers/admin-availability-overrides.ts
5004
- var import_scheduling39 = require("@ordinatio/scheduling");
5174
+ var import_scheduling41 = require("@ordinatio/scheduling");
5005
5175
 
5006
5176
  // src/availability/override-helpers.ts
5007
- var import_scheduling38 = require("@ordinatio/scheduling");
5177
+ var import_scheduling40 = require("@ordinatio/scheduling");
5008
5178
  function sanitizeBlockReason(raw) {
5009
5179
  if (!raw) return void 0;
5010
5180
  return String(raw).replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "").replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "").replace(/<[^>]*>/g, "").slice(0, 500).trim() || void 0;
5011
5181
  }
5012
5182
  async function checkOverlappingAppointments(db, calendarId, calendarTimezone, dateStr, startTime, endTime) {
5013
5183
  const tz = calendarTimezone ?? "America/New_York";
5014
- const blockStart = (0, import_scheduling38.localToUTC)(dateStr, startTime, tz);
5015
- const blockEnd = (0, import_scheduling38.localToUTC)(dateStr, endTime, tz);
5184
+ const blockStart = (0, import_scheduling40.localToUTC)(dateStr, startTime, tz);
5185
+ const blockEnd = (0, import_scheduling40.localToUTC)(dateStr, endTime, tz);
5016
5186
  const conflictCount = await db.appointment.count({
5017
5187
  where: {
5018
5188
  calendarId,
@@ -5042,14 +5212,14 @@ async function addOverride(request, { host, params }) {
5042
5212
  const isBlockedFlag = body.isBlocked ?? true;
5043
5213
  let override;
5044
5214
  if (isBlockedFlag && body.startTime && body.endTime) {
5045
- override = await (0, import_scheduling39.addTimeBlock)(db, calendarId, {
5215
+ override = await (0, import_scheduling41.addTimeBlock)(db, calendarId, {
5046
5216
  date,
5047
5217
  startTime: body.startTime,
5048
5218
  endTime: body.endTime,
5049
5219
  reason: blockReason
5050
5220
  });
5051
5221
  } else {
5052
- override = await (0, import_scheduling39.addDateOverride)(db, calendarId, {
5222
+ override = await (0, import_scheduling41.addDateOverride)(db, calendarId, {
5053
5223
  date,
5054
5224
  isBlocked: isBlockedFlag,
5055
5225
  blockReason,
@@ -5085,7 +5255,7 @@ async function addOverride(request, { host, params }) {
5085
5255
  return Response.json({ ...override, ...overlapWarning && { warning: overlapWarning } }, { status: 201 });
5086
5256
  } catch (error) {
5087
5257
  const msg = getErrorMessage(error, "Failed to add override");
5088
- if (error instanceof import_scheduling39.SchedulingValidationError) {
5258
+ if (error instanceof import_scheduling41.SchedulingValidationError) {
5089
5259
  console.error("[POST /admin/availability]", error.ref, error.code, error.context);
5090
5260
  return Response.json({ error: msg, ref: error.ref }, { status: 400 });
5091
5261
  }
@@ -5102,7 +5272,7 @@ async function removeOverride(request, { host, params }) {
5102
5272
  if (calendar instanceof Response) return calendar;
5103
5273
  const { ruleId } = await request.json();
5104
5274
  if (!ruleId) return Response.json({ error: "ruleId is required" }, { status: 400 });
5105
- const deletedRule = await (0, import_scheduling39.removeDateOverride)(db, calendarId, ruleId);
5275
+ const deletedRule = await (0, import_scheduling41.removeDateOverride)(db, calendarId, ruleId);
5106
5276
  const deletedIsTimeBlock = deletedRule?.isBlocked && !(deletedRule.startTime === "00:00" && deletedRule.endTime === "00:00");
5107
5277
  await host.activity.log(db, {
5108
5278
  action: "scheduling.date_override_removed",
@@ -5112,7 +5282,7 @@ async function removeOverride(request, { host, params }) {
5112
5282
  return Response.json({ success: true });
5113
5283
  } catch (error) {
5114
5284
  const msg = getErrorMessage(error, "Failed to remove override");
5115
- if (error instanceof import_scheduling39.SchedulingNotFoundError) {
5285
+ if (error instanceof import_scheduling41.SchedulingNotFoundError) {
5116
5286
  console.error("[DELETE /admin/availability]", error.ref, error.code, error.context);
5117
5287
  return Response.json({ error: msg, ref: error.ref }, { status: 404 });
5118
5288
  }
@@ -5121,7 +5291,7 @@ async function removeOverride(request, { host, params }) {
5121
5291
  }
5122
5292
 
5123
5293
  // src/handlers/admin-templates.ts
5124
- var import_scheduling40 = require("@ordinatio/scheduling");
5294
+ var import_scheduling42 = require("@ordinatio/scheduling");
5125
5295
 
5126
5296
  // src/sanitize/notification-body.ts
5127
5297
  var import_sanitize_html = __toESM(require("sanitize-html"));
@@ -5145,7 +5315,7 @@ async function listTemplates(request, { host }) {
5145
5315
  try {
5146
5316
  const staff = await requireAdminStaff(host, request, { action: "admin-templates-list", tier: "GENERAL" });
5147
5317
  if (staff instanceof Response) return staff;
5148
- return Response.json(await (0, import_scheduling40.listNotificationTemplates)(staff.db, staff.organizationId));
5318
+ return Response.json(await (0, import_scheduling42.listNotificationTemplates)(staff.db, staff.organizationId));
5149
5319
  } catch (error) {
5150
5320
  return Response.json({ error: getErrorMessage(error, "Failed to fetch templates") }, { status: 500 });
5151
5321
  }
@@ -5170,7 +5340,7 @@ async function createTemplate(request, { host }) {
5170
5340
  if (input.channel === "EMAIL" && !input.subject?.trim()) {
5171
5341
  return Response.json({ error: "EMAIL templates require a subject" }, { status: 400 });
5172
5342
  }
5173
- const template = await (0, import_scheduling40.createNotificationTemplate)(db, organizationId, {
5343
+ const template = await (0, import_scheduling42.createNotificationTemplate)(db, organizationId, {
5174
5344
  name: input.name,
5175
5345
  channel: input.channel,
5176
5346
  trigger: input.trigger,
@@ -5196,7 +5366,7 @@ async function createTemplate(request, { host }) {
5196
5366
  }
5197
5367
 
5198
5368
  // src/handlers/admin-template-update.ts
5199
- var import_scheduling41 = require("@ordinatio/scheduling");
5369
+ var import_scheduling43 = require("@ordinatio/scheduling");
5200
5370
  async function updateTemplate(request, { host, params }) {
5201
5371
  try {
5202
5372
  const staff = await requireAdminStaff(host, request, { action: "admin-templates-update", tier: "UPDATE" });
@@ -5228,7 +5398,7 @@ async function updateTemplate(request, { host, params }) {
5228
5398
  return Response.json({ error: "EMAIL templates require a subject" }, { status: 400 });
5229
5399
  }
5230
5400
  }
5231
- const updated = await (0, import_scheduling41.updateNotificationTemplate)(db, organizationId, id, {
5401
+ const updated = await (0, import_scheduling43.updateNotificationTemplate)(db, organizationId, id, {
5232
5402
  name: input.name,
5233
5403
  subject: sanitizedSubject,
5234
5404
  body: input.body !== void 0 ? sanitizeNotificationBody(input.body, existing.channel) : void 0,
@@ -5242,11 +5412,11 @@ async function updateTemplate(request, { host, params }) {
5242
5412
  return Response.json(updated);
5243
5413
  } catch (error) {
5244
5414
  const msg = getErrorMessage(error, "Failed to update template");
5245
- if (error instanceof import_scheduling41.SchedulingValidationError) {
5415
+ if (error instanceof import_scheduling43.SchedulingValidationError) {
5246
5416
  console.error("[PUT /admin/templates]", error.ref, error.code, error.context);
5247
5417
  return Response.json({ error: msg, ref: error.ref }, { status: 400 });
5248
5418
  }
5249
- if (error instanceof import_scheduling41.SchedulingNotFoundError) {
5419
+ if (error instanceof import_scheduling43.SchedulingNotFoundError) {
5250
5420
  console.error("[PUT /admin/templates]", error.ref, error.code, error.context);
5251
5421
  return Response.json({ error: msg, ref: error.ref }, { status: 404 });
5252
5422
  }
@@ -5263,7 +5433,7 @@ async function deleteTemplate(request, { host, params }) {
5263
5433
  where: { id, organizationId },
5264
5434
  select: { name: true }
5265
5435
  });
5266
- await (0, import_scheduling41.deleteNotificationTemplate)(db, organizationId, id);
5436
+ await (0, import_scheduling43.deleteNotificationTemplate)(db, organizationId, id);
5267
5437
  await host.activity.log(db, {
5268
5438
  action: "scheduling.template_deleted",
5269
5439
  description: `deleted notification template "${template?.name || id}"`,
@@ -5272,7 +5442,7 @@ async function deleteTemplate(request, { host, params }) {
5272
5442
  return Response.json({ success: true });
5273
5443
  } catch (error) {
5274
5444
  const msg = getErrorMessage(error, "Failed to delete template");
5275
- if (error instanceof import_scheduling41.SchedulingNotFoundError) {
5445
+ if (error instanceof import_scheduling43.SchedulingNotFoundError) {
5276
5446
  console.error("[DELETE /admin/templates]", error.ref, error.code, error.context);
5277
5447
  return Response.json({ error: msg, ref: error.ref }, { status: 404 });
5278
5448
  }
@@ -5281,7 +5451,7 @@ async function deleteTemplate(request, { host, params }) {
5281
5451
  }
5282
5452
 
5283
5453
  // src/handlers/admin-types.ts
5284
- var import_scheduling42 = require("@ordinatio/scheduling");
5454
+ var import_scheduling44 = require("@ordinatio/scheduling");
5285
5455
  async function listTypes(request, { host }) {
5286
5456
  try {
5287
5457
  const staff = await requireAdminStaff(host, request, { action: "admin-types-list", tier: "GENERAL" });
@@ -5311,7 +5481,7 @@ async function createType(request, { host }) {
5311
5481
  if (!validation.success) return validation.response;
5312
5482
  if (!organizationId) return Response.json({ error: "Organization context required" }, { status: 400 });
5313
5483
  const input = validation.data;
5314
- const type = await (0, import_scheduling42.createAppointmentType)(db, {
5484
+ const type = await (0, import_scheduling44.createAppointmentType)(db, {
5315
5485
  name: input.name,
5316
5486
  slug: input.name.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, ""),
5317
5487
  description: input.description || void 0,
@@ -5370,7 +5540,7 @@ async function createType(request, { host }) {
5370
5540
  }
5371
5541
 
5372
5542
  // src/handlers/admin-type-update.ts
5373
- var import_scheduling43 = require("@ordinatio/scheduling");
5543
+ var import_scheduling45 = require("@ordinatio/scheduling");
5374
5544
 
5375
5545
  // src/handlers/type-ownership.ts
5376
5546
  async function getOwnedAppointmentType(db, id, organizationId) {
@@ -5451,7 +5621,7 @@ async function updateType(request, { host, params }) {
5451
5621
  const validation = await parseBody(request, UpdateAppointmentTypeSchema);
5452
5622
  if (!validation.success) return validation.response;
5453
5623
  const input = validation.data;
5454
- const { type: updated, wasActive } = await (0, import_scheduling43.updateAppointmentType)(db, id, organizationId, input);
5624
+ const { type: updated, wasActive } = await (0, import_scheduling45.updateAppointmentType)(db, id, organizationId, input);
5455
5625
  if (input.isActive === false && wasActive && typeToUpdate.organizationId) {
5456
5626
  await releaseTypeSlugIfStillInactive(host, db, id, typeToUpdate.organizationId, typeToUpdate.slug);
5457
5627
  }
@@ -5468,7 +5638,7 @@ async function updateType(request, { host, params }) {
5468
5638
  return Response.json({ error: getErrorMessage(error, "Validation error") }, { status: schedErrorStatus(code) });
5469
5639
  }
5470
5640
  const message = isSchedulingServiceError(error) ? error.description || error.message : getErrorMessage(error, "Failed to update appointment type");
5471
- if (error instanceof import_scheduling43.SchedulingValidationError) return Response.json({ error: message }, { status: 400 });
5641
+ if (error instanceof import_scheduling45.SchedulingValidationError) return Response.json({ error: message }, { status: 400 });
5472
5642
  return Response.json({ error: message }, { status: 500 });
5473
5643
  }
5474
5644
  }
@@ -5720,7 +5890,7 @@ async function getStaffOptions(request, { host }) {
5720
5890
 
5721
5891
  // src/handlers/appointment-ical.ts
5722
5892
  var import_ical_generator = __toESM(require("ical-generator"));
5723
- var import_scheduling44 = require("@ordinatio/scheduling");
5893
+ var import_scheduling46 = require("@ordinatio/scheduling");
5724
5894
  async function getAppointmentIcal(request, { host }) {
5725
5895
  let token = null;
5726
5896
  try {
@@ -5748,13 +5918,13 @@ async function getAppointmentIcal(request, { host }) {
5748
5918
  const description = [appointment.type.description ?? "", `Manage your appointment: ${manageUrl}`].filter(Boolean).join("\n");
5749
5919
  const calendar = (0, import_ical_generator.default)({ name: appointment.calendar.name });
5750
5920
  calendar.createEvent({
5751
- id: `${appointment.id}@system1701`,
5921
+ id: `${appointment.id}@${host.icalUidDomain() || "ordinatio-scheduling"}`,
5752
5922
  start: appointment.startTime,
5753
5923
  end: appointment.endTime,
5754
5924
  timezone: appointment.timezone,
5755
5925
  summary,
5756
5926
  description,
5757
- location: (0, import_scheduling44.resolveLocation)(appointment) ?? void 0,
5927
+ location: (0, import_scheduling46.resolveLocation)(appointment) ?? void 0,
5758
5928
  url: manageUrl,
5759
5929
  organizer: staffName && staffEmail ? { name: staffName, email: staffEmail } : void 0
5760
5930
  });
@@ -5766,17 +5936,17 @@ async function getAppointmentIcal(request, { host }) {
5766
5936
  }
5767
5937
  });
5768
5938
  } catch (error) {
5769
- const diagnostic = (0, import_scheduling44.schedError)("SCHED_600", { error, token: token ?? "unknown" });
5939
+ const diagnostic = (0, import_scheduling46.schedError)("SCHED_600", { error, token: token ?? "unknown" });
5770
5940
  console.error("[GET /ical]", diagnostic.ref, error instanceof Error ? error.message : error);
5771
5941
  return Response.json({ error: "Failed to generate calendar file", ref: diagnostic.ref }, { status: 500 });
5772
5942
  }
5773
5943
  }
5774
5944
 
5775
5945
  // src/handlers/admin-webhooks.ts
5776
- var import_scheduling46 = require("@ordinatio/scheduling");
5946
+ var import_scheduling48 = require("@ordinatio/scheduling");
5777
5947
 
5778
5948
  // src/webhooks/require-webhooks.ts
5779
- var import_scheduling45 = require("@ordinatio/scheduling");
5949
+ var import_scheduling47 = require("@ordinatio/scheduling");
5780
5950
  async function requireWebhooksAdmin(host, request, options) {
5781
5951
  const staff = await requireAdminStaff(host, request, options);
5782
5952
  if (staff instanceof Response) return staff;
@@ -5784,10 +5954,10 @@ async function requireWebhooksAdmin(host, request, options) {
5784
5954
  return { staff, settings: host.webhooks };
5785
5955
  }
5786
5956
  function webhookErrorResponse(error, fallback) {
5787
- if (error instanceof import_scheduling45.SchedulingValidationError) {
5957
+ if (error instanceof import_scheduling47.SchedulingValidationError) {
5788
5958
  return Response.json({ error: error.message, ref: getErrorRef(error) }, { status: 400 });
5789
5959
  }
5790
- if (error instanceof import_scheduling45.SchedulingNotFoundError) {
5960
+ if (error instanceof import_scheduling47.SchedulingNotFoundError) {
5791
5961
  return Response.json({ error: error.message, ref: getErrorRef(error) }, { status: 404 });
5792
5962
  }
5793
5963
  return Response.json({ error: getErrorMessage(error, fallback) }, { status: 500 });
@@ -5799,7 +5969,7 @@ async function listWebhooks(request, { host }) {
5799
5969
  const guard = await requireWebhooksAdmin(host, request, { action: "admin-webhooks-list", tier: "GENERAL" });
5800
5970
  if (guard instanceof Response) return guard;
5801
5971
  const { db, organizationId } = guard.staff;
5802
- return Response.json({ endpoints: await (0, import_scheduling46.listWebhookEndpoints)(db, organizationId), eventTypes: import_scheduling46.WEBHOOK_EVENT_TYPES });
5972
+ return Response.json({ endpoints: await (0, import_scheduling48.listWebhookEndpoints)(db, organizationId), eventTypes: import_scheduling48.WEBHOOK_EVENT_TYPES });
5803
5973
  } catch (error) {
5804
5974
  return webhookErrorResponse(error, "Failed to list webhooks");
5805
5975
  }
@@ -5812,7 +5982,7 @@ async function createWebhook(request, { host }) {
5812
5982
  const validation = await parseBody(request, CreateWebhookEndpointSchema);
5813
5983
  if (!validation.success) return validation.response;
5814
5984
  const input = validation.data;
5815
- const { endpoint, secret } = await (0, import_scheduling46.createWebhookEndpoint)(
5985
+ const { endpoint, secret } = await (0, import_scheduling48.createWebhookEndpoint)(
5816
5986
  db,
5817
5987
  { organizationId, url: input.url, eventTypes: input.eventTypes, description: input.description },
5818
5988
  { allowInsecureTargets: guard.settings.allowInsecureTargets }
@@ -5829,14 +5999,14 @@ async function createWebhook(request, { host }) {
5829
5999
  }
5830
6000
 
5831
6001
  // src/handlers/admin-webhook-detail.ts
5832
- var import_scheduling47 = require("@ordinatio/scheduling");
6002
+ var import_scheduling49 = require("@ordinatio/scheduling");
5833
6003
  var STATUSES = /* @__PURE__ */ new Set(["PENDING", "PROCESSING", "SUCCEEDED", "DEAD_LETTER"]);
5834
6004
  async function deleteWebhook(request, { host, params }) {
5835
6005
  try {
5836
6006
  const guard = await requireWebhooksAdmin(host, request, { action: "admin-webhooks-delete", tier: "DELETE" });
5837
6007
  if (guard instanceof Response) return guard;
5838
6008
  const { db, organizationId } = guard.staff;
5839
- await (0, import_scheduling47.deleteWebhookEndpoint)(db, organizationId, params.id);
6009
+ await (0, import_scheduling49.deleteWebhookEndpoint)(db, organizationId, params.id);
5840
6010
  await host.activity.log(db, {
5841
6011
  action: "scheduling.webhook_deleted",
5842
6012
  description: "removed a webhook endpoint",
@@ -5852,7 +6022,7 @@ async function testWebhook(request, { host, params }) {
5852
6022
  const guard = await requireWebhooksAdmin(host, request, { action: "admin-webhooks-test", tier: "CREATE" });
5853
6023
  if (guard instanceof Response) return guard;
5854
6024
  const { db, organizationId } = guard.staff;
5855
- const result = await (0, import_scheduling47.sendTestWebhook)(
6025
+ const result = await (0, import_scheduling49.sendTestWebhook)(
5856
6026
  db,
5857
6027
  { organizationId, endpointId: params.id },
5858
6028
  { transport: guard.settings.transport, allowInsecureTargets: guard.settings.allowInsecureTargets }
@@ -5868,13 +6038,13 @@ async function listWebhookEndpointDeliveries(request, { host, params }) {
5868
6038
  if (guard instanceof Response) return guard;
5869
6039
  const { db, organizationId } = guard.staff;
5870
6040
  const owned = await db.webhookEndpoint.count({ where: { id: params.id, organizationId } });
5871
- if (owned === 0) throw new import_scheduling47.SchedulingNotFoundError("Webhook endpoint not found", "SCHED_1003", { endpointId: params.id });
6041
+ if (owned === 0) throw new import_scheduling49.SchedulingNotFoundError("Webhook endpoint not found", "SCHED_1003", { endpointId: params.id });
5872
6042
  const status = new URL(request.url).searchParams.get("status");
5873
6043
  if (status && !STATUSES.has(status)) {
5874
6044
  return Response.json({ error: `status must be one of ${[...STATUSES].join(", ")}` }, { status: 400 });
5875
6045
  }
5876
6046
  const { limit, offset } = parsePagination(request);
5877
- const { deliveries, total } = await (0, import_scheduling47.listWebhookDeliveries)(db, {
6047
+ const { deliveries, total } = await (0, import_scheduling49.listWebhookDeliveries)(db, {
5878
6048
  organizationId,
5879
6049
  endpointId: params.id,
5880
6050
  status: status ?? void 0,
@@ -5888,13 +6058,13 @@ async function listWebhookEndpointDeliveries(request, { host, params }) {
5888
6058
  }
5889
6059
 
5890
6060
  // src/handlers/admin-webhook-delivery-retry.ts
5891
- var import_scheduling48 = require("@ordinatio/scheduling");
6061
+ var import_scheduling50 = require("@ordinatio/scheduling");
5892
6062
  async function retryWebhook(request, { host, params }) {
5893
6063
  try {
5894
6064
  const guard = await requireWebhooksAdmin(host, request, { action: "admin-webhooks-retry", tier: "UPDATE" });
5895
6065
  if (guard instanceof Response) return guard;
5896
6066
  const { db, organizationId } = guard.staff;
5897
- await (0, import_scheduling48.retryWebhookDelivery)(db, organizationId, params.id);
6067
+ await (0, import_scheduling50.retryWebhookDelivery)(db, organizationId, params.id);
5898
6068
  return Response.json({ success: true });
5899
6069
  } catch (error) {
5900
6070
  return webhookErrorResponse(error, "Failed to retry the delivery");
@@ -5902,7 +6072,7 @@ async function retryWebhook(request, { host, params }) {
5902
6072
  }
5903
6073
 
5904
6074
  // src/handlers/internal-webhooks-deliver.ts
5905
- var import_scheduling49 = require("@ordinatio/scheduling");
6075
+ var import_scheduling51 = require("@ordinatio/scheduling");
5906
6076
  async function deliverWebhooks(request, { host }) {
5907
6077
  if (!await host.internalAccess.isAuthorized(request)) {
5908
6078
  return Response.json({ error: "Unauthorized" }, { status: 401 });
@@ -5911,7 +6081,7 @@ async function deliverWebhooks(request, { host }) {
5911
6081
  const limited = await host.rateLimit(`${request.headers.get("x-forwarded-for") ?? "worker"}:webhooks-deliver`, "INTERNAL");
5912
6082
  if (limited) return limited;
5913
6083
  try {
5914
- const summary = await (0, import_scheduling49.deliverDueWebhooks)(await host.publicDb(), {
6084
+ const summary = await (0, import_scheduling51.deliverDueWebhooks)(await host.publicDb(), {
5915
6085
  transport: host.webhooks.transport,
5916
6086
  allowInsecureTargets: host.webhooks.allowInsecureTargets
5917
6087
  });
@@ -5922,37 +6092,140 @@ async function deliverWebhooks(request, { host }) {
5922
6092
  }
5923
6093
  }
5924
6094
 
5925
- // src/handlers/appointments-book.ts
6095
+ // src/handlers/waitlist-join.ts
5926
6096
  var import_scheduling53 = require("@ordinatio/scheduling");
6097
+ var import_zod16 = require("zod");
6098
+
6099
+ // src/waitlist/waitlist-http.ts
6100
+ var import_scheduling52 = require("@ordinatio/scheduling");
6101
+ var NOT_ENABLED2 = { error: "The waitlist is not enabled on this server" };
6102
+ var STATUS_BY_CODE = {
6103
+ SCHED_1100: 404,
6104
+ SCHED_1103: 409,
6105
+ SCHED_1104: 409,
6106
+ SCHED_1106: 404,
6107
+ SCHED_1107: 410,
6108
+ SCHED_1108: 409
6109
+ };
6110
+ async function resolveWaitlistDb(host, orgSlug) {
6111
+ if (!orgSlug) return { db: await host.publicDb(), organizationId: null };
6112
+ return host.organizations.resolve({ orgSlug, logPrefix: "[waitlist]" });
6113
+ }
6114
+ function waitlistErrorResponse(cors, error, fallback) {
6115
+ if (error instanceof import_scheduling52.SchedulingValidationError || error instanceof import_scheduling52.SchedulingNotFoundError) {
6116
+ const status = STATUS_BY_CODE[error.code] ?? (error instanceof import_scheduling52.SchedulingNotFoundError ? 404 : 400);
6117
+ return corsJson(cors, { error: error.message, code: error.code, ref: getErrorRef(error) }, { status });
6118
+ }
6119
+ console.error("[waitlist]", error);
6120
+ return corsJson(cors, { error: fallback }, { status: 500 });
6121
+ }
6122
+ async function requireWaitlistAdmin(host, request, options) {
6123
+ const staff = await requireAdminStaff(host, request, options);
6124
+ if (staff instanceof Response) return staff;
6125
+ if (!host.waitlist) return Response.json(NOT_ENABLED2, { status: 501 });
6126
+ return { staff, settings: host.waitlist };
6127
+ }
6128
+
6129
+ // src/handlers/waitlist-join.ts
6130
+ var JoinWaitlistSchema = import_zod16.z.object({
6131
+ orgSlug: import_zod16.z.string().min(1).max(100).optional(),
6132
+ typeId: import_zod16.z.string().min(1),
6133
+ calendarId: import_zod16.z.string().min(1).optional(),
6134
+ day: import_zod16.z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Day must be YYYY-MM-DD"),
6135
+ slotStart: import_zod16.z.string().datetime({ message: "Invalid date/time format" }).optional(),
6136
+ clientName: import_zod16.z.string().trim().min(1, "Name is required").max(200),
6137
+ clientEmail: import_zod16.z.string().email("Invalid email").max(254),
6138
+ clientPhone: import_zod16.z.string().max(30).optional()
6139
+ });
6140
+ async function joinWaitlistRoute(request, { host }) {
6141
+ const cors = host.cors(request);
6142
+ if (!host.waitlist) return corsJson(cors, NOT_ENABLED2, { status: 501 });
6143
+ try {
6144
+ const limited = await host.rateLimit(`waitlist-join:${clientAddress(request)}`, "PUBLIC_BOOKING");
6145
+ if (limited) return limited;
6146
+ const parsed = JoinWaitlistSchema.safeParse(await request.json().catch(() => null));
6147
+ if (!parsed.success) {
6148
+ const details = parsed.error.issues.map((issue) => ({ field: issue.path.join("."), message: issue.message }));
6149
+ return corsJson(cors, { error: "Validation failed", details }, { status: 400 });
6150
+ }
6151
+ const body = parsed.data;
6152
+ const context = await resolveWaitlistDb(host, body.orgSlug);
6153
+ if (!context) return corsJson(cors, { error: "Appointment type not found" }, { status: 404 });
6154
+ let organizationId = context.organizationId;
6155
+ if (!organizationId) {
6156
+ const type = await context.db.appointmentType.findUnique({ where: { id: body.typeId }, select: { organizationId: true } });
6157
+ organizationId = type?.organizationId ?? null;
6158
+ }
6159
+ if (!organizationId) return corsJson(cors, { error: "Appointment type not found" }, { status: 404 });
6160
+ const { entry, token } = await (0, import_scheduling53.joinWaitlist)(context.db, {
6161
+ organizationId,
6162
+ typeId: body.typeId,
6163
+ calendarId: body.calendarId,
6164
+ day: body.day,
6165
+ slotStart: body.slotStart ? new Date(body.slotStart) : void 0,
6166
+ clientName: body.clientName,
6167
+ clientEmail: body.clientEmail,
6168
+ clientPhone: body.clientPhone
6169
+ });
6170
+ return corsJson(cors, { entry, token }, { status: 201, headers: { "Cache-Control": "no-store" } });
6171
+ } catch (error) {
6172
+ return waitlistErrorResponse(cors, error, "Failed to join the waitlist");
6173
+ }
6174
+ }
6175
+ async function leaveWaitlistRoute(request, { host }) {
6176
+ const cors = host.cors(request);
6177
+ if (!host.waitlist) return corsJson(cors, NOT_ENABLED2, { status: 501 });
6178
+ try {
6179
+ const limited = await host.rateLimit(`waitlist-leave:${clientAddress(request)}`, "GENERAL");
6180
+ if (limited) return limited;
6181
+ const url = new URL(request.url);
6182
+ const token = url.searchParams.get("token");
6183
+ if (!token) return corsJson(cors, { error: "token is required" }, { status: 400 });
6184
+ const context = await resolveWaitlistDb(host, url.searchParams.get("orgSlug"));
6185
+ if (!context) return corsJson(cors, { error: "No waitlist entry for this link", code: "SCHED_1106" }, { status: 404 });
6186
+ const freed = await (0, import_scheduling53.leaveWaitlist)(context.db, token);
6187
+ if (freed) await offerAndAnnounce(host, host.waitlist, context.db, freed);
6188
+ return corsJson(cors, { success: true });
6189
+ } catch (error) {
6190
+ return waitlistErrorResponse(cors, error, "Failed to leave the waitlist");
6191
+ }
6192
+ }
6193
+
6194
+ // src/handlers/waitlist-offer.ts
6195
+ var import_scheduling58 = require("@ordinatio/scheduling");
6196
+ var import_zod18 = require("zod");
6197
+
6198
+ // src/handlers/appointments-book.ts
6199
+ var import_scheduling57 = require("@ordinatio/scheduling");
5927
6200
 
5928
6201
  // src/booking/booking-schema.ts
5929
- var import_zod13 = require("zod");
5930
- var BookingSchema = import_zod13.z.object({
5931
- calendarId: import_zod13.z.string().min(1).optional(),
5932
- preferredCalendarId: import_zod13.z.string().min(1).optional(),
5933
- typeId: import_zod13.z.string().min(1),
5934
- startTime: import_zod13.z.string().datetime({ message: "Invalid date/time format" }),
5935
- timezone: import_zod13.z.string().max(50).optional(),
5936
- clientName: import_zod13.z.string().trim().min(1, "Name is required").max(200),
5937
- clientEmail: import_zod13.z.string().email("Invalid email").max(254),
5938
- clientPhone: import_zod13.z.string().max(30).optional(),
6202
+ var import_zod17 = require("zod");
6203
+ var BookingSchema = import_zod17.z.object({
6204
+ calendarId: import_zod17.z.string().min(1).optional(),
6205
+ preferredCalendarId: import_zod17.z.string().min(1).optional(),
6206
+ typeId: import_zod17.z.string().min(1),
6207
+ startTime: import_zod17.z.string().datetime({ message: "Invalid date/time format" }),
6208
+ timezone: import_zod17.z.string().max(50).optional(),
6209
+ clientName: import_zod17.z.string().trim().min(1, "Name is required").max(200),
6210
+ clientEmail: import_zod17.z.string().email("Invalid email").max(254),
6211
+ clientPhone: import_zod17.z.string().max(30).optional(),
5939
6212
  // Untrusted: the host's client resolver decides whether to honor it.
5940
- clientId: import_zod13.z.string().optional(),
5941
- notes: import_zod13.z.string().max(1e3).optional(),
6213
+ clientId: import_zod17.z.string().optional(),
6214
+ notes: import_zod17.z.string().max(1e3).optional(),
5942
6215
  // Only the primitive types a form field produces; z.unknown() would accept anything.
5943
- intakeResponses: import_zod13.z.record(
5944
- import_zod13.z.string(),
5945
- import_zod13.z.union([import_zod13.z.string().max(1e3), import_zod13.z.number(), import_zod13.z.boolean(), import_zod13.z.null()])
6216
+ intakeResponses: import_zod17.z.record(
6217
+ import_zod17.z.string(),
6218
+ import_zod17.z.union([import_zod17.z.string().max(1e3), import_zod17.z.number(), import_zod17.z.boolean(), import_zod17.z.null()])
5946
6219
  ).optional(),
5947
- paymentId: import_zod13.z.string().optional(),
5948
- couponCode: import_zod13.z.string().min(1).max(50).transform((value) => value.trim().toUpperCase()).optional(),
5949
- packagePurchaseId: import_zod13.z.string().optional(),
6220
+ paymentId: import_zod17.z.string().optional(),
6221
+ couponCode: import_zod17.z.string().min(1).max(50).transform((value) => value.trim().toUpperCase()).optional(),
6222
+ packagePurchaseId: import_zod17.z.string().optional(),
5950
6223
  // Names the organization, so the calendar and type lookups can run against its own database.
5951
- orgSlug: import_zod13.z.string().min(1).max(100).optional()
6224
+ orgSlug: import_zod17.z.string().min(1).max(100).optional()
5952
6225
  });
5953
6226
 
5954
6227
  // src/booking/finalize-booking.ts
5955
- var import_scheduling50 = require("@ordinatio/scheduling");
6228
+ var import_scheduling54 = require("@ordinatio/scheduling");
5956
6229
  async function finalizeBooking(host, cors, db, organizationId, body, appointment, appointmentType, discountCents, appliedCouponCode, noShowApprovalOverride, clientId) {
5957
6230
  const logActivity = (action, description, metadata) => host.activity.log(db, { action, description, metadata });
5958
6231
  if (noShowApprovalOverride && appointment.status === "CONFIRMED") {
@@ -5995,7 +6268,7 @@ async function finalizeBooking(host, cors, db, organizationId, body, appointment
5995
6268
  AND ("expiresAt" IS NULL OR "expiresAt" > NOW())
5996
6269
  `;
5997
6270
  if (counted === 0) {
5998
- await (0, import_scheduling50.cancelAppointment)(db, {
6271
+ await (0, import_scheduling54.cancelAppointment)(db, {
5999
6272
  appointmentId: appointment.id,
6000
6273
  cancelledBy: "system",
6001
6274
  reason: "Coupon exhausted by concurrent booking during payment"
@@ -6014,7 +6287,7 @@ async function finalizeBooking(host, cors, db, organizationId, body, appointment
6014
6287
  }
6015
6288
  let meetingUrl = null;
6016
6289
  if (appointmentType.locationType === "VIRTUAL") {
6017
- meetingUrl = (0, import_scheduling50.buildJitsiUrl)(appointment.id);
6290
+ meetingUrl = (0, import_scheduling54.buildJitsiUrl)(appointment.id);
6018
6291
  try {
6019
6292
  await db.appointment.update({ where: { id: appointment.id }, data: { meetingUrl } });
6020
6293
  } catch (meetingError) {
@@ -6039,7 +6312,7 @@ async function finalizeBooking(host, cors, db, organizationId, body, appointment
6039
6312
  const baseUrl = host.appUrl();
6040
6313
  if (!baseUrl) throw new Error("The host must supply appUrl() to book appointments");
6041
6314
  try {
6042
- await (0, import_scheduling50.scheduleNotifications)(db, appointment.id, baseUrl);
6315
+ await (0, import_scheduling54.scheduleNotifications)(db, appointment.id, baseUrl, { brand: Boolean(host.brand) });
6043
6316
  } catch (error) {
6044
6317
  await logActivity(
6045
6318
  "scheduling.notification_schedule_failed",
@@ -6048,7 +6321,7 @@ async function finalizeBooking(host, cors, db, organizationId, body, appointment
6048
6321
  );
6049
6322
  }
6050
6323
  try {
6051
- await (0, import_scheduling50.queueStaffNotification)(db, appointment.id, "CONFIRMATION", baseUrl);
6324
+ await (0, import_scheduling54.queueStaffNotification)(db, appointment.id, "CONFIRMATION", baseUrl, { brand: Boolean(host.brand) });
6052
6325
  } catch (error) {
6053
6326
  await logActivity(
6054
6327
  "scheduling.staff_notification_failed",
@@ -6102,7 +6375,7 @@ async function finalizeBooking(host, cors, db, organizationId, body, appointment
6102
6375
  }
6103
6376
 
6104
6377
  // src/booking/refund-blocked-booking.ts
6105
- var import_scheduling51 = require("@ordinatio/scheduling");
6378
+ var import_scheduling55 = require("@ordinatio/scheduling");
6106
6379
  var REFUND_ON_CODES = ["SCHED_301", "SCHED_307", "SCHED_802", "SCHED_800", "SCHED_801", "SCHED_201", "SCHED_100", "SCHED_200", "SCHED_102"];
6107
6380
  function isBlockedBookingCode(code) {
6108
6381
  return code !== void 0 && REFUND_ON_CODES.includes(code);
@@ -6117,12 +6390,12 @@ async function respondToBlockedPaidBooking(db, payments, cors, paymentId, blocke
6117
6390
  try {
6118
6391
  existingBooking = await db.appointment.findFirst({ where: { paymentId }, select: { id: true } });
6119
6392
  } catch (lookupError) {
6120
- const err = (0, import_scheduling51.schedError)("SCHED_409", { paymentId, blockerCode, error: lookupError });
6393
+ const err = (0, import_scheduling55.schedError)("SCHED_409", { paymentId, blockerCode, error: lookupError });
6121
6394
  console.error("[booking] Could not check for an existing booking before refunding:", err.ref, lookupError);
6122
6395
  return corsJson(cors, { error: "We could not confirm your booking just now. Please try again.", ref: err.ref }, { status: 503 });
6123
6396
  }
6124
6397
  if (existingBooking) {
6125
- const err = (0, import_scheduling51.schedError)("SCHED_404", { paymentId, existingAppointmentId: existingBooking.id });
6398
+ const err = (0, import_scheduling55.schedError)("SCHED_404", { paymentId, existingAppointmentId: existingBooking.id });
6126
6399
  return corsJson(
6127
6400
  cors,
6128
6401
  { error: "This payment has already been used for a booking", ref: err.ref, code: "PAYMENT_ALREADY_USED" },
@@ -6249,7 +6522,7 @@ async function resolveBookingContext(host, cors, body) {
6249
6522
  }
6250
6523
 
6251
6524
  // src/booking/verify-booking-payment.ts
6252
- var import_scheduling52 = require("@ordinatio/scheduling");
6525
+ var import_scheduling56 = require("@ordinatio/scheduling");
6253
6526
  async function verifyBookingPayment(db, payments, cors, organizationId, appointmentType, body) {
6254
6527
  const refuse = (status, payload) => ({
6255
6528
  ok: false,
@@ -6266,7 +6539,7 @@ async function verifyBookingPayment(db, payments, cors, organizationId, appointm
6266
6539
  select: { id: true }
6267
6540
  });
6268
6541
  if (existingBooking) {
6269
- const err = (0, import_scheduling52.schedError)("SCHED_404", { paymentId: body.paymentId, existingAppointmentId: existingBooking.id });
6542
+ const err = (0, import_scheduling56.schedError)("SCHED_404", { paymentId: body.paymentId, existingAppointmentId: existingBooking.id });
6270
6543
  return refuse(409, {
6271
6544
  error: "This payment has already been used for a booking",
6272
6545
  ref: err.ref,
@@ -6276,7 +6549,7 @@ async function verifyBookingPayment(db, payments, cors, organizationId, appointm
6276
6549
  const metaTypeId = payment.metadata?.typeId;
6277
6550
  const metaClientEmail = payment.metadata?.clientEmail;
6278
6551
  if (metaTypeId !== body.typeId || metaClientEmail && metaClientEmail.toLowerCase() !== body.clientEmail.toLowerCase()) {
6279
- const err = (0, import_scheduling52.schedError)("SCHED_405", {
6552
+ const err = (0, import_scheduling56.schedError)("SCHED_405", {
6280
6553
  paymentId: body.paymentId,
6281
6554
  metaTypeId,
6282
6555
  bodyTypeId: body.typeId,
@@ -6306,7 +6579,7 @@ async function verifyBookingPayment(db, payments, cors, organizationId, appointm
6306
6579
  }
6307
6580
  }
6308
6581
  if (payment.amount === void 0) {
6309
- const err = (0, import_scheduling52.schedError)("SCHED_405", { paymentId: body.paymentId, currency: payment.currency });
6582
+ const err = (0, import_scheduling56.schedError)("SCHED_405", { paymentId: body.paymentId, currency: payment.currency });
6310
6583
  return refuse(400, { error: "Payment currency is not supported", ref: err.ref });
6311
6584
  }
6312
6585
  if (Math.round(payment.amount * 100) !== expectedCents) {
@@ -6347,7 +6620,7 @@ async function bookAppointmentRoute(request, { host }) {
6347
6620
  } catch (linkError) {
6348
6621
  console.error("[booking] client link lookup failed \u2014 saving the appointment unlinked:", linkError instanceof Error ? linkError.message : linkError);
6349
6622
  }
6350
- const appointment = await (0, import_scheduling53.bookAppointment)(db, {
6623
+ const appointment = await (0, import_scheduling57.bookAppointment)(db, {
6351
6624
  calendarId: body.calendarId,
6352
6625
  preferredCalendarId: body.preferredCalendarId,
6353
6626
  typeId: body.typeId,
@@ -6409,8 +6682,466 @@ async function bookAppointmentRoute(request, { host }) {
6409
6682
  }
6410
6683
  }
6411
6684
 
6685
+ // src/handlers/waitlist-offer.ts
6686
+ async function getWaitlistOfferRoute(request, { host }) {
6687
+ const cors = host.cors(request);
6688
+ if (!host.waitlist) return corsJson(cors, NOT_ENABLED2, { status: 501 });
6689
+ try {
6690
+ const limited = await host.rateLimit(`waitlist-offer:${clientAddress(request)}`, "AVAILABILITY");
6691
+ if (limited) return limited;
6692
+ const url = new URL(request.url);
6693
+ const token = url.searchParams.get("token");
6694
+ if (!token) return corsJson(cors, { error: "token is required" }, { status: 400 });
6695
+ const context = await resolveWaitlistDb(host, url.searchParams.get("orgSlug"));
6696
+ if (!context) return corsJson(cors, { error: "No open offer for this link", code: "SCHED_1106" }, { status: 404 });
6697
+ const offer = await (0, import_scheduling58.getWaitlistOffer)(context.db, token);
6698
+ return corsJson(cors, {
6699
+ typeName: offer.typeName,
6700
+ calendarName: offer.calendarName,
6701
+ startTime: offer.startTime,
6702
+ timezone: offer.timezone,
6703
+ expiresAt: offer.expiresAt,
6704
+ clientName: offer.clientName
6705
+ });
6706
+ } catch (error) {
6707
+ return waitlistErrorResponse(cors, error, "Failed to read the offer");
6708
+ }
6709
+ }
6710
+ var AcceptSchema = import_zod18.z.object({ token: import_zod18.z.string().min(1).max(200), orgSlug: import_zod18.z.string().min(1).max(100).optional() });
6711
+ async function acceptWaitlistOfferRoute(request, context) {
6712
+ const { host } = context;
6713
+ const cors = host.cors(request);
6714
+ const settings = host.waitlist;
6715
+ if (!settings) return corsJson(cors, NOT_ENABLED2, { status: 501 });
6716
+ let entryId = null;
6717
+ let db = null;
6718
+ let booked = false;
6719
+ try {
6720
+ const limited = await host.rateLimit(`waitlist-accept:${clientAddress(request)}`, "GENERAL");
6721
+ if (limited) return limited;
6722
+ const parsed = AcceptSchema.safeParse(await request.json().catch(() => null));
6723
+ if (!parsed.success) return corsJson(cors, { error: "token is required" }, { status: 400 });
6724
+ db = await resolveWaitlistDb(host, parsed.data.orgSlug);
6725
+ if (!db) return corsJson(cors, { error: "No open offer for this link", code: "SCHED_1106" }, { status: 404 });
6726
+ const offer = await (0, import_scheduling58.beginWaitlistAccept)(db.db, parsed.data.token);
6727
+ entryId = offer.entryId;
6728
+ const headers = new Headers(request.headers);
6729
+ headers.set("content-type", "application/json");
6730
+ const response = await bookAppointmentRoute(
6731
+ new Request(request.url, {
6732
+ method: "POST",
6733
+ headers,
6734
+ body: JSON.stringify({
6735
+ calendarId: offer.calendarId,
6736
+ typeId: offer.typeId,
6737
+ startTime: offer.startTime.toISOString(),
6738
+ timezone: offer.timezone,
6739
+ clientName: offer.clientName,
6740
+ clientEmail: offer.clientEmail,
6741
+ ...offer.clientPhone ? { clientPhone: offer.clientPhone } : {},
6742
+ ...parsed.data.orgSlug ? { orgSlug: parsed.data.orgSlug } : {}
6743
+ })
6744
+ }),
6745
+ context
6746
+ );
6747
+ if (response.status === 201) {
6748
+ booked = true;
6749
+ const appointment = await response.clone().json().catch(() => null);
6750
+ try {
6751
+ await (0, import_scheduling58.completeWaitlistAccept)(db.db, entryId, appointment?.id ?? "");
6752
+ } catch (completeError) {
6753
+ console.error("[waitlist] the booking was saved but its waitlist entry could not be marked booked:", completeError);
6754
+ }
6755
+ return response;
6756
+ }
6757
+ const saved = await (0, import_scheduling58.settleBookedAccept)(db.db, entryId);
6758
+ if (saved) return corsJson(cors, saved, { status: 201 });
6759
+ await endFailedAccept(host, settings, db.db, entryId, releaseFor(response.status));
6760
+ return response;
6761
+ } catch (error) {
6762
+ if (entryId && db && !booked) {
6763
+ try {
6764
+ const saved = await (0, import_scheduling58.settleBookedAccept)(db.db, entryId);
6765
+ if (saved) return corsJson(cors, saved, { status: 201 });
6766
+ await endFailedAccept(host, settings, db.db, entryId, "KEEP_OFFER");
6767
+ } catch (releaseError) {
6768
+ console.error("[waitlist] could not settle or release an accept:", releaseError);
6769
+ }
6770
+ }
6771
+ return waitlistErrorResponse(cors, error, "Failed to accept the offer");
6772
+ }
6773
+ }
6774
+ function releaseFor(status) {
6775
+ if (status === 409) return "BACK_IN_LINE";
6776
+ if (status === 429 || status >= 500) return "KEEP_OFFER";
6777
+ return "DROP";
6778
+ }
6779
+ async function endFailedAccept(host, settings, db, entryId, outcome) {
6780
+ const freed = await (0, import_scheduling58.releaseWaitlistAccept)(db, entryId, outcome);
6781
+ if (freed) await offerAndAnnounce(host, settings, db, freed);
6782
+ }
6783
+
6784
+ // src/handlers/admin-waitlist.ts
6785
+ var import_scheduling59 = require("@ordinatio/scheduling");
6786
+ var STATUSES2 = /* @__PURE__ */ new Set(["WAITING", "OFFERED", "ACCEPTING", "BOOKED", "EXPIRED"]);
6787
+ async function listWaitlistEntries(request, { host }) {
6788
+ try {
6789
+ const guard = await requireWaitlistAdmin(host, request, { action: "admin-waitlist-list", tier: "GENERAL" });
6790
+ if (guard instanceof Response) return guard;
6791
+ const status = new URL(request.url).searchParams.get("status");
6792
+ if (status && !STATUSES2.has(status)) {
6793
+ return Response.json({ error: `status must be one of ${[...STATUSES2].join(", ")}` }, { status: 400 });
6794
+ }
6795
+ const { limit, offset } = parsePagination(request);
6796
+ const { entries, total } = await (0, import_scheduling59.listWaitlist)(guard.staff.db, {
6797
+ organizationId: guard.staff.organizationId,
6798
+ status: status ?? void 0,
6799
+ limit,
6800
+ offset
6801
+ });
6802
+ return Response.json({ entries, total, hasMore: offset + entries.length < total });
6803
+ } catch (error) {
6804
+ return webhookErrorResponse(error, "Failed to list the waitlist");
6805
+ }
6806
+ }
6807
+ async function removeWaitlistEntryRoute(request, { host, params }) {
6808
+ try {
6809
+ const guard = await requireWaitlistAdmin(host, request, { action: "admin-waitlist-remove", tier: "DELETE" });
6810
+ if (guard instanceof Response) return guard;
6811
+ const { db, organizationId } = guard.staff;
6812
+ const freed = await (0, import_scheduling59.removeWaitlistEntry)(db, organizationId, params.id);
6813
+ await host.activity.log(db, {
6814
+ action: "scheduling.waitlist_entry_removed",
6815
+ description: "removed someone from the waitlist",
6816
+ metadata: { entryId: params.id }
6817
+ });
6818
+ if (freed) await offerAndAnnounce(host, guard.settings, db, freed);
6819
+ return Response.json({ success: true });
6820
+ } catch (error) {
6821
+ return webhookErrorResponse(error, "Failed to remove the waitlist entry");
6822
+ }
6823
+ }
6824
+
6825
+ // src/handlers/internal-waitlist-sweep.ts
6826
+ var import_scheduling60 = require("@ordinatio/scheduling");
6827
+ async function sweepWaitlist(request, { host }) {
6828
+ if (!await host.internalAccess.isAuthorized(request)) return Response.json({ error: "Unauthorized" }, { status: 401 });
6829
+ if (!host.waitlist) return Response.json(NOT_ENABLED2, { status: 501 });
6830
+ const limited = await host.rateLimit(`${request.headers.get("x-forwarded-for") ?? "worker"}:waitlist-sweep`, "INTERNAL");
6831
+ if (limited) return limited;
6832
+ try {
6833
+ const db = await host.publicDb();
6834
+ const { lapsed, released, booked } = await (0, import_scheduling60.expireWaitlistOffers)(db);
6835
+ let reoffered = 0;
6836
+ for (const slot of lapsed) {
6837
+ if (await offerAndAnnounce(host, host.waitlist, db, slot)) reoffered++;
6838
+ }
6839
+ return Response.json({ lapsed: lapsed.length, released, booked, reoffered });
6840
+ } catch (error) {
6841
+ console.error("[scheduling-api] waitlist sweep failed:", error);
6842
+ return Response.json({ error: "Waitlist sweep failed" }, { status: 500 });
6843
+ }
6844
+ }
6845
+
6846
+ // src/handlers/routing-forms-public.ts
6847
+ var import_scheduling62 = require("@ordinatio/scheduling");
6848
+
6849
+ // src/routing/routing-http.ts
6850
+ var import_scheduling61 = require("@ordinatio/scheduling");
6851
+ var NOT_ENABLED3 = { error: "Routing forms are not enabled on this server" };
6852
+ var STATUS_BY_CODE2 = { SCHED_1201: 404, SCHED_1202: 409, SCHED_1204: 409 };
6853
+ function routingErrorResponse(error, fallback, cors) {
6854
+ const send = (payload, status) => cors ? corsJson(cors, payload, { status }) : Response.json(payload, { status });
6855
+ if (error instanceof import_scheduling61.SchedulingValidationError || error instanceof import_scheduling61.SchedulingNotFoundError) {
6856
+ const details = error.context.errors;
6857
+ const status = STATUS_BY_CODE2[error.code] ?? 400;
6858
+ return send({ error: error.message, code: error.code, ref: getErrorRef(error), ...details ? { details } : {} }, status);
6859
+ }
6860
+ console.error("[routing-forms]", error);
6861
+ return send({ error: fallback }, 500);
6862
+ }
6863
+ async function requireRoutingAdmin(host, request, options) {
6864
+ const staff = await requireAdminStaff(host, request, options);
6865
+ if (staff instanceof Response) return staff;
6866
+ if (!host.routingForms) return Response.json(NOT_ENABLED3, { status: 501 });
6867
+ return staff;
6868
+ }
6869
+
6870
+ // src/handlers/routing-forms-public.ts
6871
+ async function resolveOrganization(host, orgSlug) {
6872
+ if (!orgSlug) return { db: await host.publicDb(), organizationId: null };
6873
+ return host.organizations.resolve({ orgSlug, logPrefix: "[routing-forms]" });
6874
+ }
6875
+ async function getRoutingFormRoute(request, { host }) {
6876
+ const cors = host.cors(request);
6877
+ if (!host.routingForms) return corsJson(cors, NOT_ENABLED3, { status: 501 });
6878
+ try {
6879
+ const limited = await host.rateLimit(`routing-form:${clientAddress(request)}`, "AVAILABILITY");
6880
+ if (limited) return limited;
6881
+ const url = new URL(request.url);
6882
+ const slug = url.searchParams.get("slug");
6883
+ if (!slug) return corsJson(cors, { error: "slug is required" }, { status: 400 });
6884
+ const context = await resolveOrganization(host, url.searchParams.get("orgSlug"));
6885
+ if (!context) return corsJson(cors, { error: "Routing form not found", code: "SCHED_1201" }, { status: 404 });
6886
+ return corsJson(cors, await (0, import_scheduling62.getPublicRoutingForm)(context.db, { organizationId: context.organizationId, slug }));
6887
+ } catch (error) {
6888
+ return routingErrorResponse(error, "Failed to read the form", cors);
6889
+ }
6890
+ }
6891
+ async function routeClientRoute(request, { host }) {
6892
+ const cors = host.cors(request);
6893
+ if (!host.routingForms) return corsJson(cors, NOT_ENABLED3, { status: 501 });
6894
+ try {
6895
+ const limited = await host.rateLimit(`routing-route:${clientAddress(request)}`, "AVAILABILITY");
6896
+ if (limited) return limited;
6897
+ const parsed = RouteClientSchema.safeParse(await request.json().catch(() => null));
6898
+ if (!parsed.success) {
6899
+ const details = parsed.error.issues.map((issue) => ({ field: issue.path.join("."), message: issue.message }));
6900
+ return corsJson(cors, { error: "Validation failed", details }, { status: 400 });
6901
+ }
6902
+ const context = await resolveOrganization(host, parsed.data.orgSlug);
6903
+ if (!context) return corsJson(cors, { error: "Routing form not found", code: "SCHED_1201" }, { status: 404 });
6904
+ const outcome = await (0, import_scheduling62.routeClient)(context.db, { organizationId: context.organizationId, slug: parsed.data.slug, answers: parsed.data.answers });
6905
+ return corsJson(cors, outcome);
6906
+ } catch (error) {
6907
+ return routingErrorResponse(error, "Failed to route the answers", cors);
6908
+ }
6909
+ }
6910
+
6911
+ // src/handlers/admin-routing-forms.ts
6912
+ var import_scheduling63 = require("@ordinatio/scheduling");
6913
+ async function listRoutingFormsRoute(request, { host }) {
6914
+ try {
6915
+ const staff = await requireRoutingAdmin(host, request, { action: "admin-routing-forms-list", tier: "GENERAL" });
6916
+ if (staff instanceof Response) return staff;
6917
+ return Response.json({ forms: await (0, import_scheduling63.listRoutingForms)(staff.db, staff.organizationId) });
6918
+ } catch (error) {
6919
+ return routingErrorResponse(error, "Failed to list the forms");
6920
+ }
6921
+ }
6922
+ async function createRoutingFormRoute(request, { host }) {
6923
+ try {
6924
+ const staff = await requireRoutingAdmin(host, request, { action: "admin-routing-forms-create", tier: "CREATE" });
6925
+ if (staff instanceof Response) return staff;
6926
+ const validation = await parseBody(request, CreateRoutingFormSchema);
6927
+ if (!validation.success) return validation.response;
6928
+ const form = await (0, import_scheduling63.createRoutingForm)(staff.db, staff.organizationId, validation.data);
6929
+ await host.activity.log(staff.db, {
6930
+ action: "scheduling.routing_form_created",
6931
+ description: `created routing form "${form.name}"`,
6932
+ metadata: { formId: form.id, slug: form.slug }
6933
+ });
6934
+ return Response.json({ form }, { status: 201 });
6935
+ } catch (error) {
6936
+ return routingErrorResponse(error, "Failed to save the form");
6937
+ }
6938
+ }
6939
+
6940
+ // src/handlers/brand-public.ts
6941
+ var import_scheduling64 = require("@ordinatio/scheduling");
6942
+ async function getBrandRoute(request, { host }) {
6943
+ const cors = host.cors(request);
6944
+ if (!host.brand) return corsJson(cors, NOT_ENABLED, { status: 501 });
6945
+ try {
6946
+ const limited = await host.rateLimit(`brand:${clientAddress(request)}`, "AVAILABILITY");
6947
+ if (limited) return limited;
6948
+ const orgSlug = new URL(request.url).searchParams.get("orgSlug");
6949
+ const context = orgSlug ? await host.organizations.resolve({ orgSlug, logPrefix: "[brand]" }) : { db: await host.publicDb(), organizationId: null };
6950
+ const brand = context ? await (0, import_scheduling64.getPublicBrand)(context.db, context.organizationId) : null;
6951
+ if (!brand) return corsJson(cors, { error: "No brand set" }, { status: 404 });
6952
+ return corsJson(cors, { brand }, { headers: WIDGET_CACHE_HEADERS });
6953
+ } catch (error) {
6954
+ return brandErrorResponse(error, "Failed to read the brand", cors);
6955
+ }
6956
+ }
6957
+
6958
+ // src/handlers/admin-brand.ts
6959
+ var import_scheduling65 = require("@ordinatio/scheduling");
6960
+ async function getBrandAdminRoute(request, { host }) {
6961
+ try {
6962
+ const staff = await requireBrandAdmin(host, request, { action: "admin-brand-get", tier: "GENERAL" });
6963
+ if (staff instanceof Response) return staff;
6964
+ return Response.json({ brand: await (0, import_scheduling65.getBrand)(staff.db, staff.organizationId) });
6965
+ } catch (error) {
6966
+ return brandErrorResponse(error, "Failed to read the brand");
6967
+ }
6968
+ }
6969
+ async function saveBrandRoute(request, { host }) {
6970
+ try {
6971
+ const staff = await requireBrandAdmin(host, request, { action: "admin-brand-save", tier: "UPDATE" });
6972
+ if (staff instanceof Response) return staff;
6973
+ const validation = await parseBody(request, BrandSchema);
6974
+ if (!validation.success) return validation.response;
6975
+ const verifier = host.brand?.isSendingDomainVerified;
6976
+ const brand = await (0, import_scheduling65.saveBrand)(staff.db, staff.organizationId, validation.data, {
6977
+ isSendingDomainVerified: verifier ? async (domain) => Boolean(await verifier.call(host.brand, domain, staff.organizationId)) : void 0
6978
+ });
6979
+ await host.activity.log(staff.db, {
6980
+ action: "scheduling.brand_saved",
6981
+ description: "changed the brand",
6982
+ metadata: { displayName: brand.displayName, sendsFromOwnDomain: Boolean(brand.fromEmail) }
6983
+ });
6984
+ return Response.json({ brand });
6985
+ } catch (error) {
6986
+ return brandErrorResponse(error, "Failed to save the brand");
6987
+ }
6988
+ }
6989
+ async function deleteBrandRoute(request, { host }) {
6990
+ try {
6991
+ const staff = await requireBrandAdmin(host, request, { action: "admin-brand-delete", tier: "DELETE" });
6992
+ if (staff instanceof Response) return staff;
6993
+ const removed = await (0, import_scheduling65.deleteBrand)(staff.db, staff.organizationId);
6994
+ if (removed) await host.activity.log(staff.db, { action: "scheduling.brand_removed", description: "removed the brand", metadata: {} });
6995
+ return Response.json({ removed });
6996
+ } catch (error) {
6997
+ return brandErrorResponse(error, "Failed to remove the brand");
6998
+ }
6999
+ }
7000
+
7001
+ // src/handlers/admin-privacy.ts
7002
+ var import_scheduling67 = require("@ordinatio/scheduling");
7003
+
7004
+ // src/privacy/privacy-http.ts
7005
+ var import_scheduling66 = require("@ordinatio/scheduling");
7006
+ var NOT_ENABLED4 = { error: "Data export and erasure are not enabled on this server" };
7007
+ var STATUS_BY_CODE3 = { SCHED_1300: 400, SCHED_1301: 409 };
7008
+ function privacyErrorResponse(error, fallback) {
7009
+ if (error instanceof import_scheduling66.SchedulingValidationError) {
7010
+ return Response.json(
7011
+ { error: error.message, code: error.code, ref: getErrorRef(error), details: error.context },
7012
+ { status: STATUS_BY_CODE3[error.code] ?? 400 }
7013
+ );
7014
+ }
7015
+ console.error("[privacy]", error);
7016
+ return Response.json({ error: fallback }, { status: 500 });
7017
+ }
7018
+ async function requirePrivacyAdmin(host, request, options) {
7019
+ const staff = await requireAdminStaff(host, request, options);
7020
+ if (staff instanceof Response) return staff;
7021
+ if (!host.privacy) return Response.json(NOT_ENABLED4, { status: 501 });
7022
+ return staff;
7023
+ }
7024
+
7025
+ // src/handlers/admin-privacy.ts
7026
+ async function logQuietly(host, db, entry) {
7027
+ try {
7028
+ await host.activity.log(db, entry);
7029
+ } catch (error) {
7030
+ console.error("[privacy] could not write the activity entry:", error);
7031
+ }
7032
+ }
7033
+ async function exportPrivacyRoute(request, { host }) {
7034
+ try {
7035
+ const staff = await requirePrivacyAdmin(host, request, { action: "admin-privacy-export", tier: "CREATE" });
7036
+ if (staff instanceof Response) return staff;
7037
+ const validation = await parseBody(request, PrivacySubjectSchema);
7038
+ if (!validation.success) return validation.response;
7039
+ const result = await (0, import_scheduling67.exportSubject)(staff.db, { organizationId: staff.organizationId, requestedBy: staff.userId, ...validation.data });
7040
+ await logQuietly(host, staff.db, {
7041
+ action: "scheduling.privacy_export",
7042
+ description: "exported the data held about one person",
7043
+ metadata: { counts: result.counts }
7044
+ });
7045
+ const stamp = result.exportedAt.slice(0, 10);
7046
+ return new Response(JSON.stringify(result, null, 2), {
7047
+ status: 200,
7048
+ headers: {
7049
+ "content-type": "application/json; charset=utf-8",
7050
+ "content-disposition": `attachment; filename="scheduling-data-export-${stamp}.json"`,
7051
+ "cache-control": "no-store"
7052
+ }
7053
+ });
7054
+ } catch (error) {
7055
+ return privacyErrorResponse(error, "Failed to export the data");
7056
+ }
7057
+ }
7058
+ async function erasePrivacyRoute(request, { host }) {
7059
+ try {
7060
+ const staff = await requirePrivacyAdmin(host, request, { action: "admin-privacy-erase", tier: "DELETE" });
7061
+ if (staff instanceof Response) return staff;
7062
+ const validation = await parseBody(request, PrivacyEraseSchema);
7063
+ if (!validation.success) return validation.response;
7064
+ const { confirm, ...subject2 } = validation.data;
7065
+ if (confirm !== true) {
7066
+ const preview = await (0, import_scheduling67.previewErase)(staff.db, { organizationId: staff.organizationId, ...subject2 });
7067
+ return Response.json({ erased: false, preview }, { headers: { "cache-control": "no-store" } });
7068
+ }
7069
+ const { counts } = await (0, import_scheduling67.eraseSubject)(staff.db, { organizationId: staff.organizationId, requestedBy: staff.userId, ...subject2 });
7070
+ await logQuietly(host, staff.db, {
7071
+ action: "scheduling.privacy_erase",
7072
+ description: "erased the data held about one person",
7073
+ metadata: { counts }
7074
+ });
7075
+ return Response.json({ erased: true, counts }, { headers: { "cache-control": "no-store" } });
7076
+ } catch (error) {
7077
+ return privacyErrorResponse(error, "Failed to erase the data");
7078
+ }
7079
+ }
7080
+ async function listPrivacyRequestsRoute(request, { host }) {
7081
+ try {
7082
+ const staff = await requirePrivacyAdmin(host, request, { action: "admin-privacy-requests", tier: "GENERAL" });
7083
+ if (staff instanceof Response) return staff;
7084
+ const { limit, offset } = parsePagination(request);
7085
+ const { requests, total } = await (0, import_scheduling67.listPrivacyRequests)(staff.db, { organizationId: staff.organizationId, limit, offset });
7086
+ return Response.json({ requests, total, hasMore: offset + requests.length < total });
7087
+ } catch (error) {
7088
+ return privacyErrorResponse(error, "Failed to list the requests");
7089
+ }
7090
+ }
7091
+
7092
+ // src/handlers/admin-routing-form-detail.ts
7093
+ var import_scheduling68 = require("@ordinatio/scheduling");
7094
+ async function getRoutingFormAdminRoute(request, { host, params }) {
7095
+ try {
7096
+ const staff = await requireRoutingAdmin(host, request, { action: "admin-routing-forms-get", tier: "GENERAL" });
7097
+ if (staff instanceof Response) return staff;
7098
+ return Response.json({ form: await (0, import_scheduling68.getRoutingForm)(staff.db, staff.organizationId, params.id) });
7099
+ } catch (error) {
7100
+ return routingErrorResponse(error, "Failed to read the form");
7101
+ }
7102
+ }
7103
+ async function updateRoutingFormRoute(request, { host, params }) {
7104
+ try {
7105
+ const staff = await requireRoutingAdmin(host, request, { action: "admin-routing-forms-update", tier: "UPDATE" });
7106
+ if (staff instanceof Response) return staff;
7107
+ const validation = await parseBody(request, UpdateRoutingFormSchema);
7108
+ if (!validation.success) return validation.response;
7109
+ const form = await (0, import_scheduling68.updateRoutingForm)(staff.db, staff.organizationId, params.id, validation.data);
7110
+ await host.activity.log(staff.db, {
7111
+ action: "scheduling.routing_form_updated",
7112
+ description: `changed routing form "${form.name}"`,
7113
+ metadata: { formId: form.id, fields: Object.keys(validation.data) }
7114
+ });
7115
+ return Response.json({ form });
7116
+ } catch (error) {
7117
+ return routingErrorResponse(error, "Failed to save the form");
7118
+ }
7119
+ }
7120
+ async function deleteRoutingFormRoute(request, { host, params }) {
7121
+ try {
7122
+ const staff = await requireRoutingAdmin(host, request, { action: "admin-routing-forms-delete", tier: "DELETE" });
7123
+ if (staff instanceof Response) return staff;
7124
+ await (0, import_scheduling68.deleteRoutingForm)(staff.db, staff.organizationId, params.id);
7125
+ await host.activity.log(staff.db, { action: "scheduling.routing_form_deleted", description: "removed a routing form", metadata: { formId: params.id } });
7126
+ return Response.json({ success: true });
7127
+ } catch (error) {
7128
+ return routingErrorResponse(error, "Failed to remove the form");
7129
+ }
7130
+ }
7131
+ async function testRoutingFormRoute(request, { host, params }) {
7132
+ try {
7133
+ const staff = await requireRoutingAdmin(host, request, { action: "admin-routing-forms-test", tier: "GENERAL" });
7134
+ if (staff instanceof Response) return staff;
7135
+ const validation = await parseBody(request, TestRoutingFormSchema);
7136
+ if (!validation.success) return validation.response;
7137
+ return Response.json(await (0, import_scheduling68.testRoutingForm)(staff.db, { organizationId: staff.organizationId, id: params.id, answers: validation.data.answers }));
7138
+ } catch (error) {
7139
+ return routingErrorResponse(error, "Failed to test the form");
7140
+ }
7141
+ }
7142
+
6412
7143
  // src/handlers/appointments-list.ts
6413
- var import_scheduling54 = require("@ordinatio/scheduling");
7144
+ var import_scheduling69 = require("@ordinatio/scheduling");
6414
7145
  var DEFAULT_LIMIT2 = 50;
6415
7146
  var MAX_LIMIT2 = 500;
6416
7147
  async function listAppointments(request, { host }) {
@@ -6422,7 +7153,7 @@ async function listAppointments(request, { host }) {
6422
7153
  const clientId = params.get("clientId") || void 0;
6423
7154
  const status = params.get("status") || void 0;
6424
7155
  if (!clientId && !staff.isAdmin) {
6425
- const err = (0, import_scheduling54.schedError)("SCHED_900", { role: staff.role });
7156
+ const err = (0, import_scheduling69.schedError)("SCHED_900", { role: staff.role });
6426
7157
  return Response.json({ error: "Forbidden", ref: err.ref }, { status: 403 });
6427
7158
  }
6428
7159
  const startDate = params.get("startDate");
@@ -6433,7 +7164,7 @@ async function listAppointments(request, { host }) {
6433
7164
  MAX_LIMIT2
6434
7165
  );
6435
7166
  const visibility = await staff.visibleCalendars();
6436
- const where = {
7167
+ const where = (0, import_scheduling69.withOrganization)({
6437
7168
  ...visibility ? { calendar: visibility } : {},
6438
7169
  ...calendarId ? { calendarId } : {},
6439
7170
  ...clientId ? { clientId } : {},
@@ -6444,7 +7175,7 @@ async function listAppointments(request, { host }) {
6444
7175
  ...endDate ? { lte: new Date(endDate) } : {}
6445
7176
  }
6446
7177
  } : {}
6447
- };
7178
+ }, staff.organizationId);
6448
7179
  const [rows, total] = await Promise.all([
6449
7180
  staff.db.appointment.findMany({
6450
7181
  where,
@@ -6502,7 +7233,7 @@ async function listAppointments(request, { host }) {
6502
7233
  }
6503
7234
 
6504
7235
  // src/handlers/availability.ts
6505
- var import_scheduling55 = require("@ordinatio/scheduling");
7236
+ var import_scheduling70 = require("@ordinatio/scheduling");
6506
7237
 
6507
7238
  // src/availability/picked-day.ts
6508
7239
  var CALENDAR_DAY_SHAPE = /^\d{4}-\d{2}-\d{2}$/;
@@ -6615,7 +7346,7 @@ async function getAvailability(request, { host }) {
6615
7346
  const cached = await readCache(host.availabilityCache, calendarId, cacheDay, typeDuration);
6616
7347
  if (cached != null) return corsJson(cors, cached);
6617
7348
  }
6618
- const result = await (0, import_scheduling55.getAvailableSlots)(db, {
7349
+ const result = await (0, import_scheduling70.getAvailableSlots)(db, {
6619
7350
  calendarId,
6620
7351
  date: dateObj,
6621
7352
  localDate: pickedDay,
@@ -6636,7 +7367,7 @@ async function getAvailability(request, { host }) {
6636
7367
  }
6637
7368
 
6638
7369
  // src/handlers/availability-team.ts
6639
- var import_scheduling56 = require("@ordinatio/scheduling");
7370
+ var import_scheduling71 = require("@ordinatio/scheduling");
6640
7371
 
6641
7372
  // src/loaders/team-type.ts
6642
7373
  async function loadTeamType(db, typeId, organizationId) {
@@ -6684,7 +7415,7 @@ async function getTeamAvailability(request, { host }) {
6684
7415
  { status: 400 }
6685
7416
  );
6686
7417
  }
6687
- const result = await (0, import_scheduling56.getTeamAvailableSlots)(db, {
7418
+ const result = await (0, import_scheduling71.getTeamAvailableSlots)(db, {
6688
7419
  typeId,
6689
7420
  date: dateObj,
6690
7421
  localDate: pickedCalendarDay(date),
@@ -6707,7 +7438,7 @@ async function getTeamAvailability(request, { host }) {
6707
7438
  }
6708
7439
 
6709
7440
  // src/handlers/appointment-types.ts
6710
- var import_scheduling57 = require("@ordinatio/scheduling");
7441
+ var import_scheduling72 = require("@ordinatio/scheduling");
6711
7442
 
6712
7443
  // src/loaders/types-by-calendar.ts
6713
7444
  function loadTypesByCalendarSlug(cache, db, organizationId, calendarSlug) {
@@ -6781,19 +7512,19 @@ async function getAppointmentTypes(request, { host }) {
6781
7512
  }));
6782
7513
  return corsJson(cors, response, { headers: WIDGET_CACHE_HEADERS });
6783
7514
  } catch (error) {
6784
- const diagnostic = (0, import_scheduling57.schedError)("SCHED_202", { error });
7515
+ const diagnostic = (0, import_scheduling72.schedError)("SCHED_202", { error });
6785
7516
  console.error("[appointment-types]", diagnostic.ref, error);
6786
7517
  return corsJson(cors, { error: "Failed to fetch appointment types", ref: diagnostic.ref }, { status: 500 });
6787
7518
  }
6788
7519
  }
6789
7520
 
6790
7521
  // src/handlers/coupons-validate.ts
6791
- var import_zod14 = require("zod");
6792
- var import_scheduling58 = require("@ordinatio/scheduling");
6793
- var Schema4 = import_zod14.z.object({
6794
- code: import_zod14.z.string().min(1).max(50).transform((v) => v.trim().toUpperCase()),
6795
- calendarId: import_zod14.z.string().min(1),
6796
- price: import_zod14.z.number().positive()
7522
+ var import_zod19 = require("zod");
7523
+ var import_scheduling73 = require("@ordinatio/scheduling");
7524
+ var Schema4 = import_zod19.z.object({
7525
+ code: import_zod19.z.string().min(1).max(50).transform((v) => v.trim().toUpperCase()),
7526
+ calendarId: import_zod19.z.string().min(1),
7527
+ price: import_zod19.z.number().positive()
6797
7528
  });
6798
7529
  function calculateDiscount(price, discountType, discountValue) {
6799
7530
  if (discountType === "PERCENTAGE") {
@@ -6851,7 +7582,7 @@ async function validateCoupon(request, { host }) {
6851
7582
  { headers: host.cors(request) }
6852
7583
  );
6853
7584
  } catch (error) {
6854
- const err = (0, import_scheduling58.schedError)("SCHED_408", {
7585
+ const err = (0, import_scheduling73.schedError)("SCHED_408", {
6855
7586
  calendarId,
6856
7587
  error: error instanceof Error ? error.message : String(error)
6857
7588
  });
@@ -6906,7 +7637,7 @@ async function getPublicCalendar(request, { host }) {
6906
7637
  }
6907
7638
 
6908
7639
  // src/handlers/type.ts
6909
- var import_scheduling59 = require("@ordinatio/scheduling");
7640
+ var import_scheduling74 = require("@ordinatio/scheduling");
6910
7641
 
6911
7642
  // src/loaders/type-by-slug.ts
6912
7643
  function loadTypeBySlug(cache, db, organizationId, slug) {
@@ -7011,14 +7742,14 @@ async function getType(request, { host }) {
7011
7742
  { headers: WIDGET_CACHE_HEADERS }
7012
7743
  );
7013
7744
  } catch (error) {
7014
- const diagnostic = (0, import_scheduling59.schedError)("SCHED_207", { error });
7745
+ const diagnostic = (0, import_scheduling74.schedError)("SCHED_207", { error });
7015
7746
  console.error("[type]", diagnostic.ref, error);
7016
7747
  return corsJson(cors, { error: "Failed to fetch appointment type", ref: diagnostic.ref }, { status: 500 });
7017
7748
  }
7018
7749
  }
7019
7750
 
7020
7751
  // src/handlers/widget-init.ts
7021
- var import_scheduling60 = require("@ordinatio/scheduling");
7752
+ var import_scheduling75 = require("@ordinatio/scheduling");
7022
7753
 
7023
7754
  // src/loaders/widget-data.ts
7024
7755
  function loadWidgetData(cache, db, organizationId, calendarSlug) {
@@ -7107,7 +7838,7 @@ async function getWidgetInit(request, { host }) {
7107
7838
  }));
7108
7839
  return corsJson(cors, { calendar, types: sanitizedTypes }, { headers: WIDGET_CACHE_HEADERS });
7109
7840
  } catch (error) {
7110
- const diagnostic = (0, import_scheduling60.schedError)("SCHED_206", { error });
7841
+ const diagnostic = (0, import_scheduling75.schedError)("SCHED_206", { error });
7111
7842
  console.error("[widget-init]", diagnostic.ref, error);
7112
7843
  return corsJson(cors, { error: "Failed to load widget data", ref: diagnostic.ref }, { status: 500 });
7113
7844
  }
@@ -7124,6 +7855,13 @@ var ROUTES = [
7124
7855
  { method: "GET", path: "/availability", public: true, handler: getAvailability },
7125
7856
  { method: "GET", path: "/availability/team", public: true, handler: getTeamAvailability },
7126
7857
  { method: "POST", path: "/appointments", public: true, handler: bookAppointmentRoute },
7858
+ { method: "GET", path: "/routing-forms", public: true, handler: getRoutingFormRoute },
7859
+ { method: "POST", path: "/routing-forms/route", public: true, handler: routeClientRoute },
7860
+ { method: "GET", path: "/brand", public: true, handler: getBrandRoute },
7861
+ { method: "POST", path: "/waitlist", public: true, handler: joinWaitlistRoute },
7862
+ { method: "DELETE", path: "/waitlist", public: true, handler: leaveWaitlistRoute },
7863
+ { method: "GET", path: "/waitlist/offer", public: true, handler: getWaitlistOfferRoute },
7864
+ { method: "POST", path: "/waitlist/offer/accept", public: true, handler: acceptWaitlistOfferRoute },
7127
7865
  { method: "GET", path: "/appointments", public: false, handler: listAppointments },
7128
7866
  { method: "GET", path: "/appointments/capacity", public: true, handler: getCapacity },
7129
7867
  { method: "GET", path: "/appointments/ical", public: false, handler: getAppointmentIcal },
@@ -7165,6 +7903,21 @@ var ROUTES = [
7165
7903
  { method: "GET", path: "/admin/webhooks/[id]/deliveries", public: false, handler: listWebhookEndpointDeliveries },
7166
7904
  { method: "POST", path: "/admin/webhook-deliveries/[id]/retry", public: false, handler: retryWebhook },
7167
7905
  { method: "POST", path: "/internal/webhooks/deliver", public: false, handler: deliverWebhooks },
7906
+ { method: "GET", path: "/admin/routing-forms", public: false, handler: listRoutingFormsRoute },
7907
+ { method: "POST", path: "/admin/routing-forms", public: false, handler: createRoutingFormRoute },
7908
+ { method: "GET", path: "/admin/routing-forms/[id]", public: false, handler: getRoutingFormAdminRoute },
7909
+ { method: "PUT", path: "/admin/routing-forms/[id]", public: false, handler: updateRoutingFormRoute },
7910
+ { method: "DELETE", path: "/admin/routing-forms/[id]", public: false, handler: deleteRoutingFormRoute },
7911
+ { method: "POST", path: "/admin/routing-forms/[id]/test", public: false, handler: testRoutingFormRoute },
7912
+ { method: "GET", path: "/admin/brand", public: false, handler: getBrandAdminRoute },
7913
+ { method: "PUT", path: "/admin/brand", public: false, handler: saveBrandRoute },
7914
+ { method: "DELETE", path: "/admin/brand", public: false, handler: deleteBrandRoute },
7915
+ { method: "POST", path: "/admin/privacy/export", public: false, handler: exportPrivacyRoute },
7916
+ { method: "POST", path: "/admin/privacy/erase", public: false, handler: erasePrivacyRoute },
7917
+ { method: "GET", path: "/admin/privacy/requests", public: false, handler: listPrivacyRequestsRoute },
7918
+ { method: "GET", path: "/admin/waitlist", public: false, handler: listWaitlistEntries },
7919
+ { method: "DELETE", path: "/admin/waitlist/[id]", public: false, handler: removeWaitlistEntryRoute },
7920
+ { method: "POST", path: "/internal/waitlist/sweep", public: false, handler: sweepWaitlist },
7168
7921
  { method: "GET", path: "/analytics", public: false, handler: getAnalytics },
7169
7922
  { method: "GET", path: "/admin/types", public: false, handler: listTypes },
7170
7923
  { method: "POST", path: "/admin/types", public: false, handler: createType },
@@ -7234,7 +7987,13 @@ function matchPath(pattern, path) {
7234
7987
  function notFound() {
7235
7988
  return Response.json({ error: "Not found" }, { status: 404 });
7236
7989
  }
7990
+ function requireOrganizationScoping() {
7991
+ if (typeof engine.withOrganization !== "function") {
7992
+ throw new Error("@ordinatio/scheduling-api 0.3 needs @ordinatio/scheduling 0.5.0 or newer: this engine does not limit results to an organization. Update @ordinatio/scheduling.");
7993
+ }
7994
+ }
7237
7995
  function createSchedulingApi(config) {
7996
+ requireOrganizationScoping();
7238
7997
  const routes = config.routes ?? ROUTES;
7239
7998
  const basePath = (config.basePath ?? "/api/scheduling").replace(/\/+$/, "");
7240
7999
  const host = {
@@ -7243,6 +8002,11 @@ function createSchedulingApi(config) {
7243
8002
  tenantDb: config.host.tenantDb?.bind(config.host) ?? (() => config.host.publicDb()),
7244
8003
  events: { emit: async () => void 0 },
7245
8004
  webhooks: config.host.webhooks ?? null,
8005
+ waitlist: config.host.waitlist ?? null,
8006
+ routingForms: config.host.routingForms ?? null,
8007
+ privacy: config.host.privacy ?? null,
8008
+ brand: config.host.brand ?? null,
8009
+ icalUidDomain: config.host.icalUidDomain?.bind(config.host) ?? (() => null),
7246
8010
  calendarSync: config.host.calendarSync ?? { upsertEvent: async () => ({}), removeEvent: async () => void 0 },
7247
8011
  activity: config.host.activity ?? { log: async () => void 0, isOpen: async () => false, resolve: async () => void 0 },
7248
8012
  appUrl: config.host.appUrl?.bind(config.host) ?? (() => null),
@@ -7268,7 +8032,7 @@ function createSchedulingApi(config) {
7268
8032
  jsonNull: config.host.jsonNull?.bind(config.host) ?? (() => null),
7269
8033
  cors: config.host.cors?.bind(config.host) ?? defaultCorsHeaders
7270
8034
  };
7271
- host.events = withWebhooks(config.host.events ?? { emit: async () => void 0 }, host);
8035
+ host.events = withWebhooks(withWaitlist(config.host.events ?? { emit: async () => void 0 }, host), host);
7272
8036
  async function handle(request) {
7273
8037
  const { pathname } = new URL(request.url);
7274
8038
  if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return notFound();
@@ -7423,6 +8187,7 @@ function createNodeListener(api, options) {
7423
8187
  BalanceRequestInProgressError,
7424
8188
  BookingPageConfigSchema,
7425
8189
  BookingPageThemeSchema,
8190
+ BrandSchema,
7426
8191
  CancelRecurringScopeSchema,
7427
8192
  CancelRecurringSeriesSchema,
7428
8193
  CreateAppointmentCategorySchema,
@@ -7433,6 +8198,7 @@ function createNodeListener(api, options) {
7433
8198
  CreateNotificationTemplateSchema,
7434
8199
  CreatePackagePurchaseSchema,
7435
8200
  CreateRecurringSeriesSchema,
8201
+ CreateRoutingFormSchema,
7436
8202
  CreateServicePackageSchema,
7437
8203
  CreateWebhookEndpointSchema,
7438
8204
  DEFAULT_CANCELLATION_POLICY,
@@ -7441,13 +8207,17 @@ function createNodeListener(api, options) {
7441
8207
  NotificationChannelSchema,
7442
8208
  NotificationTriggerSchema,
7443
8209
  OrgCancellationPolicySchema,
8210
+ PrivacyEraseSchema,
8211
+ PrivacySubjectSchema,
7444
8212
  RETRYABLE_REFUND_STATUSES,
7445
8213
  RecurringFrequencySchema,
7446
8214
  RefundOutcomePersistenceError,
8215
+ RouteClientSchema,
7447
8216
  SLOT_GRANULARITY_DEFAULT,
7448
8217
  SLOT_GRANULARITY_OPTIONS,
7449
8218
  TERMINAL_SUCCESS_STATUSES,
7450
8219
  TOKEN_TTL_DAYS,
8220
+ TestRoutingFormSchema,
7451
8221
  UnverifiedPaymentError,
7452
8222
  UpdateAppointmentCategorySchema,
7453
8223
  UpdateAppointmentTypeSchema,
@@ -7456,6 +8226,7 @@ function createNodeListener(api, options) {
7456
8226
  UpdateCouponCodeSchema,
7457
8227
  UpdateNotificationTemplateSchema,
7458
8228
  UpdatePackagePurchaseSchema,
8229
+ UpdateRoutingFormSchema,
7459
8230
  UpdateServicePackageSchema,
7460
8231
  attemptLegRefund,
7461
8232
  createBalanceIntent,