@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/CHANGELOG.md +12 -0
- package/dist/index.d.mts +210 -2
- package/dist/index.d.ts +210 -2
- package/dist/index.js +682 -1
- package/dist/index.mjs +651 -1
- package/package.json +1 -1
- package/prisma/migrations/20261118000000_organization_api_keys/migration.sql +24 -0
- package/prisma/migrations/20261119000000_gift_certificates/migration.sql +67 -0
- package/prisma/schema.prisma +76 -0
package/dist/index.js
CHANGED
|
@@ -30,14 +30,26 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
30
30
|
// src/index.ts
|
|
31
31
|
var index_exports = {};
|
|
32
32
|
__export(index_exports, {
|
|
33
|
+
API_KEY_ACCESS: () => API_KEY_ACCESS,
|
|
34
|
+
API_KEY_FIELDS: () => API_KEY_FIELDS,
|
|
35
|
+
API_KEY_NAME_MAX: () => API_KEY_NAME_MAX,
|
|
33
36
|
BRAND_FIELDS: () => BRAND_FIELDS,
|
|
34
37
|
BlockedTargetError: () => BlockedTargetError,
|
|
35
38
|
DEFAULT_BACKOFF_SECONDS: () => DEFAULT_BACKOFF_SECONDS,
|
|
39
|
+
DEFAULT_LIST_LIMIT: () => DEFAULT_LIST_LIMIT,
|
|
36
40
|
DEFAULT_OFFER_MINUTES: () => DEFAULT_OFFER_MINUTES,
|
|
37
41
|
ERASED_EMAIL: () => ERASED_EMAIL,
|
|
38
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,
|
|
46
|
+
MAX_ACTIVE_API_KEYS: () => MAX_ACTIVE_API_KEYS,
|
|
39
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,
|
|
40
51
|
MAX_WAITING_PER_TYPE_DAY: () => MAX_WAITING_PER_TYPE_DAY,
|
|
52
|
+
MIN_GIFT_CENTS: () => MIN_GIFT_CENTS,
|
|
41
53
|
OPERATORS_BY_TYPE: () => OPERATORS_BY_TYPE,
|
|
42
54
|
RECURRING_MAX_OCCURRENCES: () => RECURRING_MAX_OCCURRENCES,
|
|
43
55
|
ROUTING_LIMITS: () => LIMITS,
|
|
@@ -69,10 +81,12 @@ __export(index_exports, {
|
|
|
69
81
|
checkAuthContract: () => checkAuthContract,
|
|
70
82
|
checkCalendarSyncContract: () => checkCalendarSyncContract,
|
|
71
83
|
checkClockContract: () => checkClockContract,
|
|
84
|
+
checkGiftCertificate: () => checkGiftCertificate,
|
|
72
85
|
checkNotificationContract: () => checkNotificationContract,
|
|
73
86
|
checkPaymentContract: () => checkPaymentContract,
|
|
74
87
|
checkWebhookUrl: () => checkWebhookUrl,
|
|
75
88
|
completeWaitlistAccept: () => completeWaitlistAccept,
|
|
89
|
+
createApiKey: () => createApiKey,
|
|
76
90
|
createAppointmentType: () => createAppointmentType,
|
|
77
91
|
createCalendar: () => createCalendar,
|
|
78
92
|
createInMemoryAdapters: () => createInMemoryAdapters,
|
|
@@ -93,6 +107,7 @@ __export(index_exports, {
|
|
|
93
107
|
eraseSubject: () => eraseSubject,
|
|
94
108
|
expireWaitlistOffers: () => expireWaitlistOffers,
|
|
95
109
|
exportSubject: () => exportSubject,
|
|
110
|
+
formatGiftCode: () => formatGiftCode,
|
|
96
111
|
generateOccurrenceDates: () => generateOccurrenceDates,
|
|
97
112
|
generateWebhookSecret: () => generateWebhookSecret,
|
|
98
113
|
getAppointment: () => getAppointment,
|
|
@@ -104,6 +119,7 @@ __export(index_exports, {
|
|
|
104
119
|
getBookingAnalytics: () => getBookingAnalytics,
|
|
105
120
|
getBrand: () => getBrand,
|
|
106
121
|
getCalendar: () => getCalendar,
|
|
122
|
+
getGiftCertificate: () => getGiftCertificate,
|
|
107
123
|
getGroupCapacity: () => getGroupCapacity,
|
|
108
124
|
getGroupSessions: () => getGroupSessions,
|
|
109
125
|
getNotificationTemplate: () => getNotificationTemplate,
|
|
@@ -114,15 +130,20 @@ __export(index_exports, {
|
|
|
114
130
|
getTextSettings: () => getTextSettings,
|
|
115
131
|
getUserDayAppointments: () => getUserDayAppointments,
|
|
116
132
|
getWaitlistOffer: () => getWaitlistOffer,
|
|
133
|
+
giftCertificateState: () => giftCertificateState,
|
|
117
134
|
isPrivateAddress: () => isPrivateAddress,
|
|
118
135
|
isSlotAvailable: () => isSlotAvailable,
|
|
119
136
|
isVirtualMeeting: () => isVirtualMeeting,
|
|
137
|
+
issueGiftCertificate: () => issueGiftCertificate,
|
|
138
|
+
issueGiftCertificateOnce: () => issueGiftCertificateOnce,
|
|
120
139
|
joinWaitlist: () => joinWaitlist,
|
|
121
140
|
leaveWaitlist: () => leaveWaitlist,
|
|
141
|
+
listApiKeys: () => listApiKeys,
|
|
122
142
|
listAppointmentTypes: () => listAppointmentTypes,
|
|
123
143
|
listAppointments: () => listAppointments,
|
|
124
144
|
listAvailabilityRules: () => listAvailabilityRules,
|
|
125
145
|
listCalendars: () => listCalendars,
|
|
146
|
+
listGiftCertificates: () => listGiftCertificates,
|
|
126
147
|
listNotificationTemplates: () => listNotificationTemplates,
|
|
127
148
|
listPrivacyRequests: () => listPrivacyRequests,
|
|
128
149
|
listRoutingForms: () => listRoutingForms,
|
|
@@ -131,8 +152,11 @@ __export(index_exports, {
|
|
|
131
152
|
listWebhookEndpoints: () => listWebhookEndpoints,
|
|
132
153
|
localDay: () => localDay,
|
|
133
154
|
localToUTC: () => localToUTC,
|
|
155
|
+
looksLikeApiKey: () => looksLikeApiKey,
|
|
156
|
+
looksLikeGiftCode: () => looksLikeGiftCode,
|
|
134
157
|
markNoShow: () => markNoShow,
|
|
135
158
|
matchingRules: () => matchingRules,
|
|
159
|
+
normalizeGiftCode: () => normalizeGiftCode,
|
|
136
160
|
normalizeTextNumber: () => normalizeTextNumber,
|
|
137
161
|
offerFreedSlot: () => offerFreedSlot,
|
|
138
162
|
parseSubject: () => parseSubject,
|
|
@@ -141,6 +165,7 @@ __export(index_exports, {
|
|
|
141
165
|
processPendingNotifications: () => processPendingNotifications,
|
|
142
166
|
queueImmediateNotification: () => queueImmediateNotification,
|
|
143
167
|
queueStaffNotification: () => queueStaffNotification,
|
|
168
|
+
redeemGiftCertificate: () => redeemGiftCertificate,
|
|
144
169
|
releaseWaitlistAccept: () => releaseWaitlistAccept,
|
|
145
170
|
removeDateOverride: () => removeDateOverride,
|
|
146
171
|
removeWaitlistEntry: () => removeWaitlistEntry,
|
|
@@ -149,7 +174,9 @@ __export(index_exports, {
|
|
|
149
174
|
resolveDestination: () => resolveDestination,
|
|
150
175
|
resolveLocation: () => resolveLocation,
|
|
151
176
|
resolveSubject: () => resolveSubject,
|
|
177
|
+
restoreGiftCertificate: () => restoreGiftCertificate,
|
|
152
178
|
retryWebhookDelivery: () => retryWebhookDelivery,
|
|
179
|
+
revokeApiKey: () => revokeApiKey,
|
|
153
180
|
routeClient: () => routeClient,
|
|
154
181
|
saveBrand: () => saveBrand,
|
|
155
182
|
saveTextSettings: () => saveTextSettings,
|
|
@@ -170,11 +197,15 @@ __export(index_exports, {
|
|
|
170
197
|
updateCalendar: () => updateCalendar,
|
|
171
198
|
updateNotificationTemplate: () => updateNotificationTemplate,
|
|
172
199
|
updateRoutingForm: () => updateRoutingForm,
|
|
200
|
+
validateApiKeyRequest: () => validateApiKeyRequest,
|
|
173
201
|
validateBrand: () => validateBrand,
|
|
202
|
+
validateGiftCertificateRequest: () => validateGiftCertificateRequest,
|
|
174
203
|
validateRoutingDestinations: () => validateRoutingDestinations,
|
|
175
204
|
validateRoutingStructure: () => validateRoutingStructure,
|
|
176
205
|
validateTextSettings: () => validateTextSettings,
|
|
206
|
+
verifyApiKey: () => verifyApiKey,
|
|
177
207
|
verifyWebhookSignature: () => verifyWebhookSignature,
|
|
208
|
+
voidGiftCertificate: () => voidGiftCertificate,
|
|
178
209
|
withCalendarVisibility: () => withCalendarVisibility,
|
|
179
210
|
withOrganization: () => withOrganization
|
|
180
211
|
});
|
|
@@ -1333,6 +1364,189 @@ var TEXT_SETTINGS_ERRORS = {
|
|
|
1333
1364
|
}
|
|
1334
1365
|
};
|
|
1335
1366
|
|
|
1367
|
+
// src/errors/registry-api-keys.ts
|
|
1368
|
+
var API_KEY_ERRORS = {
|
|
1369
|
+
SCHED_1600: {
|
|
1370
|
+
code: "SCHED_1600",
|
|
1371
|
+
file: "api-keys/",
|
|
1372
|
+
function: "validateApiKeyRequest",
|
|
1373
|
+
severity: "warning",
|
|
1374
|
+
recoverable: true,
|
|
1375
|
+
description: "The API key request is not valid",
|
|
1376
|
+
diagnosis: [
|
|
1377
|
+
"Read the list of problems in the error context: each names the field and what is wrong",
|
|
1378
|
+
"A key needs a name of at most 60 characters and an access level of READ or FULL"
|
|
1379
|
+
]
|
|
1380
|
+
},
|
|
1381
|
+
SCHED_1601: {
|
|
1382
|
+
code: "SCHED_1601",
|
|
1383
|
+
file: "api-keys/",
|
|
1384
|
+
function: "createApiKey",
|
|
1385
|
+
severity: "warning",
|
|
1386
|
+
recoverable: true,
|
|
1387
|
+
description: "The business already has the most API keys it may have",
|
|
1388
|
+
diagnosis: [
|
|
1389
|
+
"Revoke a key that is no longer used, then create the new one"
|
|
1390
|
+
]
|
|
1391
|
+
},
|
|
1392
|
+
SCHED_1602: {
|
|
1393
|
+
code: "SCHED_1602",
|
|
1394
|
+
file: "api-keys/",
|
|
1395
|
+
function: "verifyApiKey",
|
|
1396
|
+
severity: "warning",
|
|
1397
|
+
recoverable: true,
|
|
1398
|
+
description: "An API key was accepted but the time it was last used could not be recorded",
|
|
1399
|
+
diagnosis: [
|
|
1400
|
+
'The key still worked; only the "last used" time is out of date',
|
|
1401
|
+
"Check that the database is reachable and the OrganizationApiKey table has been migrated"
|
|
1402
|
+
]
|
|
1403
|
+
}
|
|
1404
|
+
};
|
|
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
|
+
|
|
1336
1550
|
// src/errors/registry.ts
|
|
1337
1551
|
var SCHEDULING_ERRORS = {
|
|
1338
1552
|
...CALENDARS_AVAILABILITY_ERRORS,
|
|
@@ -1348,7 +1562,9 @@ var SCHEDULING_ERRORS = {
|
|
|
1348
1562
|
...ROUTING_ERRORS,
|
|
1349
1563
|
...PRIVACY_ERRORS,
|
|
1350
1564
|
...BRAND_ERRORS,
|
|
1351
|
-
...TEXT_SETTINGS_ERRORS
|
|
1565
|
+
...TEXT_SETTINGS_ERRORS,
|
|
1566
|
+
...API_KEY_ERRORS,
|
|
1567
|
+
...GIFT_CERTIFICATE_ERRORS
|
|
1352
1568
|
};
|
|
1353
1569
|
|
|
1354
1570
|
// src/errors/diagnostic-error.ts
|
|
@@ -6247,16 +6463,462 @@ async function deleteTextSettings(db, organizationId) {
|
|
|
6247
6463
|
const { count } = await db.organizationTextSettings.deleteMany({ where: { organizationId } });
|
|
6248
6464
|
return count > 0;
|
|
6249
6465
|
}
|
|
6466
|
+
|
|
6467
|
+
// src/api-keys/types.ts
|
|
6468
|
+
var API_KEY_ACCESS = ["READ", "FULL"];
|
|
6469
|
+
var API_KEY_FIELDS = ["name", "access"];
|
|
6470
|
+
var MAX_ACTIVE_API_KEYS = 25;
|
|
6471
|
+
var API_KEY_NAME_MAX = 60;
|
|
6472
|
+
|
|
6473
|
+
// src/api-keys/validate.ts
|
|
6474
|
+
function validateApiKeyRequest(input) {
|
|
6475
|
+
const problems = [];
|
|
6476
|
+
if (typeof input !== "object" || input === null || Array.isArray(input)) {
|
|
6477
|
+
throw new SchedulingValidationError("The API key request is not valid", "SCHED_1600", { errors: [{ path: "", message: "Must be an object" }] });
|
|
6478
|
+
}
|
|
6479
|
+
const given = input;
|
|
6480
|
+
for (const key of Object.keys(given)) if (!API_KEY_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
|
|
6481
|
+
let name = "";
|
|
6482
|
+
if (typeof given.name !== "string" || given.name.trim() === "") problems.push({ path: "name", message: "Required" });
|
|
6483
|
+
else if (given.name.trim().length > API_KEY_NAME_MAX) problems.push({ path: "name", message: `Must be at most ${API_KEY_NAME_MAX} characters` });
|
|
6484
|
+
else name = given.name.trim();
|
|
6485
|
+
let access = "READ";
|
|
6486
|
+
if (given.access === void 0) problems.push({ path: "access", message: "Required" });
|
|
6487
|
+
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(", ")}` });
|
|
6488
|
+
else access = given.access;
|
|
6489
|
+
if (problems.length > 0) throw new SchedulingValidationError("The API key request is not valid", "SCHED_1600", { errors: problems });
|
|
6490
|
+
return { name, access };
|
|
6491
|
+
}
|
|
6492
|
+
|
|
6493
|
+
// src/api-keys/secret.ts
|
|
6494
|
+
var import_node_crypto8 = require("crypto");
|
|
6495
|
+
var API_KEY_PREFIX = "osk_";
|
|
6496
|
+
var PREFIX_SHOWN = 12;
|
|
6497
|
+
function generateApiKeySecret() {
|
|
6498
|
+
return `${API_KEY_PREFIX}${(0, import_node_crypto8.randomBytes)(32).toString("base64url")}`;
|
|
6499
|
+
}
|
|
6500
|
+
function hashApiKeySecret(secret) {
|
|
6501
|
+
return (0, import_node_crypto8.createHash)("sha256").update(secret).digest("hex");
|
|
6502
|
+
}
|
|
6503
|
+
function visiblePrefix(secret) {
|
|
6504
|
+
return secret.slice(0, PREFIX_SHOWN);
|
|
6505
|
+
}
|
|
6506
|
+
function looksLikeApiKey(text2) {
|
|
6507
|
+
return /^osk_[A-Za-z0-9_-]{43}$/.test(text2);
|
|
6508
|
+
}
|
|
6509
|
+
|
|
6510
|
+
// src/api-keys/crud.ts
|
|
6511
|
+
var VIEW = { id: true, name: true, access: true, prefix: true, createdByUserId: true, createdAt: true, lastUsedAt: true, revokedAt: true };
|
|
6512
|
+
var LAST_USED_REFRESH_MS = 10 * 60 * 1e3;
|
|
6513
|
+
async function createApiKey(db, organizationId, input, createdByUserId) {
|
|
6514
|
+
const fields = validateApiKeyRequest(input);
|
|
6515
|
+
const active = await db.organizationApiKey.count({ where: { organizationId, revokedAt: null } });
|
|
6516
|
+
if (active >= MAX_ACTIVE_API_KEYS) {
|
|
6517
|
+
throw new SchedulingValidationError(`A business may have at most ${MAX_ACTIVE_API_KEYS} API keys`, "SCHED_1601", { limit: MAX_ACTIVE_API_KEYS });
|
|
6518
|
+
}
|
|
6519
|
+
const key = generateApiKeySecret();
|
|
6520
|
+
const view2 = await db.organizationApiKey.create({
|
|
6521
|
+
data: { organizationId, ...fields, prefix: visiblePrefix(key), keyHash: hashApiKeySecret(key), createdByUserId: createdByUserId ?? null },
|
|
6522
|
+
select: VIEW
|
|
6523
|
+
});
|
|
6524
|
+
return { key, view: view2 };
|
|
6525
|
+
}
|
|
6526
|
+
async function listApiKeys(db, organizationId) {
|
|
6527
|
+
return db.organizationApiKey.findMany({ where: { organizationId }, orderBy: { createdAt: "desc" }, select: VIEW });
|
|
6528
|
+
}
|
|
6529
|
+
async function revokeApiKey(db, organizationId, id) {
|
|
6530
|
+
const { count } = await db.organizationApiKey.updateMany({ where: { id, organizationId, revokedAt: null }, data: { revokedAt: /* @__PURE__ */ new Date() } });
|
|
6531
|
+
return count > 0;
|
|
6532
|
+
}
|
|
6533
|
+
async function verifyApiKey(db, secret) {
|
|
6534
|
+
if (!looksLikeApiKey(secret)) return null;
|
|
6535
|
+
const row = await db.organizationApiKey.findUnique({
|
|
6536
|
+
where: { keyHash: hashApiKeySecret(secret) },
|
|
6537
|
+
select: { id: true, organizationId: true, access: true, createdByUserId: true, revokedAt: true, lastUsedAt: true }
|
|
6538
|
+
});
|
|
6539
|
+
if (!row || row.revokedAt) return null;
|
|
6540
|
+
if (!API_KEY_ACCESS.includes(row.access)) return null;
|
|
6541
|
+
const now = Date.now();
|
|
6542
|
+
if (!row.lastUsedAt || now - row.lastUsedAt.getTime() > LAST_USED_REFRESH_MS) {
|
|
6543
|
+
await db.organizationApiKey.updateMany({ where: { id: row.id, revokedAt: null }, data: { lastUsedAt: new Date(now) } }).catch((error) => {
|
|
6544
|
+
const diagnostic = schedError("SCHED_1602", { keyId: row.id, error });
|
|
6545
|
+
console.error(`[api-keys] ${diagnostic.code}-${diagnostic.ref} could not record last use`, error);
|
|
6546
|
+
});
|
|
6547
|
+
}
|
|
6548
|
+
return { id: row.id, organizationId: row.organizationId, access: row.access, createdByUserId: row.createdByUserId };
|
|
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
|
+
}
|
|
6250
6900
|
// Annotate the CommonJS export names for ESM import in node:
|
|
6251
6901
|
0 && (module.exports = {
|
|
6902
|
+
API_KEY_ACCESS,
|
|
6903
|
+
API_KEY_FIELDS,
|
|
6904
|
+
API_KEY_NAME_MAX,
|
|
6252
6905
|
BRAND_FIELDS,
|
|
6253
6906
|
BlockedTargetError,
|
|
6254
6907
|
DEFAULT_BACKOFF_SECONDS,
|
|
6908
|
+
DEFAULT_LIST_LIMIT,
|
|
6255
6909
|
DEFAULT_OFFER_MINUTES,
|
|
6256
6910
|
ERASED_EMAIL,
|
|
6257
6911
|
ERASED_NAME,
|
|
6912
|
+
GIFT_CERTIFICATE_FIELDS,
|
|
6913
|
+
GIFT_CERTIFICATE_STATUS,
|
|
6914
|
+
GIFT_TRANSACTION_TYPES,
|
|
6915
|
+
MAX_ACTIVE_API_KEYS,
|
|
6258
6916
|
MAX_ENDPOINTS_PER_ORGANIZATION,
|
|
6917
|
+
MAX_GIFT_CENTS,
|
|
6918
|
+
MAX_HISTORY_LINES,
|
|
6919
|
+
MAX_LIST_LIMIT,
|
|
6259
6920
|
MAX_WAITING_PER_TYPE_DAY,
|
|
6921
|
+
MIN_GIFT_CENTS,
|
|
6260
6922
|
OPERATORS_BY_TYPE,
|
|
6261
6923
|
RECURRING_MAX_OCCURRENCES,
|
|
6262
6924
|
ROUTING_LIMITS,
|
|
@@ -6288,10 +6950,12 @@ async function deleteTextSettings(db, organizationId) {
|
|
|
6288
6950
|
checkAuthContract,
|
|
6289
6951
|
checkCalendarSyncContract,
|
|
6290
6952
|
checkClockContract,
|
|
6953
|
+
checkGiftCertificate,
|
|
6291
6954
|
checkNotificationContract,
|
|
6292
6955
|
checkPaymentContract,
|
|
6293
6956
|
checkWebhookUrl,
|
|
6294
6957
|
completeWaitlistAccept,
|
|
6958
|
+
createApiKey,
|
|
6295
6959
|
createAppointmentType,
|
|
6296
6960
|
createCalendar,
|
|
6297
6961
|
createInMemoryAdapters,
|
|
@@ -6312,6 +6976,7 @@ async function deleteTextSettings(db, organizationId) {
|
|
|
6312
6976
|
eraseSubject,
|
|
6313
6977
|
expireWaitlistOffers,
|
|
6314
6978
|
exportSubject,
|
|
6979
|
+
formatGiftCode,
|
|
6315
6980
|
generateOccurrenceDates,
|
|
6316
6981
|
generateWebhookSecret,
|
|
6317
6982
|
getAppointment,
|
|
@@ -6323,6 +6988,7 @@ async function deleteTextSettings(db, organizationId) {
|
|
|
6323
6988
|
getBookingAnalytics,
|
|
6324
6989
|
getBrand,
|
|
6325
6990
|
getCalendar,
|
|
6991
|
+
getGiftCertificate,
|
|
6326
6992
|
getGroupCapacity,
|
|
6327
6993
|
getGroupSessions,
|
|
6328
6994
|
getNotificationTemplate,
|
|
@@ -6333,15 +6999,20 @@ async function deleteTextSettings(db, organizationId) {
|
|
|
6333
6999
|
getTextSettings,
|
|
6334
7000
|
getUserDayAppointments,
|
|
6335
7001
|
getWaitlistOffer,
|
|
7002
|
+
giftCertificateState,
|
|
6336
7003
|
isPrivateAddress,
|
|
6337
7004
|
isSlotAvailable,
|
|
6338
7005
|
isVirtualMeeting,
|
|
7006
|
+
issueGiftCertificate,
|
|
7007
|
+
issueGiftCertificateOnce,
|
|
6339
7008
|
joinWaitlist,
|
|
6340
7009
|
leaveWaitlist,
|
|
7010
|
+
listApiKeys,
|
|
6341
7011
|
listAppointmentTypes,
|
|
6342
7012
|
listAppointments,
|
|
6343
7013
|
listAvailabilityRules,
|
|
6344
7014
|
listCalendars,
|
|
7015
|
+
listGiftCertificates,
|
|
6345
7016
|
listNotificationTemplates,
|
|
6346
7017
|
listPrivacyRequests,
|
|
6347
7018
|
listRoutingForms,
|
|
@@ -6350,8 +7021,11 @@ async function deleteTextSettings(db, organizationId) {
|
|
|
6350
7021
|
listWebhookEndpoints,
|
|
6351
7022
|
localDay,
|
|
6352
7023
|
localToUTC,
|
|
7024
|
+
looksLikeApiKey,
|
|
7025
|
+
looksLikeGiftCode,
|
|
6353
7026
|
markNoShow,
|
|
6354
7027
|
matchingRules,
|
|
7028
|
+
normalizeGiftCode,
|
|
6355
7029
|
normalizeTextNumber,
|
|
6356
7030
|
offerFreedSlot,
|
|
6357
7031
|
parseSubject,
|
|
@@ -6360,6 +7034,7 @@ async function deleteTextSettings(db, organizationId) {
|
|
|
6360
7034
|
processPendingNotifications,
|
|
6361
7035
|
queueImmediateNotification,
|
|
6362
7036
|
queueStaffNotification,
|
|
7037
|
+
redeemGiftCertificate,
|
|
6363
7038
|
releaseWaitlistAccept,
|
|
6364
7039
|
removeDateOverride,
|
|
6365
7040
|
removeWaitlistEntry,
|
|
@@ -6368,7 +7043,9 @@ async function deleteTextSettings(db, organizationId) {
|
|
|
6368
7043
|
resolveDestination,
|
|
6369
7044
|
resolveLocation,
|
|
6370
7045
|
resolveSubject,
|
|
7046
|
+
restoreGiftCertificate,
|
|
6371
7047
|
retryWebhookDelivery,
|
|
7048
|
+
revokeApiKey,
|
|
6372
7049
|
routeClient,
|
|
6373
7050
|
saveBrand,
|
|
6374
7051
|
saveTextSettings,
|
|
@@ -6389,11 +7066,15 @@ async function deleteTextSettings(db, organizationId) {
|
|
|
6389
7066
|
updateCalendar,
|
|
6390
7067
|
updateNotificationTemplate,
|
|
6391
7068
|
updateRoutingForm,
|
|
7069
|
+
validateApiKeyRequest,
|
|
6392
7070
|
validateBrand,
|
|
7071
|
+
validateGiftCertificateRequest,
|
|
6393
7072
|
validateRoutingDestinations,
|
|
6394
7073
|
validateRoutingStructure,
|
|
6395
7074
|
validateTextSettings,
|
|
7075
|
+
verifyApiKey,
|
|
6396
7076
|
verifyWebhookSignature,
|
|
7077
|
+
voidGiftCertificate,
|
|
6397
7078
|
withCalendarVisibility,
|
|
6398
7079
|
withOrganization
|
|
6399
7080
|
});
|