@ordinatio/scheduling 0.7.0 → 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.js CHANGED
@@ -36,12 +36,20 @@ __export(index_exports, {
36
36
  BRAND_FIELDS: () => BRAND_FIELDS,
37
37
  BlockedTargetError: () => BlockedTargetError,
38
38
  DEFAULT_BACKOFF_SECONDS: () => DEFAULT_BACKOFF_SECONDS,
39
+ DEFAULT_LIST_LIMIT: () => DEFAULT_LIST_LIMIT,
39
40
  DEFAULT_OFFER_MINUTES: () => DEFAULT_OFFER_MINUTES,
40
41
  ERASED_EMAIL: () => ERASED_EMAIL,
41
42
  ERASED_NAME: () => ERASED_NAME,
43
+ GIFT_CERTIFICATE_FIELDS: () => GIFT_CERTIFICATE_FIELDS,
44
+ GIFT_CERTIFICATE_STATUS: () => GIFT_CERTIFICATE_STATUS,
45
+ GIFT_TRANSACTION_TYPES: () => GIFT_TRANSACTION_TYPES,
42
46
  MAX_ACTIVE_API_KEYS: () => MAX_ACTIVE_API_KEYS,
43
47
  MAX_ENDPOINTS_PER_ORGANIZATION: () => MAX_ENDPOINTS_PER_ORGANIZATION,
48
+ MAX_GIFT_CENTS: () => MAX_GIFT_CENTS,
49
+ MAX_HISTORY_LINES: () => MAX_HISTORY_LINES,
50
+ MAX_LIST_LIMIT: () => MAX_LIST_LIMIT,
44
51
  MAX_WAITING_PER_TYPE_DAY: () => MAX_WAITING_PER_TYPE_DAY,
52
+ MIN_GIFT_CENTS: () => MIN_GIFT_CENTS,
45
53
  OPERATORS_BY_TYPE: () => OPERATORS_BY_TYPE,
46
54
  RECURRING_MAX_OCCURRENCES: () => RECURRING_MAX_OCCURRENCES,
47
55
  ROUTING_LIMITS: () => LIMITS,
@@ -73,6 +81,7 @@ __export(index_exports, {
73
81
  checkAuthContract: () => checkAuthContract,
74
82
  checkCalendarSyncContract: () => checkCalendarSyncContract,
75
83
  checkClockContract: () => checkClockContract,
84
+ checkGiftCertificate: () => checkGiftCertificate,
76
85
  checkNotificationContract: () => checkNotificationContract,
77
86
  checkPaymentContract: () => checkPaymentContract,
78
87
  checkWebhookUrl: () => checkWebhookUrl,
@@ -98,6 +107,7 @@ __export(index_exports, {
98
107
  eraseSubject: () => eraseSubject,
99
108
  expireWaitlistOffers: () => expireWaitlistOffers,
100
109
  exportSubject: () => exportSubject,
110
+ formatGiftCode: () => formatGiftCode,
101
111
  generateOccurrenceDates: () => generateOccurrenceDates,
102
112
  generateWebhookSecret: () => generateWebhookSecret,
103
113
  getAppointment: () => getAppointment,
@@ -109,6 +119,7 @@ __export(index_exports, {
109
119
  getBookingAnalytics: () => getBookingAnalytics,
110
120
  getBrand: () => getBrand,
111
121
  getCalendar: () => getCalendar,
122
+ getGiftCertificate: () => getGiftCertificate,
112
123
  getGroupCapacity: () => getGroupCapacity,
113
124
  getGroupSessions: () => getGroupSessions,
114
125
  getNotificationTemplate: () => getNotificationTemplate,
@@ -119,9 +130,12 @@ __export(index_exports, {
119
130
  getTextSettings: () => getTextSettings,
120
131
  getUserDayAppointments: () => getUserDayAppointments,
121
132
  getWaitlistOffer: () => getWaitlistOffer,
133
+ giftCertificateState: () => giftCertificateState,
122
134
  isPrivateAddress: () => isPrivateAddress,
123
135
  isSlotAvailable: () => isSlotAvailable,
124
136
  isVirtualMeeting: () => isVirtualMeeting,
137
+ issueGiftCertificate: () => issueGiftCertificate,
138
+ issueGiftCertificateOnce: () => issueGiftCertificateOnce,
125
139
  joinWaitlist: () => joinWaitlist,
126
140
  leaveWaitlist: () => leaveWaitlist,
127
141
  listApiKeys: () => listApiKeys,
@@ -129,6 +143,7 @@ __export(index_exports, {
129
143
  listAppointments: () => listAppointments,
130
144
  listAvailabilityRules: () => listAvailabilityRules,
131
145
  listCalendars: () => listCalendars,
146
+ listGiftCertificates: () => listGiftCertificates,
132
147
  listNotificationTemplates: () => listNotificationTemplates,
133
148
  listPrivacyRequests: () => listPrivacyRequests,
134
149
  listRoutingForms: () => listRoutingForms,
@@ -138,8 +153,10 @@ __export(index_exports, {
138
153
  localDay: () => localDay,
139
154
  localToUTC: () => localToUTC,
140
155
  looksLikeApiKey: () => looksLikeApiKey,
156
+ looksLikeGiftCode: () => looksLikeGiftCode,
141
157
  markNoShow: () => markNoShow,
142
158
  matchingRules: () => matchingRules,
159
+ normalizeGiftCode: () => normalizeGiftCode,
143
160
  normalizeTextNumber: () => normalizeTextNumber,
144
161
  offerFreedSlot: () => offerFreedSlot,
145
162
  parseSubject: () => parseSubject,
@@ -148,6 +165,7 @@ __export(index_exports, {
148
165
  processPendingNotifications: () => processPendingNotifications,
149
166
  queueImmediateNotification: () => queueImmediateNotification,
150
167
  queueStaffNotification: () => queueStaffNotification,
168
+ redeemGiftCertificate: () => redeemGiftCertificate,
151
169
  releaseWaitlistAccept: () => releaseWaitlistAccept,
152
170
  removeDateOverride: () => removeDateOverride,
153
171
  removeWaitlistEntry: () => removeWaitlistEntry,
@@ -156,6 +174,7 @@ __export(index_exports, {
156
174
  resolveDestination: () => resolveDestination,
157
175
  resolveLocation: () => resolveLocation,
158
176
  resolveSubject: () => resolveSubject,
177
+ restoreGiftCertificate: () => restoreGiftCertificate,
159
178
  retryWebhookDelivery: () => retryWebhookDelivery,
160
179
  revokeApiKey: () => revokeApiKey,
161
180
  routeClient: () => routeClient,
@@ -180,11 +199,13 @@ __export(index_exports, {
180
199
  updateRoutingForm: () => updateRoutingForm,
181
200
  validateApiKeyRequest: () => validateApiKeyRequest,
182
201
  validateBrand: () => validateBrand,
202
+ validateGiftCertificateRequest: () => validateGiftCertificateRequest,
183
203
  validateRoutingDestinations: () => validateRoutingDestinations,
184
204
  validateRoutingStructure: () => validateRoutingStructure,
185
205
  validateTextSettings: () => validateTextSettings,
186
206
  verifyApiKey: () => verifyApiKey,
187
207
  verifyWebhookSignature: () => verifyWebhookSignature,
208
+ voidGiftCertificate: () => voidGiftCertificate,
188
209
  withCalendarVisibility: () => withCalendarVisibility,
189
210
  withOrganization: () => withOrganization
190
211
  });
@@ -1382,6 +1403,150 @@ var API_KEY_ERRORS = {
1382
1403
  }
1383
1404
  };
1384
1405
 
1406
+ // src/errors/registry-gift-certificates.ts
1407
+ var GIFT_CERTIFICATE_ERRORS = {
1408
+ SCHED_1700: {
1409
+ code: "SCHED_1700",
1410
+ file: "gift-certificates/",
1411
+ function: "validateGiftCertificateRequest",
1412
+ severity: "warning",
1413
+ recoverable: true,
1414
+ description: "The gift certificate request is not valid",
1415
+ diagnosis: [
1416
+ "Read the list of problems in the error context: each names the field and what is wrong",
1417
+ "An amount is a whole number of cents between 100 and 1000000; an expiry must be in the future"
1418
+ ]
1419
+ },
1420
+ SCHED_1702: {
1421
+ code: "SCHED_1702",
1422
+ file: "gift-certificates/",
1423
+ function: "redeemGiftCertificate",
1424
+ severity: "warning",
1425
+ recoverable: true,
1426
+ description: "The gift certificate cannot be used: it is void, expired or used up",
1427
+ diagnosis: [
1428
+ "The context names the reason: VOID, EXPIRED or USED_UP",
1429
+ "A voided certificate cannot be spent or topped up; issue a new one if the client is owed value"
1430
+ ]
1431
+ },
1432
+ SCHED_1703: {
1433
+ code: "SCHED_1703",
1434
+ file: "gift-certificates/",
1435
+ function: "redeemGiftCertificate",
1436
+ severity: "warning",
1437
+ recoverable: true,
1438
+ description: "The gift certificate changed while it was being updated",
1439
+ diagnosis: [
1440
+ "The certificate is locked for each change, so this should not happen; nothing was taken and the request is safe to repeat",
1441
+ "If it repeats, check that the database handle really is a transaction and that nothing else writes the certificate table"
1442
+ ]
1443
+ },
1444
+ SCHED_1704: {
1445
+ code: "SCHED_1704",
1446
+ file: "gift-certificates/",
1447
+ function: "restoreGiftCertificate",
1448
+ severity: "warning",
1449
+ recoverable: true,
1450
+ description: "More was asked to be given back than the certificate or the appointment allows",
1451
+ diagnosis: [
1452
+ "With an appointment, only what was spent on it and not yet returned can come back; a repeated refund returns nothing more",
1453
+ "Without one, the balance cannot rise above the amount the certificate was issued for"
1454
+ ]
1455
+ },
1456
+ SCHED_1705: {
1457
+ code: "SCHED_1705",
1458
+ file: "gift-certificates/",
1459
+ function: "issueGiftCertificate",
1460
+ severity: "error",
1461
+ recoverable: true,
1462
+ description: "A unique gift certificate code could not be made",
1463
+ diagnosis: [
1464
+ "Five random codes in a row already existed, which should not happen: check that the code generator has not been replaced"
1465
+ ]
1466
+ },
1467
+ SCHED_1706: {
1468
+ code: "SCHED_1706",
1469
+ file: "gift-certificates/",
1470
+ function: "redeemGiftCertificate",
1471
+ severity: "warning",
1472
+ recoverable: true,
1473
+ description: "The amount is not a positive whole number of cents",
1474
+ diagnosis: [
1475
+ "Amounts are whole cents: 1250 means 12.50; decimals, zero and negative values are refused"
1476
+ ]
1477
+ },
1478
+ SCHED_1707: {
1479
+ code: "SCHED_1707",
1480
+ file: "gift-certificates/",
1481
+ function: "redeemGiftCertificate",
1482
+ severity: "warning",
1483
+ recoverable: true,
1484
+ description: "This gift certificate was already spent on this appointment and not given back",
1485
+ diagnosis: [
1486
+ "A booking that is retried would otherwise spend the certificate twice; the first spend stands",
1487
+ "If the first spend was given back in full, spending again on the same appointment is allowed",
1488
+ "Read the certificate history to see the earlier lines"
1489
+ ]
1490
+ },
1491
+ SCHED_1708: {
1492
+ code: "SCHED_1708",
1493
+ file: "gift-certificates/",
1494
+ function: "redeemGiftCertificate",
1495
+ severity: "warning",
1496
+ recoverable: true,
1497
+ description: "The gift certificate is in a different currency from the bill",
1498
+ diagnosis: [
1499
+ "The context names both currencies; a certificate only pays a bill in its own currency"
1500
+ ]
1501
+ },
1502
+ SCHED_1709: {
1503
+ code: "SCHED_1709",
1504
+ file: "gift-certificates/",
1505
+ function: "redeemGiftCertificate",
1506
+ severity: "warning",
1507
+ recoverable: true,
1508
+ description: "An appointment id, note or currency given with the request is not valid",
1509
+ diagnosis: [
1510
+ "The context names the field; ids and currencies are non-empty text, a note is at most 500 characters"
1511
+ ]
1512
+ },
1513
+ SCHED_1710: {
1514
+ code: "SCHED_1710",
1515
+ file: "gift-certificates/",
1516
+ function: "issueGiftCertificate",
1517
+ severity: "warning",
1518
+ recoverable: true,
1519
+ description: "This payment already made a gift certificate of a different amount or currency",
1520
+ diagnosis: [
1521
+ "A payment makes one certificate; asking for another with a different amount or currency is a mistake in the caller, not a repeat",
1522
+ "Check which payment id the request carries; a genuine repeat must ask for the same amount and currency"
1523
+ ]
1524
+ },
1525
+ SCHED_1711: {
1526
+ code: "SCHED_1711",
1527
+ file: "gift-certificates/",
1528
+ function: "inTransaction",
1529
+ severity: "error",
1530
+ recoverable: false,
1531
+ description: "The database handle is neither a client nor an open transaction",
1532
+ diagnosis: [
1533
+ "Pass the Prisma client, or the client a transaction callback receives; a bare object would run without the certificate lock"
1534
+ ]
1535
+ },
1536
+ SCHED_1712: {
1537
+ code: "SCHED_1712",
1538
+ file: "gift-certificates/",
1539
+ function: "getGiftCertificate",
1540
+ severity: "warning",
1541
+ recoverable: true,
1542
+ description: "No gift certificate of this business matches",
1543
+ diagnosis: [
1544
+ "The same answer is given for an unknown code, a malformed code and a code that belongs to another business",
1545
+ "Check the code as typed, including that it belongs to this business"
1546
+ ]
1547
+ }
1548
+ };
1549
+
1385
1550
  // src/errors/registry.ts
1386
1551
  var SCHEDULING_ERRORS = {
1387
1552
  ...CALENDARS_AVAILABILITY_ERRORS,
@@ -1398,7 +1563,8 @@ var SCHEDULING_ERRORS = {
1398
1563
  ...PRIVACY_ERRORS,
1399
1564
  ...BRAND_ERRORS,
1400
1565
  ...TEXT_SETTINGS_ERRORS,
1401
- ...API_KEY_ERRORS
1566
+ ...API_KEY_ERRORS,
1567
+ ...GIFT_CERTIFICATE_ERRORS
1402
1568
  };
1403
1569
 
1404
1570
  // src/errors/diagnostic-error.ts
@@ -6381,6 +6547,356 @@ async function verifyApiKey(db, secret) {
6381
6547
  }
6382
6548
  return { id: row.id, organizationId: row.organizationId, access: row.access, createdByUserId: row.createdByUserId };
6383
6549
  }
6550
+
6551
+ // src/gift-certificates/types.ts
6552
+ var GIFT_CERTIFICATE_STATUS = ["ACTIVE", "VOID"];
6553
+ var GIFT_TRANSACTION_TYPES = ["ISSUE", "REDEEM", "RESTORE", "VOID"];
6554
+ var GIFT_CERTIFICATE_FIELDS = [
6555
+ "amountCents",
6556
+ "currency",
6557
+ "expiresAt",
6558
+ "recipientName",
6559
+ "recipientEmail",
6560
+ "purchaserName",
6561
+ "purchaserEmail",
6562
+ "message",
6563
+ "paymentId",
6564
+ "notes"
6565
+ ];
6566
+ var MIN_GIFT_CENTS = 100;
6567
+ var MAX_GIFT_CENTS = 1e6;
6568
+ var GIFT_NAME_MAX = 120;
6569
+ var GIFT_MESSAGE_MAX = 500;
6570
+ var GIFT_NOTES_MAX = 1e3;
6571
+ var GIFT_EMAIL_MAX = 254;
6572
+
6573
+ // src/gift-certificates/code.ts
6574
+ var import_node_crypto9 = require("crypto");
6575
+ var ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789";
6576
+ var GIFT_CODE_LENGTH = 12;
6577
+ var SHAPE = new RegExp(`^[${ALPHABET}]{${GIFT_CODE_LENGTH}}$`);
6578
+ var MAX_TYPED_LENGTH = 40;
6579
+ function generateGiftCode() {
6580
+ let code = "";
6581
+ for (let i = 0; i < GIFT_CODE_LENGTH; i += 1) code += ALPHABET[(0, import_node_crypto9.randomInt)(ALPHABET.length)];
6582
+ return code;
6583
+ }
6584
+ function normalizeGiftCode(input) {
6585
+ return input.toUpperCase().replace(/[\s-]+/g, "");
6586
+ }
6587
+ function looksLikeGiftCode(input) {
6588
+ return input.length <= MAX_TYPED_LENGTH && SHAPE.test(normalizeGiftCode(input));
6589
+ }
6590
+ function formatGiftCode(code) {
6591
+ return code.replace(/(.{4})(?=.)/g, "$1-");
6592
+ }
6593
+
6594
+ // src/gift-certificates/state.ts
6595
+ function giftCertificateState(certificate, now = /* @__PURE__ */ new Date()) {
6596
+ if (certificate.status !== "ACTIVE") return "VOID";
6597
+ if (certificate.expiresAt && certificate.expiresAt.getTime() <= now.getTime()) return "EXPIRED";
6598
+ if (certificate.balanceCents <= 0) return "USED_UP";
6599
+ return "ACTIVE";
6600
+ }
6601
+
6602
+ // src/gift-certificates/validate.ts
6603
+ var EMAIL3 = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
6604
+ function optionalText(given, field, max, problems, pattern, patternMessage) {
6605
+ const value = given[field];
6606
+ if (value === void 0 || value === null) return null;
6607
+ if (typeof value !== "string") {
6608
+ problems.push({ path: field, message: "Must be text" });
6609
+ return null;
6610
+ }
6611
+ const text2 = value.trim();
6612
+ if (text2 === "") return null;
6613
+ if (text2.length > max) {
6614
+ problems.push({ path: field, message: `Must be at most ${max} characters` });
6615
+ return null;
6616
+ }
6617
+ if (pattern && !pattern.test(text2)) {
6618
+ problems.push({ path: field, message: patternMessage ?? "Not valid" });
6619
+ return null;
6620
+ }
6621
+ return text2;
6622
+ }
6623
+ function expiryOf(value, now, problems) {
6624
+ if (value === void 0 || value === null) return null;
6625
+ const date = value instanceof Date ? value : typeof value === "string" ? new Date(value) : null;
6626
+ if (!date || Number.isNaN(date.getTime())) {
6627
+ problems.push({ path: "expiresAt", message: "Must be a date" });
6628
+ return null;
6629
+ }
6630
+ if (date.getTime() <= now.getTime()) {
6631
+ problems.push({ path: "expiresAt", message: "Must be in the future" });
6632
+ return null;
6633
+ }
6634
+ return date;
6635
+ }
6636
+ function validateGiftCertificateRequest(input, now = /* @__PURE__ */ new Date()) {
6637
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
6638
+ throw new SchedulingValidationError("The gift certificate request is not valid", "SCHED_1700", { errors: [{ path: "", message: "Must be an object" }] });
6639
+ }
6640
+ const given = input;
6641
+ const problems = [];
6642
+ for (const key of Object.keys(given)) if (!GIFT_CERTIFICATE_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
6643
+ let amountCents = 0;
6644
+ if (given.amountCents === void 0) problems.push({ path: "amountCents", message: "Required" });
6645
+ else if (typeof given.amountCents !== "number" || !Number.isInteger(given.amountCents)) problems.push({ path: "amountCents", message: "Must be a whole number of cents" });
6646
+ 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` });
6647
+ else amountCents = given.amountCents;
6648
+ let currency = "usd";
6649
+ if (given.currency !== void 0) {
6650
+ if (typeof given.currency !== "string" || !/^[A-Za-z]{3}$/.test(given.currency)) problems.push({ path: "currency", message: "Must be a three-letter currency code" });
6651
+ else currency = given.currency.toLowerCase();
6652
+ }
6653
+ const fields = {
6654
+ amountCents,
6655
+ currency,
6656
+ expiresAt: expiryOf(given.expiresAt, now, problems),
6657
+ recipientName: optionalText(given, "recipientName", GIFT_NAME_MAX, problems),
6658
+ recipientEmail: optionalText(given, "recipientEmail", GIFT_EMAIL_MAX, problems, EMAIL3, "Must be an email address")?.toLowerCase() ?? null,
6659
+ purchaserName: optionalText(given, "purchaserName", GIFT_NAME_MAX, problems),
6660
+ purchaserEmail: optionalText(given, "purchaserEmail", GIFT_EMAIL_MAX, problems, EMAIL3, "Must be an email address")?.toLowerCase() ?? null,
6661
+ message: optionalText(given, "message", GIFT_MESSAGE_MAX, problems),
6662
+ paymentId: optionalText(given, "paymentId", GIFT_NAME_MAX, problems),
6663
+ notes: optionalText(given, "notes", GIFT_NOTES_MAX, problems)
6664
+ };
6665
+ if (problems.length > 0) throw new SchedulingValidationError("The gift certificate request is not valid", "SCHED_1700", { errors: problems });
6666
+ return fields;
6667
+ }
6668
+
6669
+ // src/gift-certificates/guard.ts
6670
+ var TEXT_ID_MAX = 100;
6671
+ var NOTE_MAX = 500;
6672
+ function isBoundedText(value, max = TEXT_ID_MAX) {
6673
+ return typeof value === "string" && value.length > 0 && value.length <= max;
6674
+ }
6675
+ function notFound() {
6676
+ return new SchedulingNotFoundError("Gift certificate not found", "SCHED_1712");
6677
+ }
6678
+ function optionalLinkText(value, field) {
6679
+ if (value === void 0) return void 0;
6680
+ if (!isBoundedText(value, field === "note" ? NOTE_MAX : TEXT_ID_MAX)) {
6681
+ throw new SchedulingValidationError(`${field} must be non-empty text of reasonable length`, "SCHED_1709", { field });
6682
+ }
6683
+ return value;
6684
+ }
6685
+
6686
+ // src/gift-certificates/transaction.ts
6687
+ async function inTransaction(db, work) {
6688
+ const handle = typeof db === "object" && db !== null ? db : {};
6689
+ if (typeof handle.$transaction === "function") return withTransaction(db, work);
6690
+ if (typeof handle.$queryRaw === "function") return work(db);
6691
+ throw new SchedulingValidationError("The database handle is neither a client nor an open transaction", "SCHED_1711");
6692
+ }
6693
+ async function lockCertificate(tx, where) {
6694
+ const { count } = await tx.giftCertificate.updateMany({ where, data: { updatedAt: /* @__PURE__ */ new Date(), ledgerSeq: { increment: 1 } } });
6695
+ if (count === 0) throw notFound();
6696
+ }
6697
+
6698
+ // src/gift-certificates/crud.ts
6699
+ var CERTIFICATE_VIEW = {
6700
+ id: true,
6701
+ code: true,
6702
+ status: true,
6703
+ currency: true,
6704
+ initialCents: true,
6705
+ balanceCents: true,
6706
+ expiresAt: true,
6707
+ recipientName: true,
6708
+ recipientEmail: true,
6709
+ purchaserName: true,
6710
+ purchaserEmail: true,
6711
+ message: true,
6712
+ notes: true,
6713
+ paymentId: true,
6714
+ createdByUserId: true,
6715
+ createdAt: true
6716
+ };
6717
+ var LEDGER_VIEW = { id: true, seq: true, type: true, amountCents: true, balanceAfterCents: true, appointmentId: true, note: true, createdByUserId: true, createdAt: true };
6718
+ var CODE_ATTEMPTS = 5;
6719
+ var DEFAULT_LIST_LIMIT = 100;
6720
+ var MAX_LIST_LIMIT = 500;
6721
+ var MAX_HISTORY_LINES = 1e3;
6722
+ function isUniqueViolation2(error) {
6723
+ return typeof error === "object" && error !== null && error.code === "P2002";
6724
+ }
6725
+ async function issueGiftCertificateOnce(db, organizationId, input, createdByUserId) {
6726
+ const { amountCents, ...fields } = validateGiftCertificateRequest(input);
6727
+ const existingFor = async () => fields.paymentId ? await db.giftCertificate.findFirst({ where: { organizationId, paymentId: fields.paymentId }, select: CERTIFICATE_VIEW }) : null;
6728
+ const sameAs = (existing) => {
6729
+ if (existing.initialCents !== amountCents || existing.currency !== fields.currency) {
6730
+ throw new SchedulingValidationError("This payment already made a gift certificate of a different amount or currency", "SCHED_1710", { paymentId: fields.paymentId });
6731
+ }
6732
+ return { certificate: existing, created: false };
6733
+ };
6734
+ const earlier = await existingFor();
6735
+ if (earlier) return sameAs(earlier);
6736
+ for (let attempt = 0; attempt < CODE_ATTEMPTS; attempt += 1) {
6737
+ try {
6738
+ const certificate = await inTransaction(db, async (tx) => {
6739
+ const row = await tx.giftCertificate.create({
6740
+ data: { ...fields, organizationId, code: generateGiftCode(), initialCents: amountCents, balanceCents: amountCents, ledgerSeq: 1, createdByUserId: createdByUserId ?? null },
6741
+ select: CERTIFICATE_VIEW
6742
+ });
6743
+ await tx.giftCertificateTransaction.create({
6744
+ data: { certificateId: row.id, organizationId, seq: 1, type: "ISSUE", amountCents, balanceAfterCents: amountCents, createdByUserId: createdByUserId ?? null }
6745
+ });
6746
+ return row;
6747
+ });
6748
+ return { certificate, created: true };
6749
+ } catch (error) {
6750
+ if (!isUniqueViolation2(error)) throw error;
6751
+ const concurrent = await existingFor();
6752
+ if (concurrent) return sameAs(concurrent);
6753
+ }
6754
+ }
6755
+ throw new SchedulingValidationError("Could not make a unique gift certificate code", "SCHED_1705", { attempts: CODE_ATTEMPTS });
6756
+ }
6757
+ async function issueGiftCertificate(db, organizationId, input, createdByUserId) {
6758
+ return (await issueGiftCertificateOnce(db, organizationId, input, createdByUserId)).certificate;
6759
+ }
6760
+ async function listGiftCertificates(db, organizationId, options = {}) {
6761
+ const asked = Math.trunc(options.limit ?? Number.NaN);
6762
+ const limit = asked >= 1 ? Math.min(asked, MAX_LIST_LIMIT) : DEFAULT_LIST_LIMIT;
6763
+ return db.giftCertificate.findMany({
6764
+ where: { organizationId, ...options.status ? { status: options.status } : {} },
6765
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
6766
+ take: limit,
6767
+ select: CERTIFICATE_VIEW
6768
+ });
6769
+ }
6770
+ async function getGiftCertificate(db, organizationId, id) {
6771
+ if (!isBoundedText(id)) throw new SchedulingNotFoundError("Gift certificate not found", "SCHED_1712");
6772
+ const certificate = await db.giftCertificate.findFirst({ where: { id, organizationId }, select: CERTIFICATE_VIEW });
6773
+ if (!certificate) throw new SchedulingNotFoundError("Gift certificate not found", "SCHED_1712");
6774
+ const lines = await db.giftCertificateTransaction.findMany({
6775
+ where: { certificateId: id, organizationId },
6776
+ orderBy: { seq: "asc" },
6777
+ take: MAX_HISTORY_LINES + 1,
6778
+ select: LEDGER_VIEW
6779
+ });
6780
+ return { certificate, transactions: lines.slice(0, MAX_HISTORY_LINES), truncated: lines.length > MAX_HISTORY_LINES };
6781
+ }
6782
+ async function voidGiftCertificate(db, organizationId, id, userId) {
6783
+ if (!isBoundedText(id)) return false;
6784
+ return inTransaction(db, async (tx) => {
6785
+ const { count } = await tx.giftCertificate.updateMany({ where: { id, organizationId, status: "ACTIVE" }, data: { status: "VOID", ledgerSeq: { increment: 1 } } });
6786
+ if (count === 0) return false;
6787
+ const row = await tx.giftCertificate.findFirst({ where: { id, organizationId }, select: { balanceCents: true, ledgerSeq: true } });
6788
+ if (!row) throw new SchedulingNotFoundError("Gift certificate not found", "SCHED_1712");
6789
+ await tx.giftCertificateTransaction.create({
6790
+ data: { certificateId: id, organizationId, seq: row.ledgerSeq, type: "VOID", amountCents: 0, balanceAfterCents: row.balanceCents, createdByUserId: userId ?? null }
6791
+ });
6792
+ return true;
6793
+ });
6794
+ }
6795
+
6796
+ // src/gift-certificates/redeem.ts
6797
+ var MAX_AMOUNT_CENTS = 2e9;
6798
+ function requireAmount(value, field) {
6799
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > MAX_AMOUNT_CENTS) {
6800
+ throw new SchedulingValidationError("The amount must be a positive whole number of cents", "SCHED_1706", { field });
6801
+ }
6802
+ return value;
6803
+ }
6804
+ function requireCurrency(value) {
6805
+ if (typeof value !== "string" || !/^[A-Za-z]{3}$/.test(value)) {
6806
+ throw new SchedulingValidationError("The currency must be a three-letter code", "SCHED_1709", { field: "currency" });
6807
+ }
6808
+ return value.toLowerCase();
6809
+ }
6810
+ function netSpent(lines) {
6811
+ const spent = lines.filter((l) => l.type === "REDEEM").reduce((sum, l) => sum - l.amountCents, 0);
6812
+ const returned = lines.filter((l) => l.type === "RESTORE").reduce((sum, l) => sum + l.amountCents, 0);
6813
+ return spent - returned;
6814
+ }
6815
+ function changedUnderneath() {
6816
+ return new SchedulingValidationError("The gift certificate changed while it was being updated; try again", "SCHED_1703");
6817
+ }
6818
+ async function checkGiftCertificate(db, organizationId, code, now = /* @__PURE__ */ new Date()) {
6819
+ if (typeof code !== "string" || !looksLikeGiftCode(code)) return null;
6820
+ const row = await db.giftCertificate.findFirst({
6821
+ where: { organizationId, code: normalizeGiftCode(code) },
6822
+ select: { status: true, currency: true, balanceCents: true, expiresAt: true }
6823
+ });
6824
+ if (!row) return null;
6825
+ return { currency: row.currency, balanceCents: row.balanceCents, expiresAt: row.expiresAt, state: giftCertificateState(row, now) };
6826
+ }
6827
+ async function redeemGiftCertificate(db, organizationId, code, input, now = /* @__PURE__ */ new Date()) {
6828
+ const maxCents = requireAmount(input.maxCents, "maxCents");
6829
+ const currency = requireCurrency(input.currency);
6830
+ const appointmentId = optionalLinkText(input.appointmentId, "appointmentId");
6831
+ const note = optionalLinkText(input.note, "note");
6832
+ if (typeof code !== "string" || !looksLikeGiftCode(code)) throw notFound();
6833
+ const stored = normalizeGiftCode(code);
6834
+ return inTransaction(db, async (tx) => {
6835
+ await lockCertificate(tx, { organizationId, code: stored });
6836
+ const certificate = await tx.giftCertificate.findFirst({
6837
+ where: { organizationId, code: stored },
6838
+ select: { id: true, status: true, currency: true, balanceCents: true, ledgerSeq: true, expiresAt: true }
6839
+ });
6840
+ if (!certificate) throw notFound();
6841
+ const state = giftCertificateState(certificate, now);
6842
+ if (state !== "ACTIVE") throw new SchedulingValidationError(`This gift certificate cannot be used: it is ${state.toLowerCase().replace("_", " ")}`, "SCHED_1702", { reason: state });
6843
+ if (certificate.currency !== currency) {
6844
+ throw new SchedulingValidationError("This gift certificate is in a different currency from the bill", "SCHED_1708", { certificate: certificate.currency, bill: currency });
6845
+ }
6846
+ if (appointmentId) {
6847
+ const lines = await tx.giftCertificateTransaction.findMany({ where: { certificateId: certificate.id, appointmentId }, select: { type: true, amountCents: true } });
6848
+ if (netSpent(lines) > 0) throw new SchedulingValidationError("This gift certificate was already spent on this appointment", "SCHED_1707", { appointmentId });
6849
+ }
6850
+ const appliedCents = Math.min(certificate.balanceCents, maxCents);
6851
+ const balanceCents = certificate.balanceCents - appliedCents;
6852
+ const { count } = await tx.giftCertificate.updateMany({
6853
+ where: { id: certificate.id, organizationId, status: "ACTIVE", balanceCents: certificate.balanceCents },
6854
+ data: { balanceCents }
6855
+ });
6856
+ if (count === 0) throw changedUnderneath();
6857
+ const line = await tx.giftCertificateTransaction.create({
6858
+ data: { certificateId: certificate.id, organizationId, seq: certificate.ledgerSeq, type: "REDEEM", amountCents: -appliedCents, balanceAfterCents: balanceCents, appointmentId: appointmentId ?? null, note: note ?? null },
6859
+ select: { id: true }
6860
+ });
6861
+ return { certificateId: certificate.id, transactionId: line.id, currency, appliedCents, balanceCents };
6862
+ });
6863
+ }
6864
+ async function restoreGiftCertificate(db, organizationId, certificateId, input, userId) {
6865
+ const amountCents = requireAmount(input.amountCents, "amountCents");
6866
+ const appointmentId = optionalLinkText(input.appointmentId, "appointmentId");
6867
+ const note = optionalLinkText(input.note, "note");
6868
+ if (!isBoundedText(certificateId)) throw notFound();
6869
+ return inTransaction(db, async (tx) => {
6870
+ await lockCertificate(tx, { organizationId, id: certificateId });
6871
+ const certificate = await tx.giftCertificate.findFirst({
6872
+ where: { id: certificateId, organizationId },
6873
+ select: { id: true, status: true, balanceCents: true, initialCents: true, ledgerSeq: true }
6874
+ });
6875
+ if (!certificate) throw notFound();
6876
+ if (certificate.status !== "ACTIVE") throw new SchedulingValidationError("This gift certificate is void", "SCHED_1702", { reason: "VOID" });
6877
+ if (appointmentId) {
6878
+ const lines = await tx.giftCertificateTransaction.findMany({ where: { certificateId, appointmentId }, select: { type: true, amountCents: true } });
6879
+ const returnable = netSpent(lines);
6880
+ if (amountCents > returnable) {
6881
+ throw new SchedulingValidationError("More was asked back than was spent on this appointment and not yet returned", "SCHED_1704", { returnable: Math.max(returnable, 0) });
6882
+ }
6883
+ }
6884
+ if (certificate.balanceCents + amountCents > certificate.initialCents) {
6885
+ throw new SchedulingValidationError("That would put the balance above what the certificate was issued for", "SCHED_1704", { room: certificate.initialCents - certificate.balanceCents });
6886
+ }
6887
+ const balanceCents = certificate.balanceCents + amountCents;
6888
+ const { count } = await tx.giftCertificate.updateMany({
6889
+ where: { id: certificateId, organizationId, status: "ACTIVE", balanceCents: certificate.balanceCents },
6890
+ data: { balanceCents }
6891
+ });
6892
+ if (count === 0) throw changedUnderneath();
6893
+ const line = await tx.giftCertificateTransaction.create({
6894
+ data: { certificateId, organizationId, seq: certificate.ledgerSeq, type: "RESTORE", amountCents, balanceAfterCents: balanceCents, appointmentId: appointmentId ?? null, note: note ?? null, createdByUserId: userId ?? null },
6895
+ select: { id: true }
6896
+ });
6897
+ return { certificateId, transactionId: line.id, restoredCents: amountCents, balanceCents };
6898
+ });
6899
+ }
6384
6900
  // Annotate the CommonJS export names for ESM import in node:
6385
6901
  0 && (module.exports = {
6386
6902
  API_KEY_ACCESS,
@@ -6389,12 +6905,20 @@ async function verifyApiKey(db, secret) {
6389
6905
  BRAND_FIELDS,
6390
6906
  BlockedTargetError,
6391
6907
  DEFAULT_BACKOFF_SECONDS,
6908
+ DEFAULT_LIST_LIMIT,
6392
6909
  DEFAULT_OFFER_MINUTES,
6393
6910
  ERASED_EMAIL,
6394
6911
  ERASED_NAME,
6912
+ GIFT_CERTIFICATE_FIELDS,
6913
+ GIFT_CERTIFICATE_STATUS,
6914
+ GIFT_TRANSACTION_TYPES,
6395
6915
  MAX_ACTIVE_API_KEYS,
6396
6916
  MAX_ENDPOINTS_PER_ORGANIZATION,
6917
+ MAX_GIFT_CENTS,
6918
+ MAX_HISTORY_LINES,
6919
+ MAX_LIST_LIMIT,
6397
6920
  MAX_WAITING_PER_TYPE_DAY,
6921
+ MIN_GIFT_CENTS,
6398
6922
  OPERATORS_BY_TYPE,
6399
6923
  RECURRING_MAX_OCCURRENCES,
6400
6924
  ROUTING_LIMITS,
@@ -6426,6 +6950,7 @@ async function verifyApiKey(db, secret) {
6426
6950
  checkAuthContract,
6427
6951
  checkCalendarSyncContract,
6428
6952
  checkClockContract,
6953
+ checkGiftCertificate,
6429
6954
  checkNotificationContract,
6430
6955
  checkPaymentContract,
6431
6956
  checkWebhookUrl,
@@ -6451,6 +6976,7 @@ async function verifyApiKey(db, secret) {
6451
6976
  eraseSubject,
6452
6977
  expireWaitlistOffers,
6453
6978
  exportSubject,
6979
+ formatGiftCode,
6454
6980
  generateOccurrenceDates,
6455
6981
  generateWebhookSecret,
6456
6982
  getAppointment,
@@ -6462,6 +6988,7 @@ async function verifyApiKey(db, secret) {
6462
6988
  getBookingAnalytics,
6463
6989
  getBrand,
6464
6990
  getCalendar,
6991
+ getGiftCertificate,
6465
6992
  getGroupCapacity,
6466
6993
  getGroupSessions,
6467
6994
  getNotificationTemplate,
@@ -6472,9 +6999,12 @@ async function verifyApiKey(db, secret) {
6472
6999
  getTextSettings,
6473
7000
  getUserDayAppointments,
6474
7001
  getWaitlistOffer,
7002
+ giftCertificateState,
6475
7003
  isPrivateAddress,
6476
7004
  isSlotAvailable,
6477
7005
  isVirtualMeeting,
7006
+ issueGiftCertificate,
7007
+ issueGiftCertificateOnce,
6478
7008
  joinWaitlist,
6479
7009
  leaveWaitlist,
6480
7010
  listApiKeys,
@@ -6482,6 +7012,7 @@ async function verifyApiKey(db, secret) {
6482
7012
  listAppointments,
6483
7013
  listAvailabilityRules,
6484
7014
  listCalendars,
7015
+ listGiftCertificates,
6485
7016
  listNotificationTemplates,
6486
7017
  listPrivacyRequests,
6487
7018
  listRoutingForms,
@@ -6491,8 +7022,10 @@ async function verifyApiKey(db, secret) {
6491
7022
  localDay,
6492
7023
  localToUTC,
6493
7024
  looksLikeApiKey,
7025
+ looksLikeGiftCode,
6494
7026
  markNoShow,
6495
7027
  matchingRules,
7028
+ normalizeGiftCode,
6496
7029
  normalizeTextNumber,
6497
7030
  offerFreedSlot,
6498
7031
  parseSubject,
@@ -6501,6 +7034,7 @@ async function verifyApiKey(db, secret) {
6501
7034
  processPendingNotifications,
6502
7035
  queueImmediateNotification,
6503
7036
  queueStaffNotification,
7037
+ redeemGiftCertificate,
6504
7038
  releaseWaitlistAccept,
6505
7039
  removeDateOverride,
6506
7040
  removeWaitlistEntry,
@@ -6509,6 +7043,7 @@ async function verifyApiKey(db, secret) {
6509
7043
  resolveDestination,
6510
7044
  resolveLocation,
6511
7045
  resolveSubject,
7046
+ restoreGiftCertificate,
6512
7047
  retryWebhookDelivery,
6513
7048
  revokeApiKey,
6514
7049
  routeClient,
@@ -6533,11 +7068,13 @@ async function verifyApiKey(db, secret) {
6533
7068
  updateRoutingForm,
6534
7069
  validateApiKeyRequest,
6535
7070
  validateBrand,
7071
+ validateGiftCertificateRequest,
6536
7072
  validateRoutingDestinations,
6537
7073
  validateRoutingStructure,
6538
7074
  validateTextSettings,
6539
7075
  verifyApiKey,
6540
7076
  verifyWebhookSignature,
7077
+ voidGiftCertificate,
6541
7078
  withCalendarVisibility,
6542
7079
  withOrganization
6543
7080
  });