@ordinatio/scheduling 0.6.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1151,6 +1151,189 @@ var TEXT_SETTINGS_ERRORS = {
1151
1151
  }
1152
1152
  };
1153
1153
 
1154
+ // src/errors/registry-api-keys.ts
1155
+ var API_KEY_ERRORS = {
1156
+ SCHED_1600: {
1157
+ code: "SCHED_1600",
1158
+ file: "api-keys/",
1159
+ function: "validateApiKeyRequest",
1160
+ severity: "warning",
1161
+ recoverable: true,
1162
+ description: "The API key request is not valid",
1163
+ diagnosis: [
1164
+ "Read the list of problems in the error context: each names the field and what is wrong",
1165
+ "A key needs a name of at most 60 characters and an access level of READ or FULL"
1166
+ ]
1167
+ },
1168
+ SCHED_1601: {
1169
+ code: "SCHED_1601",
1170
+ file: "api-keys/",
1171
+ function: "createApiKey",
1172
+ severity: "warning",
1173
+ recoverable: true,
1174
+ description: "The business already has the most API keys it may have",
1175
+ diagnosis: [
1176
+ "Revoke a key that is no longer used, then create the new one"
1177
+ ]
1178
+ },
1179
+ SCHED_1602: {
1180
+ code: "SCHED_1602",
1181
+ file: "api-keys/",
1182
+ function: "verifyApiKey",
1183
+ severity: "warning",
1184
+ recoverable: true,
1185
+ description: "An API key was accepted but the time it was last used could not be recorded",
1186
+ diagnosis: [
1187
+ 'The key still worked; only the "last used" time is out of date',
1188
+ "Check that the database is reachable and the OrganizationApiKey table has been migrated"
1189
+ ]
1190
+ }
1191
+ };
1192
+
1193
+ // src/errors/registry-gift-certificates.ts
1194
+ var GIFT_CERTIFICATE_ERRORS = {
1195
+ SCHED_1700: {
1196
+ code: "SCHED_1700",
1197
+ file: "gift-certificates/",
1198
+ function: "validateGiftCertificateRequest",
1199
+ severity: "warning",
1200
+ recoverable: true,
1201
+ description: "The gift certificate request is not valid",
1202
+ diagnosis: [
1203
+ "Read the list of problems in the error context: each names the field and what is wrong",
1204
+ "An amount is a whole number of cents between 100 and 1000000; an expiry must be in the future"
1205
+ ]
1206
+ },
1207
+ SCHED_1702: {
1208
+ code: "SCHED_1702",
1209
+ file: "gift-certificates/",
1210
+ function: "redeemGiftCertificate",
1211
+ severity: "warning",
1212
+ recoverable: true,
1213
+ description: "The gift certificate cannot be used: it is void, expired or used up",
1214
+ diagnosis: [
1215
+ "The context names the reason: VOID, EXPIRED or USED_UP",
1216
+ "A voided certificate cannot be spent or topped up; issue a new one if the client is owed value"
1217
+ ]
1218
+ },
1219
+ SCHED_1703: {
1220
+ code: "SCHED_1703",
1221
+ file: "gift-certificates/",
1222
+ function: "redeemGiftCertificate",
1223
+ severity: "warning",
1224
+ recoverable: true,
1225
+ description: "The gift certificate changed while it was being updated",
1226
+ diagnosis: [
1227
+ "The certificate is locked for each change, so this should not happen; nothing was taken and the request is safe to repeat",
1228
+ "If it repeats, check that the database handle really is a transaction and that nothing else writes the certificate table"
1229
+ ]
1230
+ },
1231
+ SCHED_1704: {
1232
+ code: "SCHED_1704",
1233
+ file: "gift-certificates/",
1234
+ function: "restoreGiftCertificate",
1235
+ severity: "warning",
1236
+ recoverable: true,
1237
+ description: "More was asked to be given back than the certificate or the appointment allows",
1238
+ diagnosis: [
1239
+ "With an appointment, only what was spent on it and not yet returned can come back; a repeated refund returns nothing more",
1240
+ "Without one, the balance cannot rise above the amount the certificate was issued for"
1241
+ ]
1242
+ },
1243
+ SCHED_1705: {
1244
+ code: "SCHED_1705",
1245
+ file: "gift-certificates/",
1246
+ function: "issueGiftCertificate",
1247
+ severity: "error",
1248
+ recoverable: true,
1249
+ description: "A unique gift certificate code could not be made",
1250
+ diagnosis: [
1251
+ "Five random codes in a row already existed, which should not happen: check that the code generator has not been replaced"
1252
+ ]
1253
+ },
1254
+ SCHED_1706: {
1255
+ code: "SCHED_1706",
1256
+ file: "gift-certificates/",
1257
+ function: "redeemGiftCertificate",
1258
+ severity: "warning",
1259
+ recoverable: true,
1260
+ description: "The amount is not a positive whole number of cents",
1261
+ diagnosis: [
1262
+ "Amounts are whole cents: 1250 means 12.50; decimals, zero and negative values are refused"
1263
+ ]
1264
+ },
1265
+ SCHED_1707: {
1266
+ code: "SCHED_1707",
1267
+ file: "gift-certificates/",
1268
+ function: "redeemGiftCertificate",
1269
+ severity: "warning",
1270
+ recoverable: true,
1271
+ description: "This gift certificate was already spent on this appointment and not given back",
1272
+ diagnosis: [
1273
+ "A booking that is retried would otherwise spend the certificate twice; the first spend stands",
1274
+ "If the first spend was given back in full, spending again on the same appointment is allowed",
1275
+ "Read the certificate history to see the earlier lines"
1276
+ ]
1277
+ },
1278
+ SCHED_1708: {
1279
+ code: "SCHED_1708",
1280
+ file: "gift-certificates/",
1281
+ function: "redeemGiftCertificate",
1282
+ severity: "warning",
1283
+ recoverable: true,
1284
+ description: "The gift certificate is in a different currency from the bill",
1285
+ diagnosis: [
1286
+ "The context names both currencies; a certificate only pays a bill in its own currency"
1287
+ ]
1288
+ },
1289
+ SCHED_1709: {
1290
+ code: "SCHED_1709",
1291
+ file: "gift-certificates/",
1292
+ function: "redeemGiftCertificate",
1293
+ severity: "warning",
1294
+ recoverable: true,
1295
+ description: "An appointment id, note or currency given with the request is not valid",
1296
+ diagnosis: [
1297
+ "The context names the field; ids and currencies are non-empty text, a note is at most 500 characters"
1298
+ ]
1299
+ },
1300
+ SCHED_1710: {
1301
+ code: "SCHED_1710",
1302
+ file: "gift-certificates/",
1303
+ function: "issueGiftCertificate",
1304
+ severity: "warning",
1305
+ recoverable: true,
1306
+ description: "This payment already made a gift certificate of a different amount or currency",
1307
+ diagnosis: [
1308
+ "A payment makes one certificate; asking for another with a different amount or currency is a mistake in the caller, not a repeat",
1309
+ "Check which payment id the request carries; a genuine repeat must ask for the same amount and currency"
1310
+ ]
1311
+ },
1312
+ SCHED_1711: {
1313
+ code: "SCHED_1711",
1314
+ file: "gift-certificates/",
1315
+ function: "inTransaction",
1316
+ severity: "error",
1317
+ recoverable: false,
1318
+ description: "The database handle is neither a client nor an open transaction",
1319
+ diagnosis: [
1320
+ "Pass the Prisma client, or the client a transaction callback receives; a bare object would run without the certificate lock"
1321
+ ]
1322
+ },
1323
+ SCHED_1712: {
1324
+ code: "SCHED_1712",
1325
+ file: "gift-certificates/",
1326
+ function: "getGiftCertificate",
1327
+ severity: "warning",
1328
+ recoverable: true,
1329
+ description: "No gift certificate of this business matches",
1330
+ diagnosis: [
1331
+ "The same answer is given for an unknown code, a malformed code and a code that belongs to another business",
1332
+ "Check the code as typed, including that it belongs to this business"
1333
+ ]
1334
+ }
1335
+ };
1336
+
1154
1337
  // src/errors/registry.ts
