@ordinatio/scheduling 0.4.0 → 0.5.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,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.0 (2026-10-29)
4
+
5
+ - **Security fix: booking analytics and group-class lists no longer rely on the database handle being limited to one business.**
6
+ `getBookingAnalytics` and `getGroupSessions` take an optional `organizationId`; given one, nothing from another organization is
7
+ counted or listed, even when several businesses share one database. A new exported helper, `withOrganization(where, organizationId)`,
8
+ does the same for any appointment query, and `scopeToOrganization(db, organizationId)` limits every query a handle makes.
9
+ `getAppointmentDashboard`, `getAppointmentsForRange` (new 4th argument `{ organizationId }`), `getUserDayAppointments`,
10
+ `listAppointments` and `getAppointment` take the same optional `organizationId`; an appointment of another organization is reported
11
+ as not found. Left out, behavior is unchanged (for a host that gives each business its own database).
12
+ If you keep several businesses in one database, upgrade to this version and `@ordinatio/scheduling-api` 0.3.0 together: engine 0.4.0
13
+ and API 0.2.0 (and earlier) return other businesses' appointments and revenue totals to staff. If your own code calls
14
+ `getBookingAnalytics` or `getGroupSessions`, pass `organizationId` from now on.
15
+
3
16
  ## 0.4.0 (2026-10-28)
4
17
 
5
18
  - **Organization brand.** `saveBrand`, `getBrand`, `getPublicBrand` and `deleteBrand` keep a name, logo, colours, font, footer and
