@ordinatio/scheduling 0.2.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +54 -0
- package/README.md +233 -2
- package/dist/index.d.mts +817 -4
- package/dist/index.d.ts +817 -4
- package/dist/index.js +2332 -27
- package/dist/index.mjs +2253 -29
- package/package.json +1 -1
- package/prisma/migrations/20261027000000_webhooks/migration.sql +75 -0
- package/prisma/migrations/20261027100000_waitlist/migration.sql +51 -0
- package/prisma/migrations/20261027200000_routing_forms/migration.sql +26 -0
- package/prisma/migrations/20261027300000_privacy_requests/migration.sql +18 -0
- package/prisma/migrations/20261027400000_organization_brand/migration.sql +26 -0
- package/prisma/schema.prisma +158 -0
package/dist/index.mjs
CHANGED
|
@@ -902,6 +902,239 @@ var GROUP_SCOPE_ERRORS = {
|
|
|
902
902
|
}
|
|
903
903
|
};
|
|
904
904
|
|
|
905
|
+
// src/errors/registry-webhooks.ts
|
|
906
|
+
var WEBHOOK_ERRORS = {
|
|
907
|
+
SCHED_1000: {
|
|
908
|
+
code: "SCHED_1000",
|
|
909
|
+
file: "webhooks/endpoints.ts",
|
|
910
|
+
function: "createWebhookEndpoint",
|
|
911
|
+
severity: "warning",
|
|
912
|
+
recoverable: true,
|
|
913
|
+
description: "The webhook address is not allowed",
|
|
914
|
+
diagnosis: [
|
|
915
|
+
"The address must be a full https:// address with no user name or password",
|
|
916
|
+
"Addresses that point at this machine or a private network are refused",
|
|
917
|
+
"For local development only, the host can allow insecure targets"
|
|
918
|
+
]
|
|
919
|
+
},
|
|
920
|
+
SCHED_1001: {
|
|
921
|
+
code: "SCHED_1001",
|
|
922
|
+
file: "webhooks/endpoints.ts",
|
|
923
|
+
function: "createWebhookEndpoint",
|
|
924
|
+
severity: "warning",
|
|
925
|
+
recoverable: true,
|
|
926
|
+
description: "The webhook event list is empty or names an event that does not exist",
|
|
927
|
+
diagnosis: [
|
|
928
|
+
'Send at least one event name, or "*" for every event',
|
|
929
|
+
"Valid names: appointment.booked, appointment.rescheduled, appointment.cancelled, appointment.no_show, reminder.sent, waitlist.offered"
|
|
930
|
+
]
|
|
931
|
+
},
|
|
932
|
+
SCHED_1002: {
|
|
933
|
+
code: "SCHED_1002",
|
|
934
|
+
file: "webhooks/endpoints.ts",
|
|
935
|
+
function: "createWebhookEndpoint",
|
|
936
|
+
severity: "warning",
|
|
937
|
+
recoverable: true,
|
|
938
|
+
description: "The organization already has the maximum number of webhook endpoints",
|
|
939
|
+
diagnosis: ["Remove an endpoint that is no longer used, then add the new one"]
|
|
940
|
+
},
|
|
941
|
+
SCHED_1003: {
|
|
942
|
+
code: "SCHED_1003",
|
|
943
|
+
file: "webhooks/endpoints.ts",
|
|
944
|
+
function: "webhook endpoint lookup",
|
|
945
|
+
severity: "warning",
|
|
946
|
+
recoverable: true,
|
|
947
|
+
description: "Webhook endpoint not found for this organization",
|
|
948
|
+
diagnosis: [
|
|
949
|
+
"Check the endpoint id",
|
|
950
|
+
"The endpoint may belong to another organization or may have been removed"
|
|
951
|
+
]
|
|
952
|
+
},
|
|
953
|
+
SCHED_1004: {
|
|
954
|
+
code: "SCHED_1004",
|
|
955
|
+
file: "webhooks/deliveries.ts",
|
|
956
|
+
function: "retryWebhookDelivery",
|
|
957
|
+
severity: "warning",
|
|
958
|
+
recoverable: true,
|
|
959
|
+
description: "Webhook delivery not found, or it is not in the dead-letter list",
|
|
960
|
+
diagnosis: [
|
|
961
|
+
"Only a delivery that ran out of tries can be retried by hand",
|
|
962
|
+
"A delivery still waiting for its next try will be sent on its own"
|
|
963
|
+
]
|
|
964
|
+
},
|
|
965
|
+
SCHED_1005: {
|
|
966
|
+
code: "SCHED_1005",
|
|
967
|
+
file: "webhooks/attempt.ts",
|
|
968
|
+
function: "attemptDelivery",
|
|
969
|
+
severity: "warning",
|
|
970
|
+
recoverable: false,
|
|
971
|
+
description: "The webhook was not sent because its target is not allowed",
|
|
972
|
+
diagnosis: [
|
|
973
|
+
"The address, or the address its name resolves to, is on a private or local network",
|
|
974
|
+
"Remove the endpoint and add one that points at a public address"
|
|
975
|
+
]
|
|
976
|
+
},
|
|
977
|
+
SCHED_1006: {
|
|
978
|
+
code: "SCHED_1006",
|
|
979
|
+
file: "webhooks/enqueue.ts",
|
|
980
|
+
function: "enqueueWebhookEvent",
|
|
981
|
+
severity: "error",
|
|
982
|
+
recoverable: true,
|
|
983
|
+
description: "A webhook event could not be queued; the booking itself was saved",
|
|
984
|
+
diagnosis: [
|
|
985
|
+
"Check that the webhook tables exist (run the package migrations)",
|
|
986
|
+
"Check the database connection"
|
|
987
|
+
]
|
|
988
|
+
}
|
|
989
|
+
};
|
|
990
|
+
|
|
991
|
+
// src/errors/registry-waitlist.ts
|
|
992
|
+
function entry(code, fn, description, diagnosis, severity = "warning", recoverable = true) {
|
|
993
|
+
return { code, file: "waitlist/", function: fn, severity, recoverable, description, diagnosis };
|
|
994
|
+
}
|
|
995
|
+
var WAITLIST_ERRORS = {
|
|
996
|
+
SCHED_1100: entry(
|
|
997
|
+
"SCHED_1100",
|
|
998
|
+
"joinWaitlist",
|
|
999
|
+
"The appointment type or calendar for this waitlist request was not found",
|
|
1000
|
+
["Check the type id and, if given, the calendar id", "The calendar must be one that offers the type", "An inactive type has no waitlist"]
|
|
1001
|
+
),
|
|
1002
|
+
SCHED_1101: entry(
|
|
1003
|
+
"SCHED_1101",
|
|
1004
|
+
"joinWaitlist",
|
|
1005
|
+
"The waitlist day is invalid, in the past, or too far ahead",
|
|
1006
|
+
["Send the day as YYYY-MM-DD", "The day must be today or later, and within the next 90 days"]
|
|
1007
|
+
),
|
|
1008
|
+
SCHED_1102: entry(
|
|
1009
|
+
"SCHED_1102",
|
|
1010
|
+
"joinWaitlist",
|
|
1011
|
+
"The waitlist time is invalid or not on the chosen day",
|
|
1012
|
+
["Send the time as an ISO date-time on the chosen day, in the future"]
|
|
1013
|
+
),
|
|
1014
|
+
SCHED_1103: entry(
|
|
1015
|
+
"SCHED_1103",
|
|
1016
|
+
"joinWaitlist",
|
|
1017
|
+
"That time or day still has open slots, so the client should book instead of waiting",
|
|
1018
|
+
["Look up the open slots for the day", "Join the waitlist only for a slot or day that is full"]
|
|
1019
|
+
),
|
|
1020
|
+
SCHED_1104: entry(
|
|
1021
|
+
"SCHED_1104",
|
|
1022
|
+
"joinWaitlist",
|
|
1023
|
+
"This email is already waiting for that day",
|
|
1024
|
+
["The client is already on the list for this type and day", "They can leave with their link and join again"]
|
|
1025
|
+
),
|
|
1026
|
+
SCHED_1105: entry(
|
|
1027
|
+
"SCHED_1105",
|
|
1028
|
+
"joinWaitlist",
|
|
1029
|
+
"A waitlist is not available for a type that needs payment",
|
|
1030
|
+
["Payment cannot be taken when an offer is accepted", "Use a free type, or let clients book as slots open"]
|
|
1031
|
+
),
|
|
1032
|
+
SCHED_1106: entry(
|
|
1033
|
+
"SCHED_1106",
|
|
1034
|
+
"getWaitlistOffer",
|
|
1035
|
+
"No open offer for this link",
|
|
1036
|
+
["The link may be wrong, already used, or the entry may have left the list", "An offer can be accepted once"]
|
|
1037
|
+
),
|
|
1038
|
+
SCHED_1107: entry(
|
|
1039
|
+
"SCHED_1107",
|
|
1040
|
+
"beginWaitlistAccept",
|
|
1041
|
+
"The offer has expired",
|
|
1042
|
+
["The time limit ran out; the slot may have gone to the next person", "Join the waitlist again to wait for another slot"]
|
|
1043
|
+
),
|
|
1044
|
+
SCHED_1108: entry(
|
|
1045
|
+
"SCHED_1108",
|
|
1046
|
+
"joinWaitlist",
|
|
1047
|
+
"The waitlist for that day is full",
|
|
1048
|
+
["Too many people are already waiting for this type and day"]
|
|
1049
|
+
),
|
|
1050
|
+
SCHED_1109: entry(
|
|
1051
|
+
"SCHED_1109",
|
|
1052
|
+
"offerFreedSlot",
|
|
1053
|
+
"A waitlist offer could not be made; the cancellation itself was saved",
|
|
1054
|
+
["Check that the waitlist table exists (run the package migrations)", "Check the database connection"],
|
|
1055
|
+
"error"
|
|
1056
|
+
),
|
|
1057
|
+
SCHED_1110: entry(
|
|
1058
|
+
"SCHED_1110",
|
|
1059
|
+
"joinWaitlist",
|
|
1060
|
+
"A waitlist is not available for a type with required intake questions",
|
|
1061
|
+
["An accepted offer books without form answers, so the required questions could not be answered", "Make the questions optional, or let clients book as slots open"]
|
|
1062
|
+
)
|
|
1063
|
+
};
|
|
1064
|
+
|
|
1065
|
+
// src/errors/registry-routing.ts
|
|
1066
|
+
function entry2(code, fn, description, diagnosis, severity = "warning") {
|
|
1067
|
+
return { code, file: "routing/", function: fn, severity, recoverable: true, description, diagnosis };
|
|
1068
|
+
}
|
|
1069
|
+
var ROUTING_ERRORS = {
|
|
1070
|
+
SCHED_1200: entry2(
|
|
1071
|
+
"SCHED_1200",
|
|
1072
|
+
"validateRoutingForm",
|
|
1073
|
+
"The routing form is not valid",
|
|
1074
|
+
["Read the list of problems in the error context: each names the part of the form and what is wrong", "Every rule must name questions that exist, use an operator that fits the question, and send the client somewhere that is live"]
|
|
1075
|
+
),
|
|
1076
|
+
SCHED_1201: entry2(
|
|
1077
|
+
"SCHED_1201",
|
|
1078
|
+
"routing form lookup",
|
|
1079
|
+
"The routing form was not found (for the public: no active form with that slug)",
|
|
1080
|
+
["Check the form address (slug)", "A form that is switched off, or that belongs to another organization, is not found", "With several organizations in one database, name the organization"]
|
|
1081
|
+
),
|
|
1082
|
+
SCHED_1202: entry2(
|
|
1083
|
+
"SCHED_1202",
|
|
1084
|
+
"createRoutingForm / updateRoutingForm",
|
|
1085
|
+
"Another routing form already uses that slug",
|
|
1086
|
+
["Choose a different slug", "A slug is unique within the organization and must not be used by another organization in the same database"]
|
|
1087
|
+
),
|
|
1088
|
+
SCHED_1203: entry2(
|
|
1089
|
+
"SCHED_1203",
|
|
1090
|
+
"routeClient",
|
|
1091
|
+
"The answers do not fit the form",
|
|
1092
|
+
["Answer every required question", "Pick an offered option for choice questions, and send a list for checkbox questions", "Send only questions the form asks"]
|
|
1093
|
+
),
|
|
1094
|
+
SCHED_1204: entry2(
|
|
1095
|
+
"SCHED_1204",
|
|
1096
|
+
"createRoutingForm",
|
|
1097
|
+
"The organization already has the maximum number of routing forms",
|
|
1098
|
+
["Remove a form that is no longer used, then add the new one"]
|
|
1099
|
+
)
|
|
1100
|
+
};
|
|
1101
|
+
|
|
1102
|
+
// src/errors/registry-privacy.ts
|
|
1103
|
+
function entry3(code, fn, description, diagnosis) {
|
|
1104
|
+
return { code, file: "privacy/", function: fn, severity: "warning", recoverable: true, description, diagnosis };
|
|
1105
|
+
}
|
|
1106
|
+
var PRIVACY_ERRORS = {
|
|
1107
|
+
SCHED_1300: entry3(
|
|
1108
|
+
"SCHED_1300",
|
|
1109
|
+
"parseSubject",
|
|
1110
|
+
"Say whose data this is: a valid email address, a client id, or both",
|
|
1111
|
+
["Send `email` (one address) and/or `clientId`", "An address must be a single address with no spaces, at most 254 characters"]
|
|
1112
|
+
),
|
|
1113
|
+
SCHED_1301: entry3(
|
|
1114
|
+
"SCHED_1301",
|
|
1115
|
+
"eraseSubject",
|
|
1116
|
+
"This person still has upcoming bookings or an open waitlist offer, so their data cannot be erased yet",
|
|
1117
|
+
["Cancel or complete the upcoming bookings, and remove the waitlist entries that hold or are taking an offer", "Run the erase preview to see how many of each remain", "Then ask again"]
|
|
1118
|
+
)
|
|
1119
|
+
};
|
|
1120
|
+
|
|
1121
|
+
// src/errors/registry-brand.ts
|
|
1122
|
+
var BRAND_ERRORS = {
|
|
1123
|
+
SCHED_1400: {
|
|
1124
|
+
code: "SCHED_1400",
|
|
1125
|
+
file: "brand/",
|
|
1126
|
+
function: "validateBrand",
|
|
1127
|
+
severity: "warning",
|
|
1128
|
+
recoverable: true,
|
|
1129
|
+
description: "The brand settings are not valid",
|
|
1130
|
+
diagnosis: [
|
|
1131
|
+
"Read the list of problems in the error context: each names the field and what is wrong",
|
|
1132
|
+
"Colours are hex values such as #1a2b3c; the logo is an https address; email addresses are single plain addresses",
|
|
1133
|
+
"A sending address is accepted only for a domain the host has confirmed it may send from"
|
|
1134
|
+
]
|
|
1135
|
+
}
|
|
1136
|
+
};
|
|
1137
|
+
|
|
905
1138
|
// src/errors/registry.ts
|
|
906
1139
|
var SCHEDULING_ERRORS = {
|
|
907
1140
|
...CALENDARS_AVAILABILITY_ERRORS,
|
|
@@ -911,7 +1144,12 @@ var SCHEDULING_ERRORS = {
|
|
|
911
1144
|
...NOTIFICATION_MANAGE_ERRORS,
|
|
912
1145
|
...RECURRING_MISC_ERRORS,
|
|
913
1146
|
...PUBLIC_DIRECTORY_ERRORS,
|
|
914
|
-
...GROUP_SCOPE_ERRORS
|
|
1147
|
+
...GROUP_SCOPE_ERRORS,
|
|
1148
|
+
...WEBHOOK_ERRORS,
|
|
1149
|
+
...WAITLIST_ERRORS,
|
|
1150
|
+
...ROUTING_ERRORS,
|
|
1151
|
+
...PRIVACY_ERRORS,
|
|
1152
|
+
...BRAND_ERRORS
|
|
915
1153
|
};
|
|
916
1154
|
|
|
917
1155
|
// src/errors/diagnostic-error.ts
|
|
@@ -2001,9 +2239,7 @@ async function bookAppointment(db, input, callbacks) {
|
|
|
2001
2239
|
clientName: input.clientName,
|
|
2002
2240
|
clientEmail: input.clientEmail,
|
|
2003
2241
|
clientPhone: input.clientPhone ?? null,
|
|
2004
|
-
//
|
|
2005
|
-
// route passes this through from caller-supplied, unauthenticated input with no
|
|
2006
|
-
// existence/ownership check — a real, disclosed, not-yet-fixed gap.
|
|
2242
|
+
// Not verified here: a caller that takes this from unauthenticated input must check it first.
|
|
2007
2243
|
clientId: input.clientId ?? null,
|
|
2008
2244
|
intakeResponses: input.intakeResponses,
|
|
2009
2245
|
staffNotes: input.staffNotes ?? null,
|
|
@@ -2106,13 +2342,13 @@ function renderTemplate(template, context, channel = "EMAIL") {
|
|
|
2106
2342
|
for (const [key, value] of Object.entries(context)) {
|
|
2107
2343
|
if (typeof value === "string") {
|
|
2108
2344
|
const safeValue = channel === "SMS" ? value : escapeHtml(value);
|
|
2109
|
-
result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), safeValue);
|
|
2345
|
+
result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), () => safeValue);
|
|
2110
2346
|
}
|
|
2111
2347
|
}
|
|
2112
2348
|
if (context.customFields) {
|
|
2113
2349
|
for (const [key, value] of Object.entries(context.customFields)) {
|
|
2114
2350
|
const safeValue = channel === "SMS" ? value : escapeHtml(value);
|
|
2115
|
-
result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), safeValue);
|
|
2351
|
+
result = result.replace(new RegExp(`\\{\\{${key}\\}\\}`, "g"), () => safeValue);
|
|
2116
2352
|
}
|
|
2117
2353
|
}
|
|
2118
2354
|
if (channel === "SMS") {
|
|
@@ -2165,14 +2401,325 @@ function buildNotificationContext(appointment, baseUrl) {
|
|
|
2165
2401
|
};
|
|
2166
2402
|
}
|
|
2167
2403
|
|
|
2404
|
+
// src/brand/sender.ts
|
|
2405
|
+
var NOT_IN_A_SENDER_NAME = /[<>",;@\\]/g;
|
|
2406
|
+
function senderIdentity(brand) {
|
|
2407
|
+
if (!brand) return null;
|
|
2408
|
+
const fallbackName = brand.displayName.replace(/[\u0000-\u001f\u007f]/g, " ").replace(NOT_IN_A_SENDER_NAME, "").replace(/\s+/g, " ").trim();
|
|
2409
|
+
const name = brand.fromName ?? (fallbackName || void 0);
|
|
2410
|
+
return {
|
|
2411
|
+
...name ? { name } : {},
|
|
2412
|
+
...brand.fromEmail ? { email: brand.fromEmail } : {},
|
|
2413
|
+
...brand.replyToEmail ? { replyTo: brand.replyToEmail } : {}
|
|
2414
|
+
};
|
|
2415
|
+
}
|
|
2416
|
+
function brandTemplateFields(brand) {
|
|
2417
|
+
return {
|
|
2418
|
+
brandName: brand?.displayName ?? "",
|
|
2419
|
+
brandLogoUrl: brand?.logoUrl ?? "",
|
|
2420
|
+
brandColor: brand?.primaryColor ?? "",
|
|
2421
|
+
brandFooter: brand?.footerText ?? ""
|
|
2422
|
+
};
|
|
2423
|
+
}
|
|
2424
|
+
function toPublicBrand(brand) {
|
|
2425
|
+
return {
|
|
2426
|
+
displayName: brand.displayName,
|
|
2427
|
+
logoUrl: brand.logoUrl,
|
|
2428
|
+
primaryColor: brand.primaryColor,
|
|
2429
|
+
accentColor: brand.accentColor,
|
|
2430
|
+
backgroundColor: brand.backgroundColor,
|
|
2431
|
+
textColor: brand.textColor,
|
|
2432
|
+
fontFamily: brand.fontFamily,
|
|
2433
|
+
footerText: brand.footerText
|
|
2434
|
+
};
|
|
2435
|
+
}
|
|
2436
|
+
|
|
2437
|
+
// src/brand/types.ts
|
|
2438
|
+
var BRAND_FIELDS = [
|
|
2439
|
+
"displayName",
|
|
2440
|
+
"logoUrl",
|
|
2441
|
+
"primaryColor",
|
|
2442
|
+
"accentColor",
|
|
2443
|
+
"backgroundColor",
|
|
2444
|
+
"textColor",
|
|
2445
|
+
"fontFamily",
|
|
2446
|
+
"footerText",
|
|
2447
|
+
"replyToEmail",
|
|
2448
|
+
"fromName",
|
|
2449
|
+
"fromEmail"
|
|
2450
|
+
];
|
|
2451
|
+
|
|
2452
|
+
// src/brand/validate.ts
|
|
2453
|
+
var HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
|
|
2454
|
+
var FONT = /^[A-Za-z0-9 ,-]{1,100}$/;
|
|
2455
|
+
var EMAIL = /^[^\s@<>,;"'()[\]\\]+@[^\s@<>,;"'()[\]\\]+\.[^\s@<>,;"'()[\]\\]+$/;
|
|
2456
|
+
var CONTROL = /[\u0000-\u001f\u007f]/;
|
|
2457
|
+
var COLOR_FIELDS = ["primaryColor", "accentColor", "backgroundColor", "textColor"];
|
|
2458
|
+
function text(value, path, max, problems, required = false) {
|
|
2459
|
+
if (value === void 0 || value === null || value === "") {
|
|
2460
|
+
if (required) problems.push({ path, message: "Required" });
|
|
2461
|
+
return null;
|
|
2462
|
+
}
|
|
2463
|
+
if (typeof value !== "string") {
|
|
2464
|
+
problems.push({ path, message: "Must be text" });
|
|
2465
|
+
return null;
|
|
2466
|
+
}
|
|
2467
|
+
const trimmed = value.trim();
|
|
2468
|
+
if (trimmed.length === 0) {
|
|
2469
|
+
if (required) problems.push({ path, message: "Required" });
|
|
2470
|
+
return null;
|
|
2471
|
+
}
|
|
2472
|
+
if (trimmed.length > max) problems.push({ path, message: `At most ${max} characters` });
|
|
2473
|
+
else if (CONTROL.test(trimmed)) problems.push({ path, message: "Must not contain control characters" });
|
|
2474
|
+
else return trimmed;
|
|
2475
|
+
return null;
|
|
2476
|
+
}
|
|
2477
|
+
function email(value, path, problems) {
|
|
2478
|
+
const raw = text(value, path, 254, problems);
|
|
2479
|
+
if (raw === null) return null;
|
|
2480
|
+
if (!EMAIL.test(raw)) {
|
|
2481
|
+
problems.push({ path, message: "Must be a single email address" });
|
|
2482
|
+
return null;
|
|
2483
|
+
}
|
|
2484
|
+
return raw.toLowerCase();
|
|
2485
|
+
}
|
|
2486
|
+
function logo(value, problems) {
|
|
2487
|
+
const raw = text(value, "logoUrl", 500, problems);
|
|
2488
|
+
if (raw === null) return null;
|
|
2489
|
+
try {
|
|
2490
|
+
const url = new URL(raw);
|
|
2491
|
+
if (url.protocol === "https:" && !url.username && !url.password && url.hostname) return raw;
|
|
2492
|
+
} catch {
|
|
2493
|
+
}
|
|
2494
|
+
problems.push({ path: "logoUrl", message: "Must be an https address without a user name or password" });
|
|
2495
|
+
return null;
|
|
2496
|
+
}
|
|
2497
|
+
async function validateBrand(input, options) {
|
|
2498
|
+
const problems = [];
|
|
2499
|
+
if (typeof input !== "object" || input === null || Array.isArray(input)) {
|
|
2500
|
+
throw new SchedulingValidationError("The brand settings are not valid", "SCHED_1400", { errors: [{ path: "", message: "Must be an object" }] });
|
|
2501
|
+
}
|
|
2502
|
+
const given = input;
|
|
2503
|
+
for (const key of Object.keys(given)) if (!BRAND_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
|
|
2504
|
+
const out = {
|
|
2505
|
+
displayName: text(given.displayName, "displayName", 100, problems, true) ?? "",
|
|
2506
|
+
logoUrl: logo(given.logoUrl, problems),
|
|
2507
|
+
primaryColor: null,
|
|
2508
|
+
accentColor: null,
|
|
2509
|
+
backgroundColor: null,
|
|
2510
|
+
textColor: null,
|
|
2511
|
+
fontFamily: null,
|
|
2512
|
+
footerText: text(given.footerText, "footerText", 300, problems),
|
|
2513
|
+
replyToEmail: email(given.replyToEmail, "replyToEmail", problems),
|
|
2514
|
+
fromName: text(given.fromName, "fromName", 100, problems),
|
|
2515
|
+
fromEmail: email(given.fromEmail, "fromEmail", problems)
|
|
2516
|
+
};
|
|
2517
|
+
for (const field of COLOR_FIELDS) {
|
|
2518
|
+
const raw = text(given[field], field, 7, problems);
|
|
2519
|
+
if (raw === null) continue;
|
|
2520
|
+
if (HEX.test(raw)) out[field] = raw.toLowerCase();
|
|
2521
|
+
else problems.push({ path: field, message: "Must be a hex colour such as #1a2b3c" });
|
|
2522
|
+
}
|
|
2523
|
+
const font = text(given.fontFamily, "fontFamily", 100, problems);
|
|
2524
|
+
if (font !== null) {
|
|
2525
|
+
if (FONT.test(font)) out.fontFamily = font;
|
|
2526
|
+
else problems.push({ path: "fontFamily", message: "Letters, digits, spaces, commas and dashes only" });
|
|
2527
|
+
}
|
|
2528
|
+
if (out.fromName !== null && /[<>",;@\\]/.test(out.fromName)) {
|
|
2529
|
+
problems.push({ path: "fromName", message: "Must not contain quotes, angle brackets, commas, semicolons, @ or backslashes" });
|
|
2530
|
+
out.fromName = null;
|
|
2531
|
+
}
|
|
2532
|
+
if (out.fromEmail !== null && !problems.some((p) => p.path === "fromEmail")) {
|
|
2533
|
+
const domain = out.fromEmail.slice(out.fromEmail.lastIndexOf("@") + 1);
|
|
2534
|
+
let verified = false;
|
|
2535
|
+
try {
|
|
2536
|
+
verified = options.isSendingDomainVerified ? await options.isSendingDomainVerified(domain) : false;
|
|
2537
|
+
} catch (error) {
|
|
2538
|
+
console.error("[brand] the sending-domain check failed:", error);
|
|
2539
|
+
verified = false;
|
|
2540
|
+
}
|
|
2541
|
+
if (!verified) problems.push({ path: "fromEmail", message: `Sending from ${domain} is not confirmed for this server` });
|
|
2542
|
+
}
|
|
2543
|
+
if (problems.length > 0) throw new SchedulingValidationError("The brand settings are not valid", "SCHED_1400", { errors: problems });
|
|
2544
|
+
return out;
|
|
2545
|
+
}
|
|
2546
|
+
|
|
2547
|
+
// src/brand/crud.ts
|
|
2548
|
+
var SELECT = {
|
|
2549
|
+
displayName: true,
|
|
2550
|
+
logoUrl: true,
|
|
2551
|
+
primaryColor: true,
|
|
2552
|
+
accentColor: true,
|
|
2553
|
+
backgroundColor: true,
|
|
2554
|
+
textColor: true,
|
|
2555
|
+
fontFamily: true,
|
|
2556
|
+
footerText: true,
|
|
2557
|
+
replyToEmail: true,
|
|
2558
|
+
fromName: true,
|
|
2559
|
+
fromEmail: true,
|
|
2560
|
+
updatedAt: true
|
|
2561
|
+
};
|
|
2562
|
+
async function getBrand(db, organizationId) {
|
|
2563
|
+
return db.organizationBrand.findUnique({ where: { organizationId }, select: SELECT });
|
|
2564
|
+
}
|
|
2565
|
+
async function getPublicBrand(db, organizationId) {
|
|
2566
|
+
if (organizationId) {
|
|
2567
|
+
const brand = await getBrand(db, organizationId);
|
|
2568
|
+
return brand ? toPublicBrand(brand) : null;
|
|
2569
|
+
}
|
|
2570
|
+
const all = await db.organizationBrand.findMany({ take: 2, select: SELECT });
|
|
2571
|
+
return all.length === 1 ? toPublicBrand(all[0]) : null;
|
|
2572
|
+
}
|
|
2573
|
+
async function saveBrand(db, organizationId, input, options) {
|
|
2574
|
+
const fields = await validateBrand(input, options);
|
|
2575
|
+
return db.organizationBrand.upsert({
|
|
2576
|
+
where: { organizationId },
|
|
2577
|
+
create: { organizationId, ...fields },
|
|
2578
|
+
update: { ...fields },
|
|
2579
|
+
select: SELECT
|
|
2580
|
+
});
|
|
2581
|
+
}
|
|
2582
|
+
async function deleteBrand(db, organizationId) {
|
|
2583
|
+
const { count } = await db.organizationBrand.deleteMany({ where: { organizationId } });
|
|
2584
|
+
return count > 0;
|
|
2585
|
+
}
|
|
2586
|
+
|
|
2587
|
+
// src/notifications/brand-context.ts
|
|
2588
|
+
async function withBrandFields(db, organizationId, context, enabled) {
|
|
2589
|
+
if (!enabled) return context;
|
|
2590
|
+
const brand = organizationId ? await getBrand(db, organizationId) : null;
|
|
2591
|
+
return { ...context, customFields: { ...context.customFields, ...brandTemplateFields(brand) } };
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2168
2594
|
// src/notifications/process-pending-notifications.ts
|
|
2169
|
-
import { randomUUID } from "crypto";
|
|
2595
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
2170
2596
|
import { Prisma as Prisma6 } from "@prisma/client";
|
|
2597
|
+
|
|
2598
|
+
// src/webhooks/events.ts
|
|
2599
|
+
import { randomUUID } from "crypto";
|
|
2600
|
+
var WEBHOOK_EVENT_TYPES = [
|
|
2601
|
+
"appointment.booked",
|
|
2602
|
+
"appointment.rescheduled",
|
|
2603
|
+
"appointment.cancelled",
|
|
2604
|
+
"appointment.no_show",
|
|
2605
|
+
"reminder.sent",
|
|
2606
|
+
"waitlist.offered"
|
|
2607
|
+
];
|
|
2608
|
+
var WEBHOOK_TEST_EVENT = "webhook.test";
|
|
2609
|
+
var ALL_EVENTS = "*";
|
|
2610
|
+
function isWebhookEventType(value) {
|
|
2611
|
+
return typeof value === "string" && WEBHOOK_EVENT_TYPES.includes(value);
|
|
2612
|
+
}
|
|
2613
|
+
function normalizeEventTypes(input) {
|
|
2614
|
+
if (!Array.isArray(input) || input.length === 0) return null;
|
|
2615
|
+
if (input.includes(ALL_EVENTS)) return input.length === 1 ? [ALL_EVENTS] : null;
|
|
2616
|
+
if (!input.every(isWebhookEventType)) return null;
|
|
2617
|
+
return [...new Set(input)];
|
|
2618
|
+
}
|
|
2619
|
+
function buildEnvelope(args) {
|
|
2620
|
+
return {
|
|
2621
|
+
id: args.eventId ?? `evt_${randomUUID()}`,
|
|
2622
|
+
type: args.type,
|
|
2623
|
+
createdAt: args.now.toISOString(),
|
|
2624
|
+
organizationId: args.organizationId,
|
|
2625
|
+
data: args.data
|
|
2626
|
+
};
|
|
2627
|
+
}
|
|
2628
|
+
|
|
2629
|
+
// src/webhooks/enqueue.ts
|
|
2630
|
+
async function appointmentWebhookData(db, organizationId, appointmentId) {
|
|
2631
|
+
const row = await db.appointment.findUnique({
|
|
2632
|
+
where: { id: appointmentId },
|
|
2633
|
+
select: {
|
|
2634
|
+
id: true,
|
|
2635
|
+
status: true,
|
|
2636
|
+
startTime: true,
|
|
2637
|
+
endTime: true,
|
|
2638
|
+
duration: true,
|
|
2639
|
+
timezone: true,
|
|
2640
|
+
clientName: true,
|
|
2641
|
+
clientEmail: true,
|
|
2642
|
+
clientPhone: true,
|
|
2643
|
+
clientId: true,
|
|
2644
|
+
cancelledAt: true,
|
|
2645
|
+
cancelledBy: true,
|
|
2646
|
+
cancelReason: true,
|
|
2647
|
+
rescheduledFrom: true,
|
|
2648
|
+
rescheduleCount: true,
|
|
2649
|
+
calendarId: true,
|
|
2650
|
+
typeId: true,
|
|
2651
|
+
calendar: { select: { name: true, organizationId: true } },
|
|
2652
|
+
type: { select: { name: true } }
|
|
2653
|
+
}
|
|
2654
|
+
});
|
|
2655
|
+
if (!row || row.calendar.organizationId !== null && row.calendar.organizationId !== organizationId) {
|
|
2656
|
+
return { appointment: { id: appointmentId } };
|
|
2657
|
+
}
|
|
2658
|
+
const { calendar, type, ...rest } = row;
|
|
2659
|
+
return { appointment: { ...rest, calendarName: calendar.name, typeName: type.name } };
|
|
2660
|
+
}
|
|
2661
|
+
async function enqueueWebhookEvent(db, input) {
|
|
2662
|
+
const now = input.now ?? /* @__PURE__ */ new Date();
|
|
2663
|
+
const endpoints = await db.webhookEndpoint.findMany({
|
|
2664
|
+
where: {
|
|
2665
|
+
organizationId: input.organizationId,
|
|
2666
|
+
isActive: true,
|
|
2667
|
+
OR: [{ eventTypes: { has: input.type } }, { eventTypes: { has: ALL_EVENTS } }]
|
|
2668
|
+
},
|
|
2669
|
+
select: { id: true }
|
|
2670
|
+
});
|
|
2671
|
+
if (endpoints.length === 0) return { queued: 0 };
|
|
2672
|
+
const envelope = buildEnvelope({ organizationId: input.organizationId, type: input.type, data: input.data, eventId: input.eventId, now });
|
|
2673
|
+
const body = JSON.stringify(envelope);
|
|
2674
|
+
const created = await db.webhookDelivery.createMany({
|
|
2675
|
+
data: endpoints.map((endpoint) => ({
|
|
2676
|
+
organizationId: input.organizationId,
|
|
2677
|
+
endpointId: endpoint.id,
|
|
2678
|
+
eventId: envelope.id,
|
|
2679
|
+
eventType: input.type,
|
|
2680
|
+
body,
|
|
2681
|
+
nextAttemptAt: now
|
|
2682
|
+
})),
|
|
2683
|
+
skipDuplicates: true
|
|
2684
|
+
});
|
|
2685
|
+
return { queued: created.count };
|
|
2686
|
+
}
|
|
2687
|
+
async function enqueueAppointmentWebhook(db, input) {
|
|
2688
|
+
try {
|
|
2689
|
+
const data = { ...await appointmentWebhookData(db, input.organizationId, input.appointmentId), ...input.extra };
|
|
2690
|
+
await enqueueWebhookEvent(db, { organizationId: input.organizationId, type: input.type, data, eventId: input.eventId });
|
|
2691
|
+
} catch (error) {
|
|
2692
|
+
const diagnostic = schedError("SCHED_1006", { organizationId: input.organizationId, type: input.type, appointmentId: input.appointmentId, error });
|
|
2693
|
+
console.error(`[webhooks] ${diagnostic.ref} could not queue ${input.type}:`, error);
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2696
|
+
async function enqueueReminderSent(db, notification) {
|
|
2697
|
+
try {
|
|
2698
|
+
const appointment = await db.appointment.findUnique({
|
|
2699
|
+
where: { id: notification.appointmentId },
|
|
2700
|
+
select: { calendar: { select: { organizationId: true } } }
|
|
2701
|
+
});
|
|
2702
|
+
const organizationId = appointment?.calendar.organizationId;
|
|
2703
|
+
if (!organizationId) return;
|
|
2704
|
+
await enqueueAppointmentWebhook(db, {
|
|
2705
|
+
organizationId,
|
|
2706
|
+
type: "reminder.sent",
|
|
2707
|
+
appointmentId: notification.appointmentId,
|
|
2708
|
+
extra: { reminder: { channel: notification.channel, trigger: notification.trigger } },
|
|
2709
|
+
eventId: `reminder_${notification.id}`
|
|
2710
|
+
});
|
|
2711
|
+
} catch (error) {
|
|
2712
|
+
const diagnostic = schedError("SCHED_1006", { appointmentId: notification.appointmentId, error });
|
|
2713
|
+
console.error(`[webhooks] ${diagnostic.ref} could not queue reminder.sent:`, error);
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
|
|
2717
|
+
// src/notifications/process-pending-notifications.ts
|
|
2171
2718
|
async function processPendingNotifications(db, sender, options) {
|
|
2172
2719
|
const batchSize = options?.batchSize ?? 20;
|
|
2173
2720
|
const maxRetries = options?.retry?.maxRetries ?? 3;
|
|
2174
2721
|
const baseBackoff = options?.retry?.baseBackoffMinutes ?? 5;
|
|
2175
|
-
const workerId = options?.workerId ??
|
|
2722
|
+
const workerId = options?.workerId ?? randomUUID2();
|
|
2176
2723
|
const staleThresholdMs = options?.staleThresholdMs ?? 5 * 6e4;
|
|
2177
2724
|
const now = /* @__PURE__ */ new Date();
|
|
2178
2725
|
const staleThreshold = new Date(now.getTime() - staleThresholdMs);
|
|
@@ -2203,8 +2750,10 @@ async function processPendingNotifications(db, sender, options) {
|
|
|
2203
2750
|
`;
|
|
2204
2751
|
if (claimed.length === 0) return { sent: 0, failed: 0, deadLettered: 0, skipped: 0 };
|
|
2205
2752
|
const pending = await db.scheduledNotification.findMany({
|
|
2206
|
-
where: { id: { in: claimed.map((c) => c.id) } }
|
|
2753
|
+
where: { id: { in: claimed.map((c) => c.id) } },
|
|
2754
|
+
...options?.brand ? { include: { appointment: { select: { calendar: { select: { organizationId: true } } } } } } : {}
|
|
2207
2755
|
});
|
|
2756
|
+
const senders = options?.brand ? await loadSenders(db, pending) : null;
|
|
2208
2757
|
let sent = 0;
|
|
2209
2758
|
let failed = 0;
|
|
2210
2759
|
let deadLettered = 0;
|
|
@@ -2216,7 +2765,10 @@ async function processPendingNotifications(db, sender, options) {
|
|
|
2216
2765
|
notification.recipient,
|
|
2217
2766
|
notification.subject || "",
|
|
2218
2767
|
notification.body,
|
|
2219
|
-
{
|
|
2768
|
+
{
|
|
2769
|
+
trigger: notification.trigger,
|
|
2770
|
+
...senderFor(senders, notification)
|
|
2771
|
+
}
|
|
2220
2772
|
);
|
|
2221
2773
|
if (result?.skipped) {
|
|
2222
2774
|
await db.scheduledNotification.update({
|
|
@@ -2234,6 +2786,9 @@ async function processPendingNotifications(db, sender, options) {
|
|
|
2234
2786
|
data: { status: "SENT", sentAt: /* @__PURE__ */ new Date() }
|
|
2235
2787
|
});
|
|
2236
2788
|
sent++;
|
|
2789
|
+
if (options?.webhooks && notification.trigger.startsWith("REMINDER_")) {
|
|
2790
|
+
await enqueueReminderSent(db, notification);
|
|
2791
|
+
}
|
|
2237
2792
|
}
|
|
2238
2793
|
} catch (error) {
|
|
2239
2794
|
const errorMsg = error instanceof Error ? error.message : "Unknown error";
|
|
@@ -2267,6 +2822,22 @@ async function processPendingNotifications(db, sender, options) {
|
|
|
2267
2822
|
}
|
|
2268
2823
|
return { sent, failed, deadLettered, skipped };
|
|
2269
2824
|
}
|
|
2825
|
+
async function loadSenders(db, rows) {
|
|
2826
|
+
const ids = [...new Set(rows.map((row) => row.appointment?.calendar?.organizationId).filter((id) => Boolean(id)))];
|
|
2827
|
+
const senders = /* @__PURE__ */ new Map();
|
|
2828
|
+
if (ids.length === 0) return senders;
|
|
2829
|
+
const brands = await db.organizationBrand.findMany({ where: { organizationId: { in: ids } } });
|
|
2830
|
+
for (const brand of brands) {
|
|
2831
|
+
const identity = senderIdentity(brand);
|
|
2832
|
+
if (identity) senders.set(brand.organizationId, identity);
|
|
2833
|
+
}
|
|
2834
|
+
return senders;
|
|
2835
|
+
}
|
|
2836
|
+
function senderFor(senders, row) {
|
|
2837
|
+
const organizationId = row.appointment?.calendar?.organizationId;
|
|
2838
|
+
const from = senders && organizationId ? senders.get(organizationId) : void 0;
|
|
2839
|
+
return from ? { from } : {};
|
|
2840
|
+
}
|
|
2270
2841
|
|
|
2271
2842
|
// src/notifications/engine.ts
|
|
2272
2843
|
async function scheduleNotifications(db, appointmentId, baseUrl, options) {
|
|
@@ -2286,10 +2857,10 @@ async function scheduleNotifications(db, appointmentId, baseUrl, options) {
|
|
|
2286
2857
|
}
|
|
2287
2858
|
});
|
|
2288
2859
|
if (!appointment) return;
|
|
2289
|
-
const context = buildNotificationContext({
|
|
2860
|
+
const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
|
|
2290
2861
|
...appointment,
|
|
2291
2862
|
intakeResponses: appointment.intakeResponses
|
|
2292
|
-
}, baseUrl);
|
|
2863
|
+
}, baseUrl), options?.brand);
|
|
2293
2864
|
const now = /* @__PURE__ */ new Date();
|
|
2294
2865
|
const startTime = new Date(appointment.startTime);
|
|
2295
2866
|
const templates = await db.notificationTemplate.findMany({
|
|
@@ -2362,7 +2933,7 @@ async function cancelPendingNotifications(db, appointmentId) {
|
|
|
2362
2933
|
data: { status: "CANCELLED" }
|
|
2363
2934
|
});
|
|
2364
2935
|
}
|
|
2365
|
-
async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
|
|
2936
|
+
async function queueImmediateNotification(db, appointmentId, trigger, baseUrl, options) {
|
|
2366
2937
|
const appointment = await db.appointment.findUnique({
|
|
2367
2938
|
where: { id: appointmentId },
|
|
2368
2939
|
include: {
|
|
@@ -2371,10 +2942,10 @@ async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
|
|
|
2371
2942
|
}
|
|
2372
2943
|
});
|
|
2373
2944
|
if (!appointment) return;
|
|
2374
|
-
const context = buildNotificationContext({
|
|
2945
|
+
const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
|
|
2375
2946
|
...appointment,
|
|
2376
2947
|
intakeResponses: appointment.intakeResponses
|
|
2377
|
-
}, baseUrl);
|
|
2948
|
+
}, baseUrl), options?.brand);
|
|
2378
2949
|
const templates = await db.notificationTemplate.findMany({
|
|
2379
2950
|
where: { trigger, isActive: true, recipientType: "CLIENT", organizationId: appointment.calendar.organizationId ?? "" }
|
|
2380
2951
|
});
|
|
@@ -2400,7 +2971,7 @@ async function queueImmediateNotification(db, appointmentId, trigger, baseUrl) {
|
|
|
2400
2971
|
await db.scheduledNotification.createMany({ data: notifications });
|
|
2401
2972
|
}
|
|
2402
2973
|
}
|
|
2403
|
-
async function queueStaffNotification(db, appointmentId, trigger, baseUrl) {
|
|
2974
|
+
async function queueStaffNotification(db, appointmentId, trigger, baseUrl, options) {
|
|
2404
2975
|
const appointment = await db.appointment.findUnique({
|
|
2405
2976
|
where: { id: appointmentId },
|
|
2406
2977
|
include: {
|
|
@@ -2415,10 +2986,10 @@ async function queueStaffNotification(db, appointmentId, trigger, baseUrl) {
|
|
|
2415
2986
|
where: { trigger, recipientType: "STAFF", isActive: true, organizationId: appointment.calendar.organizationId ?? "" }
|
|
2416
2987
|
});
|
|
2417
2988
|
if (staffTemplates.length === 0) return;
|
|
2418
|
-
const context = buildNotificationContext({
|
|
2989
|
+
const context = await withBrandFields(db, appointment.calendar.organizationId, buildNotificationContext({
|
|
2419
2990
|
...appointment,
|
|
2420
2991
|
intakeResponses: appointment.intakeResponses
|
|
2421
|
-
}, baseUrl);
|
|
2992
|
+
}, baseUrl), options?.brand);
|
|
2422
2993
|
const now = /* @__PURE__ */ new Date();
|
|
2423
2994
|
const notifications = staffTemplates.map((template) => ({
|
|
2424
2995
|
appointmentId: appointment.id,
|
|
@@ -3365,7 +3936,7 @@ function adaptersToCallbacks(adapters, passThrough = {}) {
|
|
|
3365
3936
|
return {
|
|
3366
3937
|
...passThrough,
|
|
3367
3938
|
sendNotification: async (channel, to, subject, body, context) => {
|
|
3368
|
-
const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger });
|
|
3939
|
+
const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger, ...context?.from ? { from: context.from } : {} });
|
|
3369
3940
|
if (result.status === "SKIPPED") return { skipped: true, reason: result.reason };
|
|
3370
3941
|
return void 0;
|
|
3371
3942
|
},
|
|
@@ -3413,10 +3984,10 @@ async function checkNotificationContract(adapter) {
|
|
|
3413
3984
|
const result = await adapter.send({ channel: "EMAIL", to: "contract@example.com", subject: "Contract", body: "Body" });
|
|
3414
3985
|
if (result.status !== "SENT" && result.status !== "SKIPPED") failures.push("send() must return status SENT or SKIPPED");
|
|
3415
3986
|
});
|
|
3416
|
-
for (const
|
|
3417
|
-
await guarded(`send to an empty recipient (${JSON.stringify(
|
|
3418
|
-
const result = await adapter.send({ channel: "SMS", to:
|
|
3419
|
-
if (result?.status === "SENT") failures.push(`send() must not report SENT for an empty recipient (${JSON.stringify(
|
|
3987
|
+
for (const blank2 of ["", " "]) {
|
|
3988
|
+
await guarded(`send to an empty recipient (${JSON.stringify(blank2)})`, failures, async () => {
|
|
3989
|
+
const result = await adapter.send({ channel: "SMS", to: blank2, subject: "", body: "Body" }).catch(() => null);
|
|
3990
|
+
if (result?.status === "SENT") failures.push(`send() must not report SENT for an empty recipient (${JSON.stringify(blank2)})`);
|
|
3420
3991
|
});
|
|
3421
3992
|
}
|
|
3422
3993
|
return failures;
|
|
@@ -3436,7 +4007,7 @@ async function checkPaymentContract(adapter, options = {}) {
|
|
|
3436
4007
|
if (!await refused(() => adapter.charge({ ...request, amount: 0 }))) failures.push("a charge of 0 must not succeed");
|
|
3437
4008
|
});
|
|
3438
4009
|
await guarded("verify of an unknown payment", failures, async () => {
|
|
3439
|
-
const paid = await adapter.verify("contract-unknown-payment").then((
|
|
4010
|
+
const paid = await adapter.verify("contract-unknown-payment").then((check2) => check2.paid, () => false);
|
|
3440
4011
|
if (paid) failures.push("verify() must report an unknown payment as not paid");
|
|
3441
4012
|
});
|
|
3442
4013
|
await guarded("refund of an unknown payment", failures, async () => {
|
|
@@ -3452,10 +4023,10 @@ async function checkPaymentContract(adapter, options = {}) {
|
|
|
3452
4023
|
failures.push("a valid charge must succeed and return a paymentId");
|
|
3453
4024
|
return;
|
|
3454
4025
|
}
|
|
3455
|
-
const
|
|
3456
|
-
if (!
|
|
3457
|
-
if (
|
|
3458
|
-
if (
|
|
4026
|
+
const check2 = await adapter.verify(charge.paymentId);
|
|
4027
|
+
if (!check2.paid) failures.push("verify() must report a charged payment as paid");
|
|
4028
|
+
if (check2.amount !== void 0 && check2.amount !== request.amount) failures.push("verify() must report the amount that was charged");
|
|
4029
|
+
if (check2.metadata?.contract !== "metadata-round-trip") failures.push("verify() must return the metadata the charge was made with");
|
|
3459
4030
|
const first = await adapter.refund(charge.paymentId);
|
|
3460
4031
|
if (!first.success) failures.push("the first refund of a paid payment must succeed");
|
|
3461
4032
|
if (first.amount !== void 0 && first.amount !== request.amount) failures.push("a full refund must report the amount it refunded");
|
|
@@ -3724,7 +4295,7 @@ function buildRecurringSlots(firstDate, frequency, occurrences, startTimeLocal,
|
|
|
3724
4295
|
|
|
3725
4296
|
// src/appointments/meeting.ts
|
|
3726
4297
|
function buildJitsiUrl(appointmentId) {
|
|
3727
|
-
return `https://meet.jit.si/
|
|
4298
|
+
return `https://meet.jit.si/ordinatio-${appointmentId}`;
|
|
3728
4299
|
}
|
|
3729
4300
|
function isVirtualMeeting(locationType) {
|
|
3730
4301
|
return locationType === "VIRTUAL";
|
|
@@ -3796,17 +4367,1615 @@ async function getTeamAvailableSlots(db, query, _getSlots = getAvailableSlots) {
|
|
|
3796
4367
|
timezone: query.timezone ?? firstResult?.timezone ?? "UTC"
|
|
3797
4368
|
};
|
|
3798
4369
|
}
|
|
4370
|
+
|
|
4371
|
+
// src/webhooks/signature.ts
|
|
4372
|
+
import { createHmac, randomBytes, timingSafeEqual } from "crypto";
|
|
4373
|
+
var SIGNATURE_HEADER = "x-scheduling-signature";
|
|
4374
|
+
function generateWebhookSecret() {
|
|
4375
|
+
return `whsec_${randomBytes(32).toString("base64url")}`;
|
|
4376
|
+
}
|
|
4377
|
+
function mac(secret, timestamp, body) {
|
|
4378
|
+
return createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
|
|
4379
|
+
}
|
|
4380
|
+
function signWebhook(args) {
|
|
4381
|
+
const timestamp = Math.floor(args.now.getTime() / 1e3);
|
|
4382
|
+
return `t=${timestamp},v1=${mac(args.secret, timestamp, args.body)}`;
|
|
4383
|
+
}
|
|
4384
|
+
function verifyWebhookSignature(args) {
|
|
4385
|
+
if (!args.header) return false;
|
|
4386
|
+
let timestamp = null;
|
|
4387
|
+
const candidates = [];
|
|
4388
|
+
for (const part of args.header.split(",")) {
|
|
4389
|
+
const [key, value] = part.trim().split("=");
|
|
4390
|
+
if (key === "t" && /^\d{1,12}$/.test(value ?? "")) timestamp = Number(value);
|
|
4391
|
+
if (key === "v1" && value) candidates.push(value);
|
|
4392
|
+
}
|
|
4393
|
+
if (timestamp === null || candidates.length === 0) return false;
|
|
4394
|
+
const tolerance = args.toleranceSeconds ?? 300;
|
|
4395
|
+
const nowSeconds = Math.floor((args.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3);
|
|
4396
|
+
if (Math.abs(nowSeconds - timestamp) > tolerance) return false;
|
|
4397
|
+
const expected = Buffer.from(mac(args.secret, timestamp, args.body), "hex");
|
|
4398
|
+
return candidates.some((candidate) => {
|
|
4399
|
+
const given = Buffer.from(candidate, "hex");
|
|
4400
|
+
return given.length === expected.length && timingSafeEqual(given, expected);
|
|
4401
|
+
});
|
|
4402
|
+
}
|
|
4403
|
+
|
|
4404
|
+
// src/webhooks/url-policy.ts
|
|
4405
|
+
import { isIP } from "net";
|
|
4406
|
+
function v4Parts(ip) {
|
|
4407
|
+
return ip.split(".").map(Number);
|
|
4408
|
+
}
|
|
4409
|
+
function isPrivateV4(ip) {
|
|
4410
|
+
const [a, b, c] = v4Parts(ip);
|
|
4411
|
+
return a === 0 || a === 10 || a === 127 || a === 100 && b >= 64 && b <= 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 0 && c === 0 || a === 192 && b === 168 || a === 198 && (b === 18 || b === 19) || a >= 224;
|
|
4412
|
+
}
|
|
4413
|
+
function v6Groups(ip) {
|
|
4414
|
+
let text2 = ip.toLowerCase().replace(/^\[|\]$/g, "").split("%")[0];
|
|
4415
|
+
const tail = /(\d+\.\d+\.\d+\.\d+)$/.exec(text2);
|
|
4416
|
+
if (tail) {
|
|
4417
|
+
const [a, b, c, d] = v4Parts(tail[1]);
|
|
4418
|
+
text2 = text2.slice(0, -tail[1].length) + (a << 8 | b).toString(16) + ":" + (c << 8 | d).toString(16);
|
|
4419
|
+
}
|
|
4420
|
+
const halves = text2.split("::");
|
|
4421
|
+
if (halves.length > 2) return null;
|
|
4422
|
+
const head = halves[0] ? halves[0].split(":") : [];
|
|
4423
|
+
const rest = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
|
|
4424
|
+
const missing = 8 - head.length - rest.length;
|
|
4425
|
+
if (halves.length === 1 ? missing !== 0 : missing < 1) return null;
|
|
4426
|
+
const groups = [...head, ...Array(halves.length === 2 ? missing : 0).fill("0"), ...rest].map((g) => parseInt(g, 16));
|
|
4427
|
+
return groups.length === 8 && groups.every((g) => Number.isInteger(g) && g >= 0 && g <= 65535) ? groups : null;
|
|
4428
|
+
}
|
|
4429
|
+
function isPrivateV6(ip) {
|
|
4430
|
+
const g = v6Groups(ip);
|
|
4431
|
+
if (!g) return true;
|
|
4432
|
+
const allZeroUpTo = (n) => g.slice(0, n).every((x) => x === 0);
|
|
4433
|
+
if (allZeroUpTo(7) && g[7] <= 1) return true;
|
|
4434
|
+
if (allZeroUpTo(5) && g[5] === 65535) return isPrivateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
|
|
4435
|
+
if (allZeroUpTo(6)) return isPrivateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
|
|
4436
|
+
if (g[0] === 100 && g[1] === 65435) return isPrivateV4(`${g[6] >> 8}.${g[6] & 255}.${g[7] >> 8}.${g[7] & 255}`);
|
|
4437
|
+
return (g[0] & 65024) === 64512 || (g[0] & 65472) === 65152 || (g[0] & 65280) === 65280;
|
|
4438
|
+
}
|
|
4439
|
+
function isPrivateAddress(ip) {
|
|
4440
|
+
const bare = ip.replace(/^\[|\]$/g, "");
|
|
4441
|
+
const kind = isIP(bare);
|
|
4442
|
+
if (kind === 4) return isPrivateV4(bare);
|
|
4443
|
+
if (kind === 6) return isPrivateV6(bare);
|
|
4444
|
+
return true;
|
|
4445
|
+
}
|
|
4446
|
+
var LOCAL_NAME = /(^|\.)(localhost|local|internal|localdomain|home\.arpa)$/;
|
|
4447
|
+
function checkWebhookUrl(raw, options = {}) {
|
|
4448
|
+
let url;
|
|
4449
|
+
try {
|
|
4450
|
+
url = new URL(raw);
|
|
4451
|
+
} catch {
|
|
4452
|
+
return { ok: false, reason: "The address is not a valid web address" };
|
|
4453
|
+
}
|
|
4454
|
+
const insecure = options.allowInsecureTargets === true;
|
|
4455
|
+
if (url.protocol !== "https:" && !(insecure && url.protocol === "http:")) {
|
|
4456
|
+
return { ok: false, reason: "The address must start with https://" };
|
|
4457
|
+
}
|
|
4458
|
+
if (url.username || url.password) {
|
|
4459
|
+
return { ok: false, reason: "The address must not contain a user name or password" };
|
|
4460
|
+
}
|
|
4461
|
+
if (!insecure) {
|
|
4462
|
+
const host = url.hostname.replace(/^\[|\]$/g, "").replace(/\.$/, "");
|
|
4463
|
+
if (LOCAL_NAME.test(host.toLowerCase()) || isIP(host) !== 0 && isPrivateAddress(host)) {
|
|
4464
|
+
return { ok: false, reason: "The address points at a private or local network" };
|
|
4465
|
+
}
|
|
4466
|
+
if (!host.includes(".") && isIP(host) === 0) {
|
|
4467
|
+
return { ok: false, reason: "The address must be a public name with a domain" };
|
|
4468
|
+
}
|
|
4469
|
+
}
|
|
4470
|
+
return { ok: true, url };
|
|
4471
|
+
}
|
|
4472
|
+
|
|
4473
|
+
// src/webhooks/transport.ts
|
|
4474
|
+
import dns from "dns";
|
|
4475
|
+
import http from "http";
|
|
4476
|
+
import https from "https";
|
|
4477
|
+
var BlockedTargetError = class extends Error {
|
|
4478
|
+
constructor(hostname) {
|
|
4479
|
+
super(`Refused to connect to ${hostname}: it resolves to a private or local address`);
|
|
4480
|
+
this.name = "BlockedTargetError";
|
|
4481
|
+
}
|
|
4482
|
+
};
|
|
4483
|
+
function guardedLookup(allowPrivate) {
|
|
4484
|
+
return (hostname, options, callback) => {
|
|
4485
|
+
dns.lookup(hostname, { ...options, all: true }, (error, addresses) => {
|
|
4486
|
+
if (error) return callback(error, "", 0);
|
|
4487
|
+
const list = addresses;
|
|
4488
|
+
if (list.length === 0) return callback(Object.assign(new Error(`No address for ${hostname}`), { code: "ENOTFOUND" }), "", 0);
|
|
4489
|
+
if (!allowPrivate && list.some((a) => isPrivateAddress(a.address))) return callback(new BlockedTargetError(hostname), "", 0);
|
|
4490
|
+
if (options.all) return callback(null, list);
|
|
4491
|
+
callback(null, list[0].address, list[0].family);
|
|
4492
|
+
});
|
|
4493
|
+
};
|
|
4494
|
+
}
|
|
4495
|
+
function createNodeTransport(options = {}) {
|
|
4496
|
+
const allowPrivate = options.allowInsecureTargets === true;
|
|
4497
|
+
return ({ url, headers, body, timeoutMs }) => new Promise((resolve, reject) => {
|
|
4498
|
+
const client = url.protocol === "https:" ? https : http;
|
|
4499
|
+
let settled = false;
|
|
4500
|
+
const finish = (action) => {
|
|
4501
|
+
if (settled) return;
|
|
4502
|
+
settled = true;
|
|
4503
|
+
clearTimeout(timer);
|
|
4504
|
+
action();
|
|
4505
|
+
};
|
|
4506
|
+
const request = client.request(
|
|
4507
|
+
url,
|
|
4508
|
+
{
|
|
4509
|
+
method: "POST",
|
|
4510
|
+
headers: { ...headers, "content-length": String(Buffer.byteLength(body)) },
|
|
4511
|
+
lookup: guardedLookup(allowPrivate),
|
|
4512
|
+
agent: false
|
|
4513
|
+
},
|
|
4514
|
+
(response) => {
|
|
4515
|
+
const status = response.statusCode ?? 0;
|
|
4516
|
+
response.destroy();
|
|
4517
|
+
finish(() => resolve({ status }));
|
|
4518
|
+
}
|
|
4519
|
+
);
|
|
4520
|
+
const timer = setTimeout(() => {
|
|
4521
|
+
request.destroy(new Error(`Timed out after ${timeoutMs} ms`));
|
|
4522
|
+
}, timeoutMs);
|
|
4523
|
+
request.on("error", (error) => finish(() => reject(error)));
|
|
4524
|
+
request.end(body);
|
|
4525
|
+
});
|
|
4526
|
+
}
|
|
4527
|
+
|
|
4528
|
+
// src/webhooks/endpoints.ts
|
|
4529
|
+
var MAX_ENDPOINTS_PER_ORGANIZATION = 20;
|
|
4530
|
+
var VIEW_FIELDS = { id: true, url: true, description: true, eventTypes: true, isActive: true, createdAt: true };
|
|
4531
|
+
async function createWebhookEndpoint(db, input, options = {}) {
|
|
4532
|
+
const checked = checkWebhookUrl(input.url, options);
|
|
4533
|
+
if (!checked.ok) throw new SchedulingValidationError(checked.reason, "SCHED_1000", { url: input.url });
|
|
4534
|
+
const eventTypes = normalizeEventTypes(input.eventTypes);
|
|
4535
|
+
if (!eventTypes) throw new SchedulingValidationError("Choose at least one valid event, or *", "SCHED_1001");
|
|
4536
|
+
const existing = await db.webhookEndpoint.count({ where: { organizationId: input.organizationId } });
|
|
4537
|
+
if (existing >= MAX_ENDPOINTS_PER_ORGANIZATION) {
|
|
4538
|
+
throw new SchedulingValidationError(
|
|
4539
|
+
`An organization can have at most ${MAX_ENDPOINTS_PER_ORGANIZATION} webhook endpoints`,
|
|
4540
|
+
"SCHED_1002",
|
|
4541
|
+
{ organizationId: input.organizationId }
|
|
4542
|
+
);
|
|
4543
|
+
}
|
|
4544
|
+
const secret = generateWebhookSecret();
|
|
4545
|
+
const endpoint = await db.webhookEndpoint.create({
|
|
4546
|
+
data: {
|
|
4547
|
+
organizationId: input.organizationId,
|
|
4548
|
+
url: checked.url.toString(),
|
|
4549
|
+
description: input.description?.trim() || null,
|
|
4550
|
+
eventTypes,
|
|
4551
|
+
secret
|
|
4552
|
+
},
|
|
4553
|
+
select: VIEW_FIELDS
|
|
4554
|
+
});
|
|
4555
|
+
return { endpoint, secret };
|
|
4556
|
+
}
|
|
4557
|
+
async function listWebhookEndpoints(db, organizationId) {
|
|
4558
|
+
return db.webhookEndpoint.findMany({ where: { organizationId }, orderBy: { createdAt: "desc" }, select: VIEW_FIELDS });
|
|
4559
|
+
}
|
|
4560
|
+
async function deleteWebhookEndpoint(db, organizationId, endpointId) {
|
|
4561
|
+
const removed = await db.webhookEndpoint.deleteMany({ where: { id: endpointId, organizationId } });
|
|
4562
|
+
if (removed.count === 0) throw new SchedulingNotFoundError("Webhook endpoint not found", "SCHED_1003", { endpointId });
|
|
4563
|
+
}
|
|
4564
|
+
|
|
4565
|
+
// src/webhooks/deliver.ts
|
|
4566
|
+
import { randomUUID as randomUUID3 } from "crypto";
|
|
4567
|
+
import { Prisma as Prisma8 } from "@prisma/client";
|
|
4568
|
+
|
|
4569
|
+
// src/webhooks/attempt.ts
|
|
4570
|
+
var DEFAULT_BACKOFF_SECONDS = [60, 300, 1800, 7200, 21600];
|
|
4571
|
+
var MAX_ERROR_LENGTH = 300;
|
|
4572
|
+
function describe(error) {
|
|
4573
|
+
const code = error.code;
|
|
4574
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
4575
|
+
return (code && !message.includes(code) ? `${code}: ${message}` : message).slice(0, MAX_ERROR_LENGTH);
|
|
4576
|
+
}
|
|
4577
|
+
async function attemptDelivery(db, delivery, workerId, options = {}) {
|
|
4578
|
+
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
4579
|
+
const backoff = options.backoffSeconds ?? DEFAULT_BACKOFF_SECONDS;
|
|
4580
|
+
const maxAttempts = options.maxAttempts ?? backoff.length + 1;
|
|
4581
|
+
const transport = options.transport ?? createNodeTransport({ allowInsecureTargets: options.allowInsecureTargets });
|
|
4582
|
+
const attemptNumber = delivery.attempts + 1;
|
|
4583
|
+
const startedAt = now();
|
|
4584
|
+
let statusCode = null;
|
|
4585
|
+
let error = null;
|
|
4586
|
+
let retryable = true;
|
|
4587
|
+
const target = checkWebhookUrl(delivery.endpoint.url, { allowInsecureTargets: options.allowInsecureTargets });
|
|
4588
|
+
if (!delivery.endpoint.isActive) {
|
|
4589
|
+
error = "The endpoint is switched off";
|
|
4590
|
+
retryable = false;
|
|
4591
|
+
} else if (!target.ok) {
|
|
4592
|
+
error = `${schedError("SCHED_1005", { endpointId: delivery.endpoint.id }).ref}: ${target.reason}`;
|
|
4593
|
+
retryable = false;
|
|
4594
|
+
} else {
|
|
4595
|
+
try {
|
|
4596
|
+
const response = await transport({
|
|
4597
|
+
url: target.url,
|
|
4598
|
+
timeoutMs: options.timeoutMs ?? 1e4,
|
|
4599
|
+
body: delivery.body,
|
|
4600
|
+
headers: {
|
|
4601
|
+
"content-type": "application/json",
|
|
4602
|
+
"user-agent": "scheduling-webhooks/1",
|
|
4603
|
+
"x-scheduling-event": delivery.eventType,
|
|
4604
|
+
"x-scheduling-delivery": delivery.id,
|
|
4605
|
+
[SIGNATURE_HEADER]: signWebhook({ secret: delivery.endpoint.secret, body: delivery.body, now: startedAt })
|
|
4606
|
+
}
|
|
4607
|
+
});
|
|
4608
|
+
statusCode = response.status;
|
|
4609
|
+
if (response.status < 200 || response.status >= 300) error = `The receiver answered HTTP ${response.status}`;
|
|
4610
|
+
} catch (caught) {
|
|
4611
|
+
error = describe(caught);
|
|
4612
|
+
retryable = caught.name !== "BlockedTargetError";
|
|
4613
|
+
}
|
|
4614
|
+
}
|
|
4615
|
+
const finishedAt = now();
|
|
4616
|
+
const succeeded = error === null;
|
|
4617
|
+
const exhausted = !retryable || attemptNumber >= maxAttempts;
|
|
4618
|
+
const outcome = succeeded ? "SUCCEEDED" : exhausted ? "DEAD_LETTER" : "RETRY";
|
|
4619
|
+
const updated = await db.webhookDelivery.updateMany({
|
|
4620
|
+
where: { id: delivery.id, organizationId: delivery.organizationId, status: "PROCESSING", processingId: workerId },
|
|
4621
|
+
data: {
|
|
4622
|
+
status: outcome === "SUCCEEDED" ? "SUCCEEDED" : outcome === "DEAD_LETTER" ? "DEAD_LETTER" : "PENDING",
|
|
4623
|
+
attempts: attemptNumber,
|
|
4624
|
+
lastStatusCode: statusCode,
|
|
4625
|
+
lastError: error,
|
|
4626
|
+
deliveredAt: succeeded ? finishedAt : null,
|
|
4627
|
+
nextAttemptAt: outcome === "RETRY" ? new Date(finishedAt.getTime() + backoff[Math.min(attemptNumber - 1, backoff.length - 1)] * 1e3) : void 0,
|
|
4628
|
+
processingId: null,
|
|
4629
|
+
claimedAt: null
|
|
4630
|
+
}
|
|
4631
|
+
});
|
|
4632
|
+
if (updated.count === 0) return { outcome: "LOST_CLAIM", statusCode, error };
|
|
4633
|
+
await db.webhookAttempt.create({
|
|
4634
|
+
data: { deliveryId: delivery.id, attemptNumber, statusCode, error, durationMs: Math.max(0, finishedAt.getTime() - startedAt.getTime()) }
|
|
4635
|
+
});
|
|
4636
|
+
return { outcome, statusCode, error };
|
|
4637
|
+
}
|
|
4638
|
+
|
|
4639
|
+
// src/webhooks/deliver.ts
|
|
4640
|
+
async function deliverDueWebhooks(db, options = {}) {
|
|
4641
|
+
const now = (options.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
4642
|
+
const batchSize = Math.max(1, Math.min(200, Math.floor(options.batchSize ?? 20)));
|
|
4643
|
+
const concurrency = Math.max(1, Math.floor(options.concurrency ?? 5));
|
|
4644
|
+
const workerId = options.workerId ?? randomUUID3();
|
|
4645
|
+
const staleBefore = new Date(now.getTime() - (options.staleClaimMs ?? 5 * 6e4));
|
|
4646
|
+
const claimed = await db.$queryRaw`
|
|
4647
|
+
WITH candidates AS (
|
|
4648
|
+
SELECT id FROM "WebhookDelivery"
|
|
4649
|
+
WHERE (status = 'PENDING' AND "nextAttemptAt" <= ${now})
|
|
4650
|
+
OR (status = 'PROCESSING' AND "claimedAt" < ${staleBefore})
|
|
4651
|
+
ORDER BY "nextAttemptAt" ASC
|
|
4652
|
+
LIMIT ${Prisma8.raw(String(batchSize))}
|
|
4653
|
+
FOR UPDATE SKIP LOCKED
|
|
4654
|
+
)
|
|
4655
|
+
UPDATE "WebhookDelivery" d
|
|
4656
|
+
SET status = 'PROCESSING', "processingId" = ${workerId}, "claimedAt" = ${now}
|
|
4657
|
+
FROM candidates
|
|
4658
|
+
WHERE d.id = candidates.id
|
|
4659
|
+
RETURNING d.id
|
|
4660
|
+
`;
|
|
4661
|
+
const summary = { succeeded: 0, retried: 0, deadLettered: 0, lostClaim: 0 };
|
|
4662
|
+
if (claimed.length === 0) return summary;
|
|
4663
|
+
const rows = await db.webhookDelivery.findMany({
|
|
4664
|
+
where: { id: { in: claimed.map((c) => c.id) }, processingId: workerId },
|
|
4665
|
+
select: {
|
|
4666
|
+
id: true,
|
|
4667
|
+
organizationId: true,
|
|
4668
|
+
eventId: true,
|
|
4669
|
+
eventType: true,
|
|
4670
|
+
body: true,
|
|
4671
|
+
attempts: true,
|
|
4672
|
+
endpoint: { select: { id: true, url: true, secret: true, isActive: true } }
|
|
4673
|
+
}
|
|
4674
|
+
});
|
|
4675
|
+
for (let i = 0; i < rows.length; i += concurrency) {
|
|
4676
|
+
const results = await Promise.all(rows.slice(i, i + concurrency).map((row) => attemptDelivery(db, row, workerId, options)));
|
|
4677
|
+
for (const { outcome } of results) {
|
|
4678
|
+
if (outcome === "SUCCEEDED") summary.succeeded++;
|
|
4679
|
+
else if (outcome === "RETRY") summary.retried++;
|
|
4680
|
+
else if (outcome === "DEAD_LETTER") summary.deadLettered++;
|
|
4681
|
+
else summary.lostClaim++;
|
|
4682
|
+
}
|
|
4683
|
+
}
|
|
4684
|
+
return summary;
|
|
4685
|
+
}
|
|
4686
|
+
|
|
4687
|
+
// src/webhooks/test-send.ts
|
|
4688
|
+
import { randomUUID as randomUUID4 } from "crypto";
|
|
4689
|
+
async function sendTestWebhook(db, input, options = {}) {
|
|
4690
|
+
const endpoint = await db.webhookEndpoint.findFirst({
|
|
4691
|
+
where: { id: input.endpointId, organizationId: input.organizationId },
|
|
4692
|
+
select: { id: true, url: true, secret: true, isActive: true }
|
|
4693
|
+
});
|
|
4694
|
+
if (!endpoint) throw new SchedulingNotFoundError("Webhook endpoint not found", "SCHED_1003", { endpointId: input.endpointId });
|
|
4695
|
+
const now = (options.now ?? (() => /* @__PURE__ */ new Date()))();
|
|
4696
|
+
const workerId = randomUUID4();
|
|
4697
|
+
const envelope = buildEnvelope({
|
|
4698
|
+
organizationId: input.organizationId,
|
|
4699
|
+
type: WEBHOOK_TEST_EVENT,
|
|
4700
|
+
data: { message: "This is a test event from your scheduling system." },
|
|
4701
|
+
now
|
|
4702
|
+
});
|
|
4703
|
+
const created = await db.webhookDelivery.create({
|
|
4704
|
+
data: {
|
|
4705
|
+
organizationId: input.organizationId,
|
|
4706
|
+
endpointId: endpoint.id,
|
|
4707
|
+
eventId: envelope.id,
|
|
4708
|
+
eventType: WEBHOOK_TEST_EVENT,
|
|
4709
|
+
body: JSON.stringify(envelope),
|
|
4710
|
+
status: "PROCESSING",
|
|
4711
|
+
processingId: workerId,
|
|
4712
|
+
claimedAt: now,
|
|
4713
|
+
nextAttemptAt: now
|
|
4714
|
+
},
|
|
4715
|
+
select: { id: true, organizationId: true, eventId: true, eventType: true, body: true, attempts: true }
|
|
4716
|
+
});
|
|
4717
|
+
const result = await attemptDelivery(db, { ...created, endpoint }, workerId, { ...options, maxAttempts: 1 });
|
|
4718
|
+
return { deliveryId: created.id, ok: result.outcome === "SUCCEEDED", statusCode: result.statusCode, error: result.error };
|
|
4719
|
+
}
|
|
4720
|
+
|
|
4721
|
+
// src/webhooks/deliveries.ts
|
|
4722
|
+
async function listWebhookDeliveries(db, input) {
|
|
4723
|
+
const where = {
|
|
4724
|
+
organizationId: input.organizationId,
|
|
4725
|
+
...input.endpointId ? { endpointId: input.endpointId } : {},
|
|
4726
|
+
...input.status ? { status: input.status } : {}
|
|
4727
|
+
};
|
|
4728
|
+
const [deliveries, total] = await Promise.all([
|
|
4729
|
+
db.webhookDelivery.findMany({
|
|
4730
|
+
where,
|
|
4731
|
+
orderBy: { createdAt: "desc" },
|
|
4732
|
+
take: Math.min(input.limit ?? 50, 200),
|
|
4733
|
+
skip: input.offset ?? 0,
|
|
4734
|
+
select: {
|
|
4735
|
+
id: true,
|
|
4736
|
+
endpointId: true,
|
|
4737
|
+
eventId: true,
|
|
4738
|
+
eventType: true,
|
|
4739
|
+
status: true,
|
|
4740
|
+
attempts: true,
|
|
4741
|
+
nextAttemptAt: true,
|
|
4742
|
+
lastStatusCode: true,
|
|
4743
|
+
lastError: true,
|
|
4744
|
+
deliveredAt: true,
|
|
4745
|
+
createdAt: true,
|
|
4746
|
+
attemptLog: { orderBy: { attemptNumber: "desc" }, take: 10, select: { attemptNumber: true, statusCode: true, error: true, durationMs: true, createdAt: true } }
|
|
4747
|
+
}
|
|
4748
|
+
}),
|
|
4749
|
+
db.webhookDelivery.count({ where })
|
|
4750
|
+
]);
|
|
4751
|
+
return { deliveries, total };
|
|
4752
|
+
}
|
|
4753
|
+
async function retryWebhookDelivery(db, organizationId, deliveryId, now = /* @__PURE__ */ new Date()) {
|
|
4754
|
+
const updated = await db.webhookDelivery.updateMany({
|
|
4755
|
+
where: { id: deliveryId, organizationId, status: "DEAD_LETTER" },
|
|
4756
|
+
data: { status: "PENDING", attempts: 0, nextAttemptAt: now, processingId: null, claimedAt: null }
|
|
4757
|
+
});
|
|
4758
|
+
if (updated.count === 0) throw new SchedulingNotFoundError("Delivery not found or not in the dead-letter list", "SCHED_1004", { deliveryId });
|
|
4759
|
+
}
|
|
4760
|
+
|
|
4761
|
+
// src/waitlist/join.ts
|
|
4762
|
+
import { randomBytes as randomBytes2 } from "crypto";
|
|
4763
|
+
|
|
4764
|
+
// src/waitlist/day.ts
|
|
4765
|
+
var MAX_DAYS_AHEAD = 90;
|
|
4766
|
+
function isDayString(value) {
|
|
4767
|
+
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return false;
|
|
4768
|
+
const parsed = /* @__PURE__ */ new Date(`${value}T00:00:00Z`);
|
|
4769
|
+
return !Number.isNaN(parsed.getTime()) && parsed.toISOString().slice(0, 10) === value;
|
|
4770
|
+
}
|
|
4771
|
+
function localDay(instant, timeZone) {
|
|
4772
|
+
return new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" }).format(instant);
|
|
4773
|
+
}
|
|
4774
|
+
function daysBetween(from, to) {
|
|
4775
|
+
return Math.round((Date.parse(`${to}T00:00:00Z`) - Date.parse(`${from}T00:00:00Z`)) / 864e5);
|
|
4776
|
+
}
|
|
4777
|
+
|
|
4778
|
+
// src/waitlist/view.ts
|
|
4779
|
+
var VIEW_SELECT = {
|
|
4780
|
+
id: true,
|
|
4781
|
+
typeId: true,
|
|
4782
|
+
calendarId: true,
|
|
4783
|
+
day: true,
|
|
4784
|
+
slotStart: true,
|
|
4785
|
+
clientName: true,
|
|
4786
|
+
clientEmail: true,
|
|
4787
|
+
clientPhone: true,
|
|
4788
|
+
status: true,
|
|
4789
|
+
offerSlotStart: true,
|
|
4790
|
+
offerExpiresAt: true,
|
|
4791
|
+
createdAt: true
|
|
4792
|
+
};
|
|
4793
|
+
var LIVE_STATUSES = ["WAITING", "OFFERED", "ACCEPTING"];
|
|
4794
|
+
|
|
4795
|
+
// src/waitlist/join.ts
|
|
4796
|
+
var MAX_WAITING_PER_TYPE_DAY = 50;
|
|
4797
|
+
async function joinWaitlist(db, input, now = /* @__PURE__ */ new Date()) {
|
|
4798
|
+
const orgScope = [{ organizationId: input.organizationId }, { organizationId: null }];
|
|
4799
|
+
const type = await db.appointmentType.findFirst({
|
|
4800
|
+
where: { id: input.typeId, isActive: true, OR: orgScope },
|
|
4801
|
+
select: { id: true, duration: true, requiresPayment: true, intakeForm: true, calendars: { select: { calendarId: true } } }
|
|
4802
|
+
});
|
|
4803
|
+
if (!type) throw new SchedulingNotFoundError("Appointment type not found", "SCHED_1100", { typeId: input.typeId });
|
|
4804
|
+
if (type.requiresPayment) {
|
|
4805
|
+
throw new SchedulingValidationError("A waitlist is not available for a type that needs payment", "SCHED_1105", { typeId: input.typeId });
|
|
4806
|
+
}
|
|
4807
|
+
const intakeForm = Array.isArray(type.intakeForm) ? type.intakeForm : [];
|
|
4808
|
+
if (intakeForm.some((field) => field.required)) {
|
|
4809
|
+
throw new SchedulingValidationError("A waitlist is not available for a type with required questions", "SCHED_1110", { typeId: input.typeId });
|
|
4810
|
+
}
|
|
4811
|
+
const linked = type.calendars.map((c) => c.calendarId);
|
|
4812
|
+
if (input.calendarId && !linked.includes(input.calendarId)) {
|
|
4813
|
+
throw new SchedulingNotFoundError("Calendar not found for this type", "SCHED_1100", { calendarId: input.calendarId });
|
|
4814
|
+
}
|
|
4815
|
+
const calendars = await db.schedulingCalendar.findMany({
|
|
4816
|
+
where: { id: { in: input.calendarId ? [input.calendarId] : linked }, OR: orgScope },
|
|
4817
|
+
select: { id: true, timezone: true }
|
|
4818
|
+
});
|
|
4819
|
+
if (calendars.length === 0) throw new SchedulingNotFoundError("Calendar not found for this type", "SCHED_1100", { typeId: input.typeId });
|
|
4820
|
+
const timezone = calendars[0].timezone;
|
|
4821
|
+
if (!isDayString(input.day)) throw new SchedulingValidationError("The day must be YYYY-MM-DD", "SCHED_1101", { day: input.day });
|
|
4822
|
+
const ahead = daysBetween(localDay(now, timezone), input.day);
|
|
4823
|
+
if (ahead < 0 || ahead > MAX_DAYS_AHEAD) {
|
|
4824
|
+
throw new SchedulingValidationError(`The day must be within the next ${MAX_DAYS_AHEAD} days`, "SCHED_1101", { day: input.day });
|
|
4825
|
+
}
|
|
4826
|
+
if (input.slotStart) {
|
|
4827
|
+
if (Number.isNaN(input.slotStart.getTime()) || input.slotStart <= now || localDay(input.slotStart, timezone) !== input.day) {
|
|
4828
|
+
throw new SchedulingValidationError("The time must be in the future, on the chosen day", "SCHED_1102", { day: input.day });
|
|
4829
|
+
}
|
|
4830
|
+
}
|
|
4831
|
+
const open = [];
|
|
4832
|
+
for (const calendar of calendars) {
|
|
4833
|
+
const result = await getAvailableSlots(db, {
|
|
4834
|
+
calendarId: calendar.id,
|
|
4835
|
+
date: /* @__PURE__ */ new Date(`${input.day}T12:00:00Z`),
|
|
4836
|
+
localDate: input.day,
|
|
4837
|
+
duration: type.duration,
|
|
4838
|
+
timezone: calendar.timezone
|
|
4839
|
+
});
|
|
4840
|
+
for (const slot of result.slots) if (slot.available) open.push(slot.start);
|
|
4841
|
+
}
|
|
4842
|
+
const stillOpen = input.slotStart ? open.some((start) => start.getTime() === input.slotStart.getTime()) : open.length > 0;
|
|
4843
|
+
if (stillOpen) {
|
|
4844
|
+
throw new SchedulingValidationError("That time is open: book it instead of waiting", "SCHED_1103", { day: input.day });
|
|
4845
|
+
}
|
|
4846
|
+
const email2 = input.clientEmail.trim();
|
|
4847
|
+
const duplicate = await db.waitlistEntry.findFirst({
|
|
4848
|
+
where: {
|
|
4849
|
+
organizationId: input.organizationId,
|
|
4850
|
+
typeId: type.id,
|
|
4851
|
+
day: input.day,
|
|
4852
|
+
slotStart: input.slotStart ?? null,
|
|
4853
|
+
clientEmail: { equals: email2, mode: "insensitive" },
|
|
4854
|
+
status: { in: LIVE_STATUSES }
|
|
4855
|
+
},
|
|
4856
|
+
select: { id: true }
|
|
4857
|
+
});
|
|
4858
|
+
if (duplicate) throw new SchedulingValidationError("This email is already waiting for that day", "SCHED_1104", { day: input.day });
|
|
4859
|
+
const waiting = await db.waitlistEntry.count({ where: { organizationId: input.organizationId, typeId: type.id, day: input.day, status: "WAITING" } });
|
|
4860
|
+
if (waiting >= MAX_WAITING_PER_TYPE_DAY) {
|
|
4861
|
+
throw new SchedulingValidationError("The waitlist for that day is full", "SCHED_1108", { day: input.day });
|
|
4862
|
+
}
|
|
4863
|
+
const token = randomBytes2(24).toString("base64url");
|
|
4864
|
+
const entry4 = await db.waitlistEntry.create({
|
|
4865
|
+
data: {
|
|
4866
|
+
organizationId: input.organizationId,
|
|
4867
|
+
typeId: type.id,
|
|
4868
|
+
calendarId: input.calendarId ?? null,
|
|
4869
|
+
day: input.day,
|
|
4870
|
+
slotStart: input.slotStart ?? null,
|
|
4871
|
+
timezone,
|
|
4872
|
+
clientName: input.clientName.trim(),
|
|
4873
|
+
clientEmail: email2,
|
|
4874
|
+
clientPhone: input.clientPhone?.trim() || null,
|
|
4875
|
+
token
|
|
4876
|
+
},
|
|
4877
|
+
select: VIEW_SELECT
|
|
4878
|
+
});
|
|
4879
|
+
return { entry: entry4, token };
|
|
4880
|
+
}
|
|
4881
|
+
|
|
4882
|
+
// src/waitlist/accept.ts
|
|
4883
|
+
var ENTRY_SELECT = {
|
|
4884
|
+
id: true,
|
|
4885
|
+
organizationId: true,
|
|
4886
|
+
typeId: true,
|
|
4887
|
+
status: true,
|
|
4888
|
+
offerCalendarId: true,
|
|
4889
|
+
offerSlotStart: true,
|
|
4890
|
+
offerExpiresAt: true,
|
|
4891
|
+
clientName: true,
|
|
4892
|
+
clientEmail: true,
|
|
4893
|
+
clientPhone: true,
|
|
4894
|
+
timezone: true,
|
|
4895
|
+
type: { select: { name: true } }
|
|
4896
|
+
};
|
|
4897
|
+
async function loadOffer(db, token) {
|
|
4898
|
+
const entry4 = await db.waitlistEntry.findUnique({ where: { token }, select: ENTRY_SELECT });
|
|
4899
|
+
if (!entry4 || !entry4.offerCalendarId || !entry4.offerSlotStart || !entry4.offerExpiresAt) {
|
|
4900
|
+
throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
|
|
4901
|
+
}
|
|
4902
|
+
const calendar = await db.schedulingCalendar.findUnique({ where: { id: entry4.offerCalendarId }, select: { name: true } });
|
|
4903
|
+
return {
|
|
4904
|
+
status: entry4.status,
|
|
4905
|
+
details: {
|
|
4906
|
+
entryId: entry4.id,
|
|
4907
|
+
organizationId: entry4.organizationId,
|
|
4908
|
+
typeId: entry4.typeId,
|
|
4909
|
+
typeName: entry4.type.name,
|
|
4910
|
+
calendarId: entry4.offerCalendarId,
|
|
4911
|
+
calendarName: calendar?.name ?? "",
|
|
4912
|
+
startTime: entry4.offerSlotStart,
|
|
4913
|
+
timezone: entry4.timezone,
|
|
4914
|
+
expiresAt: entry4.offerExpiresAt,
|
|
4915
|
+
clientName: entry4.clientName,
|
|
4916
|
+
clientEmail: entry4.clientEmail,
|
|
4917
|
+
clientPhone: entry4.clientPhone
|
|
4918
|
+
}
|
|
4919
|
+
};
|
|
4920
|
+
}
|
|
4921
|
+
async function getWaitlistOffer(db, token, now = /* @__PURE__ */ new Date()) {
|
|
4922
|
+
const { details, status } = await loadOffer(db, token);
|
|
4923
|
+
if (status !== "OFFERED") throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
|
|
4924
|
+
if (details.expiresAt <= now) throw new SchedulingValidationError("The offer has expired", "SCHED_1107");
|
|
4925
|
+
return details;
|
|
4926
|
+
}
|
|
4927
|
+
async function beginWaitlistAccept(db, token, now = /* @__PURE__ */ new Date()) {
|
|
4928
|
+
const claimed = await db.waitlistEntry.updateMany({
|
|
4929
|
+
where: { token, status: "OFFERED", offerExpiresAt: { gt: now } },
|
|
4930
|
+
data: { status: "ACCEPTING", acceptingAt: now }
|
|
4931
|
+
});
|
|
4932
|
+
if (claimed.count === 0) {
|
|
4933
|
+
await getWaitlistOffer(db, token, now);
|
|
4934
|
+
throw new SchedulingNotFoundError("No open offer for this link", "SCHED_1106");
|
|
4935
|
+
}
|
|
4936
|
+
return (await loadOffer(db, token)).details;
|
|
4937
|
+
}
|
|
4938
|
+
async function completeWaitlistAccept(db, entryId, appointmentId) {
|
|
4939
|
+
await db.waitlistEntry.updateMany({
|
|
4940
|
+
where: { id: entryId, status: "ACCEPTING" },
|
|
4941
|
+
data: { status: "BOOKED", bookedAppointmentId: appointmentId }
|
|
4942
|
+
});
|
|
4943
|
+
}
|
|
4944
|
+
async function releaseWaitlistAccept(db, entryId, outcome = "BACK_IN_LINE") {
|
|
4945
|
+
const where = { id: entryId, status: "ACCEPTING" };
|
|
4946
|
+
if (outcome === "KEEP_OFFER") {
|
|
4947
|
+
await db.waitlistEntry.updateMany({ where, data: { status: "OFFERED", acceptingAt: null } });
|
|
4948
|
+
return null;
|
|
4949
|
+
}
|
|
4950
|
+
if (outcome === "BACK_IN_LINE") {
|
|
4951
|
+
await db.waitlistEntry.updateMany({
|
|
4952
|
+
where,
|
|
4953
|
+
data: { status: "WAITING", offerCalendarId: null, offerSlotStart: null, offerExpiresAt: null, offeredAt: null, acceptingAt: null }
|
|
4954
|
+
});
|
|
4955
|
+
return null;
|
|
4956
|
+
}
|
|
4957
|
+
const row = await db.waitlistEntry.findFirst({ where, select: { organizationId: true, offerCalendarId: true, offerSlotStart: true } });
|
|
4958
|
+
const ended = await db.waitlistEntry.updateMany({ where, data: { status: "EXPIRED", acceptingAt: null } });
|
|
4959
|
+
return row && ended.count > 0 && row.offerCalendarId && row.offerSlotStart ? { organizationId: row.organizationId, calendarId: row.offerCalendarId, startTime: row.offerSlotStart } : null;
|
|
4960
|
+
}
|
|
4961
|
+
async function findBookingForOffer(db, entry4) {
|
|
4962
|
+
if (!entry4.offerCalendarId || !entry4.offerSlotStart) return null;
|
|
4963
|
+
return db.appointment.findFirst({
|
|
4964
|
+
where: {
|
|
4965
|
+
calendarId: entry4.offerCalendarId,
|
|
4966
|
+
startTime: entry4.offerSlotStart,
|
|
4967
|
+
clientEmail: { equals: entry4.clientEmail, mode: "insensitive" },
|
|
4968
|
+
status: { in: ["PENDING", "CONFIRMED"] }
|
|
4969
|
+
},
|
|
4970
|
+
select: { id: true }
|
|
4971
|
+
});
|
|
4972
|
+
}
|
|
4973
|
+
async function settleBookedAccept(db, entryId) {
|
|
4974
|
+
const entry4 = await db.waitlistEntry.findFirst({
|
|
4975
|
+
where: { id: entryId, status: "ACCEPTING" },
|
|
4976
|
+
select: { offerCalendarId: true, offerSlotStart: true, clientEmail: true }
|
|
4977
|
+
});
|
|
4978
|
+
const found = entry4 ? await findBookingForOffer(db, entry4) : null;
|
|
4979
|
+
if (!found) return null;
|
|
4980
|
+
await db.waitlistEntry.updateMany({
|
|
4981
|
+
where: { id: entryId, status: "ACCEPTING" },
|
|
4982
|
+
data: { status: "BOOKED", bookedAppointmentId: found.id, acceptingAt: null }
|
|
4983
|
+
});
|
|
4984
|
+
return db.appointment.findUnique({
|
|
4985
|
+
where: { id: found.id },
|
|
4986
|
+
select: { id: true, status: true, startTime: true, endTime: true, manageToken: true, clientName: true, clientEmail: true }
|
|
4987
|
+
});
|
|
4988
|
+
}
|
|
4989
|
+
|
|
4990
|
+
// src/waitlist/offer.ts
|
|
4991
|
+
var DEFAULT_OFFER_MINUTES = 30;
|
|
4992
|
+
var CANDIDATES_PER_SLOT = 25;
|
|
4993
|
+
function isUniqueViolation(error) {
|
|
4994
|
+
return typeof error === "object" && error !== null && error.code === "P2002";
|
|
4995
|
+
}
|
|
4996
|
+
async function offerFreedSlot(db, input) {
|
|
4997
|
+
const now = input.now ?? /* @__PURE__ */ new Date();
|
|
4998
|
+
if (input.startTime <= now) return null;
|
|
4999
|
+
const calendar = await db.schedulingCalendar.findUnique({
|
|
5000
|
+
where: { id: input.calendarId },
|
|
5001
|
+
select: { name: true, timezone: true, organizationId: true }
|
|
5002
|
+
});
|
|
5003
|
+
if (!calendar || calendar.organizationId !== null && calendar.organizationId !== input.organizationId) return null;
|
|
5004
|
+
await db.waitlistEntry.updateMany({
|
|
5005
|
+
where: {
|
|
5006
|
+
organizationId: input.organizationId,
|
|
5007
|
+
status: "OFFERED",
|
|
5008
|
+
offerCalendarId: input.calendarId,
|
|
5009
|
+
offerSlotStart: input.startTime,
|
|
5010
|
+
offerExpiresAt: { lte: now }
|
|
5011
|
+
},
|
|
5012
|
+
data: { status: "EXPIRED" }
|
|
5013
|
+
});
|
|
5014
|
+
const candidates = await db.waitlistEntry.findMany({
|
|
5015
|
+
where: {
|
|
5016
|
+
organizationId: input.organizationId,
|
|
5017
|
+
status: "WAITING",
|
|
5018
|
+
day: localDay(input.startTime, calendar.timezone),
|
|
5019
|
+
// Only people whose type runs on this calendar, so earlier people it cannot fit never crowd out later ones that it can.
|
|
5020
|
+
type: { isActive: true, calendars: { some: { calendarId: input.calendarId } } },
|
|
5021
|
+
AND: [
|
|
5022
|
+
{ OR: [{ calendarId: null }, { calendarId: input.calendarId }] },
|
|
5023
|
+
{ OR: [{ slotStart: null }, { slotStart: input.startTime }] }
|
|
5024
|
+
]
|
|
5025
|
+
},
|
|
5026
|
+
orderBy: { createdAt: "asc" },
|
|
5027
|
+
take: CANDIDATES_PER_SLOT,
|
|
5028
|
+
select: { ...VIEW_SELECT, token: true, timezone: true }
|
|
5029
|
+
});
|
|
5030
|
+
const expiresAt = new Date(Math.min(now.getTime() + (input.offerMinutes ?? DEFAULT_OFFER_MINUTES) * 6e4, input.startTime.getTime()));
|
|
5031
|
+
for (const candidate of candidates) {
|
|
5032
|
+
const type = await db.appointmentType.findFirst({
|
|
5033
|
+
where: { id: candidate.typeId, isActive: true, calendars: { some: { calendarId: input.calendarId } } },
|
|
5034
|
+
select: { name: true, duration: true }
|
|
5035
|
+
});
|
|
5036
|
+
if (!type || !await isSlotAvailable(db, input.calendarId, input.startTime, type.duration)) continue;
|
|
5037
|
+
let claimed;
|
|
5038
|
+
try {
|
|
5039
|
+
claimed = await db.waitlistEntry.updateMany({
|
|
5040
|
+
where: { id: candidate.id, status: "WAITING" },
|
|
5041
|
+
data: { status: "OFFERED", offerCalendarId: input.calendarId, offerSlotStart: input.startTime, offerExpiresAt: expiresAt, offeredAt: now }
|
|
5042
|
+
});
|
|
5043
|
+
} catch (error) {
|
|
5044
|
+
if (isUniqueViolation(error)) return null;
|
|
5045
|
+
throw error;
|
|
5046
|
+
}
|
|
5047
|
+
if (claimed.count === 0) continue;
|
|
5048
|
+
const { token, timezone, ...view2 } = candidate;
|
|
5049
|
+
return {
|
|
5050
|
+
entry: { ...view2, status: "OFFERED", offerSlotStart: input.startTime, offerExpiresAt: expiresAt },
|
|
5051
|
+
token,
|
|
5052
|
+
calendarId: input.calendarId,
|
|
5053
|
+
calendarName: calendar.name,
|
|
5054
|
+
typeName: type.name,
|
|
5055
|
+
startTime: input.startTime,
|
|
5056
|
+
timezone,
|
|
5057
|
+
expiresAt
|
|
5058
|
+
};
|
|
5059
|
+
}
|
|
5060
|
+
return null;
|
|
5061
|
+
}
|
|
5062
|
+
async function tryOfferFreedSlot(db, input) {
|
|
5063
|
+
try {
|
|
5064
|
+
return await offerFreedSlot(db, input);
|
|
5065
|
+
} catch (error) {
|
|
5066
|
+
const diagnostic = schedError("SCHED_1109", { organizationId: input.organizationId, calendarId: input.calendarId, error });
|
|
5067
|
+
console.error(`[waitlist] ${diagnostic.ref} could not offer a freed slot:`, error);
|
|
5068
|
+
return null;
|
|
5069
|
+
}
|
|
5070
|
+
}
|
|
5071
|
+
async function expireWaitlistOffers(db, options = {}) {
|
|
5072
|
+
const now = options.now ?? /* @__PURE__ */ new Date();
|
|
5073
|
+
const stuckBefore = new Date(now.getTime() - (options.acceptTimeoutMs ?? 5 * 6e4));
|
|
5074
|
+
const rows = await db.$queryRaw`
|
|
5075
|
+
UPDATE "WaitlistEntry" SET status = 'EXPIRED'
|
|
5076
|
+
WHERE status = 'OFFERED' AND "offerExpiresAt" <= ${now}
|
|
5077
|
+
RETURNING "organizationId", "offerCalendarId", "offerSlotStart"
|
|
5078
|
+
`;
|
|
5079
|
+
const lapsed = rows.map((r) => ({ organizationId: r.organizationId, calendarId: r.offerCalendarId, startTime: r.offerSlotStart }));
|
|
5080
|
+
const stuck = await db.waitlistEntry.findMany({
|
|
5081
|
+
where: { status: "ACCEPTING", acceptingAt: { lte: stuckBefore } },
|
|
5082
|
+
take: 100,
|
|
5083
|
+
select: { id: true, organizationId: true, offerCalendarId: true, offerSlotStart: true, clientEmail: true }
|
|
5084
|
+
});
|
|
5085
|
+
let released = 0;
|
|
5086
|
+
let booked = 0;
|
|
5087
|
+
for (const entry4 of stuck) {
|
|
5088
|
+
const appointment = await findBookingForOffer(db, entry4);
|
|
5089
|
+
if (appointment) {
|
|
5090
|
+
const done = await db.waitlistEntry.updateMany({
|
|
5091
|
+
where: { id: entry4.id, status: "ACCEPTING" },
|
|
5092
|
+
data: { status: "BOOKED", bookedAppointmentId: appointment.id, acceptingAt: null }
|
|
5093
|
+
});
|
|
5094
|
+
booked += done.count;
|
|
5095
|
+
continue;
|
|
5096
|
+
}
|
|
5097
|
+
const back = await db.waitlistEntry.updateMany({
|
|
5098
|
+
where: { id: entry4.id, status: "ACCEPTING" },
|
|
5099
|
+
data: { status: "WAITING", offerCalendarId: null, offerSlotStart: null, offerExpiresAt: null, offeredAt: null, acceptingAt: null }
|
|
5100
|
+
});
|
|
5101
|
+
if (back.count > 0) {
|
|
5102
|
+
released++;
|
|
5103
|
+
if (entry4.offerCalendarId && entry4.offerSlotStart) {
|
|
5104
|
+
lapsed.push({ organizationId: entry4.organizationId, calendarId: entry4.offerCalendarId, startTime: entry4.offerSlotStart });
|
|
5105
|
+
}
|
|
5106
|
+
}
|
|
5107
|
+
}
|
|
5108
|
+
return { lapsed, released, booked };
|
|
5109
|
+
}
|
|
5110
|
+
|
|
5111
|
+
// src/waitlist/manage.ts
|
|
5112
|
+
var OFFER_FIELDS = { organizationId: true, status: true, offerCalendarId: true, offerSlotStart: true };
|
|
5113
|
+
function freedSlot(row) {
|
|
5114
|
+
return row.status === "OFFERED" && row.offerCalendarId && row.offerSlotStart ? { organizationId: row.organizationId, calendarId: row.offerCalendarId, startTime: row.offerSlotStart } : null;
|
|
5115
|
+
}
|
|
5116
|
+
async function listWaitlist(db, input) {
|
|
5117
|
+
const where = { organizationId: input.organizationId, ...input.status ? { status: input.status } : {} };
|
|
5118
|
+
const [entries, total] = await Promise.all([
|
|
5119
|
+
db.waitlistEntry.findMany({
|
|
5120
|
+
where,
|
|
5121
|
+
orderBy: { createdAt: "asc" },
|
|
5122
|
+
take: Math.min(input.limit ?? 50, 200),
|
|
5123
|
+
skip: input.offset ?? 0,
|
|
5124
|
+
select: VIEW_SELECT
|
|
5125
|
+
}),
|
|
5126
|
+
db.waitlistEntry.count({ where })
|
|
5127
|
+
]);
|
|
5128
|
+
return { entries, total };
|
|
5129
|
+
}
|
|
5130
|
+
async function removeWaitlistEntry(db, organizationId, entryId) {
|
|
5131
|
+
const where = { id: entryId, organizationId, status: { in: ["WAITING", "OFFERED", "EXPIRED", "BOOKED"] } };
|
|
5132
|
+
const row = await db.waitlistEntry.findFirst({ where, select: OFFER_FIELDS });
|
|
5133
|
+
const removed = row ? await db.waitlistEntry.deleteMany({ where: { ...where, status: row.status } }) : { count: 0 };
|
|
5134
|
+
if (!row || removed.count === 0) throw new SchedulingNotFoundError("Waitlist entry not found", "SCHED_1106", { entryId });
|
|
5135
|
+
return freedSlot(row);
|
|
5136
|
+
}
|
|
5137
|
+
async function leaveWaitlist(db, token) {
|
|
5138
|
+
const where = { token, status: { in: ["WAITING", "OFFERED"] } };
|
|
5139
|
+
const row = await db.waitlistEntry.findFirst({ where, select: OFFER_FIELDS });
|
|
5140
|
+
const removed = row ? await db.waitlistEntry.deleteMany({ where: { ...where, status: row.status } }) : { count: 0 };
|
|
5141
|
+
if (!row || removed.count === 0) throw new SchedulingNotFoundError("No waitlist entry for this link", "SCHED_1106");
|
|
5142
|
+
return freedSlot(row);
|
|
5143
|
+
}
|
|
5144
|
+
|
|
5145
|
+
// src/routing/types.ts
|
|
5146
|
+
var LIMITS = {
|
|
5147
|
+
questions: 20,
|
|
5148
|
+
rules: 50,
|
|
5149
|
+
conditionsPerRule: 10,
|
|
5150
|
+
options: 50,
|
|
5151
|
+
label: 200,
|
|
5152
|
+
option: 100,
|
|
5153
|
+
message: 500,
|
|
5154
|
+
textAnswer: 1e3,
|
|
5155
|
+
problems: 50,
|
|
5156
|
+
formsPerOrganization: 50
|
|
5157
|
+
};
|
|
5158
|
+
|
|
5159
|
+
// src/routing/validate-structure.ts
|
|
5160
|
+
var ID = /^[A-Za-z][A-Za-z0-9_-]{0,39}$/;
|
|
5161
|
+
var QUESTION_TYPES = ["select", "radio", "checkbox", "text", "number"];
|
|
5162
|
+
var NO_VALUE = ["is_answered", "is_empty"];
|
|
5163
|
+
var OPERATORS_BY_TYPE = {
|
|
5164
|
+
select: ["equals", "not_equals", "in", "is_answered", "is_empty"],
|
|
5165
|
+
radio: ["equals", "not_equals", "in", "is_answered", "is_empty"],
|
|
5166
|
+
checkbox: ["contains", "not_contains", "is_answered", "is_empty"],
|
|
5167
|
+
text: ["equals", "not_equals", "contains", "not_contains", "is_answered", "is_empty"],
|
|
5168
|
+
number: ["equals", "not_equals", "gt", "gte", "lt", "lte", "is_answered", "is_empty"]
|
|
5169
|
+
};
|
|
5170
|
+
var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5171
|
+
var isText = (value, max) => typeof value === "string" && value.trim().length > 0 && value.length <= max && !value.includes("\0");
|
|
5172
|
+
function checkQuestions(input, problems) {
|
|
5173
|
+
if (!Array.isArray(input) || input.length === 0) {
|
|
5174
|
+
problems.push({ path: "questions", message: "Add at least one question" });
|
|
5175
|
+
return [];
|
|
5176
|
+
}
|
|
5177
|
+
if (input.length > LIMITS.questions) problems.push({ path: "questions", message: `At most ${LIMITS.questions} questions` });
|
|
5178
|
+
const seen = /* @__PURE__ */ new Set();
|
|
5179
|
+
const questions = [];
|
|
5180
|
+
input.slice(0, LIMITS.questions).forEach((raw, i) => {
|
|
5181
|
+
const at = `questions[${i}]`;
|
|
5182
|
+
if (!isObject(raw)) return void problems.push({ path: at, message: "A question must be an object" });
|
|
5183
|
+
const { id, label, type, required, options } = raw;
|
|
5184
|
+
if (typeof id !== "string" || !ID.test(id)) problems.push({ path: `${at}.id`, message: "The id must start with a letter and use only letters, numbers, - and _ (40 characters at most)" });
|
|
5185
|
+
else if (seen.has(id)) problems.push({ path: `${at}.id`, message: `Another question already uses the id "${id}"` });
|
|
5186
|
+
else seen.add(id);
|
|
5187
|
+
if (!isText(label, LIMITS.label)) problems.push({ path: `${at}.label`, message: `A label of 1 to ${LIMITS.label} characters is required` });
|
|
5188
|
+
if (!QUESTION_TYPES.includes(type)) problems.push({ path: `${at}.type`, message: `The type must be one of ${QUESTION_TYPES.join(", ")}` });
|
|
5189
|
+
if (required !== void 0 && typeof required !== "boolean") problems.push({ path: `${at}.required`, message: "required must be true or false" });
|
|
5190
|
+
const choice = type === "select" || type === "radio" || type === "checkbox";
|
|
5191
|
+
let cleanOptions;
|
|
5192
|
+
if (choice) {
|
|
5193
|
+
if (!Array.isArray(options) || options.length < 2 || options.length > LIMITS.options) {
|
|
5194
|
+
problems.push({ path: `${at}.options`, message: `A choice question needs 2 to ${LIMITS.options} options` });
|
|
5195
|
+
} else if (!options.every((o) => isText(o, LIMITS.option))) {
|
|
5196
|
+
problems.push({ path: `${at}.options`, message: `Each option must be 1 to ${LIMITS.option} characters` });
|
|
5197
|
+
} else if (new Set(options).size !== options.length) {
|
|
5198
|
+
problems.push({ path: `${at}.options`, message: "Options must all be different" });
|
|
5199
|
+
} else cleanOptions = options;
|
|
5200
|
+
} else if (options !== void 0) {
|
|
5201
|
+
problems.push({ path: `${at}.options`, message: "Only choice questions have options" });
|
|
5202
|
+
}
|
|
5203
|
+
if (typeof id === "string" && typeof label === "string" && QUESTION_TYPES.includes(type)) {
|
|
5204
|
+
questions.push({ id, label: label.trim(), type, required: required === true, ...cleanOptions ? { options: cleanOptions } : {} });
|
|
5205
|
+
}
|
|
5206
|
+
});
|
|
5207
|
+
return questions;
|
|
5208
|
+
}
|
|
5209
|
+
function checkValue(question, condition, at, problems) {
|
|
5210
|
+
const { operator, value } = condition;
|
|
5211
|
+
if (NO_VALUE.includes(operator)) {
|
|
5212
|
+
if (value !== void 0) problems.push({ path: `${at}.value`, message: `${String(operator)} takes no value` });
|
|
5213
|
+
return void 0;
|
|
5214
|
+
}
|
|
5215
|
+
if (value === void 0) {
|
|
5216
|
+
problems.push({ path: `${at}.value`, message: "A value is required" });
|
|
5217
|
+
return void 0;
|
|
5218
|
+
}
|
|
5219
|
+
if (question.type === "number") {
|
|
5220
|
+
if (typeof value !== "number" || !Number.isFinite(value)) problems.push({ path: `${at}.value`, message: "The value must be a number" });
|
|
5221
|
+
else return value;
|
|
5222
|
+
return void 0;
|
|
5223
|
+
}
|
|
5224
|
+
if (question.type === "text") {
|
|
5225
|
+
if (!isText(value, LIMITS.option * 2)) problems.push({ path: `${at}.value`, message: "The value must be a text of 1 to 200 characters" });
|
|
5226
|
+
else return value;
|
|
5227
|
+
return void 0;
|
|
5228
|
+
}
|
|
5229
|
+
const options = question.options ?? [];
|
|
5230
|
+
if (operator === "in") {
|
|
5231
|
+
if (!Array.isArray(value) || value.length === 0 || !value.every((v) => typeof v === "string" && options.includes(v))) {
|
|
5232
|
+
problems.push({ path: `${at}.value`, message: "The value must be a list of this question's options" });
|
|
5233
|
+
return void 0;
|
|
5234
|
+
}
|
|
5235
|
+
return value;
|
|
5236
|
+
}
|
|
5237
|
+
if (typeof value !== "string" || !options.includes(value)) {
|
|
5238
|
+
problems.push({ path: `${at}.value`, message: "The value must be one of this question's options" });
|
|
5239
|
+
return void 0;
|
|
5240
|
+
}
|
|
5241
|
+
return value;
|
|
5242
|
+
}
|
|
5243
|
+
function checkDestination(raw, at, problems) {
|
|
5244
|
+
if (!isObject(raw)) {
|
|
5245
|
+
problems.push({ path: at, message: "Say where to send the client" });
|
|
5246
|
+
return null;
|
|
5247
|
+
}
|
|
5248
|
+
const { typeId, calendarId } = raw;
|
|
5249
|
+
const okType = typeId === void 0 || typeof typeId === "string" && typeId.length > 0 && typeId.length <= 100;
|
|
5250
|
+
const okCalendar = calendarId === void 0 || typeof calendarId === "string" && calendarId.length > 0 && calendarId.length <= 100;
|
|
5251
|
+
if (!okType || !okCalendar) {
|
|
5252
|
+
problems.push({ path: at, message: "typeId and calendarId must be ids" });
|
|
5253
|
+
return null;
|
|
5254
|
+
}
|
|
5255
|
+
if (typeId === void 0 && calendarId === void 0) {
|
|
5256
|
+
problems.push({ path: at, message: "Name an appointment type, a calendar, or both" });
|
|
5257
|
+
return null;
|
|
5258
|
+
}
|
|
5259
|
+
return { ...typeId !== void 0 ? { typeId } : {}, ...calendarId !== void 0 ? { calendarId } : {} };
|
|
5260
|
+
}
|
|
5261
|
+
function checkRules(input, questions, problems) {
|
|
5262
|
+
if (!Array.isArray(input) || input.length === 0) {
|
|
5263
|
+
problems.push({ path: "rules", message: "Add at least one rule" });
|
|
5264
|
+
return [];
|
|
5265
|
+
}
|
|
5266
|
+
if (input.length > LIMITS.rules) problems.push({ path: "rules", message: `At most ${LIMITS.rules} rules` });
|
|
5267
|
+
const byId = new Map(questions.map((q) => [q.id, q]));
|
|
5268
|
+
const written = new Set(input.flatMap((r) => isObject(r) && typeof r.id === "string" ? [r.id] : []));
|
|
5269
|
+
const seen = /* @__PURE__ */ new Set();
|
|
5270
|
+
const rules = [];
|
|
5271
|
+
input.slice(0, LIMITS.rules).forEach((raw, i) => {
|
|
5272
|
+
const at = `rules[${i}]`;
|
|
5273
|
+
if (!isObject(raw)) return void problems.push({ path: at, message: "A rule must be an object" });
|
|
5274
|
+
let id = typeof raw.id === "string" && ID.test(raw.id) ? raw.id : null;
|
|
5275
|
+
if (raw.id !== void 0 && id === null) problems.push({ path: `${at}.id`, message: "The id must start with a letter and use only letters, numbers, - and _" });
|
|
5276
|
+
if (id === null) {
|
|
5277
|
+
id = `rule_${i + 1}`;
|
|
5278
|
+
while (written.has(id)) id = `${id}_auto`;
|
|
5279
|
+
}
|
|
5280
|
+
if (seen.has(id)) problems.push({ path: `${at}.id`, message: `Another rule already uses the id "${id}"` });
|
|
5281
|
+
seen.add(id);
|
|
5282
|
+
if (raw.label !== void 0 && !isText(raw.label, LIMITS.label)) problems.push({ path: `${at}.label`, message: `A label must be 1 to ${LIMITS.label} characters` });
|
|
5283
|
+
const match = raw.match === void 0 ? "all" : raw.match;
|
|
5284
|
+
if (match !== "all" && match !== "any") problems.push({ path: `${at}.match`, message: 'match must be "all" or "any"' });
|
|
5285
|
+
const conditions = [];
|
|
5286
|
+
if (!Array.isArray(raw.conditions) || raw.conditions.length === 0 || raw.conditions.length > LIMITS.conditionsPerRule) {
|
|
5287
|
+
problems.push({ path: `${at}.conditions`, message: `A rule needs 1 to ${LIMITS.conditionsPerRule} conditions` });
|
|
5288
|
+
} else {
|
|
5289
|
+
raw.conditions.forEach((c, j) => {
|
|
5290
|
+
const cat = `${at}.conditions[${j}]`;
|
|
5291
|
+
if (!isObject(c)) return void problems.push({ path: cat, message: "A condition must be an object" });
|
|
5292
|
+
const question = typeof c.questionId === "string" ? byId.get(c.questionId) : void 0;
|
|
5293
|
+
if (!question) return void problems.push({ path: `${cat}.questionId`, message: "This names a question the form does not have" });
|
|
5294
|
+
if (!OPERATORS_BY_TYPE[question.type].includes(c.operator)) {
|
|
5295
|
+
return void problems.push({ path: `${cat}.operator`, message: `A ${question.type} question allows: ${OPERATORS_BY_TYPE[question.type].join(", ")}` });
|
|
5296
|
+
}
|
|
5297
|
+
const value = checkValue(question, c, cat, problems);
|
|
5298
|
+
conditions.push({ questionId: question.id, operator: c.operator, ...value !== void 0 ? { value } : {} });
|
|
5299
|
+
});
|
|
5300
|
+
}
|
|
5301
|
+
const destination = checkDestination(raw.destination, `${at}.destination`, problems);
|
|
5302
|
+
if (destination && (match === "all" || match === "any")) {
|
|
5303
|
+
rules.push({ id, ...typeof raw.label === "string" ? { label: raw.label.trim() } : {}, match, conditions, destination });
|
|
5304
|
+
}
|
|
5305
|
+
});
|
|
5306
|
+
return rules;
|
|
5307
|
+
}
|
|
5308
|
+
function checkFallback(raw, problems) {
|
|
5309
|
+
if (!isObject(raw)) {
|
|
5310
|
+
problems.push({ path: "fallback", message: "Say what happens when no rule matches" });
|
|
5311
|
+
return null;
|
|
5312
|
+
}
|
|
5313
|
+
if (raw.kind === "MESSAGE") {
|
|
5314
|
+
if (!isText(raw.message, LIMITS.message)) {
|
|
5315
|
+
problems.push({ path: "fallback.message", message: `A message of 1 to ${LIMITS.message} characters is required` });
|
|
5316
|
+
return null;
|
|
5317
|
+
}
|
|
5318
|
+
return { kind: "MESSAGE", message: raw.message.trim() };
|
|
5319
|
+
}
|
|
5320
|
+
if (raw.kind === "DESTINATION") {
|
|
5321
|
+
const destination = checkDestination(raw.destination, "fallback.destination", problems);
|
|
5322
|
+
return destination ? { kind: "DESTINATION", destination } : null;
|
|
5323
|
+
}
|
|
5324
|
+
problems.push({ path: "fallback.kind", message: 'kind must be "DESTINATION" or "MESSAGE"' });
|
|
5325
|
+
return null;
|
|
5326
|
+
}
|
|
5327
|
+
function validateRoutingStructure(input) {
|
|
5328
|
+
const problems = [];
|
|
5329
|
+
if (!isObject(input)) return { ok: false, problems: [{ path: "", message: "A routing form must be an object" }] };
|
|
5330
|
+
const questions = checkQuestions(input.questions, problems);
|
|
5331
|
+
const rules = checkRules(input.rules, questions, problems);
|
|
5332
|
+
const fallback = checkFallback(input.fallback, problems);
|
|
5333
|
+
if (problems.length > 0 || !fallback) return { ok: false, problems: problems.slice(0, LIMITS.problems) };
|
|
5334
|
+
return { ok: true, value: { questions, rules, fallback } };
|
|
5335
|
+
}
|
|
5336
|
+
|
|
5337
|
+
// src/routing/validate-destinations.ts
|
|
5338
|
+
function placesOf(definition) {
|
|
5339
|
+
const places = definition.rules.map((rule, i) => ({ path: `rules[${i}].destination`, destination: rule.destination }));
|
|
5340
|
+
if (definition.fallback.kind === "DESTINATION") places.push({ path: "fallback.destination", destination: definition.fallback.destination });
|
|
5341
|
+
return places;
|
|
5342
|
+
}
|
|
5343
|
+
async function validateRoutingDestinations(db, organizationId, definition) {
|
|
5344
|
+
const places = placesOf(definition);
|
|
5345
|
+
const typeIds = [...new Set(places.flatMap((p) => p.destination.typeId ? [p.destination.typeId] : []))];
|
|
5346
|
+
const calendarIds = [...new Set(places.flatMap((p) => p.destination.calendarId ? [p.destination.calendarId] : []))];
|
|
5347
|
+
const scope = [{ organizationId }, { organizationId: null }];
|
|
5348
|
+
const [types, calendars] = await Promise.all([
|
|
5349
|
+
typeIds.length ? db.appointmentType.findMany({ where: { id: { in: typeIds }, isActive: true, OR: scope }, select: { id: true } }) : [],
|
|
5350
|
+
calendarIds.length ? db.schedulingCalendar.findMany({ where: { id: { in: calendarIds }, isActive: true, OR: scope }, select: { id: true } }) : []
|
|
5351
|
+
]);
|
|
5352
|
+
const liveTypes = new Set(types.map((t) => t.id));
|
|
5353
|
+
const liveCalendars = new Set(calendars.map((c) => c.id));
|
|
5354
|
+
const problems = [];
|
|
5355
|
+
const pairs = [];
|
|
5356
|
+
for (const { path, destination } of places) {
|
|
5357
|
+
const typeOk = !destination.typeId || liveTypes.has(destination.typeId);
|
|
5358
|
+
const calendarOk = !destination.calendarId || liveCalendars.has(destination.calendarId);
|
|
5359
|
+
if (!typeOk) problems.push({ path: `${path}.typeId`, message: "This appointment type does not exist here or is switched off" });
|
|
5360
|
+
if (!calendarOk) problems.push({ path: `${path}.calendarId`, message: "This calendar does not exist here or is switched off" });
|
|
5361
|
+
if (typeOk && calendarOk && destination.typeId && destination.calendarId) pairs.push({ path, destination });
|
|
5362
|
+
}
|
|
5363
|
+
if (pairs.length > 0) {
|
|
5364
|
+
const links = await db.appointmentTypeCalendar.findMany({
|
|
5365
|
+
where: { OR: pairs.map((p) => ({ appointmentTypeId: p.destination.typeId, calendarId: p.destination.calendarId })) },
|
|
5366
|
+
select: { appointmentTypeId: true, calendarId: true }
|
|
5367
|
+
});
|
|
5368
|
+
const linked = new Set(links.map((l) => `${l.appointmentTypeId}:${l.calendarId}`));
|
|
5369
|
+
for (const { path, destination } of pairs) {
|
|
5370
|
+
if (!linked.has(`${destination.typeId}:${destination.calendarId}`)) {
|
|
5371
|
+
problems.push({ path, message: "This appointment type is not offered on this calendar" });
|
|
5372
|
+
}
|
|
5373
|
+
}
|
|
5374
|
+
}
|
|
5375
|
+
return problems;
|
|
5376
|
+
}
|
|
5377
|
+
|
|
5378
|
+
// src/routing/evaluate.ts
|
|
5379
|
+
var blank = (value) => value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0;
|
|
5380
|
+
function checkAnswers(questions, input) {
|
|
5381
|
+
const problems = [];
|
|
5382
|
+
const raw = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {};
|
|
5383
|
+
if (input !== void 0 && raw !== input) problems.push({ path: "answers", message: "Answers must be an object keyed by question id" });
|
|
5384
|
+
const known = new Set(questions.map((q) => q.id));
|
|
5385
|
+
for (const key of Object.keys(raw)) if (!known.has(key)) problems.push({ path: `answers.${key}`, message: "The form does not ask this question" });
|
|
5386
|
+
const answers = /* @__PURE__ */ Object.create(null);
|
|
5387
|
+
for (const q of questions) {
|
|
5388
|
+
const at = `answers.${q.id}`;
|
|
5389
|
+
const value = Object.prototype.hasOwnProperty.call(raw, q.id) ? raw[q.id] : void 0;
|
|
5390
|
+
if (blank(value)) {
|
|
5391
|
+
if (q.required) problems.push({ path: at, message: "This question needs an answer" });
|
|
5392
|
+
continue;
|
|
5393
|
+
}
|
|
5394
|
+
if (q.type === "select" || q.type === "radio") {
|
|
5395
|
+
if (typeof value !== "string" || !q.options?.includes(value)) problems.push({ path: at, message: "Pick one of the offered options" });
|
|
5396
|
+
else answers[q.id] = value;
|
|
5397
|
+
} else if (q.type === "checkbox") {
|
|
5398
|
+
if (!Array.isArray(value) || !value.every((v) => typeof v === "string" && q.options?.includes(v)) || new Set(value).size !== value.length) {
|
|
5399
|
+
problems.push({ path: at, message: "Send a list of offered options, each once" });
|
|
5400
|
+
} else answers[q.id] = value;
|
|
5401
|
+
} else if (q.type === "number") {
|
|
5402
|
+
if (typeof value !== "number" || !Number.isFinite(value)) problems.push({ path: at, message: "The answer must be a number" });
|
|
5403
|
+
else answers[q.id] = value;
|
|
5404
|
+
} else if (typeof value !== "string" || value.length > LIMITS.textAnswer) {
|
|
5405
|
+
problems.push({ path: at, message: `The answer must be a text of at most ${LIMITS.textAnswer} characters` });
|
|
5406
|
+
} else answers[q.id] = value;
|
|
5407
|
+
}
|
|
5408
|
+
return problems.length > 0 ? { ok: false, problems: problems.slice(0, LIMITS.problems) } : { ok: true, answers };
|
|
5409
|
+
}
|
|
5410
|
+
function holds(condition, answers) {
|
|
5411
|
+
const answer = answers[condition.questionId];
|
|
5412
|
+
const { operator, value } = condition;
|
|
5413
|
+
if (operator === "is_empty") return blank(answer);
|
|
5414
|
+
if (operator === "is_answered") return !blank(answer);
|
|
5415
|
+
if (blank(answer)) return false;
|
|
5416
|
+
if (typeof answer === "number") {
|
|
5417
|
+
if (typeof value !== "number") return false;
|
|
5418
|
+
return { equals: answer === value, not_equals: answer !== value, gt: answer > value, gte: answer >= value, lt: answer < value, lte: answer <= value }[operator] ?? false;
|
|
5419
|
+
}
|
|
5420
|
+
if (Array.isArray(answer)) {
|
|
5421
|
+
if (typeof value !== "string") return false;
|
|
5422
|
+
return operator === "contains" ? answer.includes(value) : operator === "not_contains" ? !answer.includes(value) : false;
|
|
5423
|
+
}
|
|
5424
|
+
if (operator === "in") return Array.isArray(value) && value.includes(answer);
|
|
5425
|
+
if (typeof value !== "string") return false;
|
|
5426
|
+
const a = answer;
|
|
5427
|
+
switch (operator) {
|
|
5428
|
+
case "equals":
|
|
5429
|
+
return a === value;
|
|
5430
|
+
case "not_equals":
|
|
5431
|
+
return a !== value;
|
|
5432
|
+
case "contains":
|
|
5433
|
+
return a.toLowerCase().includes(value.toLowerCase());
|
|
5434
|
+
case "not_contains":
|
|
5435
|
+
return !a.toLowerCase().includes(value.toLowerCase());
|
|
5436
|
+
default:
|
|
5437
|
+
return false;
|
|
5438
|
+
}
|
|
5439
|
+
}
|
|
5440
|
+
function matchingRules(definition, answers) {
|
|
5441
|
+
return definition.rules.filter(
|
|
5442
|
+
(rule) => rule.match === "any" ? rule.conditions.some((c) => holds(c, answers)) : rule.conditions.every((c) => holds(c, answers))
|
|
5443
|
+
);
|
|
5444
|
+
}
|
|
5445
|
+
|
|
5446
|
+
// src/routing/crud.ts
|
|
5447
|
+
var SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
5448
|
+
var FULL = { id: true, name: true, slug: true, description: true, isActive: true, questions: true, rules: true, fallback: true, createdAt: true, updatedAt: true };
|
|
5449
|
+
function invalid(problems) {
|
|
5450
|
+
return new SchedulingValidationError("The routing form has problems", "SCHED_1200", { errors: problems });
|
|
5451
|
+
}
|
|
5452
|
+
function view(row) {
|
|
5453
|
+
return { ...row, questions: row.questions, rules: row.rules, fallback: row.fallback };
|
|
5454
|
+
}
|
|
5455
|
+
async function check(db, organizationId, input, options) {
|
|
5456
|
+
const problems = [];
|
|
5457
|
+
const name = typeof input.name === "string" ? input.name.trim() : "";
|
|
5458
|
+
if (name.length < 1 || name.length > 100 || name.includes("\0")) problems.push({ path: "name", message: "A name of 1 to 100 characters is required" });
|
|
5459
|
+
if (typeof input.slug !== "string" || !SLUG.test(input.slug) || input.slug.length > 60) {
|
|
5460
|
+
problems.push({ path: "slug", message: "The slug must be lower-case words joined by dashes, 60 characters at most" });
|
|
5461
|
+
} else {
|
|
5462
|
+
const taken = await db.routingForm.count({ where: { slug: input.slug, organizationId: { not: organizationId } } });
|
|
5463
|
+
if (taken > 0) problems.push({ path: "slug", message: "That slug is already in use; choose another" });
|
|
5464
|
+
}
|
|
5465
|
+
const description = typeof input.description === "string" ? input.description.trim() || null : null;
|
|
5466
|
+
if (description && (description.length > 500 || description.includes("\0"))) problems.push({ path: "description", message: "The description is at most 500 characters" });
|
|
5467
|
+
const structure = validateRoutingStructure({ questions: input.questions, rules: input.rules, fallback: input.fallback });
|
|
5468
|
+
if (!structure.ok) problems.push(...structure.problems);
|
|
5469
|
+
else if (options.checkDestinations) problems.push(...await validateRoutingDestinations(db, organizationId, structure.value));
|
|
5470
|
+
if (problems.length > 0 || !structure.ok) throw invalid(problems.slice(0, LIMITS.problems));
|
|
5471
|
+
return { definition: structure.value, name, slug: input.slug, description };
|
|
5472
|
+
}
|
|
5473
|
+
async function createRoutingForm(db, organizationId, input) {
|
|
5474
|
+
const { definition, name, slug, description } = await check(db, organizationId, input, { checkDestinations: true });
|
|
5475
|
+
const existing = await db.routingForm.count({ where: { organizationId } });
|
|
5476
|
+
if (existing >= LIMITS.formsPerOrganization) {
|
|
5477
|
+
throw new SchedulingValidationError(`An organization can have at most ${LIMITS.formsPerOrganization} routing forms`, "SCHED_1204", { organizationId });
|
|
5478
|
+
}
|
|
5479
|
+
try {
|
|
5480
|
+
const row = await db.routingForm.create({
|
|
5481
|
+
data: {
|
|
5482
|
+
organizationId,
|
|
5483
|
+
name,
|
|
5484
|
+
slug,
|
|
5485
|
+
description,
|
|
5486
|
+
isActive: input.isActive ?? true,
|
|
5487
|
+
questions: definition.questions,
|
|
5488
|
+
rules: definition.rules,
|
|
5489
|
+
fallback: definition.fallback
|
|
5490
|
+
},
|
|
5491
|
+
select: FULL
|
|
5492
|
+
});
|
|
5493
|
+
return view(row);
|
|
5494
|
+
} catch (error) {
|
|
5495
|
+
if (error.code === "P2002") throw new SchedulingValidationError("That slug is already used by another form", "SCHED_1202", { slug });
|
|
5496
|
+
throw error;
|
|
5497
|
+
}
|
|
5498
|
+
}
|
|
5499
|
+
async function getRoutingForm(db, organizationId, id) {
|
|
5500
|
+
const row = await db.routingForm.findFirst({ where: { id, organizationId }, select: FULL });
|
|
5501
|
+
if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
|
|
5502
|
+
return view(row);
|
|
5503
|
+
}
|
|
5504
|
+
async function listRoutingForms(db, organizationId) {
|
|
5505
|
+
return db.routingForm.findMany({
|
|
5506
|
+
where: { organizationId },
|
|
5507
|
+
orderBy: { name: "asc" },
|
|
5508
|
+
select: { id: true, name: true, slug: true, description: true, isActive: true, updatedAt: true }
|
|
5509
|
+
});
|
|
5510
|
+
}
|
|
5511
|
+
async function updateRoutingForm(db, organizationId, id, patch) {
|
|
5512
|
+
const current = await getRoutingForm(db, organizationId, id);
|
|
5513
|
+
const merged = {
|
|
5514
|
+
name: patch.name ?? current.name,
|
|
5515
|
+
slug: patch.slug ?? current.slug,
|
|
5516
|
+
description: patch.description === void 0 ? current.description : patch.description,
|
|
5517
|
+
isActive: patch.isActive ?? current.isActive,
|
|
5518
|
+
questions: patch.questions ?? current.questions,
|
|
5519
|
+
rules: patch.rules ?? current.rules,
|
|
5520
|
+
fallback: patch.fallback ?? current.fallback
|
|
5521
|
+
};
|
|
5522
|
+
const changesRouting = patch.questions !== void 0 || patch.rules !== void 0 || patch.fallback !== void 0;
|
|
5523
|
+
const { definition, name, slug, description } = await check(db, organizationId, merged, { checkDestinations: changesRouting });
|
|
5524
|
+
try {
|
|
5525
|
+
const updated = await db.routingForm.updateMany({
|
|
5526
|
+
where: { id, organizationId },
|
|
5527
|
+
data: {
|
|
5528
|
+
name,
|
|
5529
|
+
slug,
|
|
5530
|
+
description,
|
|
5531
|
+
isActive: merged.isActive,
|
|
5532
|
+
questions: definition.questions,
|
|
5533
|
+
rules: definition.rules,
|
|
5534
|
+
fallback: definition.fallback
|
|
5535
|
+
}
|
|
5536
|
+
});
|
|
5537
|
+
if (updated.count === 0) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
|
|
5538
|
+
} catch (error) {
|
|
5539
|
+
if (error.code === "P2002") throw new SchedulingValidationError("That slug is already used by another form", "SCHED_1202", { slug });
|
|
5540
|
+
throw error;
|
|
5541
|
+
}
|
|
5542
|
+
return getRoutingForm(db, organizationId, id);
|
|
5543
|
+
}
|
|
5544
|
+
async function deleteRoutingForm(db, organizationId, id) {
|
|
5545
|
+
const removed = await db.routingForm.deleteMany({ where: { id, organizationId } });
|
|
5546
|
+
if (removed.count === 0) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id });
|
|
5547
|
+
}
|
|
5548
|
+
|
|
5549
|
+
// src/routing/route.ts
|
|
5550
|
+
var UNAVAILABLE = "Online booking is not available for this choice right now. Please contact us to book.";
|
|
5551
|
+
async function findForm(db, organizationId, slug) {
|
|
5552
|
+
const select = { organizationId: true, name: true, slug: true, description: true, questions: true, rules: true, fallback: true };
|
|
5553
|
+
if (organizationId) return db.routingForm.findFirst({ where: { organizationId, slug, isActive: true }, select });
|
|
5554
|
+
const found = await db.routingForm.findMany({ where: { slug, isActive: true }, take: 2, select });
|
|
5555
|
+
return found.length === 1 ? found[0] : null;
|
|
5556
|
+
}
|
|
5557
|
+
async function load(db, organizationId, slug) {
|
|
5558
|
+
const row = await findForm(db, organizationId, slug);
|
|
5559
|
+
if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { slug });
|
|
5560
|
+
return row;
|
|
5561
|
+
}
|
|
5562
|
+
async function getPublicRoutingForm(db, input) {
|
|
5563
|
+
const row = await load(db, input.organizationId, input.slug);
|
|
5564
|
+
return { name: row.name, slug: row.slug, description: row.description, questions: row.questions };
|
|
5565
|
+
}
|
|
5566
|
+
async function resolveDestination(db, organizationId, destination) {
|
|
5567
|
+
const scope = [{ organizationId }, { organizationId: null }];
|
|
5568
|
+
const [type, calendar] = await Promise.all([
|
|
5569
|
+
destination.typeId ? db.appointmentType.findFirst({ where: { id: destination.typeId, isActive: true, OR: scope }, select: { id: true, slug: true, name: true } }) : null,
|
|
5570
|
+
destination.calendarId ? db.schedulingCalendar.findFirst({ where: { id: destination.calendarId, isActive: true, OR: scope }, select: { id: true, slug: true, name: true } }) : null
|
|
5571
|
+
]);
|
|
5572
|
+
if (destination.typeId && !type || destination.calendarId && !calendar) return null;
|
|
5573
|
+
if (type && calendar) {
|
|
5574
|
+
const link = await db.appointmentTypeCalendar.findUnique({
|
|
5575
|
+
where: { appointmentTypeId_calendarId: { appointmentTypeId: type.id, calendarId: calendar.id } },
|
|
5576
|
+
select: { calendarId: true }
|
|
5577
|
+
});
|
|
5578
|
+
if (!link) return null;
|
|
5579
|
+
}
|
|
5580
|
+
return {
|
|
5581
|
+
typeId: type?.id ?? null,
|
|
5582
|
+
typeSlug: type?.slug ?? null,
|
|
5583
|
+
typeName: type?.name ?? null,
|
|
5584
|
+
calendarId: calendar?.id ?? null,
|
|
5585
|
+
calendarSlug: calendar?.slug ?? null,
|
|
5586
|
+
calendarName: calendar?.name ?? null
|
|
5587
|
+
};
|
|
5588
|
+
}
|
|
5589
|
+
async function decide(db, organizationId, definition, answers) {
|
|
5590
|
+
const checked = checkAnswers(definition.questions, answers);
|
|
5591
|
+
if (!checked.ok) throw new SchedulingValidationError("The answers do not fit the form", "SCHED_1203", { errors: checked.problems });
|
|
5592
|
+
for (const rule of matchingRules(definition, checked.answers)) {
|
|
5593
|
+
const destination = await resolveDestination(db, organizationId, rule.destination);
|
|
5594
|
+
if (destination) return { destination, message: null, matchedRuleId: rule.id, usedFallback: false };
|
|
5595
|
+
}
|
|
5596
|
+
if (definition.fallback.kind === "DESTINATION") {
|
|
5597
|
+
const destination = await resolveDestination(db, organizationId, definition.fallback.destination);
|
|
5598
|
+
return { destination, message: destination ? null : UNAVAILABLE, matchedRuleId: null, usedFallback: true };
|
|
5599
|
+
}
|
|
5600
|
+
return { destination: null, message: definition.fallback.message, matchedRuleId: null, usedFallback: true };
|
|
5601
|
+
}
|
|
5602
|
+
async function routeClient(db, input) {
|
|
5603
|
+
const row = await load(db, input.organizationId, input.slug);
|
|
5604
|
+
return decide(db, row.organizationId, row, input.answers);
|
|
5605
|
+
}
|
|
5606
|
+
async function testRoutingForm(db, input) {
|
|
5607
|
+
const row = await db.routingForm.findFirst({
|
|
5608
|
+
where: { id: input.id, organizationId: input.organizationId },
|
|
5609
|
+
select: { questions: true, rules: true, fallback: true }
|
|
5610
|
+
});
|
|
5611
|
+
if (!row) throw new SchedulingNotFoundError("Routing form not found", "SCHED_1201", { id: input.id });
|
|
5612
|
+
const definition = row;
|
|
5613
|
+
const outcome = await decide(db, input.organizationId, definition, input.answers);
|
|
5614
|
+
const checked = checkAnswers(definition.questions, input.answers);
|
|
5615
|
+
const allMatchedRuleIds = checked.ok ? matchingRules(definition, checked.answers).map((r) => r.id) : [];
|
|
5616
|
+
return { ...outcome, allMatchedRuleIds };
|
|
5617
|
+
}
|
|
5618
|
+
|
|
5619
|
+
// src/privacy/subject.ts
|
|
5620
|
+
import { createHash } from "crypto";
|
|
5621
|
+
var EMAIL2 = /^[^\s@]+@[^\s@]+$/;
|
|
5622
|
+
function invalid2(reason) {
|
|
5623
|
+
return new SchedulingValidationError(`Say whose data this is: ${reason}`, "SCHED_1300", { reason });
|
|
5624
|
+
}
|
|
5625
|
+
function parseSubject(input) {
|
|
5626
|
+
let email2 = null;
|
|
5627
|
+
let clientId = null;
|
|
5628
|
+
if (input.email !== void 0 && input.email !== null) {
|
|
5629
|
+
if (typeof input.email !== "string") throw invalid2("the email must be text");
|
|
5630
|
+
const trimmed = input.email.trim().toLowerCase();
|
|
5631
|
+
if (trimmed.length > 254 || !EMAIL2.test(trimmed)) throw invalid2("the email is not a single valid address");
|
|
5632
|
+
email2 = trimmed;
|
|
5633
|
+
}
|
|
5634
|
+
if (input.clientId !== void 0 && input.clientId !== null) {
|
|
5635
|
+
if (typeof input.clientId !== "string") throw invalid2("the client id must be text");
|
|
5636
|
+
const trimmed = input.clientId.trim();
|
|
5637
|
+
if (trimmed.length < 1 || trimmed.length > 200) throw invalid2("the client id must be 1 to 200 characters");
|
|
5638
|
+
clientId = trimmed;
|
|
5639
|
+
}
|
|
5640
|
+
if (!email2 && !clientId) throw invalid2("send an email address, a client id, or both");
|
|
5641
|
+
return { email: email2, clientId };
|
|
5642
|
+
}
|
|
5643
|
+
function subjectHashes(organizationId, subject) {
|
|
5644
|
+
const identifiers = [...subject.emails, ...subject.clientId ? [`client:${subject.clientId}`] : []];
|
|
5645
|
+
return identifiers.map((identifier) => createHash("sha256").update(`${organizationId}
|
|
5646
|
+
${identifier}`).digest("hex"));
|
|
5647
|
+
}
|
|
5648
|
+
async function resolveSubject(db, organizationId, parsed) {
|
|
5649
|
+
const emails = new Set(parsed.email ? [parsed.email] : []);
|
|
5650
|
+
if (parsed.clientId) {
|
|
5651
|
+
const [bookings, series] = await Promise.all([
|
|
5652
|
+
db.appointment.findMany({ where: { clientId: parsed.clientId, calendar: { organizationId } }, select: { clientEmail: true } }),
|
|
5653
|
+
db.recurringSeries.findMany({ where: { clientId: parsed.clientId, organizationId }, select: { clientEmail: true } })
|
|
5654
|
+
]);
|
|
5655
|
+
for (const row of [...bookings, ...series]) emails.add(row.clientEmail.trim().toLowerCase());
|
|
5656
|
+
}
|
|
5657
|
+
return { emails: [...emails], clientId: parsed.clientId };
|
|
5658
|
+
}
|
|
5659
|
+
|
|
5660
|
+
// src/privacy/audit.ts
|
|
5661
|
+
async function recordPrivacyRequest(db, input) {
|
|
5662
|
+
await db.dataSubjectRequest.create({
|
|
5663
|
+
data: {
|
|
5664
|
+
organizationId: input.organizationId,
|
|
5665
|
+
kind: input.kind,
|
|
5666
|
+
subjectHashes: subjectHashes(input.organizationId, input.subject),
|
|
5667
|
+
requestedBy: input.requestedBy,
|
|
5668
|
+
counts: { ...input.counts },
|
|
5669
|
+
createdAt: input.now
|
|
5670
|
+
}
|
|
5671
|
+
});
|
|
5672
|
+
}
|
|
5673
|
+
async function listPrivacyRequests(db, input) {
|
|
5674
|
+
const where = { organizationId: input.organizationId };
|
|
5675
|
+
const [requests, total] = await Promise.all([
|
|
5676
|
+
db.dataSubjectRequest.findMany({
|
|
5677
|
+
where,
|
|
5678
|
+
orderBy: { createdAt: "desc" },
|
|
5679
|
+
take: Math.min(input.limit ?? 50, 200),
|
|
5680
|
+
skip: input.offset ?? 0,
|
|
5681
|
+
select: { id: true, kind: true, requestedBy: true, counts: true, createdAt: true }
|
|
5682
|
+
}),
|
|
5683
|
+
db.dataSubjectRequest.count({ where })
|
|
5684
|
+
]);
|
|
5685
|
+
return { requests, total };
|
|
5686
|
+
}
|
|
5687
|
+
|
|
5688
|
+
// src/privacy/collect.ts
|
|
5689
|
+
var APPOINTMENT = {
|
|
5690
|
+
id: true,
|
|
5691
|
+
startTime: true,
|
|
5692
|
+
endTime: true,
|
|
5693
|
+
duration: true,
|
|
5694
|
+
timezone: true,
|
|
5695
|
+
status: true,
|
|
5696
|
+
isGroup: true,
|
|
5697
|
+
clientName: true,
|
|
5698
|
+
clientEmail: true,
|
|
5699
|
+
clientPhone: true,
|
|
5700
|
+
clientId: true,
|
|
5701
|
+
cancelledAt: true,
|
|
5702
|
+
cancelledBy: true,
|
|
5703
|
+
cancelReason: true,
|
|
5704
|
+
rescheduledFrom: true,
|
|
5705
|
+
rescheduleCount: true,
|
|
5706
|
+
intakeResponses: true,
|
|
5707
|
+
notes: true,
|
|
5708
|
+
staffNotes: true,
|
|
5709
|
+
location: true,
|
|
5710
|
+
meetingUrl: true,
|
|
5711
|
+
paymentStatus: true,
|
|
5712
|
+
paymentAmount: true,
|
|
5713
|
+
depositAmount: true,
|
|
5714
|
+
tipAmount: true,
|
|
5715
|
+
paymentProvider: true,
|
|
5716
|
+
paymentId: true,
|
|
5717
|
+
balancePaymentId: true,
|
|
5718
|
+
couponCode: true,
|
|
5719
|
+
discountAmount: true,
|
|
5720
|
+
cancellationFeeAmount: true,
|
|
5721
|
+
refundAmount: true,
|
|
5722
|
+
refundStatus: true,
|
|
5723
|
+
recurringId: true,
|
|
5724
|
+
recurringIndex: true,
|
|
5725
|
+
packagePurchaseId: true,
|
|
5726
|
+
createdAt: true,
|
|
5727
|
+
updatedAt: true,
|
|
5728
|
+
calendar: { select: { name: true } },
|
|
5729
|
+
type: { select: { name: true } }
|
|
5730
|
+
};
|
|
5731
|
+
var NOTIFICATION = {
|
|
5732
|
+
id: true,
|
|
5733
|
+
appointmentId: true,
|
|
5734
|
+
channel: true,
|
|
5735
|
+
trigger: true,
|
|
5736
|
+
recipient: true,
|
|
5737
|
+
subject: true,
|
|
5738
|
+
body: true,
|
|
5739
|
+
status: true,
|
|
5740
|
+
scheduledFor: true,
|
|
5741
|
+
sentAt: true,
|
|
5742
|
+
createdAt: true
|
|
5743
|
+
};
|
|
5744
|
+
var WAITLIST = {
|
|
5745
|
+
id: true,
|
|
5746
|
+
typeId: true,
|
|
5747
|
+
calendarId: true,
|
|
5748
|
+
day: true,
|
|
5749
|
+
slotStart: true,
|
|
5750
|
+
timezone: true,
|
|
5751
|
+
clientName: true,
|
|
5752
|
+
clientEmail: true,
|
|
5753
|
+
clientPhone: true,
|
|
5754
|
+
status: true,
|
|
5755
|
+
offerSlotStart: true,
|
|
5756
|
+
offerExpiresAt: true,
|
|
5757
|
+
offeredAt: true,
|
|
5758
|
+
bookedAppointmentId: true,
|
|
5759
|
+
createdAt: true
|
|
5760
|
+
};
|
|
5761
|
+
var PURCHASE = {
|
|
5762
|
+
id: true,
|
|
5763
|
+
packageId: true,
|
|
5764
|
+
clientEmail: true,
|
|
5765
|
+
clientName: true,
|
|
5766
|
+
sessionsTotal: true,
|
|
5767
|
+
sessionsUsed: true,
|
|
5768
|
+
expiresAt: true,
|
|
5769
|
+
purchasedAt: true,
|
|
5770
|
+
status: true,
|
|
5771
|
+
paymentId: true,
|
|
5772
|
+
notes: true,
|
|
5773
|
+
pricePaidCents: true,
|
|
5774
|
+
createdAt: true
|
|
5775
|
+
};
|
|
5776
|
+
var SERIES = {
|
|
5777
|
+
id: true,
|
|
5778
|
+
calendarId: true,
|
|
5779
|
+
typeId: true,
|
|
5780
|
+
frequency: true,
|
|
5781
|
+
occurrences: true,
|
|
5782
|
+
startTimeLocal: true,
|
|
5783
|
+
durationMins: true,
|
|
5784
|
+
timezone: true,
|
|
5785
|
+
endsAt: true,
|
|
5786
|
+
clientEmail: true,
|
|
5787
|
+
clientName: true,
|
|
5788
|
+
clientPhone: true,
|
|
5789
|
+
clientId: true,
|
|
5790
|
+
notes: true,
|
|
5791
|
+
status: true,
|
|
5792
|
+
createdAt: true
|
|
5793
|
+
};
|
|
5794
|
+
var DELIVERY = { id: true, eventId: true, eventType: true, body: true, status: true, createdAt: true };
|
|
5795
|
+
var emailIs = (field, emails) => emails.map((email2) => ({ [field]: { equals: email2, mode: "insensitive" } }));
|
|
5796
|
+
var escape = (text2) => text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
5797
|
+
function mentions(body, emails, ids) {
|
|
5798
|
+
const lower = body.toLowerCase();
|
|
5799
|
+
const whole = emails.some((email2) => new RegExp(`(?<![a-z0-9._%+-])${escape(email2.toLowerCase())}(?![a-z0-9_-]|\\.[a-z0-9])`).test(lower));
|
|
5800
|
+
return whole || ids.some((id) => body.includes(`"${id}"`));
|
|
5801
|
+
}
|
|
5802
|
+
async function collectSubjectRows(db, organizationId, subject) {
|
|
5803
|
+
const person = (field) => [...emailIs(field, subject.emails), ...subject.clientId ? [{ clientId: subject.clientId }] : []];
|
|
5804
|
+
const byEmail = emailIs("clientEmail", subject.emails);
|
|
5805
|
+
const none = subject.emails.length === 0 && !subject.clientId;
|
|
5806
|
+
const appointments = none ? [] : await db.appointment.findMany({
|
|
5807
|
+
where: { calendar: { organizationId }, OR: person("clientEmail") },
|
|
5808
|
+
orderBy: { startTime: "asc" },
|
|
5809
|
+
select: APPOINTMENT
|
|
5810
|
+
});
|
|
5811
|
+
const appointmentIds = appointments.map((row) => row.id);
|
|
5812
|
+
const [notifications, waitlistEntries, packagePurchases, recurringSeries] = await Promise.all([
|
|
5813
|
+
appointmentIds.length ? db.scheduledNotification.findMany({ where: { appointmentId: { in: appointmentIds } }, orderBy: { createdAt: "asc" }, select: NOTIFICATION }) : [],
|
|
5814
|
+
byEmail.length ? db.waitlistEntry.findMany({ where: { organizationId, OR: byEmail }, orderBy: { createdAt: "asc" }, select: WAITLIST }) : [],
|
|
5815
|
+
byEmail.length ? db.packagePurchase.findMany({ where: { organizationId, OR: byEmail }, orderBy: { createdAt: "asc" }, select: PURCHASE }) : [],
|
|
5816
|
+
none ? [] : db.recurringSeries.findMany({ where: { organizationId, OR: person("clientEmail") }, orderBy: { createdAt: "asc" }, select: SERIES })
|
|
5817
|
+
]);
|
|
5818
|
+
const terms = [...subject.emails, ...appointmentIds.map((id) => `"${id}"`), ...waitlistEntries.map((row) => `"${row.id}"`)];
|
|
5819
|
+
const deliveries = /* @__PURE__ */ new Map();
|
|
5820
|
+
for (let start = 0; start < terms.length; start += 40) {
|
|
5821
|
+
const chunk = terms.slice(start, start + 40);
|
|
5822
|
+
const rows = await db.webhookDelivery.findMany({
|
|
5823
|
+
where: { organizationId, OR: chunk.map((term) => ({ body: { contains: term, mode: "insensitive" } })) },
|
|
5824
|
+
orderBy: { createdAt: "asc" },
|
|
5825
|
+
select: DELIVERY
|
|
5826
|
+
});
|
|
5827
|
+
for (const row of rows) if (mentions(row.body, subject.emails, [...appointmentIds, ...waitlistEntries.map((entry4) => entry4.id)])) deliveries.set(row.id, row);
|
|
5828
|
+
}
|
|
5829
|
+
return { appointments, notifications, waitlistEntries, packagePurchases, recurringSeries, webhookDeliveries: [...deliveries.values()] };
|
|
5830
|
+
}
|
|
5831
|
+
function countRows(rows) {
|
|
5832
|
+
return {
|
|
5833
|
+
appointments: rows.appointments.length,
|
|
5834
|
+
notifications: rows.notifications.length,
|
|
5835
|
+
waitlistEntries: rows.waitlistEntries.length,
|
|
5836
|
+
packagePurchases: rows.packagePurchases.length,
|
|
5837
|
+
recurringSeries: rows.recurringSeries.length,
|
|
5838
|
+
webhookDeliveries: rows.webhookDeliveries.length
|
|
5839
|
+
};
|
|
5840
|
+
}
|
|
5841
|
+
|
|
5842
|
+
// src/privacy/export.ts
|
|
5843
|
+
function withoutOfferToken(body) {
|
|
5844
|
+
try {
|
|
5845
|
+
const parsed = JSON.parse(body);
|
|
5846
|
+
if (parsed?.data?.offer && "token" in parsed.data.offer) {
|
|
5847
|
+
delete parsed.data.offer.token;
|
|
5848
|
+
return JSON.stringify(parsed);
|
|
5849
|
+
}
|
|
5850
|
+
} catch {
|
|
5851
|
+
}
|
|
5852
|
+
return body;
|
|
5853
|
+
}
|
|
5854
|
+
function withoutLinks(body) {
|
|
5855
|
+
return body.replace(/\/appt\/[A-Za-z0-9_-]+/g, "/appt/[removed]").replace(/([?&]token=)[A-Za-z0-9_-]+/g, "$1[removed]");
|
|
5856
|
+
}
|
|
5857
|
+
async function exportSubject(db, input) {
|
|
5858
|
+
const parsed = parseSubject(input);
|
|
5859
|
+
const now = input.now ?? /* @__PURE__ */ new Date();
|
|
5860
|
+
const subject = await resolveSubject(db, input.organizationId, parsed);
|
|
5861
|
+
const rows = await collectSubjectRows(db, input.organizationId, subject);
|
|
5862
|
+
const counts = countRows(rows);
|
|
5863
|
+
await recordPrivacyRequest(db, { organizationId: input.organizationId, kind: "EXPORT", subject, requestedBy: input.requestedBy, counts, now });
|
|
5864
|
+
return {
|
|
5865
|
+
format: "ordinatio-scheduling-subject-export",
|
|
5866
|
+
version: 1,
|
|
5867
|
+
exportedAt: now.toISOString(),
|
|
5868
|
+
organizationId: input.organizationId,
|
|
5869
|
+
subject,
|
|
5870
|
+
counts,
|
|
5871
|
+
appointments: rows.appointments.map(({ calendar, type, ...rest }) => ({ ...rest, calendarName: calendar.name, typeName: type.name })),
|
|
5872
|
+
notifications: rows.notifications.map((row) => ({ ...row, body: withoutLinks(row.body) })),
|
|
5873
|
+
waitlistEntries: rows.waitlistEntries,
|
|
5874
|
+
packagePurchases: rows.packagePurchases,
|
|
5875
|
+
recurringSeries: rows.recurringSeries,
|
|
5876
|
+
webhookDeliveries: rows.webhookDeliveries.map((row) => ({ ...row, body: withoutOfferToken(row.body) }))
|
|
5877
|
+
};
|
|
5878
|
+
}
|
|
5879
|
+
|
|
5880
|
+
// src/privacy/erase.ts
|
|
5881
|
+
import { randomUUID as randomUUID5 } from "crypto";
|
|
5882
|
+
import { Prisma as Prisma9 } from "@prisma/client";
|
|
5883
|
+
var ERASED_NAME = "Erased client";
|
|
5884
|
+
var ERASED_EMAIL = "erased@erased.invalid";
|
|
5885
|
+
var LIVE_BOOKING = ["PENDING", "CONFIRMED"];
|
|
5886
|
+
var LIVE_OFFER = ["OFFERED", "ACCEPTING"];
|
|
5887
|
+
function blockersOf(rows, now) {
|
|
5888
|
+
return {
|
|
5889
|
+
upcomingAppointments: rows.appointments.filter((row) => LIVE_BOOKING.includes(row.status) && row.endTime > now).length,
|
|
5890
|
+
liveWaitlistEntries: rows.waitlistEntries.filter((row) => LIVE_OFFER.includes(row.status)).length
|
|
5891
|
+
};
|
|
5892
|
+
}
|
|
5893
|
+
function warningsOf(rows) {
|
|
5894
|
+
const unused = rows.packagePurchases.filter((row) => row.status === "ACTIVE").reduce((sum, row) => sum + Math.max(0, row.sessionsTotal - row.sessionsUsed), 0);
|
|
5895
|
+
return unused > 0 ? [`An active package still has ${unused} unused sessions; after erasure it can no longer be matched to this person`] : [];
|
|
5896
|
+
}
|
|
5897
|
+
var blocked = (blockers) => blockers.upcomingAppointments + blockers.liveWaitlistEntries > 0;
|
|
5898
|
+
async function previewErase(db, input) {
|
|
5899
|
+
const subject = await resolveSubject(db, input.organizationId, parseSubject(input));
|
|
5900
|
+
const rows = await collectSubjectRows(db, input.organizationId, subject);
|
|
5901
|
+
const blockers = blockersOf(rows, input.now ?? /* @__PURE__ */ new Date());
|
|
5902
|
+
return { counts: countRows(rows), blockers, canErase: !blocked(blockers), warnings: warningsOf(rows) };
|
|
5903
|
+
}
|
|
5904
|
+
async function eraseSubject(db, input) {
|
|
5905
|
+
const parsed = parseSubject(input);
|
|
5906
|
+
const now = input.now ?? /* @__PURE__ */ new Date();
|
|
5907
|
+
const { organizationId } = input;
|
|
5908
|
+
return withTransaction(db, async (tx) => {
|
|
5909
|
+
const subject = await resolveSubject(tx, organizationId, parsed);
|
|
5910
|
+
const rows = await collectSubjectRows(tx, organizationId, subject);
|
|
5911
|
+
const blockers = blockersOf(rows, now);
|
|
5912
|
+
if (blocked(blockers)) {
|
|
5913
|
+
throw new SchedulingValidationError("This person still has upcoming bookings or an open waitlist offer", "SCHED_1301", { blockers });
|
|
5914
|
+
}
|
|
5915
|
+
for (const { id } of rows.appointments) {
|
|
5916
|
+
await tx.appointment.update({
|
|
5917
|
+
where: { id },
|
|
5918
|
+
data: {
|
|
5919
|
+
clientName: ERASED_NAME,
|
|
5920
|
+
clientEmail: ERASED_EMAIL,
|
|
5921
|
+
clientPhone: null,
|
|
5922
|
+
clientId: null,
|
|
5923
|
+
intakeResponses: Prisma9.DbNull,
|
|
5924
|
+
notes: null,
|
|
5925
|
+
staffNotes: null,
|
|
5926
|
+
cancelReason: null,
|
|
5927
|
+
manageToken: `erased_${randomUUID5()}`
|
|
5928
|
+
}
|
|
5929
|
+
});
|
|
5930
|
+
}
|
|
5931
|
+
const idsOf = (list) => list.map((row) => row.id);
|
|
5932
|
+
if (rows.notifications.length) await tx.scheduledNotification.deleteMany({ where: { id: { in: idsOf(rows.notifications) } } });
|
|
5933
|
+
if (rows.waitlistEntries.length) await tx.waitlistEntry.deleteMany({ where: { organizationId, id: { in: idsOf(rows.waitlistEntries) } } });
|
|
5934
|
+
if (rows.webhookDeliveries.length) await tx.webhookDelivery.deleteMany({ where: { organizationId, id: { in: idsOf(rows.webhookDeliveries) } } });
|
|
5935
|
+
if (rows.packagePurchases.length) {
|
|
5936
|
+
await tx.packagePurchase.updateMany({
|
|
5937
|
+
where: { organizationId, id: { in: idsOf(rows.packagePurchases) } },
|
|
5938
|
+
data: { clientEmail: ERASED_EMAIL, clientName: null, notes: null }
|
|
5939
|
+
});
|
|
5940
|
+
}
|
|
5941
|
+
if (rows.recurringSeries.length) {
|
|
5942
|
+
await tx.recurringSeries.updateMany({
|
|
5943
|
+
where: { organizationId, id: { in: idsOf(rows.recurringSeries) } },
|
|
5944
|
+
data: { clientEmail: ERASED_EMAIL, clientName: ERASED_NAME, clientPhone: null, clientId: null, notes: null }
|
|
5945
|
+
});
|
|
5946
|
+
}
|
|
5947
|
+
const counts = countRows(rows);
|
|
5948
|
+
await recordPrivacyRequest(tx, { organizationId, kind: "ERASE", subject, requestedBy: input.requestedBy, counts, now });
|
|
5949
|
+
return { counts };
|
|
5950
|
+
}, { timeout: 12e4 });
|
|
5951
|
+
}
|
|
3799
5952
|
export {
|
|
5953
|
+
BRAND_FIELDS,
|
|
5954
|
+
BlockedTargetError,
|
|
5955
|
+
DEFAULT_BACKOFF_SECONDS,
|
|
5956
|
+
DEFAULT_OFFER_MINUTES,
|
|
5957
|
+
ERASED_EMAIL,
|
|
5958
|
+
ERASED_NAME,
|
|
5959
|
+
MAX_ENDPOINTS_PER_ORGANIZATION,
|
|
5960
|
+
MAX_WAITING_PER_TYPE_DAY,
|
|
5961
|
+
OPERATORS_BY_TYPE,
|
|
3800
5962
|
RECURRING_MAX_OCCURRENCES,
|
|
5963
|
+
LIMITS as ROUTING_LIMITS,
|
|
3801
5964
|
SCHEDULING_ERRORS,
|
|
5965
|
+
SIGNATURE_HEADER,
|
|
3802
5966
|
SchedulingNotFoundError,
|
|
3803
5967
|
SchedulingValidationError,
|
|
3804
5968
|
USER_DAY_LIMIT,
|
|
5969
|
+
WEBHOOK_EVENT_TYPES,
|
|
5970
|
+
WEBHOOK_TEST_EVENT,
|
|
3805
5971
|
adaptersToCallbacks,
|
|
3806
5972
|
addDateOverride,
|
|
3807
5973
|
addTimeBlock,
|
|
5974
|
+
appointmentWebhookData,
|
|
3808
5975
|
archiveCalendar,
|
|
5976
|
+
beginWaitlistAccept,
|
|
3809
5977
|
bookAppointment,
|
|
5978
|
+
brandTemplateFields,
|
|
3810
5979
|
buildJitsiUrl,
|
|
3811
5980
|
buildNotificationContext,
|
|
3812
5981
|
buildOccurrenceStartTime,
|
|
@@ -3814,18 +5983,35 @@ export {
|
|
|
3814
5983
|
calculateCancellationFee,
|
|
3815
5984
|
cancelAppointment,
|
|
3816
5985
|
cancelPendingNotifications,
|
|
5986
|
+
checkAnswers,
|
|
3817
5987
|
checkAuthContract,
|
|
3818
5988
|
checkCalendarSyncContract,
|
|
3819
5989
|
checkClockContract,
|
|
3820
5990
|
checkNotificationContract,
|
|
3821
5991
|
checkPaymentContract,
|
|
5992
|
+
checkWebhookUrl,
|
|
5993
|
+
completeWaitlistAccept,
|
|
3822
5994
|
createAppointmentType,
|
|
3823
5995
|
createCalendar,
|
|
3824
5996
|
createInMemoryAdapters,
|
|
5997
|
+
createNodeTransport,
|
|
3825
5998
|
createNotificationTemplate,
|
|
5999
|
+
createRoutingForm,
|
|
6000
|
+
createWebhookEndpoint,
|
|
6001
|
+
deleteBrand,
|
|
3826
6002
|
deleteCalendar,
|
|
3827
6003
|
deleteNotificationTemplate,
|
|
6004
|
+
deleteRoutingForm,
|
|
6005
|
+
deleteWebhookEndpoint,
|
|
6006
|
+
deliverDueWebhooks,
|
|
6007
|
+
enqueueAppointmentWebhook,
|
|
6008
|
+
enqueueReminderSent,
|
|
6009
|
+
enqueueWebhookEvent,
|
|
6010
|
+
eraseSubject,
|
|
6011
|
+
expireWaitlistOffers,
|
|
6012
|
+
exportSubject,
|
|
3828
6013
|
generateOccurrenceDates,
|
|
6014
|
+
generateWebhookSecret,
|
|
3829
6015
|
getAppointment,
|
|
3830
6016
|
getAppointmentDashboard,
|
|
3831
6017
|
getAppointmentType,
|
|
@@ -3833,35 +6019,73 @@ export {
|
|
|
3833
6019
|
getAvailableDates,
|
|
3834
6020
|
getAvailableSlots,
|
|
3835
6021
|
getBookingAnalytics,
|
|
6022
|
+
getBrand,
|
|
3836
6023
|
getCalendar,
|
|
3837
6024
|
getGroupCapacity,
|
|
3838
6025
|
getGroupSessions,
|
|
3839
6026
|
getNotificationTemplate,
|
|
6027
|
+
getPublicBrand,
|
|
6028
|
+
getPublicRoutingForm,
|
|
6029
|
+
getRoutingForm,
|
|
3840
6030
|
getTeamAvailableSlots,
|
|
3841
6031
|
getUserDayAppointments,
|
|
6032
|
+
getWaitlistOffer,
|
|
6033
|
+
isPrivateAddress,
|
|
3842
6034
|
isSlotAvailable,
|
|
3843
6035
|
isVirtualMeeting,
|
|
6036
|
+
joinWaitlist,
|
|
6037
|
+
leaveWaitlist,
|
|
3844
6038
|
listAppointmentTypes,
|
|
3845
6039
|
listAppointments,
|
|
3846
6040
|
listAvailabilityRules,
|
|
3847
6041
|
listCalendars,
|
|
3848
6042
|
listNotificationTemplates,
|
|
6043
|
+
listPrivacyRequests,
|
|
6044
|
+
listRoutingForms,
|
|
6045
|
+
listWaitlist,
|
|
6046
|
+
listWebhookDeliveries,
|
|
6047
|
+
listWebhookEndpoints,
|
|
6048
|
+
localDay,
|
|
3849
6049
|
localToUTC,
|
|
3850
6050
|
markNoShow,
|
|
6051
|
+
matchingRules,
|
|
6052
|
+
offerFreedSlot,
|
|
6053
|
+
parseSubject,
|
|
3851
6054
|
parseTimeLocal,
|
|
6055
|
+
previewErase,
|
|
3852
6056
|
processPendingNotifications,
|
|
3853
6057
|
queueImmediateNotification,
|
|
3854
6058
|
queueStaffNotification,
|
|
6059
|
+
releaseWaitlistAccept,
|
|
3855
6060
|
removeDateOverride,
|
|
6061
|
+
removeWaitlistEntry,
|
|
3856
6062
|
renderTemplate,
|
|
3857
6063
|
rescheduleAppointment,
|
|
6064
|
+
resolveDestination,
|
|
3858
6065
|
resolveLocation,
|
|
6066
|
+
resolveSubject,
|
|
6067
|
+
retryWebhookDelivery,
|
|
6068
|
+
routeClient,
|
|
6069
|
+
saveBrand,
|
|
3859
6070
|
schedError,
|
|
3860
6071
|
scheduleNotifications,
|
|
3861
6072
|
selectCalendarForBooking,
|
|
6073
|
+
sendTestWebhook,
|
|
6074
|
+
senderIdentity,
|
|
3862
6075
|
setWeeklyAvailability,
|
|
6076
|
+
settleBookedAccept,
|
|
6077
|
+
signWebhook,
|
|
6078
|
+
subjectHashes,
|
|
6079
|
+
testRoutingForm,
|
|
6080
|
+
toPublicBrand,
|
|
6081
|
+
tryOfferFreedSlot,
|
|
3863
6082
|
updateAppointmentType,
|
|
3864
6083
|
updateCalendar,
|
|
3865
6084
|
updateNotificationTemplate,
|
|
6085
|
+
updateRoutingForm,
|
|
6086
|
+
validateBrand,
|
|
6087
|
+
validateRoutingDestinations,
|
|
6088
|
+
validateRoutingStructure,
|
|
6089
|
+
verifyWebhookSignature,
|
|
3866
6090
|
withCalendarVisibility
|
|
3867
6091
|
};
|