@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/CHANGELOG.md +9 -0
- package/dist/index.d.mts +157 -2
- package/dist/index.d.ts +157 -2
- package/dist/index.js +538 -1
- package/dist/index.mjs +517 -1
- package/package.json +1 -1
- package/prisma/migrations/20261119000000_gift_certificates/migration.sql +67 -0
- package/prisma/schema.prisma +56 -0
package/dist/index.mjs
CHANGED
|
@@ -1190,6 +1190,150 @@ var API_KEY_ERRORS = {
|
|
|
1190
1190
|
}
|
|
1191
1191
|
};
|
|
1192
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
|
+
|
|
1193
1337
|
// src/errors/registry.ts
|
|
1194
1338
|
var SCHEDULING_ERRORS = {
|
|
1195
1339
|
...CALENDARS_AVAILABILITY_ERRORS,
|
|
@@ -1206,7 +1350,8 @@ var SCHEDULING_ERRORS = {
|
|
|
1206
1350
|
...PRIVACY_ERRORS,
|
|
1207
1351
|
...BRAND_ERRORS,
|
|
1208
1352
|
...TEXT_SETTINGS_ERRORS,
|
|
1209
|
-
...API_KEY_ERRORS
|
|
1353
|
+
...API_KEY_ERRORS,
|
|
1354
|
+
...GIFT_CERTIFICATE_ERRORS
|
|
1210
1355
|
};
|
|
1211
1356
|
|
|
1212
1357
|
// src/errors/diagnostic-error.ts
|
|
@@ -6189,6 +6334,356 @@ async function verifyApiKey(db, secret) {
|
|
|
6189
6334
|
}
|
|
6190
6335
|
return { id: row.id, organizationId: row.organizationId, access: row.access, createdByUserId: row.createdByUserId };
|
|
6191
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
|
+
}
|
|
6192
6687
|
export {
|
|
6193
6688
|
API_KEY_ACCESS,
|
|
6194
6689
|
API_KEY_FIELDS,
|
|
@@ -6196,12 +6691,20 @@ export {
|
|
|
6196
6691
|
BRAND_FIELDS,
|
|
6197
6692
|
BlockedTargetError,
|
|
6198
6693
|
DEFAULT_BACKOFF_SECONDS,
|
|
6694
|
+
DEFAULT_LIST_LIMIT,
|
|
6199
6695
|
DEFAULT_OFFER_MINUTES,
|
|
6200
6696
|
ERASED_EMAIL,
|
|
6201
6697
|
ERASED_NAME,
|
|
6698
|
+
GIFT_CERTIFICATE_FIELDS,
|
|
6699
|
+
GIFT_CERTIFICATE_STATUS,
|
|
6700
|
+
GIFT_TRANSACTION_TYPES,
|
|
6202
6701
|
MAX_ACTIVE_API_KEYS,
|
|
6203
6702
|
MAX_ENDPOINTS_PER_ORGANIZATION,
|
|
6703
|
+
MAX_GIFT_CENTS,
|
|
6704
|
+
MAX_HISTORY_LINES,
|
|
6705
|
+
MAX_LIST_LIMIT,
|
|
6204
6706
|
MAX_WAITING_PER_TYPE_DAY,
|
|
6707
|
+
MIN_GIFT_CENTS,
|
|
6205
6708
|
OPERATORS_BY_TYPE,
|
|
6206
6709
|
RECURRING_MAX_OCCURRENCES,
|
|
6207
6710
|
LIMITS as ROUTING_LIMITS,
|
|
@@ -6233,6 +6736,7 @@ export {
|
|
|
6233
6736
|
checkAuthContract,
|
|
6234
6737
|
checkCalendarSyncContract,
|
|
6235
6738
|
checkClockContract,
|
|
6739
|
+
checkGiftCertificate,
|
|
6236
6740
|
checkNotificationContract,
|
|
6237
6741
|
checkPaymentContract,
|
|
6238
6742
|
checkWebhookUrl,
|
|
@@ -6258,6 +6762,7 @@ export {
|
|
|
6258
6762
|
eraseSubject,
|
|
6259
6763
|
expireWaitlistOffers,
|
|
6260
6764
|
exportSubject,
|
|
6765
|
+
formatGiftCode,
|
|
6261
6766
|
generateOccurrenceDates,
|
|
6262
6767
|
generateWebhookSecret,
|
|
6263
6768
|
getAppointment,
|
|
@@ -6269,6 +6774,7 @@ export {
|
|
|
6269
6774
|
getBookingAnalytics,
|
|
6270
6775
|
getBrand,
|
|
6271
6776
|
getCalendar,
|
|
6777
|
+
getGiftCertificate,
|
|
6272
6778
|
getGroupCapacity,
|
|
6273
6779
|
getGroupSessions,
|
|
6274
6780
|
getNotificationTemplate,
|
|
@@ -6279,9 +6785,12 @@ export {
|
|
|
6279
6785
|
getTextSettings,
|
|
6280
6786
|
getUserDayAppointments,
|
|
6281
6787
|
getWaitlistOffer,
|
|
6788
|
+
giftCertificateState,
|
|
6282
6789
|
isPrivateAddress,
|
|
6283
6790
|
isSlotAvailable,
|
|
6284
6791
|
isVirtualMeeting,
|
|
6792
|
+
issueGiftCertificate,
|
|
6793
|
+
issueGiftCertificateOnce,
|
|
6285
6794
|
joinWaitlist,
|
|
6286
6795
|
leaveWaitlist,
|
|
6287
6796
|
listApiKeys,
|
|
@@ -6289,6 +6798,7 @@ export {
|
|
|
6289
6798
|
listAppointments,
|
|
6290
6799
|
listAvailabilityRules,
|
|
6291
6800
|
listCalendars,
|
|
6801
|
+
listGiftCertificates,
|
|
6292
6802
|
listNotificationTemplates,
|
|
6293
6803
|
listPrivacyRequests,
|
|
6294
6804
|
listRoutingForms,
|
|
@@ -6298,8 +6808,10 @@ export {
|
|
|
6298
6808
|
localDay,
|
|
6299
6809
|
localToUTC,
|
|
6300
6810
|
looksLikeApiKey,
|
|
6811
|
+
looksLikeGiftCode,
|
|
6301
6812
|
markNoShow,
|
|
6302
6813
|
matchingRules,
|
|
6814
|
+
normalizeGiftCode,
|
|
6303
6815
|
normalizeTextNumber,
|
|
6304
6816
|
offerFreedSlot,
|
|
6305
6817
|
parseSubject,
|
|
@@ -6308,6 +6820,7 @@ export {
|
|
|
6308
6820
|
processPendingNotifications,
|
|
6309
6821
|
queueImmediateNotification,
|
|
6310
6822
|
queueStaffNotification,
|
|
6823
|
+
redeemGiftCertificate,
|
|
6311
6824
|
releaseWaitlistAccept,
|
|
6312
6825
|
removeDateOverride,
|
|
6313
6826
|
removeWaitlistEntry,
|
|
@@ -6316,6 +6829,7 @@ export {
|
|
|
6316
6829
|
resolveDestination,
|
|
6317
6830
|
resolveLocation,
|
|
6318
6831
|
resolveSubject,
|
|
6832
|
+
restoreGiftCertificate,
|
|
6319
6833
|
retryWebhookDelivery,
|
|
6320
6834
|
revokeApiKey,
|
|
6321
6835
|
routeClient,
|
|
@@ -6340,11 +6854,13 @@ export {
|
|
|
6340
6854
|
updateRoutingForm,
|
|
6341
6855
|
validateApiKeyRequest,
|
|
6342
6856
|
validateBrand,
|
|
6857
|
+
validateGiftCertificateRequest,
|
|
6343
6858
|
validateRoutingDestinations,
|
|
6344
6859
|
validateRoutingStructure,
|
|
6345
6860
|
validateTextSettings,
|
|
6346
6861
|
verifyApiKey,
|
|
6347
6862
|
verifyWebhookSignature,
|
|
6863
|
+
voidGiftCertificate,
|
|
6348
6864
|
withCalendarVisibility,
|
|
6349
6865
|
withOrganization
|
|
6350
6866
|
};
|