@ordinatio/scheduling-api 0.4.1 → 0.5.1

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
@@ -1050,6 +1050,13 @@ async function requireAdminStaff(host, request, options) {
1050
1050
  return staff;
1051
1051
  }
1052
1052
 
1053
+ // src/handlers/staff-appointment.ts
1054
+ function withoutManageToken(appointment) {
1055
+ if (appointment === null || appointment === void 0) return null;
1056
+ const { manageToken: _manageToken, ...rest } = appointment;
1057
+ return rest;
1058
+ }
1059
+
1053
1060
  // src/handlers/appointment-cancel.ts
1054
1061
  async function cancelByStaff(request, { host, params }) {
1055
1062
  try {
@@ -1122,7 +1129,7 @@ async function cancelByStaff(request, { host, params }) {
1122
1129
  description: `cancelled ${appointment.clientName}'s appointment`,
1123
1130
  metadata: { appointmentId: id, clientName: appointment.clientName }
1124
1131
  });
1125
- return Response.json(result);
1132
+ return Response.json(withoutManageToken(result));
1126
1133
  } catch (error) {
1127
1134
  if (error instanceof import_scheduling13.SchedulingNotFoundError) {
1128
1135
  return Response.json({ error: error.message, ref: error.ref }, { status: 404 });
@@ -1466,7 +1473,7 @@ async function rejectAppointment(host, db, organizationId, appointment, reason)
1466
1473
  description: `rejected ${appointment.clientName}'s appointment request`,
1467
1474
  metadata: { appointmentId: id, clientName: appointment.clientName, reason }
1468
1475
  });
1469
- return Response.json({ success: true, status: "CANCELLED", appointment: result });
1476
+ return Response.json({ success: true, status: "CANCELLED", appointment: withoutManageToken(result) });
1470
1477
  }
1471
1478
  async function approveOrReject(request, { host, params }) {
1472
1479
  try {
@@ -1522,7 +1529,7 @@ async function approveOrReject(request, { host, params }) {
1522
1529
  metadata: { appointmentId: id, clientName: appointment.clientName }
1523
1530
  });
1524
1531
  const confirmedAppointment = await (0, import_scheduling15.getAppointment)(db, id);
1525
- return Response.json({ success: true, status: "CONFIRMED", appointment: confirmedAppointment });
1532
+ return Response.json({ success: true, status: "CONFIRMED", appointment: withoutManageToken(confirmedAppointment) });
1526
1533
  } catch (error) {
1527
1534
  if (getErrorCode(error) === "SCHED_306") {
1528
1535
  return Response.json({ error: "Appointment was already processed by a concurrent request" }, { status: 409 });
@@ -1612,7 +1619,7 @@ async function rescheduleByStaff(request, { host, params }) {
1612
1619
  newTime: newTime.toISOString()
1613
1620
  }
1614
1621
  });
1615
- return Response.json(result);
1622
+ return Response.json(withoutManageToken(result));
1616
1623
  } catch (error) {
1617
1624
  if (error instanceof import_scheduling16.SchedulingValidationError) return Response.json({ error: error.message }, { status: 400 });
1618
1625
  if (error instanceof import_scheduling16.SchedulingNotFoundError) return Response.json({ error: error.message }, { status: 404 });
@@ -1735,7 +1742,7 @@ async function reassignAppointment(request, { host, params }) {
1735
1742
  err instanceof Error ? err.message : err
1736
1743
  );
1737
1744
  }
1738
- return Response.json(updated);
1745
+ return Response.json(withoutManageToken(updated));
1739
1746
  } catch (error) {
1740
1747
  const ref = getErrorRef(error);
1741
1748
  console.error("[reassign]", ref, error instanceof Error ? error.message : error);
@@ -1894,7 +1901,7 @@ async function markAppointmentNoShow(request, { host, params }) {
1894
1901
  description: `marked ${appointment.clientName}'s appointment as no-show`,
1895
1902
  metadata: { appointmentId: id, clientName: appointment.clientName }
1896
1903
  });
