@ordinatio/scheduling-api 0.5.1 → 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 +6 -0
- package/dist/agent/index.js +1 -0
- package/dist/agent/index.mjs +1 -0
- package/dist/index.d.mts +82 -1
- package/dist/index.d.ts +82 -1
- package/dist/index.js +231 -2
- package/dist/index.mjs +221 -1
- package/package.json +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
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
|
+
|
|
3
9
|
## 0.5.1 (prepared 2026-11-12)
|
|
4
10
|
|
|
5
11
|
- **Security fix: staff answers no longer include the client's private manage token.** Five staff routes answered with the stored appointment,
|
package/dist/agent/index.js
CHANGED
|
@@ -2294,6 +2294,7 @@ var SCHEDULING_AGENT_EXCLUDED = {
|
|
|
2294
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.",
|
|
2295
2295
|
"GET /type": "Public page data for one booking link; the staff tools list the same types.",
|
|
2296
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.",
|
|
2297
2298
|
"POST /payments/intent": "Creates a card payment in the visitor's own browser session; staff take payment with the collect-balance tool.",
|
|
2298
2299
|
"GET /brand": "Public copy of the brand settings; the brand tool for staff returns the same data.",
|
|
2299
2300
|
"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/agent/index.mjs
CHANGED
|
@@ -2265,6 +2265,7 @@ var SCHEDULING_AGENT_EXCLUDED = {
|
|
|
2265
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.",
|
|
2266
2266
|
"GET /type": "Public page data for one booking link; the staff tools list the same types.",
|
|
2267
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.",
|
|
2268
2269
|
"POST /payments/intent": "Creates a card payment in the visitor's own browser session; staff take payment with the collect-balance tool.",
|
|
2269
2270
|
"GET /brand": "Public copy of the brand settings; the brand tool for staff returns the same data.",
|
|
2270
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
|
|
|
@@ -7747,6 +7756,31 @@ async function getPublicCalendar(request, { host }) {
|
|
|
7747
7756
|
}
|
|
7748
7757
|
}
|
|
7749
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
|
+
|
|
7750
7784
|
// src/handlers/type.ts
|
|
7751
7785
|
var import_scheduling74 = require("@ordinatio/scheduling");
|
|
7752
7786
|
|
|
@@ -7963,6 +7997,7 @@ var ROUTES = [
|
|
|
7963
7997
|
{ method: "GET", path: "/type", public: true, handler: getType },
|
|
7964
7998
|
{ method: "GET", path: "/appointment-types", public: true, handler: getAppointmentTypes },
|
|
7965
7999
|
{ method: "GET", path: "/calendars", public: true, handler: getPublicCalendar },
|
|
8000
|
+
{ method: "GET", path: "/calendars/active", public: false, handler: listActiveCalendars },
|
|
7966
8001
|
{ method: "GET", path: "/availability", public: true, handler: getAvailability },
|
|
7967
8002
|
{ method: "GET", path: "/availability/team", public: true, handler: getTeamAvailability },
|
|
7968
8003
|
{ method: "POST", path: "/appointments", public: true, handler: bookAppointmentRoute },
|
|
@@ -8178,6 +8213,150 @@ function createSchedulingApi(config) {
|
|
|
8178
8213
|
return { routes, handle, handler };
|
|
8179
8214
|
}
|
|
8180
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
|
+
|
|
8181
8360
|
// src/staff/simple-staff.ts
|
|
8182
8361
|
var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
|
|
8183
8362
|
function createStaffContext(input) {
|
|
@@ -8216,6 +8395,47 @@ function createBearerStaffResolver(input) {
|
|
|
8216
8395
|
};
|
|
8217
8396
|
}
|
|
8218
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
|
+
|
|
8219
8439
|
// src/node/node-listener.ts
|
|
8220
8440
|
var CONNECTION_HEADERS = ["host", "connection", "content-length", "transfer-encoding", "keep-alive", "upgrade"];
|
|
8221
8441
|
var PROXY_HEADERS = ["x-forwarded-for", "x-real-ip"];
|
|
@@ -8339,7 +8559,11 @@ function createNodeListener(api, options) {
|
|
|
8339
8559
|
UpdatePackagePurchaseSchema,
|
|
8340
8560
|
UpdateRoutingFormSchema,
|
|
8341
8561
|
UpdateServicePackageSchema,
|
|
8562
|
+
assertStripeTestKey,
|
|
8342
8563
|
attemptLegRefund,
|
|
8564
|
+
calendarVisibilityFilter,
|
|
8565
|
+
canSeeAppointmentInScope,
|
|
8566
|
+
canSeeCalendarInScope,
|
|
8343
8567
|
createBalanceIntent,
|
|
8344
8568
|
createBearerStaffResolver,
|
|
8345
8569
|
createMemoryAvailabilityCache,
|
|
@@ -8349,19 +8573,24 @@ function createNodeListener(api, options) {
|
|
|
8349
8573
|
createNoPaymentAdapter,
|
|
8350
8574
|
createNodeListener,
|
|
8351
8575
|
createSchedulingApi,
|
|
8576
|
+
createScopedVisibility,
|
|
8352
8577
|
createSingleOrganizationDirectory,
|
|
8353
8578
|
createSingleOrganizationResolver,
|
|
8354
8579
|
createStaffContext,
|
|
8580
|
+
createStripePaymentAdapter,
|
|
8355
8581
|
decimalToCents,
|
|
8356
8582
|
defaultCorsHeaders,
|
|
8357
8583
|
getErrorCode,
|
|
8358
8584
|
getErrorMessage,
|
|
8359
8585
|
getErrorRef,
|
|
8586
|
+
isCalendarVisibleInScope,
|
|
8360
8587
|
isSchedulingServiceError,
|
|
8588
|
+
isSupportedCurrency,
|
|
8361
8589
|
isTokenExpired,
|
|
8362
8590
|
parsePagination,
|
|
8363
8591
|
persistRefundOutcome,
|
|
8364
8592
|
recordBalanceIntent,
|
|
8365
8593
|
runCalendarRemoveWithoutBlocking,
|
|
8366
|
-
runCalendarSyncWithoutBlocking
|
|
8594
|
+
runCalendarSyncWithoutBlocking,
|
|
8595
|
+
visibleCalendarIdsInScope
|
|
8367
8596
|
});
|
package/dist/index.mjs
CHANGED
|
@@ -7291,6 +7291,31 @@ async function getPublicCalendar(request, { host }) {
|
|
|
7291
7291
|
}
|
|
7292
7292
|
}
|
|
7293
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
|
+
|
|
7294
7319
|
// src/handlers/type.ts
|
|
7295
7320
|
import { schedError as schedError31 } from "@ordinatio/scheduling";
|
|
7296
7321
|
|
|
@@ -7507,6 +7532,7 @@ var ROUTES = [
|
|
|
7507
7532
|
{ method: "GET", path: "/type", public: true, handler: getType },
|
|
7508
7533
|
{ method: "GET", path: "/appointment-types", public: true, handler: getAppointmentTypes },
|
|
7509
7534
|
{ method: "GET", path: "/calendars", public: true, handler: getPublicCalendar },
|
|
7535
|
+
{ method: "GET", path: "/calendars/active", public: false, handler: listActiveCalendars },
|
|
7510
7536
|
{ method: "GET", path: "/availability", public: true, handler: getAvailability },
|
|
7511
7537
|
{ method: "GET", path: "/availability/team", public: true, handler: getTeamAvailability },
|
|
7512
7538
|
{ method: "POST", path: "/appointments", public: true, handler: bookAppointmentRoute },
|
|
@@ -7722,6 +7748,150 @@ function createSchedulingApi(config) {
|
|
|
7722
7748
|
return { routes, handle, handler };
|
|
7723
7749
|
}
|
|
7724
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
|
+
|
|
7725
7895
|
// src/staff/simple-staff.ts
|
|
7726
7896
|
var DEFAULT_ADMIN_ROLES = ["OWNER", "ADMIN", "MANAGER"];
|
|
7727
7897
|
function createStaffContext(input) {
|
|
@@ -7760,6 +7930,47 @@ function createBearerStaffResolver(input) {
|
|
|
7760
7930
|
};
|
|
7761
7931
|
}
|
|
7762
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
|
+
|
|
7763
7974
|
// src/node/node-listener.ts
|
|
7764
7975
|
var CONNECTION_HEADERS = ["host", "connection", "content-length", "transfer-encoding", "keep-alive", "upgrade"];
|
|
7765
7976
|
var PROXY_HEADERS = ["x-forwarded-for", "x-real-ip"];
|
|
@@ -7882,7 +8093,11 @@ export {
|
|
|
7882
8093
|
UpdatePackagePurchaseSchema,
|
|
7883
8094
|
UpdateRoutingFormSchema,
|
|
7884
8095
|
UpdateServicePackageSchema,
|
|
8096
|
+
assertStripeTestKey,
|
|
7885
8097
|
attemptLegRefund,
|
|
8098
|
+
calendarVisibilityFilter,
|
|
8099
|
+
canSeeAppointmentInScope,
|
|
8100
|
+
canSeeCalendarInScope,
|
|
7886
8101
|
createBalanceIntent,
|
|
7887
8102
|
createBearerStaffResolver,
|
|
7888
8103
|
createMemoryAvailabilityCache,
|
|
@@ -7892,19 +8107,24 @@ export {
|
|
|
7892
8107
|
createNoPaymentAdapter,
|
|
7893
8108
|
createNodeListener,
|
|
7894
8109
|
createSchedulingApi,
|
|
8110
|
+
createScopedVisibility,
|
|
7895
8111
|
createSingleOrganizationDirectory,
|
|
7896
8112
|
createSingleOrganizationResolver,
|
|
7897
8113
|
createStaffContext,
|
|
8114
|
+
createStripePaymentAdapter,
|
|
7898
8115
|
decimalToCents,
|
|
7899
8116
|
defaultCorsHeaders,
|
|
7900
8117
|
getErrorCode,
|
|
7901
8118
|
getErrorMessage,
|
|
7902
8119
|
getErrorRef,
|
|
8120
|
+
isCalendarVisibleInScope,
|
|
7903
8121
|
isSchedulingServiceError,
|
|
8122
|
+
isSupportedCurrency,
|
|
7904
8123
|
isTokenExpired,
|
|
7905
8124
|
parsePagination,
|
|
7906
8125
|
persistRefundOutcome,
|
|
7907
8126
|
recordBalanceIntent,
|
|
7908
8127
|
runCalendarRemoveWithoutBlocking,
|
|
7909
|
-
runCalendarSyncWithoutBlocking
|
|
8128
|
+
runCalendarSyncWithoutBlocking,
|
|
8129
|
+
visibleCalendarIdsInScope
|
|
7910
8130
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ordinatio/scheduling-api",
|
|
3
|
-
"version": "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",
|