package/dist/index.d.mts CHANGED
@@ -1184,11 +1184,12 @@ declare function rescheduleAppointment(db: SchedulingDb, input: RescheduleInput,
1184
1184
  /**
1185
1185
  * Get a single appointment by ID.
1186
1186
  *
1187
- * Org-scoping precondition: no organizationId check is performed here; the caller
1188
- * must already have verified ownership or be passing a tenant-resolved `db` handle.
1189
- * Confirmed callers today (`approve/route.ts`) already do so via `requireSchedulingAuth()`.
1187
+ * Pass `organizationId` and an appointment of another organization is reported as not found. Without it no organization
1188
+ * check is made here: the caller must already have verified ownership or be passing a database handle that holds one business.
1190
1189
  */
1191
- declare function getAppointment(db: SchedulingDb, appointmentId: string): Promise<AppointmentWithDetails>;
1190
+ declare function getAppointment(db: SchedulingDb, appointmentId: string, options?: {
1191
+ organizationId?: string;
1192
+ }): Promise<AppointmentWithDetails>;
1192
1193
  /**
1193
1194
  * List appointments with filters.
1194
1195
  *
@@ -1201,7 +1202,9 @@ declare function getAppointment(db: SchedulingDb, appointmentId: string): Promis
1201
1202
  * equivalent ownership verification) before invoking this — there is no runtime guard
1202
1203
  * here to catch a caller that skips this.
1203
1204
  */
1204
- declare function listAppointments(db: SchedulingDb, options?: {
1205
+ declare function listAppointments(unscopedDb: SchedulingDb, options?: {
1206
+ /** Only this organization's appointments. Leave it out when the database holds one business. */
1207
+ organizationId?: string;
1205
1208
  calendarId?: string;
1206
1209
  status?: string;
1207
1210
  clientEmail?: string;
@@ -1274,6 +1277,8 @@ declare function getGroupSessions(db: SchedulingDb, params: {
1274
1277
  calendarId?: string;
1275
1278
  /** Task #83 — omitted means unrestricted, byte-identical to before. See visibility-filter.ts. */
1276
1279
  visibleCalendarIds?: string[];
1280
+ /** Only this organization's classes count. Leave it out when the database holds one business. */
1281
+ organizationId?: string;
1277
1282
  }): Promise<GroupSessionsResult>;
1278
1283
 
1279
1284
  /**
@@ -1285,9 +1290,13 @@ declare function getBookingAnalytics(db: SchedulingDb, options?: {
1285
1290
  calendarId?: string;
1286
1291
  days?: number;
1287
1292
  visibleCalendarIds?: string[];
1293
+ /** Only this organization's appointments count. Leave it out when the database holds one business. */
1294
+ organizationId?: string;
1288
1295
  }): Promise<BookingAnalytics>;
1289
1296
 
1290
1297
  interface DashboardQuery {
1298
+ /** Only this organization's appointments. Leave it out when the database holds one business. */
1299
+ organizationId?: string;
1291
1300
  /** Search by client name, email, or phone */
1292
1301
  search?: string;
1293
1302
  /** Filter history by status */
@@ -1329,7 +1338,7 @@ interface DashboardQuery {
1329
1338
  * - Upcoming (after this week, soonest first, capped)
1330
1339
  * - Upcoming count (all of them, so a capped list can say so)
1331
1340
  */
1332
- declare function getAppointmentDashboard(db: SchedulingDb, query?: DashboardQuery): Promise<AppointmentDashboardData>;
1341
+ declare function getAppointmentDashboard(unscopedDb: SchedulingDb, query?: DashboardQuery): Promise<AppointmentDashboardData>;
1333
1342
  interface AppointmentsForRangeResult {
1334
1343
  appointments: AppointmentDashboardItem[];
1335
1344
  /**
@@ -1345,10 +1354,14 @@ interface AppointmentsForRangeResult {
1345
1354
  * Used by calendar views (day/week/month).
1346
1355
  * Includes all statuses (cancelled shown greyed out in the UI).
1347
1356
  */
1348
- declare function getAppointmentsForRange(db: SchedulingDb, rangeStart: Date, rangeEnd: Date): Promise<AppointmentsForRangeResult>;
1357
+ declare function getAppointmentsForRange(unscopedDb: SchedulingDb, rangeStart: Date, rangeEnd: Date, options?: {
1358
+ organizationId?: string;
1359
+ }): Promise<AppointmentsForRangeResult>;
1349
1360
 
1350
1361
  declare const USER_DAY_LIMIT = 200;
1351
1362
  interface UserDayInput {
1363
+ /** Only this organization's appointments and calendars. Leave it out when the database holds one business. */
1364
+ organizationId?: string;
1352
1365
  /** The staff member whose day it is (the id stored in SchedulingCalendar.userId). */
1353
1366
  userId: string;
1354
1367
  /** The local calendar day, 'YYYY-MM-DD', in `timezone`. */
@@ -1383,7 +1396,7 @@ interface UserDayResult {
1383
1396
  /** Calendars linked to this user that the caller can see; 0 means "nothing linked", not "free day". */
1384
1397
  linkedCalendarCount: number;
1385
1398
  }
1386
- declare function getUserDayAppointments(db: SchedulingDb, input: UserDayInput): Promise<UserDayResult>;
1399
+ declare function getUserDayAppointments(unscopedDb: SchedulingDb, input: UserDayInput): Promise<UserDayResult>;
1387
1400
 
1388
1401
  interface Clock {
1389
1402
  now(): Date;
@@ -1576,6 +1589,22 @@ declare function checkAuthContract(adapter: AuthAdapter, validHeaders?: Record<s
1576
1589
  */
1577
1590
  declare function withCalendarVisibility(where: Record<string, unknown>, visibleCalendarIds: string[] | undefined): Record<string, unknown>;
1578
1591
 
1592
+ /**
1593
+ * Limits a Prisma `where` on appointments to one organization, through the appointment's calendar.
1594
+ *
1595
+ * The package does not assume the database handle it is given is already limited to one business: a host that keeps
1596
+ * several businesses in one database passes the organization here and nothing from another business can come back.
1597
+ * Left out, the `where` is returned unchanged (the same object), for a host that gives each business its own database.
1598
+ * Wrapped in `AND` so it combines with any `OR` or `calendar` condition already in the `where`.
1599
+ */
1600
+ declare function withOrganization(where: Record<string, unknown>, organizationId: string | undefined): Record<string, unknown>;
1601
+ /**
1602
+ * The same database handle, but every appointment query is limited to one organization (through the calendar) and every
1603
+ * calendar query to the organization itself. For the package's read functions that run several queries, so none of them can be
1604
+ * left unscoped by accident. Given no organization the handle is returned as it is.
1605
+ */
1606
+ declare function scopeToOrganization(db: SchedulingDb, organizationId: string | undefined): SchedulingDb;
1607
+
1579
1608
  declare function renderTemplate(template: string, context: NotificationContext, channel?: NotificationChannel): string;
1580
1609
  /**
1581
1610
  * Build notification context from an appointment + related data.
@@ -2711,4 +2740,4 @@ declare function senderIdentity(brand: BrandFields | null): SenderIdentity | nul
2711
2740
  declare function brandTemplateFields(brand: BrandFields | null): Record<string, string>;
2712
2741
  declare function toPublicBrand(brand: BrandFields): PublicBrand;
2713
2742
 
2714
- export { type AcceptRelease, type AddTimeBlockInput, type AppointmentDashboardData, type AppointmentDashboardItem, type AppointmentDashboardStats, type AppointmentLocationType, type AppointmentStatus, type AppointmentWithDetails, type AssignmentStrategy, type AttemptOptions, type AuthAdapter, type AuthContext, type AvailabilityQuery, type AvailabilityResult, type AvailabilityRuleInput, BRAND_FIELDS, BlockedTargetError, type BookAppointmentInput, type BookingAnalytics, type BrandFields, type BrandProblem, type BrandView, type CalendarEvent, type CalendarEventRef, type CalendarSyncAdapter, type CalendarType, type CancelInput, type CancelRecurringScope, type CancellationFeeConfig, type CancellationFeeResult, type ChargeRequest, type ChargeResult, type Clock, type CreateAppointmentTypeInput, type CreateCalendarInput, DEFAULT_BACKOFF_SECONDS, DEFAULT_OFFER_MINUTES, type DashboardQuery, type DayAppointment, type DeliverOptions, type DeliverSummary, ERASED_EMAIL, ERASED_NAME, type EraseBlockers, type ErasePreview, type FreedSlot, type GroupCapacityResult, type GroupSession, type GroupSessionAttendee, type InMemoryClockControl, type InMemoryOptions, type InMemoryRecords, type IntakeFormField, type JoinWaitlistInput, LIMITS, MAX_ENDPOINTS_PER_ORGANIZATION, MAX_WAITING_PER_TYPE_DAY, type MarkNoShowInput, type NotificationAdapter, type NotificationChannel, type NotificationContext, type NotificationSender, type NotificationTrigger, OPERATORS_BY_TYPE, type OfferDetails, type OrgCancellationPolicy, type OutboundMessage, type ParsedSubject, type PaymentAdapter, type PaymentCheck, type PaymentContractOptions, type PaymentProcessor, type PaymentResult, type PrivacyRequestKind, type PrivacyRequestView, type PublicBrand, type PublicRoutingForm, type QuestionType, RECURRING_MAX_OCCURRENCES, LIMITS as ROUTING_LIMITS, type RecurringFrequency, type RefundOptions, type RefundResult, type RescheduleInput, type ResolvedDestination, type ResolvedSubject, type RetryConfig, type RoutingAnswers, type RoutingCondition, type RoutingDestination, type RoutingFallback, type RoutingFormDefinition, type RoutingFormInput, type RoutingFormSummary, type RoutingFormView, type RoutingOperator, type RoutingOutcome, type RoutingProblem, type RoutingQuestion, type RoutingRule, SCHEDULING_ERRORS, SIGNATURE_HEADER, type SchedulingAdapters, type SchedulingCallbacks, type SchedulingDb, SchedulingNotFoundError, SchedulingValidationError, type SendResult, type SettledBooking, type SubjectCounts, type SubjectExport, type TeamAvailabilityQuery, type TeamAvailabilityResult, type TestSendResult, type TimeSlot, type TransportRequest, USER_DAY_LIMIT, type UpdateCalendarInput, type UrlCheckOptions, type UserDayInput, type UserDayResult, type ValidateBrandOptions, WEBHOOK_EVENT_TYPES, WEBHOOK_TEST_EVENT, type WaitlistEntryView, type WaitlistOffer, type WebhookDeliveryView, type WebhookEndpointView, type WebhookEnvelope, type WebhookEventType, type WebhookTransport, adaptersToCallbacks, addDateOverride, addTimeBlock, appointmentWebhookData, archiveCalendar, beginWaitlistAccept, bookAppointment, brandTemplateFields, buildJitsiUrl, buildNotificationContext, buildOccurrenceStartTime, buildRecurringSlots, calculateCancellationFee, cancelAppointment, cancelPendingNotifications, checkAnswers, checkAuthContract, checkCalendarSyncContract, checkClockContract, checkNotificationContract, checkPaymentContract, checkWebhookUrl, completeWaitlistAccept, createAppointmentType, createCalendar, createInMemoryAdapters, createNodeTransport, createNotificationTemplate, createRoutingForm, createWebhookEndpoint, deleteBrand, deleteCalendar, deleteNotificationTemplate, deleteRoutingForm, deleteWebhookEndpoint, deliverDueWebhooks, enqueueAppointmentWebhook, enqueueReminderSent, enqueueWebhookEvent, eraseSubject, expireWaitlistOffers, exportSubject, generateOccurrenceDates, generateWebhookSecret, getAppointment, getAppointmentDashboard, getAppointmentType, getAppointmentsForRange, getAvailableDates, getAvailableSlots, getBookingAnalytics, getBrand, getCalendar, getGroupCapacity, getGroupSessions, getNotificationTemplate, getPublicBrand, getPublicRoutingForm, getRoutingForm, getTeamAvailableSlots, getUserDayAppointments, getWaitlistOffer, isPrivateAddress, isSlotAvailable, isVirtualMeeting, joinWaitlist, leaveWaitlist, listAppointmentTypes, listAppointments, listAvailabilityRules, listCalendars, listNotificationTemplates, listPrivacyRequests, listRoutingForms, listWaitlist, listWebhookDeliveries, listWebhookEndpoints, localDay, localToUTC, markNoShow, matchingRules, offerFreedSlot, parseSubject, parseTimeLocal, previewErase, processPendingNotifications, queueImmediateNotification, queueStaffNotification, releaseWaitlistAccept, removeDateOverride, removeWaitlistEntry, renderTemplate, rescheduleAppointment, resolveDestination, resolveLocation, resolveSubject, retryWebhookDelivery, routeClient, saveBrand, schedError, scheduleNotifications, selectCalendarForBooking, sendTestWebhook, senderIdentity, setWeeklyAvailability, settleBookedAccept, signWebhook, subjectHashes, testRoutingForm, toPublicBrand, tryOfferFreedSlot, updateAppointmentType, updateCalendar, updateNotificationTemplate, updateRoutingForm, validateBrand, validateRoutingDestinations, validateRoutingStructure, verifyWebhookSignature, withCalendarVisibility };
2743
+ export { type AcceptRelease, type AddTimeBlockInput, type AppointmentDashboardData, type AppointmentDashboardItem, type AppointmentDashboardStats, type AppointmentLocationType, type AppointmentStatus, type AppointmentWithDetails, type AssignmentStrategy, type AttemptOptions, type AuthAdapter, type AuthContext, type AvailabilityQuery, type AvailabilityResult, type AvailabilityRuleInput, BRAND_FIELDS, BlockedTargetError, type BookAppointmentInput, type BookingAnalytics, type BrandFields, type BrandProblem, type BrandView, type CalendarEvent, type CalendarEventRef, type CalendarSyncAdapter, type CalendarType, type CancelInput, type CancelRecurringScope, type CancellationFeeConfig, type CancellationFeeResult, type ChargeRequest, type ChargeResult, type Clock, type CreateAppointmentTypeInput, type CreateCalendarInput, DEFAULT_BACKOFF_SECONDS, DEFAULT_OFFER_MINUTES, type DashboardQuery, type DayAppointment, type DeliverOptions, type DeliverSummary, ERASED_EMAIL, ERASED_NAME, type EraseBlockers, type ErasePreview, type FreedSlot, type GroupCapacityResult, type GroupSession, type GroupSessionAttendee, type InMemoryClockControl, type InMemoryOptions, type InMemoryRecords, type IntakeFormField, type JoinWaitlistInput, LIMITS, MAX_ENDPOINTS_PER_ORGANIZATION, MAX_WAITING_PER_TYPE_DAY, type MarkNoShowInput, type NotificationAdapter, type NotificationChannel, type NotificationContext, type NotificationSender, type NotificationTrigger, OPERATORS_BY_TYPE, type OfferDetails, type OrgCancellationPolicy, type OutboundMessage, type ParsedSubject, type PaymentAdapter, type PaymentCheck, type PaymentContractOptions, type PaymentProcessor, type PaymentResult, type PrivacyRequestKind, type PrivacyRequestView, type PublicBrand, type PublicRoutingForm, type QuestionType, RECURRING_MAX_OCCURRENCES, LIMITS as ROUTING_LIMITS, type RecurringFrequency, type RefundOptions, type RefundResult, type RescheduleInput, type ResolvedDestination, type ResolvedSubject, type RetryConfig, type RoutingAnswers, type RoutingCondition, type RoutingDestination, type RoutingFallback, type RoutingFormDefinition, type RoutingFormInput, type RoutingFormSummary, type RoutingFormView, type RoutingOperator, type RoutingOutcome, type RoutingProblem, type RoutingQuestion, type RoutingRule, SCHEDULING_ERRORS, SIGNATURE_HEADER, type SchedulingAdapters, type SchedulingCallbacks, type SchedulingDb, SchedulingNotFoundError, SchedulingValidationError, type SendResult, type SettledBooking, type SubjectCounts, type SubjectExport, type TeamAvailabilityQuery, type TeamAvailabilityResult, type TestSendResult, type TimeSlot, type TransportRequest, USER_DAY_LIMIT, type UpdateCalendarInput, type UrlCheckOptions, type UserDayInput, type UserDayResult, type ValidateBrandOptions, WEBHOOK_EVENT_TYPES, WEBHOOK_TEST_EVENT, type WaitlistEntryView, type WaitlistOffer, type WebhookDeliveryView, type WebhookEndpointView, type WebhookEnvelope, type WebhookEventType, type WebhookTransport, adaptersToCallbacks, addDateOverride, addTimeBlock, appointmentWebhookData, archiveCalendar, beginWaitlistAccept, bookAppointment, brandTemplateFields, buildJitsiUrl, buildNotificationContext, buildOccurrenceStartTime, buildRecurringSlots, calculateCancellationFee, cancelAppointment, cancelPendingNotifications, checkAnswers, checkAuthContract, checkCalendarSyncContract, checkClockContract, checkNotificationContract, checkPaymentContract, checkWebhookUrl, completeWaitlistAccept, createAppointmentType, createCalendar, createInMemoryAdapters, createNodeTransport, createNotificationTemplate, createRoutingForm, createWebhookEndpoint, deleteBrand, deleteCalendar, deleteNotificationTemplate, deleteRoutingForm, deleteWebhookEndpoint, deliverDueWebhooks, enqueueAppointmentWebhook, enqueueReminderSent, enqueueWebhookEvent, eraseSubject, expireWaitlistOffers, exportSubject, generateOccurrenceDates, generateWebhookSecret, getAppointment, getAppointmentDashboard, getAppointmentType, getAppointmentsForRange, getAvailableDates, getAvailableSlots, getBookingAnalytics, getBrand, getCalendar, getGroupCapacity, getGroupSessions, getNotificationTemplate, getPublicBrand, getPublicRoutingForm, getRoutingForm, getTeamAvailableSlots, getUserDayAppointments, getWaitlistOffer, isPrivateAddress, isSlotAvailable, isVirtualMeeting, joinWaitlist, leaveWaitlist, listAppointmentTypes, listAppointments, listAvailabilityRules, listCalendars, listNotificationTemplates, listPrivacyRequests, listRoutingForms, listWaitlist, listWebhookDeliveries, listWebhookEndpoints, localDay, localToUTC, markNoShow, matchingRules, offerFreedSlot, parseSubject, parseTimeLocal, previewErase, processPendingNotifications, queueImmediateNotification, queueStaffNotification, releaseWaitlistAccept, removeDateOverride, removeWaitlistEntry, renderTemplate, rescheduleAppointment, resolveDestination, resolveLocation, resolveSubject, retryWebhookDelivery, routeClient, saveBrand, schedError, scheduleNotifications, scopeToOrganization, selectCalendarForBooking, sendTestWebhook, senderIdentity, setWeeklyAvailability, settleBookedAccept, signWebhook, subjectHashes, testRoutingForm, toPublicBrand, tryOfferFreedSlot, updateAppointmentType, updateCalendar, updateNotificationTemplate, updateRoutingForm, validateBrand, validateRoutingDestinations, validateRoutingStructure, verifyWebhookSignature, withCalendarVisibility, withOrganization };
package/dist/index.d.ts CHANGED
@@ -1184,11 +1184,12 @@ declare function rescheduleAppointment(db: SchedulingDb, input: RescheduleInput,
1184
1184
  /**
1185
1185
  * Get a single appointment by ID.
1186
1186
  *
1187
- * Org-scoping precondition: no organizationId check is performed here; the caller
1188
- * must already have verified ownership or be passing a tenant-resolved `db` handle.
1189
- * Confirmed callers today (`approve/route.ts`) already do so via `requireSchedulingAuth()`.
1187
+ * Pass `organizationId` and an appointment of another organization is reported as not found. Without it no organization
1188
+ * check is made here: the caller must already have verified ownership or be passing a database handle that holds one business.
1190
1189
  */
1191
- declare function getAppointment(db: SchedulingDb, appointmentId: string): Promise<AppointmentWithDetails>;
1190
+ declare function getAppointment(db: SchedulingDb, appointmentId: string, options?: {
1191
+ organizationId?: string;
1192
+ }): Promise<AppointmentWithDetails>;
1192
1193
  /**
1193
1194
  * List appointments with filters.
1194
1195
  *
@@ -1201,7 +1202,9 @@ declare function getAppointment(db: SchedulingDb, appointmentId: string): Promis
1201
1202
  * equivalent ownership verification) before invoking this — there is no runtime guard
1202
1203
  * here to catch a caller that skips this.
1203
1204
  */
1204
- declare function listAppointments(db: SchedulingDb, options?: {
1205
+ declare function listAppointments(unscopedDb: SchedulingDb, options?: {
1206
+ /** Only this organization's appointments. Leave it out when the database holds one business. */
1207
+ organizationId?: string;
1205
1208
  calendarId?: string;
1206
1209
  status?: string;
1207
1210
  clientEmail?: string;
@@ -1274,6 +1277,8 @@ declare function getGroupSessions(db: SchedulingDb, params: {
1274
1277
  calendarId?: string;
1275
1278
  /** Task #83 — omitted means unrestricted, byte-identical to before. See visibility-filter.ts. */
1276
1279
  visibleCalendarIds?: string[];
1280
+ /** Only this organization's classes count. Leave it out when the database holds one business. */
1281
+ organizationId?: string;
1277
1282
  }): Promise<GroupSessionsResult>;
1278
1283
 
1279
1284
  /**
@@ -1285,9 +1290,13 @@ declare function getBookingAnalytics(db: SchedulingDb, options?: {
1285
1290
  calendarId?: string;
1286
1291
  days?: number;
1287
1292
  visibleCalendarIds?: string[];
1293
+ /** Only this organization's appointments count. Leave it out when the database holds one business. */
1294
+ organizationId?: string;
1288
1295
  }): Promise<BookingAnalytics>;
1289
1296
 
1290
1297
  interface DashboardQuery {
1298
+ /** Only this organization's appointments. Leave it out when the database holds one business. */
1299
+ organizationId?: string;
1291
1300
  /** Search by client name, email, or phone */
1292
1301
  search?: string;
1293
1302
  /** Filter history by status */
@@ -1329,7 +1338,7 @@ interface DashboardQuery {
1329
1338
  * - Upcoming (after this week, soonest first, capped)
1330
1339
  * - Upcoming count (all of them, so a capped list can say so)
1331
1340
  */
1332
- declare function getAppointmentDashboard(db: SchedulingDb, query?: DashboardQuery): Promise<AppointmentDashboardData>;
1341
+ declare function getAppointmentDashboard(unscopedDb: SchedulingDb, query?: DashboardQuery): Promise<AppointmentDashboardData>;
1333
1342
  interface AppointmentsForRangeResult {
1334
1343
  appointments: AppointmentDashboardItem[];
1335
1344
  /**
@@ -1345,10 +1354,14 @@ interface AppointmentsForRangeResult {
1345
1354
  * Used by calendar views (day/week/month).
1346
1355
  * Includes all statuses (cancelled shown greyed out in the UI).
1347
1356
  */
1348
- declare function getAppointmentsForRange(db: SchedulingDb, rangeStart: Date, rangeEnd: Date): Promise<AppointmentsForRangeResult>;
1357
+ declare function getAppointmentsForRange(unscopedDb: SchedulingDb, rangeStart: Date, rangeEnd: Date, options?: {
1358
+ organizationId?: string;
1359
+ }): Promise<AppointmentsForRangeResult>;
1349
1360
 
1350
1361
  declare const USER_DAY_LIMIT = 200;
1351
1362
  interface UserDayInput {
1363
+ /** Only this organization's appointments and calendars. Leave it out when the database holds one business. */
1364
+ organizationId?: string;
1352
1365
  /** The staff member whose day it is (the id stored in SchedulingCalendar.userId). */
1353
1366
  userId: string;
1354
1367
  /** The local calendar day, 'YYYY-MM-DD', in `timezone`. */
@@ -1383,7 +1396,7 @@ interface UserDayResult {
1383
1396
  /** Calendars linked to this user that the caller can see; 0 means "nothing linked", not "free day". */
1384
1397
  linkedCalendarCount: number;
1385
1398
  }
1386
- declare function getUserDayAppointments(db: SchedulingDb, input: UserDayInput): Promise<UserDayResult>;
1399
+ declare function getUserDayAppointments(unscopedDb: SchedulingDb, input: UserDayInput): Promise<UserDayResult>;
1387
1400
 
1388
1401
  interface Clock {
1389
1402
  now(): Date;
@@ -1576,6 +1589,22 @@ declare function checkAuthContract(adapter: AuthAdapter, validHeaders?: Record<s
1576
1589
  */
1577
1590
  declare function withCalendarVisibility(where: Record<string, unknown>, visibleCalendarIds: string[] | undefined): Record<string, unknown>;
1578
1591
 
1592
+ /**
1593
+ * Limits a Prisma `where` on appointments to one organization, through the appointment's calendar.
1594
+ *
1595
+ * The package does not assume the database handle it is given is already limited to one business: a host that keeps
1596
+ * several businesses in one database passes the organization here and nothing from another business can come back.
1597
+ * Left out, the `where` is returned unchanged (the same object), for a host that gives each business its own database.
1598
+ * Wrapped in `AND` so it combines with any `OR` or `calendar` condition already in the `where`.
1599
+ */
1600
+ declare function withOrganization(where: Record<string, unknown>, organizationId: string | undefined): Record<string, unknown>;
1601
+ /**
1602
+ * The same database handle, but every appointment query is limited to one organization (through the calendar) and every
1603
+ * calendar query to the organization itself. For the package's read functions that run several queries, so none of them can be
1604
+ * left unscoped by accident. Given no organization the handle is returned as it is.
1605
+ */
1606
+ declare function scopeToOrganization(db: SchedulingDb, organizationId: string | undefined): SchedulingDb;
1607
+
1579
1608
  declare function renderTemplate(template: string, context: NotificationContext, channel?: NotificationChannel): string;
1580
1609
  /**
1581
1610
  * Build notification context from an appointment + related data.
@@ -2711,4 +2740,4 @@ declare function senderIdentity(brand: BrandFields | null): SenderIdentity | nul
2711
2740
  declare function brandTemplateFields(brand: BrandFields | null): Record<string, string>;
2712
2741
  declare function toPublicBrand(brand: BrandFields): PublicBrand;
2713
2742
 
2714
- export { type AcceptRelease, type AddTimeBlockInput, type AppointmentDashboardData, type AppointmentDashboardItem, type AppointmentDashboardStats, type AppointmentLocationType, type AppointmentStatus, type AppointmentWithDetails, type AssignmentStrategy, type AttemptOptions, type AuthAdapter, type AuthContext, type AvailabilityQuery, type AvailabilityResult, type AvailabilityRuleInput, BRAND_FIELDS, BlockedTargetError, type BookAppointmentInput, type BookingAnalytics, type BrandFields, type BrandProblem, type BrandView, type CalendarEvent, type CalendarEventRef, type CalendarSyncAdapter, type CalendarType, type CancelInput, type CancelRecurringScope, type CancellationFeeConfig, type CancellationFeeResult, type ChargeRequest, type ChargeResult, type Clock, type CreateAppointmentTypeInput, type CreateCalendarInput, DEFAULT_BACKOFF_SECONDS, DEFAULT_OFFER_MINUTES, type DashboardQuery, type DayAppointment, type DeliverOptions, type DeliverSummary, ERASED_EMAIL, ERASED_NAME, type EraseBlockers, type ErasePreview, type FreedSlot, type GroupCapacityResult, type GroupSession, type GroupSessionAttendee, type InMemoryClockControl, type InMemoryOptions, type InMemoryRecords, type IntakeFormField, type JoinWaitlistInput, LIMITS, MAX_ENDPOINTS_PER_ORGANIZATION, MAX_WAITING_PER_TYPE_DAY, type MarkNoShowInput, type NotificationAdapter, type NotificationChannel, type NotificationContext, type NotificationSender, type NotificationTrigger, OPERATORS_BY_TYPE, type OfferDetails, type OrgCancellationPolicy, type OutboundMessage, type ParsedSubject, type PaymentAdapter, type PaymentCheck, type PaymentContractOptions, type PaymentProcessor, type PaymentResult, type PrivacyRequestKind, type PrivacyRequestView, type PublicBrand, type PublicRoutingForm, type QuestionType, RECURRING_MAX_OCCURRENCES, LIMITS as ROUTING_LIMITS, type RecurringFrequency, type RefundOptions, type RefundResult, type RescheduleInput, type ResolvedDestination, type ResolvedSubject, type RetryConfig, type RoutingAnswers, type RoutingCondition, type RoutingDestination, type RoutingFallback, type RoutingFormDefinition, type RoutingFormInput, type RoutingFormSummary, type RoutingFormView, type RoutingOperator, type RoutingOutcome, type RoutingProblem, type RoutingQuestion, type RoutingRule, SCHEDULING_ERRORS, SIGNATURE_HEADER, type SchedulingAdapters, type SchedulingCallbacks, type SchedulingDb, SchedulingNotFoundError, SchedulingValidationError, type SendResult, type SettledBooking, type SubjectCounts, type SubjectExport, type TeamAvailabilityQuery, type TeamAvailabilityResult, type TestSendResult, type TimeSlot, type TransportRequest, USER_DAY_LIMIT, type UpdateCalendarInput, type UrlCheckOptions, type UserDayInput, type UserDayResult, type ValidateBrandOptions, WEBHOOK_EVENT_TYPES, WEBHOOK_TEST_EVENT, type WaitlistEntryView, type WaitlistOffer, type WebhookDeliveryView, type WebhookEndpointView, type WebhookEnvelope, type WebhookEventType, type WebhookTransport, adaptersToCallbacks, addDateOverride, addTimeBlock, appointmentWebhookData, archiveCalendar, beginWaitlistAccept, bookAppointment, brandTemplateFields, buildJitsiUrl, buildNotificationContext, buildOccurrenceStartTime, buildRecurringSlots, calculateCancellationFee, cancelAppointment, cancelPendingNotifications, checkAnswers, checkAuthContract, checkCalendarSyncContract, checkClockContract, checkNotificationContract, checkPaymentContract, checkWebhookUrl, completeWaitlistAccept, createAppointmentType, createCalendar, createInMemoryAdapters, createNodeTransport, createNotificationTemplate, createRoutingForm, createWebhookEndpoint, deleteBrand, deleteCalendar, deleteNotificationTemplate, deleteRoutingForm, deleteWebhookEndpoint, deliverDueWebhooks, enqueueAppointmentWebhook, enqueueReminderSent, enqueueWebhookEvent, eraseSubject, expireWaitlistOffers, exportSubject, generateOccurrenceDates, generateWebhookSecret, getAppointment, getAppointmentDashboard, getAppointmentType, getAppointmentsForRange, getAvailableDates, getAvailableSlots, getBookingAnalytics, getBrand, getCalendar, getGroupCapacity, getGroupSessions, getNotificationTemplate, getPublicBrand, getPublicRoutingForm, getRoutingForm, getTeamAvailableSlots, getUserDayAppointments, getWaitlistOffer, isPrivateAddress, isSlotAvailable, isVirtualMeeting, joinWaitlist, leaveWaitlist, listAppointmentTypes, listAppointments, listAvailabilityRules, listCalendars, listNotificationTemplates, listPrivacyRequests, listRoutingForms, listWaitlist, listWebhookDeliveries, listWebhookEndpoints, localDay, localToUTC, markNoShow, matchingRules, offerFreedSlot, parseSubject, parseTimeLocal, previewErase, processPendingNotifications, queueImmediateNotification, queueStaffNotification, releaseWaitlistAccept, removeDateOverride, removeWaitlistEntry, renderTemplate, rescheduleAppointment, resolveDestination, resolveLocation, resolveSubject, retryWebhookDelivery, routeClient, saveBrand, schedError, scheduleNotifications, selectCalendarForBooking, sendTestWebhook, senderIdentity, setWeeklyAvailability, settleBookedAccept, signWebhook, subjectHashes, testRoutingForm, toPublicBrand, tryOfferFreedSlot, updateAppointmentType, updateCalendar, updateNotificationTemplate, updateRoutingForm, validateBrand, validateRoutingDestinations, validateRoutingStructure, verifyWebhookSignature, withCalendarVisibility };
2743
+ export { type AcceptRelease, type AddTimeBlockInput, type AppointmentDashboardData, type AppointmentDashboardItem, type AppointmentDashboardStats, type AppointmentLocationType, type AppointmentStatus, type AppointmentWithDetails, type AssignmentStrategy, type AttemptOptions, type AuthAdapter, type AuthContext, type AvailabilityQuery, type AvailabilityResult, type AvailabilityRuleInput, BRAND_FIELDS, BlockedTargetError, type BookAppointmentInput, type BookingAnalytics, type BrandFields, type BrandProblem, type BrandView, type CalendarEvent, type CalendarEventRef, type CalendarSyncAdapter, type CalendarType, type CancelInput, type CancelRecurringScope, type CancellationFeeConfig, type CancellationFeeResult, type ChargeRequest, type ChargeResult, type Clock, type CreateAppointmentTypeInput, type CreateCalendarInput, DEFAULT_BACKOFF_SECONDS, DEFAULT_OFFER_MINUTES, type DashboardQuery, type DayAppointment, type DeliverOptions, type DeliverSummary, ERASED_EMAIL, ERASED_NAME, type EraseBlockers, type ErasePreview, type FreedSlot, type GroupCapacityResult, type GroupSession, type GroupSessionAttendee, type InMemoryClockControl, type InMemoryOptions, type InMemoryRecords, type IntakeFormField, type JoinWaitlistInput, LIMITS, MAX_ENDPOINTS_PER_ORGANIZATION, MAX_WAITING_PER_TYPE_DAY, type MarkNoShowInput, type NotificationAdapter, type NotificationChannel, type NotificationContext, type NotificationSender, type NotificationTrigger, OPERATORS_BY_TYPE, type OfferDetails, type OrgCancellationPolicy, type OutboundMessage, type ParsedSubject, type PaymentAdapter, type PaymentCheck, type PaymentContractOptions, type PaymentProcessor, type PaymentResult, type PrivacyRequestKind, type PrivacyRequestView, type PublicBrand, type PublicRoutingForm, type QuestionType, RECURRING_MAX_OCCURRENCES, LIMITS as ROUTING_LIMITS, type RecurringFrequency, type RefundOptions, type RefundResult, type RescheduleInput, type ResolvedDestination, type ResolvedSubject, type RetryConfig, type RoutingAnswers, type RoutingCondition, type RoutingDestination, type RoutingFallback, type RoutingFormDefinition, type RoutingFormInput, type RoutingFormSummary, type RoutingFormView, type RoutingOperator, type RoutingOutcome, type RoutingProblem, type RoutingQuestion, type RoutingRule, SCHEDULING_ERRORS, SIGNATURE_HEADER, type SchedulingAdapters, type SchedulingCallbacks, type SchedulingDb, SchedulingNotFoundError, SchedulingValidationError, type SendResult, type SettledBooking, type SubjectCounts, type SubjectExport, type TeamAvailabilityQuery, type TeamAvailabilityResult, type TestSendResult, type TimeSlot, type TransportRequest, USER_DAY_LIMIT, type UpdateCalendarInput, type UrlCheckOptions, type UserDayInput, type UserDayResult, type ValidateBrandOptions, WEBHOOK_EVENT_TYPES, WEBHOOK_TEST_EVENT, type WaitlistEntryView, type WaitlistOffer, type WebhookDeliveryView, type WebhookEndpointView, type WebhookEnvelope, type WebhookEventType, type WebhookTransport, adaptersToCallbacks, addDateOverride, addTimeBlock, appointmentWebhookData, archiveCalendar, beginWaitlistAccept, bookAppointment, brandTemplateFields, buildJitsiUrl, buildNotificationContext, buildOccurrenceStartTime, buildRecurringSlots, calculateCancellationFee, cancelAppointment, cancelPendingNotifications, checkAnswers, checkAuthContract, checkCalendarSyncContract, checkClockContract, checkNotificationContract, checkPaymentContract, checkWebhookUrl, completeWaitlistAccept, createAppointmentType, createCalendar, createInMemoryAdapters, createNodeTransport, createNotificationTemplate, createRoutingForm, createWebhookEndpoint, deleteBrand, deleteCalendar, deleteNotificationTemplate, deleteRoutingForm, deleteWebhookEndpoint, deliverDueWebhooks, enqueueAppointmentWebhook, enqueueReminderSent, enqueueWebhookEvent, eraseSubject, expireWaitlistOffers, exportSubject, generateOccurrenceDates, generateWebhookSecret, getAppointment, getAppointmentDashboard, getAppointmentType, getAppointmentsForRange, getAvailableDates, getAvailableSlots, getBookingAnalytics, getBrand, getCalendar, getGroupCapacity, getGroupSessions, getNotificationTemplate, getPublicBrand, getPublicRoutingForm, getRoutingForm, getTeamAvailableSlots, getUserDayAppointments, getWaitlistOffer, isPrivateAddress, isSlotAvailable, isVirtualMeeting, joinWaitlist, leaveWaitlist, listAppointmentTypes, listAppointments, listAvailabilityRules, listCalendars, listNotificationTemplates, listPrivacyRequests, listRoutingForms, listWaitlist, listWebhookDeliveries, listWebhookEndpoints, localDay, localToUTC, markNoShow, matchingRules, offerFreedSlot, parseSubject, parseTimeLocal, previewErase, processPendingNotifications, queueImmediateNotification, queueStaffNotification, releaseWaitlistAccept, removeDateOverride, removeWaitlistEntry, renderTemplate, rescheduleAppointment, resolveDestination, resolveLocation, resolveSubject, retryWebhookDelivery, routeClient, saveBrand, schedError, scheduleNotifications, scopeToOrganization, selectCalendarForBooking, sendTestWebhook, senderIdentity, setWeeklyAvailability, settleBookedAccept, signWebhook, subjectHashes, testRoutingForm, toPublicBrand, tryOfferFreedSlot, updateAppointmentType, updateCalendar, updateNotificationTemplate, updateRoutingForm, validateBrand, validateRoutingDestinations, validateRoutingStructure, verifyWebhookSignature, withCalendarVisibility, withOrganization };
package/dist/index.js CHANGED
@@ -149,6 +149,7 @@ __export(index_exports, {
149
149
  saveBrand: () => saveBrand,
150
150
  schedError: () => schedError,
151
151
  scheduleNotifications: () => scheduleNotifications,
152
+ scopeToOrganization: () => scopeToOrganization,
152
153
  selectCalendarForBooking: () => selectCalendarForBooking,
153
154
  sendTestWebhook: () => sendTestWebhook,
154
155
  senderIdentity: () => senderIdentity,
@@ -167,7 +168,8 @@ __export(index_exports, {
167
168
  validateRoutingDestinations: () => validateRoutingDestinations,
168
169
  validateRoutingStructure: () => validateRoutingStructure,
169
170
  verifyWebhookSignature: () => verifyWebhookSignature,
170
- withCalendarVisibility: () => withCalendarVisibility
171
+ withCalendarVisibility: () => withCalendarVisibility,
172
+ withOrganization: () => withOrganization
171
173
  });
172
174
  module.exports = __toCommonJS(index_exports);
173
175
 
@@ -2232,6 +2234,37 @@ function buildConfirmationBody(appointment, type, calendar) {
2232
2234
  ].filter(Boolean).join("\n");
2233
2235
  }
2234
2236
 
2237
+ // src/appointments/organization-filter.ts
2238
+ function withOrganization(where, organizationId) {
2239
+ if (organizationId === void 0) return where;
2240
+ return { AND: [where, { calendar: { organizationId } }] };
2241
+ }
2242
+ var NARROWED_METHODS = /* @__PURE__ */ new Set(["findMany", "findFirst", "count"]);
2243
+ function narrowModel(model, narrow) {
2244
+ return new Proxy(model, {
2245
+ get(target, property) {
2246
+ const value = Reflect.get(target, property, target);
2247
+ if (typeof property === "string" && NARROWED_METHODS.has(property) && typeof value === "function") {
2248
+ return (args = {}) => value.call(target, { ...args, where: narrow(args.where ?? {}) });
2249
+ }
2250
+ return typeof value === "function" ? value.bind(target) : value;
2251
+ }
2252
+ });
2253
+ }
2254
+ function scopeToOrganization(db, organizationId) {
2255
+ if (organizationId === void 0) return db;
2256
+ const appointment = narrowModel(db.appointment, (where) => withOrganization(where, organizationId));
2257
+ const schedulingCalendar = narrowModel(db.schedulingCalendar, (where) => ({ AND: [where, { organizationId }] }));
2258
+ return new Proxy(db, {
2259
+ get(target, property) {
2260
+ if (property === "appointment") return appointment;
2261
+ if (property === "schedulingCalendar") return schedulingCalendar;
2262
+ const value = Reflect.get(target, property, target);
2263
+ return typeof value === "function" ? value.bind(target) : value;
2264
+ }
2265
+ });
2266
+ }
2267
+
2235
2268
  // src/appointments/book-appointment.ts
2236
2269
  var import_client5 = require("@prisma/client");
2237
2270
 
@@ -3490,20 +3523,19 @@ async function rescheduleAppointment(db, input, callbacks) {
3490
3523
  }
3491
3524
 
3492
3525
  // src/appointments/crud.ts
3493
- async function getAppointment(db, appointmentId) {
3494
- const appointment = await db.appointment.findUnique({
3495
- where: { id: appointmentId },
3496
- include: {
3497
- calendar: { select: { name: true } },
3498
- type: { select: { name: true } }
3499
- }
3500
- });
3526
+ async function getAppointment(db, appointmentId, options = {}) {
3527
+ const include = {
3528
+ calendar: { select: { name: true } },
3529
+ type: { select: { name: true } }
3530
+ };
3531
+ const appointment = options.organizationId === void 0 ? await db.appointment.findUnique({ where: { id: appointmentId }, include }) : await db.appointment.findFirst({ where: { id: appointmentId, calendar: { organizationId: options.organizationId } }, include });
3501
3532
  if (!appointment) {
3502
3533
  throw schedError("SCHED_300", { appointmentId });
3503
3534
  }
3504
3535
  return mapToDetails(appointment);
3505
3536
  }
3506
- async function listAppointments(db, options = {}) {
3537
+ async function listAppointments(unscopedDb, options = {}) {
3538
+ const db = scopeToOrganization(unscopedDb, options.organizationId);
3507
3539
  const where = {};
3508
3540
  if (options.calendarId) where.calendarId = options.calendarId;
3509
3541
  if (options.status) where.status = options.status;
@@ -3581,13 +3613,13 @@ var STATUS_ORDER = {
3581
3613
  CANCELLED: 4
3582
3614
  };
3583
3615
  async function getGroupSessions(db, params) {
3584
- const { startDate, endDate, calendarId, visibleCalendarIds } = params;
3616
+ const { startDate, endDate, calendarId, visibleCalendarIds, organizationId } = params;
3585
3617
  const RAW_TAKE_CAP = 1e3;
3586
- const where = withCalendarVisibility({
3618
+ const where = withOrganization(withCalendarVisibility({
3587
3619
  isGroup: true,
3588
3620
  startTime: { gte: startDate, lt: endDate },
3589
3621
  ...calendarId ? { calendarId } : {}
3590
- }, visibleCalendarIds);
3622
+ }, visibleCalendarIds), organizationId);
3591
3623
  const appointments = await db.appointment.findMany({
3592
3624
  where,
3593
3625
  include: {
@@ -3656,7 +3688,7 @@ async function getBookingAnalytics(db, options = {}) {
3656
3688
  startTime: { gte: start, lte: end }
3657
3689
  };
3658
3690
  if (options.calendarId) baseWhere.calendarId = options.calendarId;
3659
- const where = withCalendarVisibility(baseWhere, options.visibleCalendarIds);
3691
+ const where = withOrganization(withCalendarVisibility(baseWhere, options.visibleCalendarIds), options.organizationId);
3660
3692
  const appointments = await db.appointment.findMany({
3661
3693
  where,
3662
3694
  select: {
@@ -3788,7 +3820,8 @@ function weekBoundsUTC(localDateStr, tz) {
3788
3820
  const end = preciseDayEnd(computeDayBoundsUTC(toDateStr(sunday), tz).end);
3789
3821
  return { start, end };
3790
3822
  }
3791
- async function getAppointmentDashboard(db, query = {}) {
3823
+ async function getAppointmentDashboard(unscopedDb, query = {}) {
3824
+ const db = scopeToOrganization(unscopedDb, query.organizationId);
3792
3825
  const now = /* @__PURE__ */ new Date();
3793
3826
  const tz = query.timezone || DEFAULT_DASHBOARD_TIMEZONE;
3794
3827
  const localDateStr = now.toLocaleDateString("en-CA", { timeZone: tz });
@@ -3895,7 +3928,8 @@ async function getAppointmentDashboard(db, query = {}) {
3895
3928
  };
3896
3929
  }
3897
3930
  var RANGE_TAKE_CAP = 2e3;
3898
- async function getAppointmentsForRange(db, rangeStart, rangeEnd) {
3931
+ async function getAppointmentsForRange(unscopedDb, rangeStart, rangeEnd, options = {}) {
3932
+ const db = scopeToOrganization(unscopedDb, options.organizationId);
3899
3933
  const appointments = await db.appointment.findMany({
3900
3934
  where: {
3901
3935
  startTime: { gte: rangeStart, lte: rangeEnd }
@@ -3959,7 +3993,8 @@ function nextDate(date) {
3959
3993
  next.setUTCDate(next.getUTCDate() + 1);
3960
3994
  return next.toISOString().slice(0, 10);
3961
3995
  }
3962
- async function getUserDayAppointments(db, input) {
3996
+ async function getUserDayAppointments(unscopedDb, input) {
3997
+ const db = scopeToOrganization(unscopedDb, input.organizationId);
3963
3998
  if (!input.userId) throw new SchedulingValidationError("A user id is required for a day query");
3964
3999
  if (!validDate(input.date)) throw new SchedulingValidationError("date must be a real day in the form YYYY-MM-DD", void 0, { date: input.date });
3965
4000
  if (!validTimezone(input.timezone)) throw new SchedulingValidationError("timezone must be an IANA time zone", void 0, { timezone: input.timezone });
@@ -6243,6 +6278,7 @@ async function eraseSubject(db, input) {
6243
6278
  saveBrand,
6244
6279
  schedError,
6245
6280
  scheduleNotifications,
6281
+ scopeToOrganization,
6246
6282
  selectCalendarForBooking,
6247
6283
  sendTestWebhook,
6248
6284
  senderIdentity,
@@ -6261,5 +6297,6 @@ async function eraseSubject(db, input) {
6261
6297
  validateRoutingDestinations,
6262
6298
  validateRoutingStructure,
6263
6299
  verifyWebhookSignature,
6264
- withCalendarVisibility
6300
+ withCalendarVisibility,
6301
+ withOrganization
6265
6302
  });
package/dist/index.mjs CHANGED
@@ -2059,6 +2059,37 @@ function buildConfirmationBody(appointment, type, calendar) {
2059
2059
  ].filter(Boolean).join("\n");
2060
2060
  }
2061
2061
 
2062
+ // src/appointments/organization-filter.ts
2063
+ function withOrganization(where, organizationId) {
2064
+ if (organizationId === void 0) return where;
2065
+ return { AND: [where, { calendar: { organizationId } }] };
2066
+ }
2067
+ var NARROWED_METHODS = /* @__PURE__ */ new Set(["findMany", "findFirst", "count"]);
2068
+ function narrowModel(model, narrow) {
2069
+ return new Proxy(model, {
2070
+ get(target, property) {
2071
+ const value = Reflect.get(target, property, target);
2072
+ if (typeof property === "string" && NARROWED_METHODS.has(property) && typeof value === "function") {
2073
+ return (args = {}) => value.call(target, { ...args, where: narrow(args.where ?? {}) });
2074
+ }
2075
+ return typeof value === "function" ? value.bind(target) : value;
2076
+ }
2077
+ });
2078
+ }
2079
+ function scopeToOrganization(db, organizationId) {
2080
+ if (organizationId === void 0) return db;
2081
+ const appointment = narrowModel(db.appointment, (where) => withOrganization(where, organizationId));
2082
+ const schedulingCalendar = narrowModel(db.schedulingCalendar, (where) => ({ AND: [where, { organizationId }] }));
2083
+ return new Proxy(db, {
2084
+ get(target, property) {
2085
+ if (property === "appointment") return appointment;
2086
+ if (property === "schedulingCalendar") return schedulingCalendar;
2087
+ const value = Reflect.get(target, property, target);
2088
+ return typeof value === "function" ? value.bind(target) : value;
2089
+ }
2090
+ });
2091
+ }
2092
+
2062
2093
  // src/appointments/book-appointment.ts
2063
2094
  import { Prisma as Prisma5 } from "@prisma/client";
2064
2095
 
@@ -3317,20 +3348,19 @@ async function rescheduleAppointment(db, input, callbacks) {
3317
3348
  }
3318
3349
 
3319
3350
  // src/appointments/crud.ts
3320
- async function getAppointment(db, appointmentId) {
3321
- const appointment = await db.appointment.findUnique({
3322
- where: { id: appointmentId },
3323
- include: {
3324
- calendar: { select: { name: true } },
3325
- type: { select: { name: true } }
3326
- }
3327
- });
3351
+ async function getAppointment(db, appointmentId, options = {}) {
3352
+ const include = {
3353
+ calendar: { select: { name: true } },
3354
+ type: { select: { name: true } }
3355
+ };
3356
+ const appointment = options.organizationId === void 0 ? await db.appointment.findUnique({ where: { id: appointmentId }, include }) : await db.appointment.findFirst({ where: { id: appointmentId, calendar: { organizationId: options.organizationId } }, include });
3328
3357
  if (!appointment) {
3329
3358
  throw schedError("SCHED_300", { appointmentId });
3330
3359
  }
3331
3360
  return mapToDetails(appointment);
3332
3361
  }
3333
- async function listAppointments(db, options = {}) {
3362
+ async function listAppointments(unscopedDb, options = {}) {
3363
+ const db = scopeToOrganization(unscopedDb, options.organizationId);
3334
3364
  const where = {};
3335
3365
  if (options.calendarId) where.calendarId = options.calendarId;
3336
3366
  if (options.status) where.status = options.status;
@@ -3408,13 +3438,13 @@ var STATUS_ORDER = {
3408
3438
  CANCELLED: 4
3409
3439
  };
3410
3440
  async function getGroupSessions(db, params) {
3411
- const { startDate, endDate, calendarId, visibleCalendarIds } = params;
3441
+ const { startDate, endDate, calendarId, visibleCalendarIds, organizationId } = params;
3412
3442
  const RAW_TAKE_CAP = 1e3;
3413
- const where = withCalendarVisibility({
3443
+ const where = withOrganization(withCalendarVisibility({
3414
3444
  isGroup: true,
3415
3445
  startTime: { gte: startDate, lt: endDate },
3416
3446
  ...calendarId ? { calendarId } : {}
3417
- }, visibleCalendarIds);
3447
+ }, visibleCalendarIds), organizationId);
3418
3448
  const appointments = await db.appointment.findMany({
3419
3449
  where,
3420
3450
  include: {
@@ -3483,7 +3513,7 @@ async function getBookingAnalytics(db, options = {}) {
3483
3513
  startTime: { gte: start, lte: end }
3484
3514
  };
3485
3515
  if (options.calendarId) baseWhere.calendarId = options.calendarId;
3486
- const where = withCalendarVisibility(baseWhere, options.visibleCalendarIds);
3516
+ const where = withOrganization(withCalendarVisibility(baseWhere, options.visibleCalendarIds), options.organizationId);
3487
3517
  const appointments = await db.appointment.findMany({
3488
3518
  where,
3489
3519
  select: {
@@ -3615,7 +3645,8 @@ function weekBoundsUTC(localDateStr, tz) {
3615
3645
  const end = preciseDayEnd(computeDayBoundsUTC(toDateStr(sunday), tz).end);
3616
3646
  return { start, end };
3617
3647
  }
3618
- async function getAppointmentDashboard(db, query = {}) {
3648
+ async function getAppointmentDashboard(unscopedDb, query = {}) {
3649
+ const db = scopeToOrganization(unscopedDb, query.organizationId);
3619
3650
  const now = /* @__PURE__ */ new Date();
3620
3651
  const tz = query.timezone || DEFAULT_DASHBOARD_TIMEZONE;
3621
3652
  const localDateStr = now.toLocaleDateString("en-CA", { timeZone: tz });
@@ -3722,7 +3753,8 @@ async function getAppointmentDashboard(db, query = {}) {
3722
3753
  };
3723
3754
  }
3724
3755
  var RANGE_TAKE_CAP = 2e3;
3725
- async function getAppointmentsForRange(db, rangeStart, rangeEnd) {
3756
+ async function getAppointmentsForRange(unscopedDb, rangeStart, rangeEnd, options = {}) {
3757
+ const db = scopeToOrganization(unscopedDb, options.organizationId);
3726
3758
  const appointments = await db.appointment.findMany({
3727
3759
  where: {
3728
3760
  startTime: { gte: rangeStart, lte: rangeEnd }
@@ -3786,7 +3818,8 @@ function nextDate(date) {
3786
3818
  next.setUTCDate(next.getUTCDate() + 1);
3787
3819
  return next.toISOString().slice(0, 10);
3788
3820
  }
3789
- async function getUserDayAppointments(db, input) {
3821
+ async function getUserDayAppointments(unscopedDb, input) {
3822
+ const db = scopeToOrganization(unscopedDb, input.organizationId);
3790
3823
  if (!input.userId) throw new SchedulingValidationError("A user id is required for a day query");
3791
3824
  if (!validDate(input.date)) throw new SchedulingValidationError("date must be a real day in the form YYYY-MM-DD", void 0, { date: input.date });
3792
3825
  if (!validTimezone(input.timezone)) throw new SchedulingValidationError("timezone must be an IANA time zone", void 0, { timezone: input.timezone });
@@ -6069,6 +6102,7 @@ export {
6069
6102
  saveBrand,
6070
6103
  schedError,
6071
6104
  scheduleNotifications,
6105
+ scopeToOrganization,
6072
6106
  selectCalendarForBooking,
6073
6107
  sendTestWebhook,
6074
6108
  senderIdentity,
@@ -6087,5 +6121,6 @@ export {
6087
6121
  validateRoutingDestinations,
6088
6122
  validateRoutingStructure,
6089
6123
  verifyWebhookSignature,
6090
- withCalendarVisibility
6124
+ withCalendarVisibility,
6125
+ withOrganization
6091
6126
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/scheduling",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "license": "MIT",
5
5
  "description": "Scheduling engine for appointment-based businesses. API-first, no iframes.",
6
6
  "main": "./dist/index.js",