1897
- return Response.json(result);
1904
+ return Response.json(withoutManageToken(result));
1898
1905
  } catch (error) {
1899
1906
  if (error instanceof import_scheduling18.SchedulingNotFoundError) {
1900
1907
  return Response.json({ error: error.message, ref: error.ref }, { status: 404 });
@@ -3483,7 +3490,7 @@ async function createCoupon(request, { host }) {
3483
3490
  async function getOwnedCoupon(db, id, organizationId) {
3484
3491
  return db.couponCode.findFirst({
3485
3492
  where: { id, organizationId },
3486
- select: { id: true, code: true, usedCount: true, isActive: true }
3493
+ select: { id: true, code: true, usedCount: true, isActive: true, discountType: true, discountValue: true }
3487
3494
  });
3488
3495
  }
3489
3496
  async function updateCoupon(request, { host, params }) {
@@ -3503,6 +3510,11 @@ async function updateCoupon(request, { host, params }) {
3503
3510
  const validation = await parseBody(request, UpdateCouponCodeSchema);
3504
3511
  if (!validation.success) return validation.response;
3505
3512
  const input = validation.data;
3513
+ const finalType = input.discountType ?? existing.discountType;
3514
+ const finalValue = input.discountValue ?? Number(existing.discountValue);
3515
+ if (finalType === "PERCENTAGE" && finalValue > 100) {
3516
+ return Response.json({ error: "Percentage discount cannot exceed 100%" }, { status: 400 });
3517
+ }
3506
3518
  const updated = await db.couponCode.update({
3507
3519
  where: { id, organizationId },
3508
3520
  data: {
@@ -3521,6 +3533,9 @@ async function updateCoupon(request, { host, params }) {
3521
3533
  });
3522
3534
  return Response.json({ coupon: updated });
3523
3535
  } catch (error) {
3536
+ if (getErrorCode(error) === "P2002") {
3537
+ return Response.json({ error: "A coupon with this code already exists" }, { status: 409 });
3538
+ }
3524
3539
  return Response.json({ error: getErrorMessage(error, "Failed to update coupon") }, { status: 500 });
3525
3540
  }
3526
3541
  }
@@ -3588,6 +3603,10 @@ async function createPackage(request, { host }) {
3588
3603
  const validation = await parseBody(request, CreateServicePackageSchema);
3589
3604
  if (!validation.success) return validation.response;
3590
3605
  const input = validation.data;
3606
+ if (input.typeId) {
3607
+ const type = await db.appointmentType.findFirst({ where: { id: input.typeId, organizationId }, select: { id: true } });
3608
+ if (!type) return Response.json({ error: "Appointment type not found" }, { status: 404 });
3609
+ }
3591
3610
  const pkg = await db.servicePackage.create({
3592
3611
  data: {
3593
3612
  name: input.name,
@@ -3639,6 +3658,10 @@ async function updatePackage(request, { host, params }) {
3639
3658
  const validation = await parseBody(request, UpdateServicePackageSchema);
3640
3659
  if (!validation.success) return validation.response;
3641
3660
  const input = validation.data;
3661
+ if (input.typeId) {
3662
+ const type = await db.appointmentType.findFirst({ where: { id: input.typeId, organizationId }, select: { id: true } });
3663
+ if (!type) return Response.json({ error: "Appointment type not found" }, { status: 404 });
3664
+ }
3642
3665
  const updated = await db.servicePackage.update({
3643
3666
  where: { id, organizationId },
3644
3667
  data: {
@@ -4140,46 +4163,54 @@ async function createRecurringSeries(request, { host }) {
4140
4163
  { status: 422 }
4141
4164
  );
4142
4165
  }
4143
- const series = await db.$transaction(async (tx) => {
4144
- const created = await tx.recurringSeries.create({
4145
- data: {
4146
- organizationId,
4147
- calendarId: input.calendarId,
4148
- typeId: input.typeId,
4149
- frequency: input.frequency,
4150
- occurrences: slots.length,
4151
- startTimeLocal: input.startTimeLocal,
4152
- durationMins: apptType.duration,
4153
- timezone: input.timezone,
4154
- endsAt: endsAt ?? null,
4155
- clientEmail: input.clientEmail,
4156
- clientName: input.clientName,
4157
- clientPhone: input.clientPhone ?? null,
4158
- clientId,
4159
- notes: input.notes ?? null,
4160
- status: "ACTIVE"
4161
- }
4162
- });
4163
- await tx.appointment.createMany({
4164
- data: slots.map(({ startTime, endTime }, idx) => ({
4165
- calendarId: input.calendarId,
4166
- typeId: input.typeId,
4167
- clientEmail: input.clientEmail,
4168
- clientName: input.clientName,
4169
- clientPhone: input.clientPhone ?? null,
4170
- clientId,
4171
- startTime,
4172
- endTime,
4173
- duration: apptType.duration,
4174
- timezone: input.timezone,
4175
- notes: input.notes ?? null,
4176
- status: "CONFIRMED",
4177
- recurringId: created.id,
4178
- recurringIndex: idx + 1
4179
- }))
4166
+ let series;
4167
+ try {
4168
+ series = await db.$transaction(async (tx) => {
4169
+ const created = await tx.recurringSeries.create({
4170
+ data: {
4171
+ organizationId,
4172
+ calendarId: input.calendarId,
4173
+ typeId: input.typeId,
4174
+ frequency: input.frequency,
4175
+ occurrences: slots.length,
4176
+ startTimeLocal: input.startTimeLocal,
4177
+ durationMins: apptType.duration,
4178
+ timezone: input.timezone,
4179
+ endsAt: endsAt ?? null,
4180
+ clientEmail: input.clientEmail,
4181
+ clientName: input.clientName,
4182
+ clientPhone: input.clientPhone ?? null,
4183
+ clientId,
4184
+ notes: input.notes ?? null,
4185
+ status: "ACTIVE"
4186
+ }
4187
+ });
4188
+ await tx.appointment.createMany({
4189
+ data: slots.map(({ startTime, endTime }, idx) => ({
4190
+ calendarId: input.calendarId,
4191
+ typeId: input.typeId,
4192
+ clientEmail: input.clientEmail,
4193
+ clientName: input.clientName,
4194
+ clientPhone: input.clientPhone ?? null,
4195
+ clientId,
4196
+ startTime,
4197
+ endTime,
4198
+ duration: apptType.duration,
4199
+ timezone: input.timezone,
4200
+ notes: input.notes ?? null,
4201
+ status: "CONFIRMED",
4202
+ recurringId: created.id,
4203
+ recurringIndex: idx + 1
4204
+ }))
4205
+ });
4206
+ return created;
4180
4207
  });
4181
- return created;
4182
- });
4208
+ } catch (error) {
4209
+ if (getErrorCode(error) === "P2002") {
4210
+ return Response.json({ error: "One of the visits would start at exactly the same time as a booking already on this calendar. Nothing was saved." }, { status: 409 });
4211
+ }
4212
+ throw error;
4213
+ }
4183
4214
  await host.activity.log(db, {
4184
4215
  action: "scheduling.recurring_series_created",
4185
4216
  description: `created ${slots.length}-occurrence ${input.frequency} series for ${input.clientName} (${input.clientEmail})`,
@@ -4885,6 +4916,13 @@ async function putCalendar(request, { host, params }) {
4885
4916
  const input = validation.data;
4886
4917
  const linkError = input.userId === void 0 ? null : await validateStaffLink(host, input.userId, organizationId);
4887
4918
  if (linkError) return linkError;
4919
+ if (input.name !== void 0 && input.name !== existing.name) {
4920
+ const taken = await db.schedulingCalendar.findFirst({
4921
+ where: { organizationId, isActive: true, id: { not: id }, name: { equals: input.name, mode: "insensitive" } },
4922
+ select: { id: true }
4923
+ });
4924
+ if (taken) return Response.json({ error: "A calendar with this name already exists" }, { status: 409 });
4925
+ }
4888
4926
  const archiving = input.isActive === false && existing.isActive;
4889
4927
  let archived = false;
4890
4928
  let updated;
@@ -4898,7 +4936,7 @@ async function putCalendar(request, { host, params }) {
4898
4936
  if (archived) await undoArchive(host, db, id, organizationId, existing.slug);
4899
4937
  throw error;
4900
4938
  }
4901
- if (input.slotGranularityMinutes !== void 0) await host.availabilityCache.invalidate(id);
4939
+ if (input.slotGranularityMinutes !== void 0 || input.timezone !== void 0) await host.availabilityCache.invalidate(id);
4902
4940
  if (archiving) await releaseCalendarSlugIfStillInactive(host, db, id, organizationId, existing.slug);
4903
4941
  await bustCalendarCachesOnUpdate(host, organizationId, existing.slug, input, id);
4904
4942
  await host.activity.log(db, {
@@ -5406,7 +5444,7 @@ async function createTemplate(request, { host }) {
5406
5444
  if (input.channel === "SMS" && input.subject) {
5407
5445
  return Response.json({ error: "SMS templates cannot have a subject" }, { status: 400 });
5408
5446
  }
5409
- if (input.channel === "EMAIL" && !input.subject?.trim()) {
5447
+ if (input.channel === "EMAIL" && !stripHtml(input.subject).trim()) {
5410
5448
  return Response.json({ error: "EMAIL templates require a subject" }, { status: 400 });
5411
5449
  }
5412
5450
  const template = await (0, import_scheduling42.createNotificationTemplate)(db, organizationId, {
@@ -6575,7 +6613,7 @@ async function resolveBookingContext(host, cors, body) {
6575
6613
  if (body.packagePurchaseId) {
6576
6614
  const purchase = await db.packagePurchase.findFirst({
6577
6615
  where: { id: body.packagePurchaseId, organizationId: orgId },
6578
- select: { id: true, status: true, expiresAt: true, sessionsUsed: true, sessionsTotal: true, clientEmail: true }
6616
+ select: { id: true, status: true, expiresAt: true, sessionsUsed: true, sessionsTotal: true, clientEmail: true, package: { select: { typeId: true } } }
6579
6617
  });
6580
6618
  if (!purchase) return fail(404, { error: "Package purchase not found" });
6581
6619
  if (purchase.status !== "ACTIVE") {
@@ -6586,6 +6624,10 @@ async function resolveBookingContext(host, cors, body) {
6586
6624
  if (purchase.clientEmail.toLowerCase() !== body.clientEmail.toLowerCase()) {
6587
6625
  return fail(403, { error: "Package does not belong to this client" });
6588
6626
  }
6627
+ const packageTypeId = purchase.package?.typeId ?? null;
6628
+ if (packageTypeId && packageTypeId !== body.typeId) {
6629
+ return fail(409, { error: "This package cannot be used for this appointment type" });
6630
+ }
6589
6631
  }
6590
6632
  return { ok: true, orgId, db, calendar, appointmentType, noShowApprovalOverride };
6591
6633
  }
package/dist/index.mjs CHANGED
@@ -987,6 +987,13 @@ async function requireAdminStaff(host, request, options) {
987
987
  return staff;
988
988
  }
989
989
 
990
+ // src/handlers/staff-appointment.ts
991
+ function withoutManageToken(appointment) {
992
+ if (appointment === null || appointment === void 0) return null;
993
+ const { manageToken: _manageToken, ...rest } = appointment;
994
+ return rest;
995
+ }
996
+
990
997
  // src/handlers/appointment-cancel.ts
991
998
  async function cancelByStaff(request, { host, params }) {
992
999
  try {
@@ -1059,7 +1066,7 @@ async function cancelByStaff(request, { host, params }) {
1059
1066
  description: `cancelled ${appointment.clientName}'s appointment`,
1060
1067
  metadata: { appointmentId: id, clientName: appointment.clientName }
1061
1068
  });
1062
- return Response.json(result);
1069
+ return Response.json(withoutManageToken(result));
1063
1070
  } catch (error) {
1064
1071
  if (error instanceof SchedulingNotFoundError) {
1065
1072
  return Response.json({ error: error.message, ref: error.ref }, { status: 404 });
@@ -1408,7 +1415,7 @@ async function rejectAppointment(host, db, organizationId, appointment, reason)
1408
1415
  description: `rejected ${appointment.clientName}'s appointment request`,
1409
1416
  metadata: { appointmentId: id, clientName: appointment.clientName, reason }
1410
1417
  });
1411
- return Response.json({ success: true, status: "CANCELLED", appointment: result });
1418
+ return Response.json({ success: true, status: "CANCELLED", appointment: withoutManageToken(result) });
1412
1419
  }
1413
1420
  async function approveOrReject(request, { host, params }) {
1414
1421
  try {
@@ -1464,7 +1471,7 @@ async function approveOrReject(request, { host, params }) {
1464
1471
  metadata: { appointmentId: id, clientName: appointment.clientName }
1465
1472
  });
1466
1473
  const confirmedAppointment = await getAppointment(db, id);
1467
- return Response.json({ success: true, status: "CONFIRMED", appointment: confirmedAppointment });
1474
+ return Response.json({ success: true, status: "CONFIRMED", appointment: withoutManageToken(confirmedAppointment) });
1468
1475
  } catch (error) {
1469
1476
  if (getErrorCode(error) === "SCHED_306") {
1470
1477
  return Response.json({ error: "Appointment was already processed by a concurrent request" }, { status: 409 });
@@ -1561,7 +1568,7 @@ async function rescheduleByStaff(request, { host, params }) {
1561
1568
  newTime: newTime.toISOString()
1562
1569
  }
1563
1570
  });
1564
- return Response.json(result);
1571
+ return Response.json(withoutManageToken(result));
1565
1572
  } catch (error) {
1566
1573
  if (error instanceof SchedulingValidationError2) return Response.json({ error: error.message }, { status: 400 });
1567
1574
  if (error instanceof SchedulingNotFoundError3) return Response.json({ error: error.message }, { status: 404 });
@@ -1684,7 +1691,7 @@ async function reassignAppointment(request, { host, params }) {
1684
1691
  err instanceof Error ? err.message : err
1685
1692
  );
1686
1693
  }
1687
- return Response.json(updated);
1694
+ return Response.json(withoutManageToken(updated));
1688
1695
  } catch (error) {
1689
1696
  const ref = getErrorRef(error);
1690
1697
  console.error("[reassign]", ref, error instanceof Error ? error.message : error);
@@ -1843,7 +1850,7 @@ async function markAppointmentNoShow(request, { host, params }) {
1843
1850
  description: `marked ${appointment.clientName}'s appointment as no-show`,
1844
1851
  metadata: { appointmentId: id, clientName: appointment.clientName }
1845
1852
  });
1846
- return Response.json(result);
1853
+ return Response.json(withoutManageToken(result));
1847
1854
  } catch (error) {
1848
1855
  if (error instanceof SchedulingNotFoundError4) {
1849
1856
  return Response.json({ error: error.message, ref: error.ref }, { status: 404 });
@@ -3001,7 +3008,7 @@ async function createCoupon(request, { host }) {
3001
3008
  async function getOwnedCoupon(db, id, organizationId) {
3002
3009
  return db.couponCode.findFirst({
3003
3010
  where: { id, organizationId },
3004
- select: { id: true, code: true, usedCount: true, isActive: true }
3011
+ select: { id: true, code: true, usedCount: true, isActive: true, discountType: true, discountValue: true }
3005
3012
  });
3006
3013
  }
3007
3014
  async function updateCoupon(request, { host, params }) {
@@ -3021,6 +3028,11 @@ async function updateCoupon(request, { host, params }) {
3021
3028
  const validation = await parseBody(request, UpdateCouponCodeSchema);
3022
3029
  if (!validation.success) return validation.response;
3023
3030
  const input = validation.data;
3031
+ const finalType = input.discountType ?? existing.discountType;
3032
+ const finalValue = input.discountValue ?? Number(existing.discountValue);
3033
+ if (finalType === "PERCENTAGE" && finalValue > 100) {
3034
+ return Response.json({ error: "Percentage discount cannot exceed 100%" }, { status: 400 });
3035
+ }
3024
3036
  const updated = await db.couponCode.update({
3025
3037
  where: { id, organizationId },
3026
3038
  data: {
@@ -3039,6 +3051,9 @@ async function updateCoupon(request, { host, params }) {
3039
3051
  });
3040
3052
  return Response.json({ coupon: updated });
3041
3053
  } catch (error) {
3054
+ if (getErrorCode(error) === "P2002") {
3055
+ return Response.json({ error: "A coupon with this code already exists" }, { status: 409 });
3056
+ }
3042
3057
  return Response.json({ error: getErrorMessage(error, "Failed to update coupon") }, { status: 500 });
3043
3058
  }
3044
3059
  }
@@ -3106,6 +3121,10 @@ async function createPackage(request, { host }) {
3106
3121
  const validation = await parseBody(request, CreateServicePackageSchema);
3107
3122
  if (!validation.success) return validation.response;
3108
3123
  const input = validation.data;
3124
+ if (input.typeId) {
3125
+ const type = await db.appointmentType.findFirst({ where: { id: input.typeId, organizationId }, select: { id: true } });
3126
+ if (!type) return Response.json({ error: "Appointment type not found" }, { status: 404 });
3127
+ }
3109
3128
  const pkg = await db.servicePackage.create({
3110
3129
  data: {
3111
3130
  name: input.name,
@@ -3157,6 +3176,10 @@ async function updatePackage(request, { host, params }) {
3157
3176
  const validation = await parseBody(request, UpdateServicePackageSchema);
3158
3177
  if (!validation.success) return validation.response;
3159
3178
  const input = validation.data;
3179
+ if (input.typeId) {
3180
+ const type = await db.appointmentType.findFirst({ where: { id: input.typeId, organizationId }, select: { id: true } });
3181
+ if (!type) return Response.json({ error: "Appointment type not found" }, { status: 404 });
3182
+ }
3160
3183
  const updated = await db.servicePackage.update({
3161
3184
  where: { id, organizationId },
3162
3185
  data: {
@@ -3663,46 +3686,54 @@ async function createRecurringSeries(request, { host }) {
3663
3686
  { status: 422 }
3664
3687
  );
3665
3688
  }
3666
- const series = await db.$transaction(async (tx) => {
3667
- const created = await tx.recurringSeries.create({
3668
- data: {
3669
- organizationId,
3670
- calendarId: input.calendarId,
3671
- typeId: input.typeId,
3672
- frequency: input.frequency,
3673
- occurrences: slots.length,
3674
- startTimeLocal: input.startTimeLocal,
3675
- durationMins: apptType.duration,
3676
- timezone: input.timezone,
3677
- endsAt: endsAt ?? null,
3678
- clientEmail: input.clientEmail,
3679
- clientName: input.clientName,
3680
- clientPhone: input.clientPhone ?? null,
3681
- clientId,
3682
- notes: input.notes ?? null,
3683
- status: "ACTIVE"
3684
- }
3685
- });
3686
- await tx.appointment.createMany({
3687
- data: slots.map(({ startTime, endTime }, idx) => ({
3688
- calendarId: input.calendarId,
3689
- typeId: input.typeId,
3690
- clientEmail: input.clientEmail,
3691
- clientName: input.clientName,
3692
- clientPhone: input.clientPhone ?? null,
3693
- clientId,
3694
- startTime,
3695
- endTime,
3696
- duration: apptType.duration,
3697
- timezone: input.timezone,
3698
- notes: input.notes ?? null,
3699
- status: "CONFIRMED",
3700
- recurringId: created.id,
3701
- recurringIndex: idx + 1
3702
- }))
3689
+ let series;
3690
+ try {
3691
+ series = await db.$transaction(async (tx) => {
3692
+ const created = await tx.recurringSeries.create({
3693
+ data: {
3694
+ organizationId,
3695
+ calendarId: input.calendarId,
3696
+ typeId: input.typeId,
3697
+ frequency: input.frequency,
3698
+ occurrences: slots.length,
3699
+ startTimeLocal: input.startTimeLocal,
3700
+ durationMins: apptType.duration,
3701
+ timezone: input.timezone,
3702
+ endsAt: endsAt ?? null,
3703
+ clientEmail: input.clientEmail,
3704
+ clientName: input.clientName,
3705
+ clientPhone: input.clientPhone ?? null,
3706
+ clientId,
3707
+ notes: input.notes ?? null,
3708
+ status: "ACTIVE"
3709
+ }
3710
+ });
3711
+ await tx.appointment.createMany({
3712
+ data: slots.map(({ startTime, endTime }, idx) => ({
3713
+ calendarId: input.calendarId,
3714
+ typeId: input.typeId,
3715
+ clientEmail: input.clientEmail,
3716
+ clientName: input.clientName,
3717
+ clientPhone: input.clientPhone ?? null,
3718
+ clientId,
3719
+ startTime,
3720
+ endTime,
3721
+ duration: apptType.duration,
3722
+ timezone: input.timezone,
3723
+ notes: input.notes ?? null,
3724
+ status: "CONFIRMED",
3725
+ recurringId: created.id,
3726
+ recurringIndex: idx + 1
3727
+ }))
3728
+ });
3729
+ return created;
3703
3730
  });
3704
- return created;
3705
- });
3731
+ } catch (error) {
3732
+ if (getErrorCode(error) === "P2002") {
3733
+ return Response.json({ error: "One of the visits would start at exactly the same time as a booking already on this calendar. Nothing was saved." }, { status: 409 });
3734
+ }
3735
+ throw error;
3736
+ }
3706
3737
  await host.activity.log(db, {
3707
3738
  action: "scheduling.recurring_series_created",
3708
3739
  description: `created ${slots.length}-occurrence ${input.frequency} series for ${input.clientName} (${input.clientEmail})`,
@@ -4408,6 +4439,13 @@ async function putCalendar(request, { host, params }) {
4408
4439
  const input = validation.data;
4409
4440
  const linkError = input.userId === void 0 ? null : await validateStaffLink(host, input.userId, organizationId);
4410
4441
  if (linkError) return linkError;
4442
+ if (input.name !== void 0 && input.name !== existing.name) {
4443
+ const taken = await db.schedulingCalendar.findFirst({
4444
+ where: { organizationId, isActive: true, id: { not: id }, name: { equals: input.name, mode: "insensitive" } },
4445
+ select: { id: true }
4446
+ });
4447
+ if (taken) return Response.json({ error: "A calendar with this name already exists" }, { status: 409 });
4448
+ }
4411
4449
  const archiving = input.isActive === false && existing.isActive;
4412
4450
  let archived = false;
4413
4451
  let updated;
@@ -4421,7 +4459,7 @@ async function putCalendar(request, { host, params }) {
4421
4459
  if (archived) await undoArchive(host, db, id, organizationId, existing.slug);
4422
4460
  throw error;
4423
4461
  }
4424
- if (input.slotGranularityMinutes !== void 0) await host.availabilityCache.invalidate(id);
4462
+ if (input.slotGranularityMinutes !== void 0 || input.timezone !== void 0) await host.availabilityCache.invalidate(id);
4425
4463
  if (archiving) await releaseCalendarSlugIfStillInactive(host, db, id, organizationId, existing.slug);
4426
4464
  await bustCalendarCachesOnUpdate(host, organizationId, existing.slug, input, id);
4427
4465
  await host.activity.log(db, {
@@ -4935,7 +4973,7 @@ async function createTemplate(request, { host }) {
4935
4973
  if (input.channel === "SMS" && input.subject) {
4936
4974
  return Response.json({ error: "SMS templates cannot have a subject" }, { status: 400 });
4937
4975
  }
4938
- if (input.channel === "EMAIL" && !input.subject?.trim()) {
4976
+ if (input.channel === "EMAIL" && !stripHtml(input.subject).trim()) {
4939
4977
  return Response.json({ error: "EMAIL templates require a subject" }, { status: 400 });
4940
4978
  }
4941
4979
  const template = await createNotificationTemplate(db, organizationId, {
@@ -6119,7 +6157,7 @@ async function resolveBookingContext(host, cors, body) {
6119
6157
  if (body.packagePurchaseId) {
6120
6158
  const purchase = await db.packagePurchase.findFirst({
6121
6159
  where: { id: body.packagePurchaseId, organizationId: orgId },
6122
- select: { id: true, status: true, expiresAt: true, sessionsUsed: true, sessionsTotal: true, clientEmail: true }
6160
+ select: { id: true, status: true, expiresAt: true, sessionsUsed: true, sessionsTotal: true, clientEmail: true, package: { select: { typeId: true } } }
6123
6161
  });
6124
6162
  if (!purchase) return fail(404, { error: "Package purchase not found" });
6125
6163
  if (purchase.status !== "ACTIVE") {
@@ -6130,6 +6168,10 @@ async function resolveBookingContext(host, cors, body) {
6130
6168
  if (purchase.clientEmail.toLowerCase() !== body.clientEmail.toLowerCase()) {
6131
6169
  return fail(403, { error: "Package does not belong to this client" });
6132
6170
  }
6171
+ const packageTypeId = purchase.package?.typeId ?? null;
6172
+ if (packageTypeId && packageTypeId !== body.typeId) {
6173
+ return fail(409, { error: "This package cannot be used for this appointment type" });
6174
+ }
6133
6175
  }
6134
6176
  return { ok: true, orgId, db, calendar, appointmentType, noShowApprovalOverride };
6135
6177
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/scheduling-api",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "license": "MIT",
5
5
  "description": "HTTP API for @ordinatio/scheduling. Every handler takes a Request and returns a Response.",
6
6
  "main": "./dist/index.js",
@@ -11,14 +11,14 @@
11
11
  "sanitize-html": "^2.16.0"
12
12
  },
13
13
  "peerDependencies": {
14
- "@ordinatio/scheduling": "^0.5.0"
14
+ "@ordinatio/scheduling": "^0.6.0"
15
15
  },
16
16
  "devDependencies": {
17
17
  "@types/sanitize-html": "^2.13.0",
18
18
  "tsup": "^8.0.0",
19
19
  "typescript": "5",
20
20
  "vitest": "4.0.18",
21
- "@ordinatio/scheduling": "0.5.1"
21
+ "@ordinatio/scheduling": "0.6.0"
22
22
  },
23
23
  "engines": {
24
24
  "node": ">=22.0.0"