@ordinatio/scheduling-api 0.5.0 → 0.6.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 CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.0 (prepared 2026-11-13)
4
+
5
+ - **New route: `GET /calendars/active`.** The active calendars the signed-in person may see, as a short list (`id`, `name`, `slug`, `staffName`) for pickers. Any member of the organization may ask, whatever their role, and the "scheduling is switched on" setting is not checked. Calendars outside the person's groups are left out, and the list never reaches beyond their organization. It is counted against the person under `admin-calendars-list`, the same name `GET /admin/calendars` uses. A host that served this list from its own route can serve it from here instead.
6
+ - **New: the staff visibility rules, ready to use.** A host that has teams works out a `StaffScope` (`{ mode: 'unrestricted' }` or `{ mode: 'restricted', visibleUserIds }`, the staff accounts whose calendars one person may see) from its own team model, and `createScopedVisibility(db, getScope)` answers the four visibility questions of a `StaffContext`: `visibleCalendars`, `visibleCalendarIds`, `canSeeCalendar` and `canSeeAppointment`. The parts are exported too: `isCalendarVisibleInScope`, `calendarVisibilityFilter`, `visibleCalendarIdsInScope`, `canSeeCalendarInScope` and `canSeeAppointmentInScope`. A calendar with no staff member linked is visible to everyone. A calendar or appointment that does not exist is not visible, so a hidden one looks missing. `visibleCalendarIdsInScope` lists only calendars linked to a visible staff member; the engine's dashboard, analytics and group-session queries add the unlinked calendars themselves, so a host that passes this list to them loses nothing. Use `calendarVisibilityFilter` where you build the query yourself.
7
+ - **New: a ready-made Stripe payment adapter.** `createStripePaymentAdapter(stripeClient)` is the `PaymentAdapter` the booking routes need for Stripe PaymentIntents: charge, server-side verify, and refund with idempotency keys. Pass your own Stripe client; the package does not depend on the `stripe` package. It refuses currencies other than usd, eur, gbp, cad and aud rather than guess an amount. `isSupportedCurrency`, the `StripeLike` type and `assertStripeTestKey` (refuses a live key before a script makes test payments) are exported too.
8
+
9
+ ## 0.5.1 (prepared 2026-11-12)
10
+
11
+ - **Security fix: staff answers no longer include the client's private manage token.** Five staff routes answered with the stored appointment,
12
+ including `manageToken`, the secret in the client's cancel and reschedule links: reassign (`PATCH /appointments/[id]/reassign`), cancel,
13
+ reschedule, no-show, and approve or reject (both answers). Staff do not need it, and these answers end up in logs, browser tools and agent
14
+ transcripts. All five now leave it out and every other field is unchanged. The agent tools for cancel, reschedule, no-show and reassign no
15
+ longer list it in their answers. The public booking route still returns it to the person who just booked, who is its rightful holder.
16
+ If you read `manageToken` from one of these staff answers, read it from the appointment record instead.
17
+ - **Fix: renaming a calendar to a name another active calendar already has is now refused with 409.** `PUT /admin/calendars/[id]` accepted it, so two
18
+ calendars could share one name in every staff picker, while `POST /admin/calendars` already refused a taken name. Capital letters are ignored, the
19
+ calendar's own name never counts, archived calendars are ignored, and the check only runs when the name actually changes. The web address
20
+ (slug) is still never changed by a rename. The update agent tool's text says so.
21
+
3
22
  ## 0.5.0 (prepared 2026-11-10)
4
23
 
5
24
  - **New agent tools for the waitlist, data export and erasure, and booking analytics (6 more), which completes the agent tools.** Every staff-facing
@@ -29,6 +29,7 @@ module.exports = __toCommonJS(agent_exports);
29
29
 
30
30
  // src/agent/appointment-tools.ts
31
31
  var APPOINTMENT_FIELDS = "id, calendarId, calendarName, staffName, typeId, typeName, startTime, endTime, duration, timezone, status, clientName, clientEmail, clientPhone, intakeResponses, staffNotes, location, paymentId, paymentStatus, paymentAmount, depositAmount, paymentProvider, couponCode, discountAmount, isGroup, manageToken, createdAt";
32
+ var STAFF_APPOINTMENT_FIELDS = "id, calendarId, calendarName, staffName, typeId, typeName, startTime, endTime, duration, timezone, status, clientName, clientEmail, clientPhone, intakeResponses, staffNotes, location, paymentId, paymentStatus, paymentAmount, depositAmount, paymentProvider, couponCode, discountAmount, isGroup, createdAt";
32
33
  var ID = { name: "id", type: "string", required: true, description: "Appointment id" };