1155
1338
  var SCHEDULING_ERRORS = {
1156
1339
  ...CALENDARS_AVAILABILITY_ERRORS,
@@ -1166,7 +1349,9 @@ var SCHEDULING_ERRORS = {
1166
1349
  ...ROUTING_ERRORS,
1167
1350
  ...PRIVACY_ERRORS,
1168
1351
  ...BRAND_ERRORS,
1169
- ...TEXT_SETTINGS_ERRORS
1352
+ ...TEXT_SETTINGS_ERRORS,
1353
+ ...API_KEY_ERRORS,
1354
+ ...GIFT_CERTIFICATE_ERRORS
1170
1355
  };
1171
1356
 
1172
1357
  // src/errors/diagnostic-error.ts
@@ -6065,15 +6250,461 @@ async function deleteTextSettings(db, organizationId) {
6065
6250
  const { count } = await db.organizationTextSettings.deleteMany({ where: { organizationId } });
6066
6251
  return count > 0;
6067
6252
  }
6253
+
6254
+ // src/api-keys/types.ts
6255
+ var API_KEY_ACCESS = ["READ", "FULL"];
6256
+ var API_KEY_FIELDS = ["name", "access"];
6257
+ var MAX_ACTIVE_API_KEYS = 25;
6258
+ var API_KEY_NAME_MAX = 60;
6259
+
6260
+ // src/api-keys/validate.ts
6261
+ function validateApiKeyRequest(input) {
6262
+ const problems = [];
6263
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
6264
+ throw new SchedulingValidationError("The API key request is not valid", "SCHED_1600", { errors: [{ path: "", message: "Must be an object" }] });
6265
+ }
6266
+ const given = input;
6267
+ for (const key of Object.keys(given)) if (!API_KEY_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
6268
+ let name = "";
6269
+ if (typeof given.name !== "string" || given.name.trim() === "") problems.push({ path: "name", message: "Required" });
6270
+ else if (given.name.trim().length > API_KEY_NAME_MAX) problems.push({ path: "name", message: `Must be at most ${API_KEY_NAME_MAX} characters` });
6271
+ else name = given.name.trim();
6272
+ let access = "READ";
6273
+ if (given.access === void 0) problems.push({ path: "access", message: "Required" });
6274
+ else if (typeof given.access !== "string" || !API_KEY_ACCESS.includes(given.access)) problems.push({ path: "access", message: `Must be one of: ${API_KEY_ACCESS.join(", ")}` });
6275
+ else access = given.access;
6276
+ if (problems.length > 0) throw new SchedulingValidationError("The API key request is not valid", "SCHED_1600", { errors: problems });
6277
+ return { name, access };
6278
+ }
6279
+
6280
+ // src/api-keys/secret.ts
6281
+ import { createHash as createHash2, randomBytes as randomBytes3 } from "crypto";
6282
+ var API_KEY_PREFIX = "osk_";
6283
+ var PREFIX_SHOWN = 12;
6284
+ function generateApiKeySecret() {
6285
+ return `${API_KEY_PREFIX}${randomBytes3(32).toString("base64url")}`;
6286
+ }
6287
+ function hashApiKeySecret(secret) {
6288
+ return createHash2("sha256").update(secret).digest("hex");
6289
+ }
6290
+ function visiblePrefix(secret) {
6291
+ return secret.slice(0, PREFIX_SHOWN);
6292
+ }
6293
+ function looksLikeApiKey(text2) {
6294
+ return /^osk_[A-Za-z0-9_-]{43}$/.test(text2);
6295
+ }
6296
+
6297
+ // src/api-keys/crud.ts
6298
+ var VIEW = { id: true, name: true, access: true, prefix: true, createdByUserId: true, createdAt: true, lastUsedAt: true, revokedAt: true };
6299
+ var LAST_USED_REFRESH_MS = 10 * 60 * 1e3;
6300
+ async function createApiKey(db, organizationId, input, createdByUserId) {
6301
+ const fields = validateApiKeyRequest(input);
6302
+ const active = await db.organizationApiKey.count({ where: { organizationId, revokedAt: null } });
6303
+ if (active >= MAX_ACTIVE_API_KEYS) {
6304
+ throw new SchedulingValidationError(`A business may have at most ${MAX_ACTIVE_API_KEYS} API keys`, "SCHED_1601", { limit: MAX_ACTIVE_API_KEYS });
6305
+ }
6306
+ const key = generateApiKeySecret();
6307
+ const view2 = await db.organizationApiKey.create({
6308
+ data: { organizationId, ...fields, prefix: visiblePrefix(key), keyHash: hashApiKeySecret(key), createdByUserId: createdByUserId ?? null },
6309
+ select: VIEW
6310
+ });
6311
+ return { key, view: view2 };
6312
+ }
6313
+ async function listApiKeys(db, organizationId) {
6314
+ return db.organizationApiKey.findMany({ where: { organizationId }, orderBy: { createdAt: "desc" }, select: VIEW });
6315
+ }
6316
+ async function revokeApiKey(db, organizationId, id) {
6317
+ const { count } = await db.organizationApiKey.updateMany({ where: { id, organizationId, revokedAt: null }, data: { revokedAt: /* @__PURE__ */ new Date() } });
6318
+ return count > 0;
6319
+ }
6320
+ async function verifyApiKey(db, secret) {
6321
+ if (!looksLikeApiKey(secret)) return null;
6322
+ const row = await db.organizationApiKey.findUnique({
6323
+ where: { keyHash: hashApiKeySecret(secret) },
6324
+ select: { id: true, organizationId: true, access: true, createdByUserId: true, revokedAt: true, lastUsedAt: true }
6325
+ });
6326
+ if (!row || row.revokedAt) return null;
6327
+ if (!API_KEY_ACCESS.includes(row.access)) return null;
6328
+ const now = Date.now();
6329
+ if (!row.lastUsedAt || now - row.lastUsedAt.getTime() > LAST_USED_REFRESH_MS) {
6330
+ await db.organizationApiKey.updateMany({ where: { id: row.id, revokedAt: null }, data: { lastUsedAt: new Date(now) } }).catch((error) => {
6331
+ const diagnostic = schedError("SCHED_1602", { keyId: row.id, error });
6332
+ console.error(`[api-keys] ${diagnostic.code}-${diagnostic.ref} could not record last use`, error);
6333
+ });
6334
+ }
6335
+ return { id: row.id, organizationId: row.organizationId, access: row.access, createdByUserId: row.createdByUserId };
6336
+ }
6337
+
6338
+ // src/gift-certificates/types.ts
6339
+ var GIFT_CERTIFICATE_STATUS = ["ACTIVE", "VOID"];
6340
+ var GIFT_TRANSACTION_TYPES = ["ISSUE", "REDEEM", "RESTORE", "VOID"];
6341
+ var GIFT_CERTIFICATE_FIELDS = [
6342
+ "amountCents",
6343
+ "currency",
6344
+ "expiresAt",
6345
+ "recipientName",
6346
+ "recipientEmail",
6347
+ "purchaserName",
6348
+ "purchaserEmail",
6349
+ "message",
6350
+ "paymentId",
6351
+ "notes"
6352
+ ];
6353
+ var MIN_GIFT_CENTS = 100;
6354
+ var MAX_GIFT_CENTS = 1e6;
6355
+ var GIFT_NAME_MAX = 120;
6356
+ var GIFT_MESSAGE_MAX = 500;
6357
+ var GIFT_NOTES_MAX = 1e3;
6358
+ var GIFT_EMAIL_MAX = 254;
6359
+
6360
+ // src/gift-certificates/code.ts
6361
+ import { randomInt } from "crypto";
6362
+ var ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
6363
+ var GIFT_CODE_LENGTH = 12;
6364
+ var SHAPE = new RegExp(`^[${ALPHABET}]{${GIFT_CODE_LENGTH}}$`);
6365
+ var MAX_TYPED_LENGTH = 40;
6366
+ function generateGiftCode() {
6367
+ let code = "";
6368
+ for (let i = 0; i < GIFT_CODE_LENGTH; i += 1) code += ALPHABET[randomInt(ALPHABET.length)];
6369
+ return code;
6370
+ }
6371
+ function normalizeGiftCode(input) {
6372
+ return input.toUpperCase().replace(/[\s-]+/g, "");
6373
+ }
6374
+ function looksLikeGiftCode(input) {
6375
+ return input.length <= MAX_TYPED_LENGTH && SHAPE.test(normalizeGiftCode(input));
6376
+ }
6377
+ function formatGiftCode(code) {
6378
+ return code.replace(/(.{4})(?=.)/g, "$1-");
6379
+ }
6380
+
6381
+ // src/gift-certificates/state.ts
6382
+ function giftCertificateState(certificate, now = /* @__PURE__ */ new Date()) {
6383
+ if (certificate.status !== "ACTIVE") return "VOID";
6384
+ if (certificate.expiresAt && certificate.expiresAt.getTime() <= now.getTime()) return "EXPIRED";
6385
+ if (certificate.balanceCents <= 0) return "USED_UP";
6386
+ return "ACTIVE";
6387
+ }
6388
+
6389
+ // src/gift-certificates/validate.ts
6390
+ var EMAIL3 = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
6391
+ function optionalText(given, field, max, problems, pattern, patternMessage) {
6392
+ const value = given[field];
6393
+ if (value === void 0 || value === null) return null;
6394
+ if (typeof value !== "string") {
6395
+ problems.push({ path: field, message: "Must be text" });
6396
+ return null;
6397
+ }
6398
+ const text2 = value.trim();
6399
+ if (text2 === "") return null;
6400
+ if (text2.length > max) {
6401
+ problems.push({ path: field, message: `Must be at most ${max} characters` });
6402
+ return null;
6403
+ }
6404
+ if (pattern && !pattern.test(text2)) {
6405
+ problems.push({ path: field, message: patternMessage ?? "Not valid" });
6406
+ return null;
6407
+ }
6408
+ return text2;
6409
+ }
6410
+ function expiryOf(value, now, problems) {
6411
+ if (value === void 0 || value === null) return null;
6412
+ const date = value instanceof Date ? value : typeof value === "string" ? new Date(value) : null;
6413
+ if (!date || Number.isNaN(date.getTime())) {
6414
+ problems.push({ path: "expiresAt", message: "Must be a date" });
6415
+ return null;
6416
+ }
6417
+ if (date.getTime() <= now.getTime()) {
6418
+ problems.push({ path: "expiresAt", message: "Must be in the future" });
6419
+ return null;
6420
+ }
6421
+ return date;
6422
+ }
6423
+ function validateGiftCertificateRequest(input, now = /* @__PURE__ */ new Date()) {
6424
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
6425
+ throw new SchedulingValidationError("The gift certificate request is not valid", "SCHED_1700", { errors: [{ path: "", message: "Must be an object" }] });
6426
+ }
6427
+ const given = input;
6428
+ const problems = [];
6429
+ for (const key of Object.keys(given)) if (!GIFT_CERTIFICATE_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
6430
+ let amountCents = 0;
6431
+ if (given.amountCents === void 0) problems.push({ path: "amountCents", message: "Required" });
6432
+ else if (typeof given.amountCents !== "number" || !Number.isInteger(given.amountCents)) problems.push({ path: "amountCents", message: "Must be a whole number of cents" });
6433
+ else if (given.amountCents < MIN_GIFT_CENTS || given.amountCents > MAX_GIFT_CENTS) problems.push({ path: "amountCents", message: `Must be between ${MIN_GIFT_CENTS} and ${MAX_GIFT_CENTS} cents` });
6434
+ else amountCents = given.amountCents;
6435
+ let currency = "usd";
6436
+ if (given.currency !== void 0) {
6437
+ if (typeof given.currency !== "string" || !/^[A-Za-z]{3}$/.test(given.currency)) problems.push({ path: "currency", message: "Must be a three-letter currency code" });
6438
+ else currency = given.currency.toLowerCase();
6439
+ }
6440
+ const fields = {
6441
+ amountCents,
6442
+ currency,
6443
+ expiresAt: expiryOf(given.expiresAt, now, problems),
6444
+ recipientName: optionalText(given, "recipientName", GIFT_NAME_MAX, problems),
6445
+ recipientEmail: optionalText(given, "recipientEmail", GIFT_EMAIL_MAX, problems, EMAIL3, "Must be an email address")?.toLowerCase() ?? null,
6446
+ purchaserName: optionalText(given, "purchaserName", GIFT_NAME_MAX, problems),
6447
+ purchaserEmail: optionalText(given, "purchaserEmail", GIFT_EMAIL_MAX, problems, EMAIL3, "Must be an email address")?.toLowerCase() ?? null,
6448
+ message: optionalText(given, "message", GIFT_MESSAGE_MAX, problems),
6449
+ paymentId: optionalText(given, "paymentId", GIFT_NAME_MAX, problems),
6450
+ notes: optionalText(given, "notes", GIFT_NOTES_MAX, problems)
6451
+ };
6452
+ if (problems.length > 0) throw new SchedulingValidationError("The gift certificate request is not valid", "SCHED_1700", { errors: problems });
6453
+ return fields;
6454
+ }
6455
+
6456
+ // src/gift-certificates/guard.ts
6457
+ var TEXT_ID_MAX = 100;
6458
+ var NOTE_MAX = 500;
6459
+ function isBoundedText(value, max = TEXT_ID_MAX) {
6460
+ return typeof value === "string" && value.length > 0 && value.length <= max;
6461
+ }
6462
+ function notFound() {
6463
+ return new SchedulingNotFoundError("Gift certificate not found", "SCHED_1712");
6464
+ }
6465
+ function optionalLinkText(value, field) {
6466
+ if (value === void 0) return void 0;
6467
+ if (!isBoundedText(value, field === "note" ? NOTE_MAX : TEXT_ID_MAX)) {
6468
+ throw new SchedulingValidationError(`${field} must be non-empty text of reasonable length`, "SCHED_1709", { field });
6469
+ }
6470
+ return value;
6471
+ }
6472
+
6473
+ // src/gift-certificates/transaction.ts
6474
+ async function inTransaction(db, work) {
6475
+ const handle = typeof db === "object" && db !== null ? db : {};
6476
+ if (typeof handle.$transaction === "function") return withTransaction(db, work);
6477
+ if (typeof handle.$queryRaw === "function") return work(db);
6478
+ throw new SchedulingValidationError("The database handle is neither a client nor an open transaction", "SCHED_1711");
6479
+ }
6480
+ async function lockCertificate(tx, where) {
6481
+ const { count } = await tx.giftCertificate.updateMany({ where, data: { updatedAt: /* @__PURE__ */ new Date(), ledgerSeq: { increment: 1 } } });
6482
+ if (count === 0) throw notFound();
6483
+ }
6484
+
6485
+ // src/gift-certificates/crud.ts
6486
+ var CERTIFICATE_VIEW = {
6487
+ id: true,
6488
+ code: true,
6489
+ status: true,
6490
+ currency: true,
6491
+ initialCents: true,
6492
+ balanceCents: true,
6493
+ expiresAt: true,
6494
+ recipientName: true,
6495
+ recipientEmail: true,
6496
+ purchaserName: true,
6497
+ purchaserEmail: true,
6498
+ message: true,
6499
+ notes: true,
6500
+ paymentId: true,
6501
+ createdByUserId: true,
6502
+ createdAt: true
6503
+ };
6504
+ var LEDGER_VIEW = { id: true, seq: true, type: true, amountCents: true, balanceAfterCents: true, appointmentId: true, note: true, createdByUserId: true, createdAt: true };
6505
+ var CODE_ATTEMPTS = 5;
6506
+ var DEFAULT_LIST_LIMIT = 100;
6507
+ var MAX_LIST_LIMIT = 500;
6508
+ var MAX_HISTORY_LINES = 1e3;
6509
+ function isUniqueViolation2(error) {
6510
+ return typeof error === "object" && error !== null && error.code === "P2002";
6511
+ }
6512
+ async function issueGiftCertificateOnce(db, organizationId, input, createdByUserId) {
6513
+ const { amountCents, ...fields } = validateGiftCertificateRequest(input);
6514
+ const existingFor = async () => fields.paymentId ? await db.giftCertificate.findFirst({ where: { organizationId, paymentId: fields.paymentId }, select: CERTIFICATE_VIEW }) : null;
6515
+ const sameAs = (existing) => {
6516
+ if (existing.initialCents !== amountCents || existing.currency !== fields.currency) {
6517
+ throw new SchedulingValidationError("This payment already made a gift certificate of a different amount or currency", "SCHED_1710", { paymentId: fields.paymentId });
6518
+ }
6519
+ return { certificate: existing, created: false };
6520
+ };
6521
+ const earlier = await existingFor();
6522
+ if (earlier) return sameAs(earlier);
6523
+ for (let attempt = 0; attempt < CODE_ATTEMPTS; attempt += 1) {
6524
+ try {
6525
+ const certificate = await inTransaction(db, async (tx) => {
6526
+ const row = await tx.giftCertificate.create({
6527
+ data: { ...fields, organizationId, code: generateGiftCode(), initialCents: amountCents, balanceCents: amountCents, ledgerSeq: 1, createdByUserId: createdByUserId ?? null },
6528
+ select: CERTIFICATE_VIEW
6529
+ });
6530
+ await tx.giftCertificateTransaction.create({
6531
+ data: { certificateId: row.id, organizationId, seq: 1, type: "ISSUE", amountCents, balanceAfterCents: amountCents, createdByUserId: createdByUserId ?? null }
6532
+ });
6533
+ return row;
6534
+ });
6535
+ return { certificate, created: true };
6536
+ } catch (error) {
6537
+ if (!isUniqueViolation2(error)) throw error;
6538
+ const concurrent = await existingFor();
6539
+ if (concurrent) return sameAs(concurrent);
6540
+ }
6541
+ }
6542
+ throw new SchedulingValidationError("Could not make a unique gift certificate code", "SCHED_1705", { attempts: CODE_ATTEMPTS });
6543
+ }
6544
+ async function issueGiftCertificate(db, organizationId, input, createdByUserId) {
6545
+ return (await issueGiftCertificateOnce(db, organizationId, input, createdByUserId)).certificate;
6546
+ }
6547
+ async function listGiftCertificates(db, organizationId, options = {}) {
6548
+ const asked = Math.trunc(options.limit ?? Number.NaN);
6549
+ const limit = asked >= 1 ? Math.min(asked, MAX_LIST_LIMIT) : DEFAULT_LIST_LIMIT;
6550
+ return db.giftCertificate.findMany({
6551
+ where: { organizationId, ...options.status ? { status: options.status } : {} },
6552
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
6553
+ take: limit,
6554
+ select: CERTIFICATE_VIEW
6555
+ });
6556
+ }
6557
+ async function getGiftCertificate(db, organizationId, id) {
6558
+ if (!isBoundedText(id)) throw new SchedulingNotFoundError("Gift certificate not found", "SCHED_1712");
6559
+ const certificate = await db.giftCertificate.findFirst({ where: { id, organizationId }, select: CERTIFICATE_VIEW });
6560
+ if (!certificate) throw new SchedulingNotFoundError("Gift certificate not found", "SCHED_1712");
6561
+ const lines = await db.giftCertificateTransaction.findMany({
6562
+ where: { certificateId: id, organizationId },
6563
+ orderBy: { seq: "asc" },
6564
+ take: MAX_HISTORY_LINES + 1,
6565
+ select: LEDGER_VIEW
6566
+ });
6567
+ return { certificate, transactions: lines.slice(0, MAX_HISTORY_LINES), truncated: lines.length > MAX_HISTORY_LINES };
6568
+ }
6569
+ async function voidGiftCertificate(db, organizationId, id, userId) {
6570
+ if (!isBoundedText(id)) return false;
6571
+ return inTransaction(db, async (tx) => {
6572
+ const { count } = await tx.giftCertificate.updateMany({ where: { id, organizationId, status: "ACTIVE" }, data: { status: "VOID", ledgerSeq: { increment: 1 } } });
6573
+ if (count === 0) return false;
6574
+ const row = await tx.giftCertificate.findFirst({ where: { id, organizationId }, select: { balanceCents: true, ledgerSeq: true } });
6575
+ if (!row) throw new SchedulingNotFoundError("Gift certificate not found", "SCHED_1712");
6576
+ await tx.giftCertificateTransaction.create({
6577
+ data: { certificateId: id, organizationId, seq: row.ledgerSeq, type: "VOID", amountCents: 0, balanceAfterCents: row.balanceCents, createdByUserId: userId ?? null }
6578
+ });
6579
+ return true;
6580
+ });
6581
+ }
6582
+
6583
+ // src/gift-certificates/redeem.ts
6584
+ var MAX_AMOUNT_CENTS = 2e9;
6585
+ function requireAmount(value, field) {
6586
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > MAX_AMOUNT_CENTS) {
6587
+ throw new SchedulingValidationError("The amount must be a positive whole number of cents", "SCHED_1706", { field });
6588
+ }
6589
+ return value;
6590
+ }
6591
+ function requireCurrency(value) {
6592
+ if (typeof value !== "string" || !/^[A-Za-z]{3}$/.test(value)) {
6593
+ throw new SchedulingValidationError("The currency must be a three-letter code", "SCHED_1709", { field: "currency" });
6594
+ }
6595
+ return value.toLowerCase();
6596
+ }
6597
+ function netSpent(lines) {
6598
+ const spent = lines.filter((l) => l.type === "REDEEM").reduce((sum, l) => sum - l.amountCents, 0);
6599
+ const returned = lines.filter((l) => l.type === "RESTORE").reduce((sum, l) => sum + l.amountCents, 0);
6600
+ return spent - returned;
6601
+ }
6602
+ function changedUnderneath() {
6603
+ return new SchedulingValidationError("The gift certificate changed while it was being updated; try again", "SCHED_1703");
6604
+ }
6605
+ async function checkGiftCertificate(db, organizationId, code, now = /* @__PURE__ */ new Date()) {
6606
+ if (typeof code !== "string" || !looksLikeGiftCode(code)) return null;
6607
+ const row = await db.giftCertificate.findFirst({
6608
+ where: { organizationId, code: normalizeGiftCode(code) },
6609
+ select: { status: true, currency: true, balanceCents: true, expiresAt: true }
6610
+ });
6611
+ if (!row) return null;
6612
+ return { currency: row.currency, balanceCents: row.balanceCents, expiresAt: row.expiresAt, state: giftCertificateState(row, now) };
6613
+ }
6614
+ async function redeemGiftCertificate(db, organizationId, code, input, now = /* @__PURE__ */ new Date()) {
6615
+ const maxCents = requireAmount(input.maxCents, "maxCents");
6616
+ const currency = requireCurrency(input.currency);
6617
+ const appointmentId = optionalLinkText(input.appointmentId, "appointmentId");
6618
+ const note = optionalLinkText(input.note, "note");
6619
+ if (typeof code !== "string" || !looksLikeGiftCode(code)) throw notFound();
6620
+ const stored = normalizeGiftCode(code);
6621
+ return inTransaction(db, async (tx) => {
6622
+ await lockCertificate(tx, { organizationId, code: stored });
6623
+ const certificate = await tx.giftCertificate.findFirst({
6624
+ where: { organizationId, code: stored },
6625
+ select: { id: true, status: true, currency: true, balanceCents: true, ledgerSeq: true, expiresAt: true }
6626
+ });
6627
+ if (!certificate) throw notFound();
6628
+ const state = giftCertificateState(certificate, now);
6629
+ if (state !== "ACTIVE") throw new SchedulingValidationError(`This gift certificate cannot be used: it is ${state.toLowerCase().replace("_", " ")}`, "SCHED_1702", { reason: state });
6630
+ if (certificate.currency !== currency) {
6631
+ throw new SchedulingValidationError("This gift certificate is in a different currency from the bill", "SCHED_1708", { certificate: certificate.currency, bill: currency });
6632
+ }
6633
+ if (appointmentId) {
6634
+ const lines = await tx.giftCertificateTransaction.findMany({ where: { certificateId: certificate.id, appointmentId }, select: { type: true, amountCents: true } });
6635
+ if (netSpent(lines) > 0) throw new SchedulingValidationError("This gift certificate was already spent on this appointment", "SCHED_1707", { appointmentId });
6636
+ }
6637
+ const appliedCents = Math.min(certificate.balanceCents, maxCents);
6638
+ const balanceCents = certificate.balanceCents - appliedCents;
6639
+ const { count } = await tx.giftCertificate.updateMany({
6640
+ where: { id: certificate.id, organizationId, status: "ACTIVE", balanceCents: certificate.balanceCents },
6641
+ data: { balanceCents }
6642
+ });
6643
+ if (count === 0) throw changedUnderneath();
6644
+ const line = await tx.giftCertificateTransaction.create({
6645
+ data: { certificateId: certificate.id, organizationId, seq: certificate.ledgerSeq, type: "REDEEM", amountCents: -appliedCents, balanceAfterCents: balanceCents, appointmentId: appointmentId ?? null, note: note ?? null },
6646
+ select: { id: true }
6647
+ });
6648
+ return { certificateId: certificate.id, transactionId: line.id, currency, appliedCents, balanceCents };
6649
+ });
6650
+ }
6651
+ async function restoreGiftCertificate(db, organizationId, certificateId, input, userId) {
6652
+ const amountCents = requireAmount(input.amountCents, "amountCents");
6653
+ const appointmentId = optionalLinkText(input.appointmentId, "appointmentId");
6654
+ const note = optionalLinkText(input.note, "note");
6655
+ if (!isBoundedText(certificateId)) throw notFound();
6656
+ return inTransaction(db, async (tx) => {
6657
+ await lockCertificate(tx, { organizationId, id: certificateId });
6658
+ const certificate = await tx.giftCertificate.findFirst({
6659
+ where: { id: certificateId, organizationId },
6660
+ select: { id: true, status: true, balanceCents: true, initialCents: true, ledgerSeq: true }
6661
+ });
6662
+ if (!certificate) throw notFound();
6663
+ if (certificate.status !== "ACTIVE") throw new SchedulingValidationError("This gift certificate is void", "SCHED_1702", { reason: "VOID" });
6664
+ if (appointmentId) {
6665
+ const lines = await tx.giftCertificateTransaction.findMany({ where: { certificateId, appointmentId }, select: { type: true, amountCents: true } });
6666
+ const returnable = netSpent(lines);
6667
+ if (amountCents > returnable) {
6668
+ throw new SchedulingValidationError("More was asked back than was spent on this appointment and not yet returned", "SCHED_1704", { returnable: Math.max(returnable, 0) });
6669
+ }
6670
+ }
6671
+ if (certificate.balanceCents + amountCents > certificate.initialCents) {
6672
+ throw new SchedulingValidationError("That would put the balance above what the certificate was issued for", "SCHED_1704", { room: certificate.initialCents - certificate.balanceCents });
6673
+ }
6674
+ const balanceCents = certificate.balanceCents + amountCents;
6675
+ const { count } = await tx.giftCertificate.updateMany({
6676
+ where: { id: certificateId, organizationId, status: "ACTIVE", balanceCents: certificate.balanceCents },
6677
+ data: { balanceCents }
6678
+ });
6679
+ if (count === 0) throw changedUnderneath();
6680
+ const line = await tx.giftCertificateTransaction.create({
6681
+ data: { certificateId, organizationId, seq: certificate.ledgerSeq, type: "RESTORE", amountCents, balanceAfterCents: balanceCents, appointmentId: appointmentId ?? null, note: note ?? null, createdByUserId: userId ?? null },
6682
+ select: { id: true }
6683
+ });
6684
+ return { certificateId, transactionId: line.id, restoredCents: amountCents, balanceCents };
6685
+ });
6686
+ }
6068
6687
  export {
6688
+ API_KEY_ACCESS,
6689
+ API_KEY_FIELDS,
6690
+ API_KEY_NAME_MAX,
6069
6691
  BRAND_FIELDS,
6070
6692
  BlockedTargetError,
6071
6693
  DEFAULT_BACKOFF_SECONDS,
6694
+ DEFAULT_LIST_LIMIT,
6072
6695
  DEFAULT_OFFER_MINUTES,
6073
6696
  ERASED_EMAIL,
6074
6697
  ERASED_NAME,
6698
+ GIFT_CERTIFICATE_FIELDS,
6699
+ GIFT_CERTIFICATE_STATUS,
6700
+ GIFT_TRANSACTION_TYPES,
6701
+ MAX_ACTIVE_API_KEYS,
6075
6702
  MAX_ENDPOINTS_PER_ORGANIZATION,
6703
+ MAX_GIFT_CENTS,
6704
+ MAX_HISTORY_LINES,
6705
+ MAX_LIST_LIMIT,
6076
6706
  MAX_WAITING_PER_TYPE_DAY,
6707
+ MIN_GIFT_CENTS,
6077
6708
  OPERATORS_BY_TYPE,
6078
6709
  RECURRING_MAX_OCCURRENCES,
6079
6710
  LIMITS as ROUTING_LIMITS,
@@ -6105,10 +6736,12 @@ export {
6105
6736
  checkAuthContract,
6106
6737
  checkCalendarSyncContract,
6107
6738
  checkClockContract,
6739
+ checkGiftCertificate,
6108
6740
  checkNotificationContract,
6109
6741
  checkPaymentContract,
6110
6742
  checkWebhookUrl,
6111
6743
  completeWaitlistAccept,
6744
+ createApiKey,
6112
6745
  createAppointmentType,
6113
6746
  createCalendar,
6114
6747
  createInMemoryAdapters,
@@ -6129,6 +6762,7 @@ export {
6129
6762
  eraseSubject,
6130
6763
  expireWaitlistOffers,
6131
6764
  exportSubject,
6765
+ formatGiftCode,
6132
6766
  generateOccurrenceDates,
6133
6767
  generateWebhookSecret,
6134
6768
  getAppointment,
@@ -6140,6 +6774,7 @@ export {
6140
6774
  getBookingAnalytics,
6141
6775
  getBrand,
6142
6776
  getCalendar,
6777
+ getGiftCertificate,
6143
6778
  getGroupCapacity,
6144
6779
  getGroupSessions,
6145
6780
  getNotificationTemplate,
@@ -6150,15 +6785,20 @@ export {
6150
6785
  getTextSettings,
6151
6786
  getUserDayAppointments,
6152
6787
  getWaitlistOffer,
6788
+ giftCertificateState,
6153
6789
  isPrivateAddress,
6154
6790
  isSlotAvailable,
6155
6791
  isVirtualMeeting,
6792
+ issueGiftCertificate,
6793
+ issueGiftCertificateOnce,
6156
6794
  joinWaitlist,
6157
6795
  leaveWaitlist,
6796
+ listApiKeys,
6158
6797
  listAppointmentTypes,
6159
6798
  listAppointments,
6160
6799
  listAvailabilityRules,
6161
6800
  listCalendars,
6801
+ listGiftCertificates,
6162
6802
  listNotificationTemplates,
6163
6803
  listPrivacyRequests,
6164
6804
  listRoutingForms,
@@ -6167,8 +6807,11 @@ export {
6167
6807
  listWebhookEndpoints,
6168
6808
  localDay,
6169
6809
  localToUTC,
6810
+ looksLikeApiKey,
6811
+ looksLikeGiftCode,
6170
6812
  markNoShow,
6171
6813
  matchingRules,
6814
+ normalizeGiftCode,
6172
6815
  normalizeTextNumber,
6173
6816
  offerFreedSlot,
6174
6817
  parseSubject,
@@ -6177,6 +6820,7 @@ export {
6177
6820
  processPendingNotifications,
6178
6821
  queueImmediateNotification,
6179
6822
  queueStaffNotification,
6823
+ redeemGiftCertificate,
6180
6824
  releaseWaitlistAccept,
6181
6825
  removeDateOverride,
6182
6826
  removeWaitlistEntry,
@@ -6185,7 +6829,9 @@ export {
6185
6829
  resolveDestination,
6186
6830
  resolveLocation,
6187
6831
  resolveSubject,
6832
+ restoreGiftCertificate,
6188
6833
  retryWebhookDelivery,
6834
+ revokeApiKey,
6189
6835
  routeClient,
6190
6836
  saveBrand,
6191
6837
  saveTextSettings,
@@ -6206,11 +6852,15 @@ export {
6206
6852
  updateCalendar,
6207
6853
  updateNotificationTemplate,
6208
6854
  updateRoutingForm,
6855
+ validateApiKeyRequest,
6209
6856
  validateBrand,
6857
+ validateGiftCertificateRequest,
6210
6858
  validateRoutingDestinations,
6211
6859
  validateRoutingStructure,
6212
6860
  validateTextSettings,
6861
+ verifyApiKey,
6213
6862
  verifyWebhookSignature,
6863
+ voidGiftCertificate,
6214
6864
  withCalendarVisibility,
6215
6865
  withOrganization
6216
6866
  };