33
34
  var APPOINTMENT_TOOLS = [
34
35
  {
@@ -207,7 +208,7 @@ var APPOINTMENT_TOOLS = [
207
208
  description: "Cancel an appointment as staff. The calendar entry is removed, the staff member is notified and a paid booking is flagged for refund review. This route does not message the client itself; the host may send a notice when it hears the appointment.cancelled event.",
208
209
  params: [ID, { name: "reason", type: "string", required: false, description: "Why, up to 500 characters; stored as the cancellation reason" }],
209
210
  example: { id: "appt_1", reason: "Staff member is unwell" },
210
- responseShape: `{ ${APPOINTMENT_FIELDS} } with status "CANCELLED"`,
211
+ responseShape: `{ ${STAFF_APPOINTMENT_FIELDS} } with status "CANCELLED"`,
211
212
  pitfalls: ["Staff can cancel even after the type's client cancellation deadline; those limits apply only to the client's own link. Refused with 409 only when the appointment is no longer pending or confirmed."],
212
213
  whenToUse: "When staff, not the client, ends the booking.",
213
214
  dataSensitivity: "sensitive",
@@ -227,7 +228,7 @@ var APPOINTMENT_TOOLS = [
227
228
  description: "Move an appointment to a new start time on the same calendar. The client is sent a reschedule notice and their reminders are redone for the new time.",
228
229
  params: [ID, { name: "newStartTime", type: "string", required: true, description: "New start in UTC, ending in Z; a time with no zone is read in the server's own zone and lands in the wrong place" }],
229
230
  example: { id: "appt_1", newStartTime: "2026-11-04T16:00:00Z" },
230
- responseShape: `{ ${APPOINTMENT_FIELDS} }`,
231
+ responseShape: `{ ${STAFF_APPOINTMENT_FIELDS} }`,
231
232
  whenToUse: "When a time change was asked for. Check availability for the new time first.",
232
233
  pitfalls: ["A time that is taken, a time in the past, an appointment that has already started, a type that does not allow moving, or a change made at the same moment by someone else, is refused."],
233
234
  dataSensitivity: "sensitive",
@@ -271,9 +272,9 @@ var APPOINTMENT_TOOLS = [
271
272
  description: "Hand an appointment to a different calendar, which means a different staff member, at the same time.",
272
273
  params: [ID, { name: "calendarId", type: "string", required: true, description: "Calendar to move it to" }],
273
274
  example: { id: "appt_1", calendarId: "cal_2" },
274
- responseShape: "{ id, calendarId, typeId, startTime, endTime, duration, timezone, clientName, clientEmail, clientPhone, status, staffNotes, location, paymentStatus, manageToken, createdAt, updatedAt } (the stored record, which has more fields than the other appointment answers)",
275
+ responseShape: "{ id, calendarId, typeId, startTime, endTime, duration, timezone, clientName, clientEmail, clientPhone, status, staffNotes, location, paymentStatus, createdAt, updatedAt } (the stored record without the client's private manage token)",
275
276
  whenToUse: "When a different person should take the appointment.",
276
- pitfalls: ["The answer is the stored record and holds the client's private manage token; never repeat it in a message.", "Admin roles only. Only pending or confirmed appointments, and not group sessions. The new calendar must be in the appointment type's team and free at that time; otherwise it is refused."],
277
+ pitfalls: ["Admin roles only. Only pending or confirmed appointments, and not group sessions. The new calendar must be in the appointment type's team and free at that time; otherwise it is refused."],
277
278
  dataSensitivity: "sensitive",
278
279
  risk: "act",
279
280
  requiresApproval: {
@@ -291,7 +292,7 @@ var APPOINTMENT_TOOLS = [
291
292
  description: "Record that the client did not come.",
292
293
  params: [ID],
293
294
  example: { id: "appt_1" },
294
- responseShape: `{ ${APPOINTMENT_FIELDS} } with status "NO_SHOW"`,
295
+ responseShape: `{ ${STAFF_APPOINTMENT_FIELDS} } with status "NO_SHOW"`,
295
296
  whenToUse: "After the start time has passed and the client did not arrive.",
296
297
  pitfalls: ["Refused with 409 unless the appointment is pending or confirmed and its start time has passed."],
297
298
  dataSensitivity: "sensitive",
@@ -1011,6 +1012,7 @@ var CALENDAR_TOOLS = [
1011
1012
  whenToUse: "To rename a calendar, change its time zone or slot size, link it to a person, or switch it off or on.",
1012
1013
  pitfalls: [
1013
1014
  "Changing the time zone changes what the opening hours mean in real time.",
1015
+ "Renaming a calendar to the name of another active calendar, ignoring capital letters, is refused with 409. A name that only gives the same web address is not checked on rename, because renaming never changes the web address.",
1014
1016
  "Switching off the last active calendar is refused with 409, as archiving is. If the other changes in the same request then fail to save, the calendar is switched back on.",
1015
1017
  "Linking a calendar to a person (userId) changes who can see it when staff are limited to their groups.",
1016
1018
  "Switching a calendar back on (isActive true) does not give back its short booking address; only the organization-qualified address works until it is registered again."
@@ -2292,6 +2294,7 @@ var SCHEDULING_AGENT_EXCLUDED = {
2292
2294
  "GET /widget-init": "Boots the public booking widget in a visitor's browser; an agent reads the same facts from the type and calendar tools.",
2293
2295
  "GET /type": "Public page data for one booking link; the staff tools list the same types.",
2294
2296
  "GET /calendars": "Public booking-page data for visitors; the admin calendar tools cover this for staff.",
2297
+ "GET /calendars/active": "A short calendar list for the pickers in a staff dashboard; the admin calendar list tool, for admin roles, returns every calendar with more detail, inactive ones too.",
2295
2298
  "POST /payments/intent": "Creates a card payment in the visitor's own browser session; staff take payment with the collect-balance tool.",
2296
2299
  "GET /brand": "Public copy of the brand settings; the brand tool for staff returns the same data.",
2297
2300
  "GET /routing-forms": "Public form shown to a visitor; staff read the whole form, rules and fallback included, with scheduling_get_routing_form.",
@@ -1,5 +1,6 @@
1
1
  // src/agent/appointment-tools.ts
2
2
  var APPOINTMENT_FIELDS = "id, calendarId, calendarName, staffName, typeId, typeName, startTime, endTime, duration, timezone, status, clientName, clientEmail, clientPhone, intakeResponses, staffNotes, location, paymentId, paymentStatus, paymentAmount, depositAmount, paymentProvider, couponCode, discountAmount, isGroup, manageToken, createdAt";
3
+ var STAFF_APPOINTMENT_FIELDS = "id, calendarId, calendarName, staffName, typeId, typeName, startTime, endTime, duration, timezone, status, clientName, clientEmail, clientPhone, intakeResponses, staffNotes, location, paymentId, paymentStatus, paymentAmount, depositAmount, paymentProvider, couponCode, discountAmount, isGroup, createdAt";
3
4
  var ID = { name: "id", type: "string", required: true, description: "Appointment id" };
4
5
  var APPOINTMENT_TOOLS = [
5
6
  {
@@ -178,7 +179,7 @@ var APPOINTMENT_TOOLS = [
178
179
  description: "Cancel an appointment as staff. The calendar entry is removed, the staff member is notified and a paid booking is flagged for refund review. This route does not message the client itself; the host may send a notice when it hears the appointment.cancelled event.",
179
180
  params: [ID, { name: "reason", type: "string", required: false, description: "Why, up to 500 characters; stored as the cancellation reason" }],
180
181
  example: { id: "appt_1", reason: "Staff member is unwell" },
181
- responseShape: `{ ${APPOINTMENT_FIELDS} } with status "CANCELLED"`,
182
+ responseShape: `{ ${STAFF_APPOINTMENT_FIELDS} } with status "CANCELLED"`,
182
183
  pitfalls: ["Staff can cancel even after the type's client cancellation deadline; those limits apply only to the client's own link. Refused with 409 only when the appointment is no longer pending or confirmed."],
183
184
  whenToUse: "When staff, not the client, ends the booking.",
184
185
  dataSensitivity: "sensitive",
@@ -198,7 +199,7 @@ var APPOINTMENT_TOOLS = [
198
199
  description: "Move an appointment to a new start time on the same calendar. The client is sent a reschedule notice and their reminders are redone for the new time.",
199
200
  params: [ID, { name: "newStartTime", type: "string", required: true, description: "New start in UTC, ending in Z; a time with no zone is read in the server's own zone and lands in the wrong place" }],
200
201
  example: { id: "appt_1", newStartTime: "2026-11-04T16:00:00Z" },
201
- responseShape: `{ ${APPOINTMENT_FIELDS} }`,
202
+ responseShape: `{ ${STAFF_APPOINTMENT_FIELDS} }`,
202
203
  whenToUse: "When a time change was asked for. Check availability for the new time first.",
203
204
  pitfalls: ["A time that is taken, a time in the past, an appointment that has already started, a type that does not allow moving, or a change made at the same moment by someone else, is refused."],
204
205
  dataSensitivity: "sensitive",
@@ -242,9 +243,9 @@ var APPOINTMENT_TOOLS = [
242
243
  description: "Hand an appointment to a different calendar, which means a different staff member, at the same time.",
243
244
  params: [ID, { name: "calendarId", type: "string", required: true, description: "Calendar to move it to" }],
244
245
  example: { id: "appt_1", calendarId: "cal_2" },
245
- responseShape: "{ id, calendarId, typeId, startTime, endTime, duration, timezone, clientName, clientEmail, clientPhone, status, staffNotes, location, paymentStatus, manageToken, createdAt, updatedAt } (the stored record, which has more fields than the other appointment answers)",
246
+ responseShape: "{ id, calendarId, typeId, startTime, endTime, duration, timezone, clientName, clientEmail, clientPhone, status, staffNotes, location, paymentStatus, createdAt, updatedAt } (the stored record without the client's private manage token)",
246
247
  whenToUse: "When a different person should take the appointment.",
247
- pitfalls: ["The answer is the stored record and holds the client's private manage token; never repeat it in a message.", "Admin roles only. Only pending or confirmed appointments, and not group sessions. The new calendar must be in the appointment type's team and free at that time; otherwise it is refused."],
248
+ pitfalls: ["Admin roles only. Only pending or confirmed appointments, and not group sessions. The new calendar must be in the appointment type's team and free at that time; otherwise it is refused."],
248
249
  dataSensitivity: "sensitive",
249
250
  risk: "act",
250
251
  requiresApproval: {
@@ -262,7 +263,7 @@ var APPOINTMENT_TOOLS = [
262
263
  description: "Record that the client did not come.",
263
264
  params: [ID],
264
265
  example: { id: "appt_1" },
265
- responseShape: `{ ${APPOINTMENT_FIELDS} } with status "NO_SHOW"`,
266
+ responseShape: `{ ${STAFF_APPOINTMENT_FIELDS} } with status "NO_SHOW"`,
266
267
  whenToUse: "After the start time has passed and the client did not arrive.",
267
268
  pitfalls: ["Refused with 409 unless the appointment is pending or confirmed and its start time has passed."],
268
269
  dataSensitivity: "sensitive",
@@ -982,6 +983,7 @@ var CALENDAR_TOOLS = [
982
983
  whenToUse: "To rename a calendar, change its time zone or slot size, link it to a person, or switch it off or on.",
983
984
  pitfalls: [
984
985
  "Changing the time zone changes what the opening hours mean in real time.",
986
+ "Renaming a calendar to the name of another active calendar, ignoring capital letters, is refused with 409. A name that only gives the same web address is not checked on rename, because renaming never changes the web address.",
985
987
  "Switching off the last active calendar is refused with 409, as archiving is. If the other changes in the same request then fail to save, the calendar is switched back on.",
986
988
  "Linking a calendar to a person (userId) changes who can see it when staff are limited to their groups.",
987
989
  "Switching a calendar back on (isActive true) does not give back its short booking address; only the organization-qualified address works until it is registered again."
@@ -2263,6 +2265,7 @@ var SCHEDULING_AGENT_EXCLUDED = {
2263
2265
  "GET /widget-init": "Boots the public booking widget in a visitor's browser; an agent reads the same facts from the type and calendar tools.",
2264
2266
  "GET /type": "Public page data for one booking link; the staff tools list the same types.",
2265
2267
  "GET /calendars": "Public booking-page data for visitors; the admin calendar tools cover this for staff.",
2268
+ "GET /calendars/active": "A short calendar list for the pickers in a staff dashboard; the admin calendar list tool, for admin roles, returns every calendar with more detail, inactive ones too.",
2266
2269
  "POST /payments/intent": "Creates a card payment in the visitor's own browser session; staff take payment with the collect-balance tool.",
2267
2270
  "GET /brand": "Public copy of the brand settings; the brand tool for staff returns the same data.",
2268
2271
  "GET /routing-forms": "Public form shown to a visitor; staff read the whole form, rules and fallback included, with scheduling_get_routing_form.",
package/dist/index.d.mts CHANGED
@@ -88,6 +88,51 @@ declare class UnverifiedPaymentError extends Error {
88
88
  constructor(paymentId: string, cause: unknown);
89
89
  }
90
90
 
91
+ /** The slice of the Stripe client this adapter uses, so tests can supply a fake. */
92
+ interface StripeLike {
93
+ paymentIntents: {
94
+ create(params: {
95
+ amount: number;
96
+ currency: string;
97
+ metadata?: Record<string, string>;
98
+ }, options?: {
99
+ idempotencyKey?: string;
100
+ }): Promise<StripeIntent>;
101
+ retrieve(id: string, params?: {
102
+ expand?: string[];
103
+ }): Promise<StripeIntent>;
104
+ };
105
+ refunds: {
106
+ create(params: {
107
+ payment_intent: string;
108
+ amount?: number;
109
+ }, options?: {
110
+ idempotencyKey?: string;
111
+ }): Promise<{
112
+ id: string;
113
+ amount: number;
114
+ status: string | null;
115
+ currency?: string;
116
+ }>;
117
+ };
118
+ }
119
+ interface StripeIntent {
120
+ id: string;
121
+ amount: number;
122
+ currency: string;
123
+ status: string;
124
+ client_secret?: string | null;
125
+ metadata?: Record<string, string> | null;
126
+ latest_charge?: string | {
127
+ amount_refunded?: number;
128
+ } | null;
129
+ }
130
+ declare function isSupportedCurrency(currency: string | undefined): boolean;
131
+ declare function createStripePaymentAdapter(client: StripeLike): PaymentAdapter;
132
+
133
+ /** Returns the key when it is a Stripe test-mode secret key. A live key must never reach a script that creates and refunds payments. */
134
+ declare function assertStripeTestKey(raw: string | undefined): string;
135
+
91
136
  /**
92
137
  * Converts a Prisma Decimal (or anything Number() can coerce) to integer cents, rounded to the nearest cent.
93
138
  * Throws SchedulingValidationError (SCHED_406) instead of returning NaN: a null or non-numeric value almost
@@ -271,6 +316,42 @@ interface BearerStaffResolverInput {
271
316
  /** Signs in a request from its `Authorization: Bearer <token>` header; the host decides what a token means. */
272
317
  declare function createBearerStaffResolver(input: BearerStaffResolverInput): StaffResolver;
273
318
 
319
+ type StaffScope = {
320
+ mode: 'unrestricted';
321
+ } | {
322
+ mode: 'restricted';
323
+ visibleUserIds: string[];
324
+ };
325
+ /**
326
+ * A calendar with no staff member linked to it is visible to everyone, in either mode: until someone links a
327
+ * calendar to a person it is not part of any team's data.
328
+ */
329
+ declare function isCalendarVisibleInScope(calendarUserId: string | null, scope: StaffScope): boolean;
330
+ /** A filter that narrows a calendar or appointment query to what the scope allows, or undefined when nothing is hidden. */
331
+ declare function calendarVisibilityFilter(scope: StaffScope): {
332
+ OR: [{
333
+ userId: {
334
+ in: string[];
335
+ };
336
+ }, {
337
+ userId: null;
338
+ }];
339
+ } | undefined;
340
+ /**
341
+ * The ids of the calendars linked to a visible staff member, or undefined when nothing is hidden. Unlinked calendars
342
+ * are not in the list; a caller that wants them adds `userId: null` itself, as calendarVisibilityFilter does.
343
+ */
344
+ declare function visibleCalendarIdsInScope(db: Pick<SchedulingDb, 'schedulingCalendar'>, scope: StaffScope): Promise<string[] | undefined>;
345
+ /**
346
+ * Whether the scope lets this person see the calendar. A calendar that does not exist is not visible, so a hidden one
347
+ * and a missing one look the same. Pass the scope as a promise to look the calendar up while the scope is worked out.
348
+ */
349
+ declare function canSeeCalendarInScope(db: Pick<SchedulingDb, 'schedulingCalendar'>, calendarId: string, scope: StaffScope | Promise<StaffScope>): Promise<boolean>;
350
+ /** Whether the scope lets this person see the appointment, by the calendar it is on. False when it does not exist. */
351
+ declare function canSeeAppointmentInScope(db: Pick<SchedulingDb, 'appointment'>, appointmentId: string, scope: StaffScope | Promise<StaffScope>): Promise<boolean>;
352
+ /** The visibility half of a StaffContext, for a host that works out the scope itself. `getScope` runs on every question. */
353
+ declare function createScopedVisibility(db: SchedulingDb, getScope: () => Promise<StaffScope>): Pick<StaffContext, 'visibleCalendars' | 'visibleCalendarIds' | 'canSeeCalendar' | 'canSeeAppointment'>;
354
+
274
355
  interface NodeListenerOptions {
275
356
  /** The address this server is reached at from outside, such as https://api.example.com. */
276
357
  publicUrl: string;
@@ -288,4 +369,4 @@ declare function createNodeListener(api: {
288
369
  handle(request: Request): Promise<Response>;
289
370
  }, options: NodeListenerOptions): (incoming: IncomingMessage, outgoing: ServerResponse) => void;
290
371
 
291
- export { ALL_REFUND_STATUSES, AvailabilityCache, BALANCE_APPOINTMENT_SELECT, BALANCE_BLOCKED_APPOINTMENT_STATUS, BALANCE_REQUIRED_PAYMENT_STATUS, BALANCE_REQUIRED_REFUND_STATUS, BalanceIntentGenerationsExhaustedError, BalancePaymentControl, BalanceRequestInProgressError, type BearerStaffResolverInput, HttpMethod, type NodeListenerOptions, type Pagination, PublicBookingResolver, PublicOrganizationResolver, RETRYABLE_REFUND_STATUSES, RateLimitTier, RefundOutcomePersistenceError, Route, type SchedulingApi, type SchedulingApiConfig, SchedulingCache, SchedulingHost, type SchedulingServiceError, type SignedInPerson, StaffContext, type StaffContextInput, StaffResolver, TERMINAL_SUCCESS_STATUSES, TOKEN_TTL_DAYS, UnverifiedPaymentError, attemptLegRefund, createBalanceIntent, createBearerStaffResolver, createMemoryAvailabilityCache, createMemoryCache, createMemoryRateLimiter, createNoBalancePaymentControl, createNoPaymentAdapter, createNodeListener, createSchedulingApi, createSingleOrganizationDirectory, createSingleOrganizationResolver, createStaffContext, decimalToCents, defaultCorsHeaders, getErrorCode, getErrorMessage, getErrorRef, isSchedulingServiceError, isTokenExpired, parsePagination, persistRefundOutcome, recordBalanceIntent, runCalendarRemoveWithoutBlocking, runCalendarSyncWithoutBlocking };
372
+ export { ALL_REFUND_STATUSES, AvailabilityCache, BALANCE_APPOINTMENT_SELECT, BALANCE_BLOCKED_APPOINTMENT_STATUS, BALANCE_REQUIRED_PAYMENT_STATUS, BALANCE_REQUIRED_REFUND_STATUS, BalanceIntentGenerationsExhaustedError, BalancePaymentControl, BalanceRequestInProgressError, type BearerStaffResolverInput, HttpMethod, type NodeListenerOptions, type Pagination, PublicBookingResolver, PublicOrganizationResolver, RETRYABLE_REFUND_STATUSES, RateLimitTier, RefundOutcomePersistenceError, Route, type SchedulingApi, type SchedulingApiConfig, SchedulingCache, SchedulingHost, type SchedulingServiceError, type SignedInPerson, StaffContext, type StaffContextInput, StaffResolver, type StaffScope, type StripeLike, TERMINAL_SUCCESS_STATUSES, TOKEN_TTL_DAYS, UnverifiedPaymentError, assertStripeTestKey, attemptLegRefund, calendarVisibilityFilter, canSeeAppointmentInScope, canSeeCalendarInScope, createBalanceIntent, createBearerStaffResolver, createMemoryAvailabilityCache, createMemoryCache, createMemoryRateLimiter, createNoBalancePaymentControl, createNoPaymentAdapter, createNodeListener, createSchedulingApi, createScopedVisibility, createSingleOrganizationDirectory, createSingleOrganizationResolver, createStaffContext, createStripePaymentAdapter, decimalToCents, defaultCorsHeaders, getErrorCode, getErrorMessage, getErrorRef, isCalendarVisibleInScope, isSchedulingServiceError, isSupportedCurrency, isTokenExpired, parsePagination, persistRefundOutcome, recordBalanceIntent, runCalendarRemoveWithoutBlocking, runCalendarSyncWithoutBlocking, visibleCalendarIdsInScope };
package/dist/index.d.ts CHANGED
@@ -88,6 +88,51 @@ declare class UnverifiedPaymentError extends Error {
88
88
  constructor(paymentId: string, cause: unknown);
89
89
  }
90
90
 
91
+ /** The slice of the Stripe client this adapter uses, so tests can supply a fake. */
92
+ interface StripeLike {
93
+ paymentIntents: {
94
+ create(params: {
95
+ amount: number;
96
+ currency: string;
97
+ metadata?: Record<string, string>;
98
+ }, options?: {
99
+ idempotencyKey?: string;
100
+ }): Promise<StripeIntent>;
101
+ retrieve(id: string, params?: {
102
+ expand?: string[];
103
+ }): Promise<StripeIntent>;
104
+ };
105
+ refunds: {
106
+ create(params: {
107
+ payment_intent: string;
108
+ amount?: number;
109
+ }, options?: {
110
+ idempotencyKey?: string;
111
+ }): Promise<{
112
+ id: string;
113
+ amount: number;
114
+ status: string | null;
115
+ currency?: string;
116
+ }>;
117
+ };
118
+ }
119
+ interface StripeIntent {
120
+ id: string;
121
+ amount: number;
122
+ currency: string;
123
+ status: string;
124
+ client_secret?: string | null;
125
+ metadata?: Record<string, string> | null;
126
+ latest_charge?: string | {
127
+ amount_refunded?: number;
128
+ } | null;
129
+ }
130
+ declare function isSupportedCurrency(currency: string | undefined): boolean;
131
+ declare function createStripePaymentAdapter(client: StripeLike): PaymentAdapter;
132
+
133
+ /** Returns the key when it is a Stripe test-mode secret key. A live key must never reach a script that creates and refunds payments. */
134
+ declare function assertStripeTestKey(raw: string | undefined): string;
135
+
91
136
  /**
92
137
  * Converts a Prisma Decimal (or anything Number() can coerce) to integer cents, rounded to the nearest cent.
93
138
  * Throws SchedulingValidationError (SCHED_406) instead of returning NaN: a null or non-numeric value almost
@@ -271,6 +316,42 @@ interface BearerStaffResolverInput {
271
316
  /** Signs in a request from its `Authorization: Bearer <token>` header; the host decides what a token means. */
272
317
  declare function createBearerStaffResolver(input: BearerStaffResolverInput): StaffResolver;
273
318
 
319
+ type StaffScope = {
320
+ mode: 'unrestricted';
321
+ } | {
322
+ mode: 'restricted';
323
+ visibleUserIds: string[];
324
+ };
325
+ /**
326
+ * A calendar with no staff member linked to it is visible to everyone, in either mode: until someone links a
327
+ * calendar to a person it is not part of any team's data.
328
+ */
329
+ declare function isCalendarVisibleInScope(calendarUserId: string | null, scope: StaffScope): boolean;
330
+ /** A filter that narrows a calendar or appointment query to what the scope allows, or undefined when nothing is hidden. */
331
+ declare function calendarVisibilityFilter(scope: StaffScope): {
332
+ OR: [{
333
+ userId: {
334
+ in: string[];
335
+ };
336
+ }, {
337
+ userId: null;
338
+ }];
339
+ } | undefined;
340
+ /**
341
+ * The ids of the calendars linked to a visible staff member, or undefined when nothing is hidden. Unlinked calendars
342
+ * are not in the list; a caller that wants them adds `userId: null` itself, as calendarVisibilityFilter does.
343
+ */
344
+ declare function visibleCalendarIdsInScope(db: Pick<SchedulingDb, 'schedulingCalendar'>, scope: StaffScope): Promise<string[] | undefined>;
345
+ /**
346
+ * Whether the scope lets this person see the calendar. A calendar that does not exist is not visible, so a hidden one
347
+ * and a missing one look the same. Pass the scope as a promise to look the calendar up while the scope is worked out.
348
+ */
349
+ declare function canSeeCalendarInScope(db: Pick<SchedulingDb, 'schedulingCalendar'>, calendarId: string, scope: StaffScope | Promise<StaffScope>): Promise<boolean>;
350
+ /** Whether the scope lets this person see the appointment, by the calendar it is on. False when it does not exist. */
351
+ declare function canSeeAppointmentInScope(db: Pick<SchedulingDb, 'appointment'>, appointmentId: string, scope: StaffScope | Promise<StaffScope>): Promise<boolean>;
352
+ /** The visibility half of a StaffContext, for a host that works out the scope itself. `getScope` runs on every question. */
353
+ declare function createScopedVisibility(db: SchedulingDb, getScope: () => Promise<StaffScope>): Pick<StaffContext, 'visibleCalendars' | 'visibleCalendarIds' | 'canSeeCalendar' | 'canSeeAppointment'>;
354
+
274
355
  interface NodeListenerOptions {
275
356
  /** The address this server is reached at from outside, such as https://api.example.com. */
276
357
  publicUrl: string;
@@ -288,4 +369,4 @@ declare function createNodeListener(api: {
288
369
  handle(request: Request): Promise<Response>;
289
370
  }, options: NodeListenerOptions): (incoming: IncomingMessage, outgoing: ServerResponse) => void;
290
371
 
291
- export { ALL_REFUND_STATUSES, AvailabilityCache, BALANCE_APPOINTMENT_SELECT, BALANCE_BLOCKED_APPOINTMENT_STATUS, BALANCE_REQUIRED_PAYMENT_STATUS, BALANCE_REQUIRED_REFUND_STATUS, BalanceIntentGenerationsExhaustedError, BalancePaymentControl, BalanceRequestInProgressError, type BearerStaffResolverInput, HttpMethod, type NodeListenerOptions, type Pagination, PublicBookingResolver, PublicOrganizationResolver, RETRYABLE_REFUND_STATUSES, RateLimitTier, RefundOutcomePersistenceError, Route, type SchedulingApi, type SchedulingApiConfig, SchedulingCache, SchedulingHost, type SchedulingServiceError, type SignedInPerson, StaffContext, type StaffContextInput, StaffResolver, TERMINAL_SUCCESS_STATUSES, TOKEN_TTL_DAYS, UnverifiedPaymentError, attemptLegRefund, createBalanceIntent, createBearerStaffResolver, createMemoryAvailabilityCache, createMemoryCache, createMemoryRateLimiter, createNoBalancePaymentControl, createNoPaymentAdapter, createNodeListener, createSchedulingApi, createSingleOrganizationDirectory, createSingleOrganizationResolver, createStaffContext, decimalToCents, defaultCorsHeaders, getErrorCode, getErrorMessage, getErrorRef, isSchedulingServiceError, isTokenExpired, parsePagination, persistRefundOutcome, recordBalanceIntent, runCalendarRemoveWithoutBlocking, runCalendarSyncWithoutBlocking };
372
+ export { ALL_REFUND_STATUSES, AvailabilityCache, BALANCE_APPOINTMENT_SELECT, BALANCE_BLOCKED_APPOINTMENT_STATUS, BALANCE_REQUIRED_PAYMENT_STATUS, BALANCE_REQUIRED_REFUND_STATUS, BalanceIntentGenerationsExhaustedError, BalancePaymentControl, BalanceRequestInProgressError, type BearerStaffResolverInput, HttpMethod, type NodeListenerOptions, type Pagination, PublicBookingResolver, PublicOrganizationResolver, RETRYABLE_REFUND_STATUSES, RateLimitTier, RefundOutcomePersistenceError, Route, type SchedulingApi, type SchedulingApiConfig, SchedulingCache, SchedulingHost, type SchedulingServiceError, type SignedInPerson, StaffContext, type StaffContextInput, StaffResolver, type StaffScope, type StripeLike, TERMINAL_SUCCESS_STATUSES, TOKEN_TTL_DAYS, UnverifiedPaymentError, assertStripeTestKey, attemptLegRefund, calendarVisibilityFilter, canSeeAppointmentInScope, canSeeCalendarInScope, createBalanceIntent, createBearerStaffResolver, createMemoryAvailabilityCache, createMemoryCache, createMemoryRateLimiter, createNoBalancePaymentControl, createNoPaymentAdapter, createNodeListener, createSchedulingApi, createScopedVisibility, createSingleOrganizationDirectory, createSingleOrganizationResolver, createStaffContext, createStripePaymentAdapter, decimalToCents, defaultCorsHeaders, getErrorCode, getErrorMessage, getErrorRef, isCalendarVisibleInScope, isSchedulingServiceError, isSupportedCurrency, isTokenExpired, parsePagination, persistRefundOutcome, recordBalanceIntent, runCalendarRemoveWithoutBlocking, runCalendarSyncWithoutBlocking, visibleCalendarIdsInScope };
package/dist/index.js CHANGED
@@ -80,7 +80,11 @@ __export(index_exports, {
80
80
  UpdatePackagePurchaseSchema: () => UpdatePackagePurchaseSchema,
81
81
  UpdateRoutingFormSchema: () => UpdateRoutingFormSchema,
82
82
  UpdateServicePackageSchema: () => UpdateServicePackageSchema,
83
+ assertStripeTestKey: () => assertStripeTestKey,
83
84
  attemptLegRefund: () => attemptLegRefund,
85
+ calendarVisibilityFilter: () => calendarVisibilityFilter,
86
+ canSeeAppointmentInScope: () => canSeeAppointmentInScope,
87
+ canSeeCalendarInScope: () => canSeeCalendarInScope,
84
88
  createBalanceIntent: () => createBalanceIntent,
85
89
  createBearerStaffResolver: () => createBearerStaffResolver,
86
90
  createMemoryAvailabilityCache: () => createMemoryAvailabilityCache,
@@ -90,21 +94,26 @@ __export(index_exports, {
90
94
  createNoPaymentAdapter: () => createNoPaymentAdapter,
91
95
  createNodeListener: () => createNodeListener,
92
96
  createSchedulingApi: () => createSchedulingApi,
97
+ createScopedVisibility: () => createScopedVisibility,
93
98
  createSingleOrganizationDirectory: () => createSingleOrganizationDirectory,
94
99
  createSingleOrganizationResolver: () => createSingleOrganizationResolver,
95
100
  createStaffContext: () => createStaffContext,
101
+ createStripePaymentAdapter: () => createStripePaymentAdapter,
96
102
  decimalToCents: () => decimalToCents,
97
103
  defaultCorsHeaders: () => defaultCorsHeaders,
98
104
  getErrorCode: () => getErrorCode,
99
105
  getErrorMessage: () => getErrorMessage,
100
106
  getErrorRef: () => getErrorRef,
107
+ isCalendarVisibleInScope: () => isCalendarVisibleInScope,
101
108
  isSchedulingServiceError: () => isSchedulingServiceError,
109
+ isSupportedCurrency: () => isSupportedCurrency,
102
110
  isTokenExpired: () => isTokenExpired,
103
111
  parsePagination: () => parsePagination,
104
112
  persistRefundOutcome: () => persistRefundOutcome,
105
113
  recordBalanceIntent: () => recordBalanceIntent,
106
114
  runCalendarRemoveWithoutBlocking: () => runCalendarRemoveWithoutBlocking,
107
- runCalendarSyncWithoutBlocking: () => runCalendarSyncWithoutBlocking
115
+ runCalendarSyncWithoutBlocking: () => runCalendarSyncWithoutBlocking,
116
+ visibleCalendarIdsInScope: () => visibleCalendarIdsInScope
108
117
  });
109
118
  module.exports = __toCommonJS(index_exports);
110
119
 
@@ -1050,6 +1059,13 @@ async function requireAdminStaff(host, request, options) {
1050
1059
  return staff;
1051
1060
  }
1052
1061
 
1062
+ // src/handlers/staff-appointment.ts
1063
+ function withoutManageToken(appointment) {
1064
+ if (appointment === null || appointment === void 0) return null;
1065
+ const { manageToken: _manageToken, ...rest } = appointment;
1066
+ return rest;
1067
+ }
1068
+
1053
1069
  // src/handlers/appointment-cancel.ts
1054
1070
  async function cancelByStaff(request, { host, params }) {
1055
1071
  try {
@@ -1122,7 +1138,7 @@ async function cancelByStaff(request, { host, params }) {
1122
1138
  description: `cancelled ${appointment.clientName}'s appointment`,
1123
1139
  metadata: { appointmentId: id, clientName: appointment.clientName }
1124
1140
  });
1125
- return Response.json(result);
1141
+ return Response.json(withoutManageToken(result));
1126
1142
  } catch (error) {
1127
1143
  if (error instanceof import_scheduling13.SchedulingNotFoundError) {
1128
1144
  return Response.json({ error: error.message, ref: error.ref }, { status: 404 });
@@ -1466,7 +1482,7 @@ async function rejectAppointment(host, db, organizationId, appointment, reason)
1466
1482
  description: `rejected ${appointment.clientName}'s appointment request`,
1467
1483
  metadata: { appointmentId: id, clientName: appointment.clientName, reason }
1468
1484
  });
1469
- return Response.json({ success: true, status: "CANCELLED", appointment: result });
1485
+ return Response.json({ success: true, status: "CANCELLED", appointment: withoutManageToken(result) });
1470
1486
  }
1471
1487
  async function approveOrReject(request, { host, params }) {
1472
1488
  try {
@@ -1522,7 +1538,7 @@ async function approveOrReject(request, { host, params }) {
1522
1538
  metadata: { appointmentId: id, clientName: appointment.clientName }
1523
1539
  });
1524
1540
  const confirmedAppointment = await (0, import_scheduling15.getAppointment)(db, id);
1525
- return Response.json({ success: true, status: "CONFIRMED", appointment: confirmedAppointment });
1541
+ return Response.json({ success: true, status: "CONFIRMED", appointment: withoutManageToken(confirmedAppointment) });
1526
1542
  } catch (error) {
1527
1543
  if (getErrorCode(error) === "SCHED_306") {
1528
1544
  return Response.json({ error: "Appointment was already processed by a concurrent request" }, { status: 409 });
@@ -1612,7 +1628,7 @@ async function rescheduleByStaff(request, { host, params }) {
1612
1628
  newTime: newTime.toISOString()
1613
1629
  }
1614
1630
  });
1615
- return Response.json(result);
1631
+ return Response.json(withoutManageToken(result));
1616
1632
  } catch (error) {
1617
1633
  if (error instanceof import_scheduling16.SchedulingValidationError) return Response.json({ error: error.message }, { status: 400 });
1618
1634
  if (error instanceof import_scheduling16.SchedulingNotFoundError) return Response.json({ error: error.message }, { status: 404 });
@@ -1735,7 +1751,7 @@ async function reassignAppointment(request, { host, params }) {
1735
1751
  err instanceof Error ? err.message : err
1736
1752
  );
1737
1753
  }
1738
- return Response.json(updated);
1754
+ return Response.json(withoutManageToken(updated));
1739
1755
  } catch (error) {
1740
1756
  const ref = getErrorRef(error);
1741
1757
  console.error("[reassign]", ref, error instanceof Error ? error.message : error);
@@ -1894,7 +1910,7 @@ async function markAppointmentNoShow(request, { host, params }) {
1894
1910
  description: `marked ${appointment.clientName}'s appointment as no-show`,
1895
1911
  metadata: { appointmentId: id, clientName: appointment.clientName }
1896
1912
  });
1897
- return Response.json(result);
1913
+ return Response.json(withoutManageToken(result));
1898
1914
  } catch (error) {
1899
1915
  if (error instanceof import_scheduling18.SchedulingNotFoundError) {
1900
1916
  return Response.json({ error: error.message, ref: error.ref }, { status: 404 });
@@ -4909,6 +4925,13 @@ async function putCalendar(request, { host, params }) {
4909
4925
  const input = validation.data;
4910
4926
  const linkError = input.userId === void 0 ? null : await validateStaffLink(host, input.userId, organizationId);
4911
4927
  if (linkError) return linkError;
4928
+ if (input.name !== void 0 && input.name !== existing.name) {
4929
+ const taken = await db.schedulingCalendar.findFirst({
4930
+ where: { organizationId, isActive: true, id: { not: id }, name: { equals: input.name, mode: "insensitive" } },
4931
+ select: { id: true }
4932
+ });
4933
+ if (taken) return Response.json({ error: "A calendar with this name already exists" }, { status: 409 });
4934
+ }
4912
4935
  const archiving = input.isActive === false && existing.isActive;
4913
4936
  let archived = false;
4914
4937
  let updated;
@@ -7733,6 +7756,31 @@ async function getPublicCalendar(request, { host }) {
7733
7756
  }
7734
7757
  }
7735
7758
 
7759
+ // src/handlers/calendars-active.ts
7760
+ async function listActiveCalendars(request, { host }) {
7761
+ try {
7762
+ const staff = await requireAdminStaff(host, request, {
7763
+ action: "admin-calendars-list",
7764
+ tier: "GENERAL",
7765
+ allowAnyRole: true,
7766
+ ignoreSchedulingSwitch: true
7767
+ });
7768
+ if (staff instanceof Response) return staff;
7769
+ const { db, organizationId } = staff;
7770
+ const visibility = await staff.visibleCalendars();
7771
+ const calendars = await db.schedulingCalendar.findMany({
7772
+ // organizationId comes last so a filter can never widen the list beyond this organization.
7773
+ where: { isActive: true, ...visibility, organizationId },
7774
+ select: { id: true, name: true, slug: true, staffName: true },
7775
+ orderBy: { name: "asc" }
7776
+ });
7777
+ return Response.json(calendars);
7778
+ } catch (error) {
7779
+ console.warn("[calendars/active]", error instanceof Error ? error.message : error);
7780
+ return Response.json({ error: "Failed to fetch calendars" }, { status: 500 });
7781
+ }
7782
+ }
7783
+
7736
7784
  // src/handlers/type.ts
7737
7785
  var import_scheduling74 = require("@ordinatio/scheduling");
7738
7786
 
@@ -7949,6 +7997,7 @@ var ROUTES = [
7949
7997
  { method: "GET", path: "/type", public: true, handler: getType },
7950
7998
  { method: "GET", path: "/appointment-types", public: true, handler: getAppointmentTypes },
7951
7999
  { method: "GET", path: "/calendars", public: true, handler: getPublicCalendar },
8000
+ { method: "GET", path: "/calendars/active", public: false, handler: listActiveCalendars },
7952
8001
  { method: "GET", path: "/availability", public: true, handler: getAvailability },
7953
8002
  { method: "GET", path: "/availability/team", public: true, handler: getTeamAvailability },
7954
8003
  { method: "POST", path: "/appointments", public: true, handler: bookAppointmentRoute },
@@ -8164,6 +8213,150 @@ function createSchedulingApi(config) {
8164
8213
  return { routes, handle, handler };
8165
8214
  }
8166
8215
 
8216
+ // src/payments/stripe/stripe-payments.ts
8217
+ var TWO_DECIMAL_CURRENCIES = ["usd", "eur", "gbp", "cad", "aud"];
8218
+ var REFUSAL_TYPES = ["StripeInvalidRequestError", "StripeCardError"];
8219
+ var IN_FLIGHT_CODES = ["idempotency_key_in_use", "lock_timeout"];
8220
+ function asStripeError(error) {
8221
+ if (typeof error !== "object" || error === null) return {};
8222
+ const shape = error;
8223
+ return shape.code === void 0 && shape.raw?.code !== void 0 ? { ...shape, code: shape.raw.code } : shape;
8224
+ }
8225
+ function isKeyMismatch(error) {
8226
+ return error.type === "StripeIdempotencyError" || error.raw?.type === "idempotency_error";
8227
+ }
8228
+ function isRefusal(error) {
8229
+ return error.type !== void 0 && REFUSAL_TYPES.includes(error.type);
8230
+ }
8231
+ function isReplayedFailure(error) {
8232
+ const header = Object.entries(error.headers ?? {}).find(([name]) => name.toLowerCase() === "idempotent-replayed");
8233
+ return header?.[1] === "true";
8234
+ }
8235
+ function isSupportedCurrency(currency) {
8236
+ return currency !== void 0 && TWO_DECIMAL_CURRENCIES.includes(currency.toLowerCase());
8237
+ }
8238
+ function toMinor(amount) {
8239
+ if (!Number.isFinite(amount) || amount <= 0) return null;
8240
+ const minor = Math.round(amount * 100);
8241
+ if (minor < 1 || !Number.isSafeInteger(minor)) return null;
8242
+ return Math.abs(amount * 100 - minor) < 1e-6 ? minor : null;
8243
+ }
8244
+ function toMajor(minor, currency) {
8245
+ return isSupportedCurrency(currency) ? minor / 100 : void 0;
8246
+ }
8247
+ function unsupportedCurrency(currency) {
8248
+ return `Currency ${currency.toUpperCase()} is not supported by this adapter (supported: ${TWO_DECIMAL_CURRENCIES.join(", ").toUpperCase()})`;
8249
+ }
8250
+ var BAD_AMOUNT = "amount must be greater than 0 and have at most 2 decimals";
8251
+ function createStripePaymentAdapter(client) {
8252
+ async function verifyPayment(paymentId) {
8253
+ let intent;
8254
+ try {
8255
+ intent = await client.paymentIntents.retrieve(paymentId, { expand: ["latest_charge"] });
8256
+ } catch (error) {
8257
+ if (asStripeError(error).code === "resource_missing") return { paid: false, status: "not_found" };
8258
+ throw error;
8259
+ }
8260
+ const charge = intent.latest_charge;
8261
+ const metadata = intent.metadata ?? {};
8262
+ const currency = intent.currency.toUpperCase();
8263
+ const amount = toMajor(intent.amount, intent.currency);
8264
+ if (intent.status === "succeeded" && (typeof charge !== "object" || charge === null)) {
8265
+ return { paid: false, amount, currency, status: "refund_state_unknown", metadata };
8266
+ }
8267
+ const refunded = typeof charge === "object" && charge !== null ? charge.amount_refunded ?? 0 : 0;
8268
+ const fullyRefunded = intent.status === "succeeded" && refunded >= intent.amount;
8269
+ return {
8270
+ paid: intent.status === "succeeded" && !fullyRefunded,
8271
+ amount,
8272
+ currency,
8273
+ status: fullyRefunded ? "refunded" : intent.status,
8274
+ metadata
8275
+ };
8276
+ }
8277
+ return {
8278
+ async charge(request) {
8279
+ const currency = request.currency.toLowerCase();
8280
+ if (!isSupportedCurrency(currency)) return { success: false, error: unsupportedCurrency(request.currency) };
8281
+ const amount = toMinor(request.amount);
8282
+ if (amount === null) return { success: false, error: BAD_AMOUNT };
8283
+ let intent;
8284
+ try {
8285
+ intent = await client.paymentIntents.create(
8286
+ { amount, currency, ...request.metadata ? { metadata: request.metadata } : {} },
8287
+ request.idempotencyKey ? { idempotencyKey: request.idempotencyKey } : void 0
8288
+ );
8289
+ } catch (error) {
8290
+ const stripeError = asStripeError(error);
8291
+ if (stripeError.code && IN_FLIGHT_CODES.includes(stripeError.code)) return { success: false, code: "IN_PROGRESS", error: stripeError.message };
8292
+ if (isKeyMismatch(stripeError)) return { success: false, code: "KEY_REUSED", error: stripeError.message };
8293
+ if (isRefusal(stripeError)) return { success: false, error: stripeError.message };
8294
+ throw error;
8295
+ }
8296
+ let status = intent.status;
8297
+ if (request.idempotencyKey) {
8298
+ try {
8299
+ status = (await client.paymentIntents.retrieve(intent.id)).status;
8300
+ } catch (error) {
8301
+ throw new UnverifiedPaymentError(intent.id, error);
8302
+ }
8303
+ if (status === "canceled") return { success: false, code: "CANCELED", error: "the payment saved for this key was canceled; retry with a new key" };
8304
+ }
8305
+ return {
8306
+ success: true,
8307
+ paymentId: intent.id,
8308
+ status: status === "succeeded" ? "SUCCEEDED" : "REQUIRES_ACTION",
8309
+ clientSecret: intent.client_secret ?? void 0
8310
+ };
8311
+ },
8312
+ verify: verifyPayment,
8313
+ async refund(paymentId, options = {}) {
8314
+ let amountMinor;
8315
+ if (options.amount !== void 0) {
8316
+ if (!options.idempotencyKey) return { success: false, error: "a partial refund needs an idempotencyKey" };
8317
+ const minor = toMinor(options.amount);
8318
+ if (minor === null) return { success: false, error: BAD_AMOUNT };
8319
+ amountMinor = minor;
8320
+ const check = await verifyPayment(paymentId);
8321
+ if (check.status === "not_found") return { success: false, error: "unknown payment" };
8322
+ if (!isSupportedCurrency(check.currency)) return { success: false, error: unsupportedCurrency(check.currency ?? "unknown") };
8323
+ }
8324
+ try {
8325
+ const refund = await client.refunds.create(
8326
+ { payment_intent: paymentId, ...amountMinor !== void 0 ? { amount: amountMinor } : {} },
8327
+ options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : void 0
8328
+ );
8329
+ const amount = toMajor(refund.amount, refund.currency);
8330
+ if (refund.status === "succeeded") return { success: true, refundId: refund.id, amount, status: "SUCCEEDED" };
8331
+ if (refund.status === "pending" || refund.status === "requires_action") {
8332
+ return { success: true, refundId: refund.id, amount, status: "PENDING" };
8333
+ }
8334
+ return { success: false, refundId: refund.id, error: `Stripe refund ${refund.status ?? "unknown"}` };
8335
+ } catch (error) {
8336
+ const stripeError = asStripeError(error);
8337
+ const requestId = stripeError.requestId;
8338
+ if (stripeError.code === "charge_already_refunded") return { success: false, error: stripeError.message, code: "ALREADY_REFUNDED", requestId };
8339
+ if (stripeError.code && IN_FLIGHT_CODES.includes(stripeError.code)) return { success: false, error: stripeError.message, code: "IN_PROGRESS", requestId };
8340
+ if (stripeError.code === "resource_missing") return { success: false, error: "unknown payment", requestId };
8341
+ if (isKeyMismatch(stripeError)) return { success: false, error: stripeError.message, code: "KEY_REUSED", requestId };
8342
+ if (isRefusal(stripeError)) {
8343
+ return { success: false, error: stripeError.message, requestId, ...isReplayedFailure(stripeError) ? { code: "REPLAYED_FAILURE" } : {} };
8344
+ }
8345
+ if (isReplayedFailure(stripeError)) return { success: false, error: stripeError.message, requestId, code: "REPLAYED_FAILURE" };
8346
+ throw error;
8347
+ }
8348
+ }
8349
+ };
8350
+ }
8351
+
8352
+ // src/payments/stripe/stripe-test-key.ts
8353
+ function assertStripeTestKey(raw) {
8354
+ const key = raw?.trim();
8355
+ if (!key) throw new Error("STRIPE_SECRET_KEY is not set");
8356
+ if (!key.startsWith("sk_test_")) throw new Error("STRIPE_SECRET_KEY is not a test-mode secret key (it must start with sk_test_)");
8357
+ return key;
8358
+ }
8359
+
8167
8360
  // src/staff/simple-staff.ts
8168
8361
  var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
8169
8362
  function createStaffContext(input) {
@@ -8202,6 +8395,47 @@ function createBearerStaffResolver(input) {
8202
8395
  };
8203
8396
  }
8204
8397
 
8398
+ // src/staff/staff-scope.ts
8399
+ function isCalendarVisibleInScope(calendarUserId, scope) {
8400
+ if (calendarUserId === null) return true;
8401
+ if (scope.mode === "unrestricted") return true;
8402
+ return scope.visibleUserIds.includes(calendarUserId);
8403
+ }
8404
+ function calendarVisibilityFilter(scope) {
8405
+ if (scope.mode === "unrestricted") return void 0;
8406
+ return { OR: [{ userId: { in: scope.visibleUserIds } }, { userId: null }] };
8407
+ }
8408
+ async function visibleCalendarIdsInScope(db, scope) {
8409
+ if (scope.mode === "unrestricted") return void 0;
8410
+ const calendars = await db.schedulingCalendar.findMany({
8411
+ where: { userId: { in: scope.visibleUserIds } },
8412
+ select: { id: true }
8413
+ });
8414
+ return calendars.map((calendar) => calendar.id);
8415
+ }
8416
+ async function canSeeCalendarInScope(db, calendarId, scope) {
8417
+ const [resolved, calendar] = await Promise.all([
8418
+ scope,
8419
+ db.schedulingCalendar.findUnique({ where: { id: calendarId }, select: { userId: true } })
8420
+ ]);
8421
+ return calendar != null && isCalendarVisibleInScope(calendar.userId, resolved);
8422
+ }
8423
+ async function canSeeAppointmentInScope(db, appointmentId, scope) {
8424
+ const [resolved, appointment] = await Promise.all([
8425
+ scope,
8426
+ db.appointment.findUnique({ where: { id: appointmentId }, select: { calendar: { select: { userId: true } } } })
8427
+ ]);
8428
+ return appointment != null && isCalendarVisibleInScope(appointment.calendar.userId, resolved);
8429
+ }
8430
+ function createScopedVisibility(db, getScope) {
8431
+ return {
8432
+ visibleCalendars: async () => calendarVisibilityFilter(await getScope()) ?? null,
8433
+ visibleCalendarIds: async () => await visibleCalendarIdsInScope(db, await getScope()),
8434
+ canSeeCalendar: async (calendarId) => await canSeeCalendarInScope(db, calendarId, getScope()),
8435
+ canSeeAppointment: async (appointmentId) => await canSeeAppointmentInScope(db, appointmentId, getScope())
8436
+ };
8437
+ }
8438
+
8205
8439
  // src/node/node-listener.ts
8206
8440
  var CONNECTION_HEADERS = ["host", "connection", "content-length", "transfer-encoding", "keep-alive", "upgrade"];
8207
8441
  var PROXY_HEADERS = ["x-forwarded-for", "x-real-ip"];
@@ -8325,7 +8559,11 @@ function createNodeListener(api, options) {
8325
8559
  UpdatePackagePurchaseSchema,
8326
8560
  UpdateRoutingFormSchema,
8327
8561
  UpdateServicePackageSchema,
8562
+ assertStripeTestKey,
8328
8563
  attemptLegRefund,
8564
+ calendarVisibilityFilter,
8565
+ canSeeAppointmentInScope,
8566
+ canSeeCalendarInScope,
8329
8567
  createBalanceIntent,
8330
8568
  createBearerStaffResolver,
8331
8569
  createMemoryAvailabilityCache,
@@ -8335,19 +8573,24 @@ function createNodeListener(api, options) {
8335
8573
  createNoPaymentAdapter,
8336
8574
  createNodeListener,
8337
8575
  createSchedulingApi,
8576
+ createScopedVisibility,
8338
8577
  createSingleOrganizationDirectory,
8339
8578
  createSingleOrganizationResolver,
8340
8579
  createStaffContext,
8580
+ createStripePaymentAdapter,
8341
8581
  decimalToCents,
8342
8582
  defaultCorsHeaders,
8343
8583
  getErrorCode,
8344
8584
  getErrorMessage,
8345
8585
  getErrorRef,
8586
+ isCalendarVisibleInScope,
8346
8587
  isSchedulingServiceError,
8588
+ isSupportedCurrency,
8347
8589
  isTokenExpired,
8348
8590
  parsePagination,
8349
8591
  persistRefundOutcome,
8350
8592
  recordBalanceIntent,
8351
8593
  runCalendarRemoveWithoutBlocking,
8352
- runCalendarSyncWithoutBlocking
8594
+ runCalendarSyncWithoutBlocking,
8595
+ visibleCalendarIdsInScope
8353
8596
  });
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 });
@@ -4432,6 +4439,13 @@ async function putCalendar(request, { host, params }) {
4432
4439
  const input = validation.data;
4433
4440
  const linkError = input.userId === void 0 ? null : await validateStaffLink(host, input.userId, organizationId);
4434
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
+ }
4435
4449
  const archiving = input.isActive === false && existing.isActive;
4436
4450
  let archived = false;
4437
4451
  let updated;
@@ -7277,6 +7291,31 @@ async function getPublicCalendar(request, { host }) {
7277
7291
  }
7278
7292
  }
7279
7293
 
7294
+ // src/handlers/calendars-active.ts
7295
+ async function listActiveCalendars(request, { host }) {
7296
+ try {
7297
+ const staff = await requireAdminStaff(host, request, {
7298
+ action: "admin-calendars-list",
7299
+ tier: "GENERAL",
7300
+ allowAnyRole: true,
7301
+ ignoreSchedulingSwitch: true
7302
+ });
7303
+ if (staff instanceof Response) return staff;
7304
+ const { db, organizationId } = staff;
7305
+ const visibility = await staff.visibleCalendars();
7306
+ const calendars = await db.schedulingCalendar.findMany({
7307
+ // organizationId comes last so a filter can never widen the list beyond this organization.
7308
+ where: { isActive: true, ...visibility, organizationId },
7309
+ select: { id: true, name: true, slug: true, staffName: true },
7310
+ orderBy: { name: "asc" }
7311
+ });
7312
+ return Response.json(calendars);
7313
+ } catch (error) {
7314
+ console.warn("[calendars/active]", error instanceof Error ? error.message : error);
7315
+ return Response.json({ error: "Failed to fetch calendars" }, { status: 500 });
7316
+ }
7317
+ }
7318
+
7280
7319
  // src/handlers/type.ts
7281
7320
  import { schedError as schedError31 } from "@ordinatio/scheduling";
7282
7321
 
@@ -7493,6 +7532,7 @@ var ROUTES = [
7493
7532
  { method: "GET", path: "/type", public: true, handler: getType },
7494
7533
  { method: "GET", path: "/appointment-types", public: true, handler: getAppointmentTypes },
7495
7534
  { method: "GET", path: "/calendars", public: true, handler: getPublicCalendar },
7535
+ { method: "GET", path: "/calendars/active", public: false, handler: listActiveCalendars },
7496
7536
  { method: "GET", path: "/availability", public: true, handler: getAvailability },
7497
7537
  { method: "GET", path: "/availability/team", public: true, handler: getTeamAvailability },
7498
7538
  { method: "POST", path: "/appointments", public: true, handler: bookAppointmentRoute },
@@ -7708,6 +7748,150 @@ function createSchedulingApi(config) {
7708
7748
  return { routes, handle, handler };
7709
7749
  }
7710
7750
 
7751
+ // src/payments/stripe/stripe-payments.ts
7752
+ var TWO_DECIMAL_CURRENCIES = ["usd", "eur", "gbp", "cad", "aud"];
7753
+ var REFUSAL_TYPES = ["StripeInvalidRequestError", "StripeCardError"];
7754
+ var IN_FLIGHT_CODES = ["idempotency_key_in_use", "lock_timeout"];
7755
+ function asStripeError(error) {
7756
+ if (typeof error !== "object" || error === null) return {};
7757
+ const shape = error;
7758
+ return shape.code === void 0 && shape.raw?.code !== void 0 ? { ...shape, code: shape.raw.code } : shape;
7759
+ }
7760
+ function isKeyMismatch(error) {
7761
+ return error.type === "StripeIdempotencyError" || error.raw?.type === "idempotency_error";
7762
+ }
7763
+ function isRefusal(error) {
7764
+ return error.type !== void 0 && REFUSAL_TYPES.includes(error.type);
7765
+ }
7766
+ function isReplayedFailure(error) {
7767
+ const header = Object.entries(error.headers ?? {}).find(([name]) => name.toLowerCase() === "idempotent-replayed");
7768
+ return header?.[1] === "true";
7769
+ }
7770
+ function isSupportedCurrency(currency) {
7771
+ return currency !== void 0 && TWO_DECIMAL_CURRENCIES.includes(currency.toLowerCase());
7772
+ }
7773
+ function toMinor(amount) {
7774
+ if (!Number.isFinite(amount) || amount <= 0) return null;
7775
+ const minor = Math.round(amount * 100);
7776
+ if (minor < 1 || !Number.isSafeInteger(minor)) return null;
7777
+ return Math.abs(amount * 100 - minor) < 1e-6 ? minor : null;
7778
+ }
7779
+ function toMajor(minor, currency) {
7780
+ return isSupportedCurrency(currency) ? minor / 100 : void 0;
7781
+ }
7782
+ function unsupportedCurrency(currency) {
7783
+ return `Currency ${currency.toUpperCase()} is not supported by this adapter (supported: ${TWO_DECIMAL_CURRENCIES.join(", ").toUpperCase()})`;
7784
+ }
7785
+ var BAD_AMOUNT = "amount must be greater than 0 and have at most 2 decimals";
7786
+ function createStripePaymentAdapter(client) {
7787
+ async function verifyPayment(paymentId) {
7788
+ let intent;
7789
+ try {
7790
+ intent = await client.paymentIntents.retrieve(paymentId, { expand: ["latest_charge"] });
7791
+ } catch (error) {
7792
+ if (asStripeError(error).code === "resource_missing") return { paid: false, status: "not_found" };
7793
+ throw error;
7794
+ }
7795
+ const charge = intent.latest_charge;
7796
+ const metadata = intent.metadata ?? {};
7797
+ const currency = intent.currency.toUpperCase();
7798
+ const amount = toMajor(intent.amount, intent.currency);
7799
+ if (intent.status === "succeeded" && (typeof charge !== "object" || charge === null)) {
7800
+ return { paid: false, amount, currency, status: "refund_state_unknown", metadata };
7801
+ }
7802
+ const refunded = typeof charge === "object" && charge !== null ? charge.amount_refunded ?? 0 : 0;
7803
+ const fullyRefunded = intent.status === "succeeded" && refunded >= intent.amount;
7804
+ return {
7805
+ paid: intent.status === "succeeded" && !fullyRefunded,
7806
+ amount,
7807
+ currency,
7808
+ status: fullyRefunded ? "refunded" : intent.status,
7809
+ metadata
7810
+ };
7811
+ }
7812
+ return {
7813
+ async charge(request) {
7814
+ const currency = request.currency.toLowerCase();
7815
+ if (!isSupportedCurrency(currency)) return { success: false, error: unsupportedCurrency(request.currency) };
7816
+ const amount = toMinor(request.amount);
7817
+ if (amount === null) return { success: false, error: BAD_AMOUNT };
7818
+ let intent;
7819
+ try {
7820
+ intent = await client.paymentIntents.create(
7821
+ { amount, currency, ...request.metadata ? { metadata: request.metadata } : {} },
7822
+ request.idempotencyKey ? { idempotencyKey: request.idempotencyKey } : void 0
7823
+ );
7824
+ } catch (error) {
7825
+ const stripeError = asStripeError(error);
7826
+ if (stripeError.code && IN_FLIGHT_CODES.includes(stripeError.code)) return { success: false, code: "IN_PROGRESS", error: stripeError.message };
7827
+ if (isKeyMismatch(stripeError)) return { success: false, code: "KEY_REUSED", error: stripeError.message };
7828
+ if (isRefusal(stripeError)) return { success: false, error: stripeError.message };
7829
+ throw error;
7830
+ }
7831
+ let status = intent.status;
7832
+ if (request.idempotencyKey) {
7833
+ try {
7834
+ status = (await client.paymentIntents.retrieve(intent.id)).status;
7835
+ } catch (error) {
7836
+ throw new UnverifiedPaymentError(intent.id, error);
7837
+ }
7838
+ if (status === "canceled") return { success: false, code: "CANCELED", error: "the payment saved for this key was canceled; retry with a new key" };
7839
+ }
7840
+ return {
7841
+ success: true,
7842
+ paymentId: intent.id,
7843
+ status: status === "succeeded" ? "SUCCEEDED" : "REQUIRES_ACTION",
7844
+ clientSecret: intent.client_secret ?? void 0
7845
+ };
7846
+ },
7847
+ verify: verifyPayment,
7848
+ async refund(paymentId, options = {}) {
7849
+ let amountMinor;
7850
+ if (options.amount !== void 0) {
7851
+ if (!options.idempotencyKey) return { success: false, error: "a partial refund needs an idempotencyKey" };
7852
+ const minor = toMinor(options.amount);
7853
+ if (minor === null) return { success: false, error: BAD_AMOUNT };
7854
+ amountMinor = minor;
7855
+ const check = await verifyPayment(paymentId);
7856
+ if (check.status === "not_found") return { success: false, error: "unknown payment" };
7857
+ if (!isSupportedCurrency(check.currency)) return { success: false, error: unsupportedCurrency(check.currency ?? "unknown") };
7858
+ }
7859
+ try {
7860
+ const refund = await client.refunds.create(
7861
+ { payment_intent: paymentId, ...amountMinor !== void 0 ? { amount: amountMinor } : {} },
7862
+ options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : void 0
7863
+ );
7864
+ const amount = toMajor(refund.amount, refund.currency);
7865
+ if (refund.status === "succeeded") return { success: true, refundId: refund.id, amount, status: "SUCCEEDED" };
7866
+ if (refund.status === "pending" || refund.status === "requires_action") {
7867
+ return { success: true, refundId: refund.id, amount, status: "PENDING" };
7868
+ }
7869
+ return { success: false, refundId: refund.id, error: `Stripe refund ${refund.status ?? "unknown"}` };
7870
+ } catch (error) {
7871
+ const stripeError = asStripeError(error);
7872
+ const requestId = stripeError.requestId;
7873
+ if (stripeError.code === "charge_already_refunded") return { success: false, error: stripeError.message, code: "ALREADY_REFUNDED", requestId };
7874
+ if (stripeError.code && IN_FLIGHT_CODES.includes(stripeError.code)) return { success: false, error: stripeError.message, code: "IN_PROGRESS", requestId };
7875
+ if (stripeError.code === "resource_missing") return { success: false, error: "unknown payment", requestId };
7876
+ if (isKeyMismatch(stripeError)) return { success: false, error: stripeError.message, code: "KEY_REUSED", requestId };
7877
+ if (isRefusal(stripeError)) {
7878
+ return { success: false, error: stripeError.message, requestId, ...isReplayedFailure(stripeError) ? { code: "REPLAYED_FAILURE" } : {} };
7879
+ }
7880
+ if (isReplayedFailure(stripeError)) return { success: false, error: stripeError.message, requestId, code: "REPLAYED_FAILURE" };
7881
+ throw error;
7882
+ }
7883
+ }
7884
+ };
7885
+ }
7886
+
7887
+ // src/payments/stripe/stripe-test-key.ts
7888
+ function assertStripeTestKey(raw) {
7889
+ const key = raw?.trim();
7890
+ if (!key) throw new Error("STRIPE_SECRET_KEY is not set");
7891
+ if (!key.startsWith("sk_test_")) throw new Error("STRIPE_SECRET_KEY is not a test-mode secret key (it must start with sk_test_)");
7892
+ return key;
7893
+ }
7894
+
7711
7895
  // src/staff/simple-staff.ts
7712
7896
  var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
7713
7897
  function createStaffContext(input) {
@@ -7746,6 +7930,47 @@ function createBearerStaffResolver(input) {
7746
7930
  };
7747
7931
  }
7748
7932
 
7933
+ // src/staff/staff-scope.ts
7934
+ function isCalendarVisibleInScope(calendarUserId, scope) {
7935
+ if (calendarUserId === null) return true;
7936
+ if (scope.mode === "unrestricted") return true;
7937
+ return scope.visibleUserIds.includes(calendarUserId);
7938
+ }
7939
+ function calendarVisibilityFilter(scope) {
7940
+ if (scope.mode === "unrestricted") return void 0;
7941
+ return { OR: [{ userId: { in: scope.visibleUserIds } }, { userId: null }] };
7942
+ }
7943
+ async function visibleCalendarIdsInScope(db, scope) {
7944
+ if (scope.mode === "unrestricted") return void 0;
7945
+ const calendars = await db.schedulingCalendar.findMany({
7946
+ where: { userId: { in: scope.visibleUserIds } },
7947
+ select: { id: true }
7948
+ });
7949
+ return calendars.map((calendar) => calendar.id);
7950
+ }
7951
+ async function canSeeCalendarInScope(db, calendarId, scope) {
7952
+ const [resolved, calendar] = await Promise.all([
7953
+ scope,
7954
+ db.schedulingCalendar.findUnique({ where: { id: calendarId }, select: { userId: true } })
7955
+ ]);
7956
+ return calendar != null && isCalendarVisibleInScope(calendar.userId, resolved);
7957
+ }
7958
+ async function canSeeAppointmentInScope(db, appointmentId, scope) {
7959
+ const [resolved, appointment] = await Promise.all([
7960
+ scope,
7961
+ db.appointment.findUnique({ where: { id: appointmentId }, select: { calendar: { select: { userId: true } } } })
7962
+ ]);
7963
+ return appointment != null && isCalendarVisibleInScope(appointment.calendar.userId, resolved);
7964
+ }
7965
+ function createScopedVisibility(db, getScope) {
7966
+ return {
7967
+ visibleCalendars: async () => calendarVisibilityFilter(await getScope()) ?? null,
7968
+ visibleCalendarIds: async () => await visibleCalendarIdsInScope(db, await getScope()),
7969
+ canSeeCalendar: async (calendarId) => await canSeeCalendarInScope(db, calendarId, getScope()),
7970
+ canSeeAppointment: async (appointmentId) => await canSeeAppointmentInScope(db, appointmentId, getScope())
7971
+ };
7972
+ }
7973
+
7749
7974
  // src/node/node-listener.ts
7750
7975
  var CONNECTION_HEADERS = ["host", "connection", "content-length", "transfer-encoding", "keep-alive", "upgrade"];
7751
7976
  var PROXY_HEADERS = ["x-forwarded-for", "x-real-ip"];
@@ -7868,7 +8093,11 @@ export {
7868
8093
  UpdatePackagePurchaseSchema,
7869
8094
  UpdateRoutingFormSchema,
7870
8095
  UpdateServicePackageSchema,
8096
+ assertStripeTestKey,
7871
8097
  attemptLegRefund,
8098
+ calendarVisibilityFilter,
8099
+ canSeeAppointmentInScope,
8100
+ canSeeCalendarInScope,
7872
8101
  createBalanceIntent,
7873
8102
  createBearerStaffResolver,
7874
8103
  createMemoryAvailabilityCache,
@@ -7878,19 +8107,24 @@ export {
7878
8107
  createNoPaymentAdapter,
7879
8108
  createNodeListener,
7880
8109
  createSchedulingApi,
8110
+ createScopedVisibility,
7881
8111
  createSingleOrganizationDirectory,
7882
8112
  createSingleOrganizationResolver,
7883
8113
  createStaffContext,
8114
+ createStripePaymentAdapter,
7884
8115
  decimalToCents,
7885
8116
  defaultCorsHeaders,
7886
8117
  getErrorCode,
7887
8118
  getErrorMessage,
7888
8119
  getErrorRef,
8120
+ isCalendarVisibleInScope,
7889
8121
  isSchedulingServiceError,
8122
+ isSupportedCurrency,
7890
8123
  isTokenExpired,
7891
8124
  parsePagination,
7892
8125
  persistRefundOutcome,
7893
8126
  recordBalanceIntent,
7894
8127
  runCalendarRemoveWithoutBlocking,
7895
- runCalendarSyncWithoutBlocking
8128
+ runCalendarSyncWithoutBlocking,
8129
+ visibleCalendarIdsInScope
7896
8130
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/scheduling-api",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
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",
@@ -15,6 +15,7 @@
15
15
  },
16
16
  "devDependencies": {
17
17
  "@types/sanitize-html": "^2.13.0",
18
+ "stripe": "^22.1.1",
18
19
  "tsup": "^8.0.0",
19
20
  "typescript": "5",
20
21
  "vitest": "4.0.18",