@ordinatio/scheduling 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.1 (2026-10-29)
4
+
5
+ - **Fix: a weekday with no opening hours is now closed once the calendar has any hours.** Before, a calendar with hours set only for some
6
+ weekdays still offered slots all day on the other weekdays. A calendar with no availability rules at all is still open around the
7
+ clock (nothing is configured yet), and a date override still opens a day. If you relied on an empty weekday being open, add hours for it.
8
+
9
+ ## 0.5.0 (2026-10-29)
10
+
11
+ - **Security fix: booking analytics and group-class lists no longer rely on the database handle being limited to one business.**
12
+ `getBookingAnalytics` and `getGroupSessions` take an optional `organizationId`; given one, nothing from another organization is
13
+ counted or listed, even when several businesses share one database. A new exported helper, `withOrganization(where, organizationId)`,
14
+ does the same for any appointment query, and `scopeToOrganization(db, organizationId)` limits every query a handle makes.
15
+ `getAppointmentDashboard`, `getAppointmentsForRange` (new 4th argument `{ organizationId }`), `getUserDayAppointments`,
16
+ `listAppointments` and `getAppointment` take the same optional `organizationId`; an appointment of another organization is reported
17
+ as not found. Left out, behavior is unchanged (for a host that gives each business its own database).
18
+ If you keep several businesses in one database, upgrade to this version and `@ordinatio/scheduling-api` 0.3.0 together: engine 0.4.0
19
+ and API 0.2.0 (and earlier) return other businesses' appointments and revenue totals to staff. If your own code calls
20
+ `getBookingAnalytics` or `getGroupSessions`, pass `organizationId` from now on.
21
+
3
22
  ## 0.4.0 (2026-10-28)
4
23
 
5
24
  - **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
 
@@ -1589,7 +1591,8 @@ function computeAvailableSlots(ctx, query) {
1589
1591
  );
1590
1592
  let activeRules = dateOverride ? [dateOverride] : [...weeklyRules];
1591
1593
  if (activeRules.length === 0) {
1592
- if (partialBlockConflicts.length > 0) {
1594
+ const hasConfiguredHours = rules.some((r) => !r.isBlocked);
1595
+ if (hasConfiguredHours || partialBlockConflicts.length > 0) {
1593
1596
  return { date: dateStr, calendarId, slots: [], timezone: tz };
1594
1597
  }
1595
1598
  activeRules.push({
@@ -2232,6 +2235,37 @@ function buildConfirmationBody(appointment, type, calendar) {
2232
2235
  ].filter(Boolean).join("\n");
2233
2236
  }
2234
2237
 
2238
+ // src/appointments/organization-filter.ts
2239
+ function withOrganization(where, organizationId) {
2240
+ if (organizationId === void 0) return where;
2241
+ return { AND: [where, { calendar: { organizationId } }] };
2242
+ }
2243
+ var NARROWED_METHODS = /* @__PURE__ */ new Set(["findMany", "findFirst", "count"]);
2244
+ function narrowModel(model, narrow) {
2245
+ return new Proxy(model, {
2246
+ get(target, property) {
2247
+ const value = Reflect.get(target, property, target);
2248
+ if (typeof property === "string" && NARROWED_METHODS.has(property) && typeof value === "function") {
2249
+ return (args = {}) => value.call(target, { ...args, where: narrow(args.where ?? {}) });
2250
+ }
2251
+ return typeof value === "function" ? value.bind(target) : value;
2252
+ }
2253
+ });
2254
+ }
2255
+ function scopeToOrganization(db, organizationId) {
2256
+ if (organizationId === void 0) return db;
2257
+ const appointment = narrowModel(db.appointment, (where) => withOrganization(where, organizationId));
2258
+ const schedulingCalendar = narrowModel(db.schedulingCalendar, (where) => ({ AND: [where, { organizationId }] }));
2259
+ return new Proxy(db, {
2260
+ get(target, property) {
2261
+ if (property === "appointment") return appointment;
2262
+ if (property === "schedulingCalendar") return schedulingCalendar;
2263
+ const value = Reflect.get(target, property, target);
2264
+ return typeof value === "function" ? value.bind(target) : value;
2265
+ }
2266
+ });
2267
+ }
2268
+
2235
2269
  // src/appointments/book-appointment.ts
2236
2270
  var import_client5 = require("@prisma/client");
2237
2271
 
@@ -3490,20 +3524,19 @@ async function rescheduleAppointment(db, input, callbacks) {
3490
3524
  }
3491
3525
 
3492
3526
  // 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
- });
3527
+ async function getAppointment(db, appointmentId, options = {}) {
3528
+ const include = {
3529
+ calendar: { select: { name: true } },
3530
+ type: { select: { name: true } }
3531
+ };
3532
+ 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
3533
  if (!appointment) {
3502
3534
  throw schedError("SCHED_300", { appointmentId });
3503
3535
  }
3504
3536
  return mapToDetails(appointment);
3505
3537
  }
3506
- async function listAppointments(db, options = {}) {
3538
+ async function listAppointments(unscopedDb, options = {}) {
3539
+ const db = scopeToOrganization(unscopedDb, options.organizationId);
3507
3540
  const where = {};
3508
3541
  if (options.calendarId) where.calendarId = options.calendarId;
3509
3542
  if (options.status) where.status = options.status;
@@ -3581,13 +3614,13 @@ var STATUS_ORDER = {
3581
3614
  CANCELLED: 4
3582
3615
  };
3583
3616
  async function getGroupSessions(db, params) {
3584
- const { startDate, endDate, calendarId, visibleCalendarIds } = params;
3617
+ const { startDate, endDate, calendarId, visibleCalendarIds, organizationId } = params;
3585
3618
  const RAW_TAKE_CAP = 1e3;
3586
- const where = withCalendarVisibility({
3619
+ const where = withOrganization(withCalendarVisibility({
3587
3620
  isGroup: true,
3588
3621
  startTime: { gte: startDate, lt: endDate },
3589
3622
  ...calendarId ? { calendarId } : {}
3590
- }, visibleCalendarIds);
3623
+ }, visibleCalendarIds), organizationId);
3591
3624
  const appointments = await db.appointment.findMany({
3592
3625
  where,
3593
3626
  include: {
@@ -3656,7 +3689,7 @@ async function getBookingAnalytics(db, options = {}) {
3656
3689
  startTime: { gte: start, lte: end }
3657
3690
  };
3658
3691
  if (options.calendarId) baseWhere.calendarId = options.calendarId;
3659
- const where = withCalendarVisibility(baseWhere, options.visibleCalendarIds);
3692
+ const where = withOrganization(withCalendarVisibility(baseWhere, options.visibleCalendarIds), options.organizationId);
3660
3693
  const appointments = await db.appointment.findMany({
3661
3694
  where,
3662
3695
  select: {
@@ -3788,7 +3821,8 @@ function weekBoundsUTC(localDateStr, tz) {
3788
3821
  const end = preciseDayEnd(computeDayBoundsUTC(toDateStr(sunday), tz).end);
3789
3822
  return { start, end };
3790
3823
  }
3791
- async function getAppointmentDashboard(db, query = {}) {
3824
+ async function getAppointmentDashboard(unscopedDb, query = {}) {
3825
+ const db = scopeToOrganization(unscopedDb, query.organizationId);
3792
3826
  const now = /* @__PURE__ */ new Date();
3793
3827
  const tz = query.timezone || DEFAULT_DASHBOARD_TIMEZONE;
3794
3828
  const localDateStr = now.toLocaleDateString("en-CA", { timeZone: tz });
@@ -3895,7 +3929,8 @@ async function getAppointmentDashboard(db, query = {}) {
3895
3929
  };
3896
3930
  }
3897
3931
  var RANGE_TAKE_CAP = 2e3;
3898
- async function getAppointmentsForRange(db, rangeStart, rangeEnd) {
3932
+ async function getAppointmentsForRange(unscopedDb, rangeStart, rangeEnd, options = {}) {
3933
+ const db = scopeToOrganization(unscopedDb, options.organizationId);
3899
3934
  const appointments = await db.appointment.findMany({
3900
3935
  where: {
3901
3936
  startTime: { gte: rangeStart, lte: rangeEnd }
@@ -3959,7 +3994,8 @@ function nextDate(date) {
3959
3994
  next.setUTCDate(next.getUTCDate() + 1);
3960
3995
  return next.toISOString().slice(0, 10);
3961
3996
  }
3962
- async function getUserDayAppointments(db, input) {
3997
+ async function getUserDayAppointments(unscopedDb, input) {
3998
+ const db = scopeToOrganization(unscopedDb, input.organizationId);
3963
3999
  if (!input.userId) throw new SchedulingValidationError("A user id is required for a day query");
3964
4000
  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
4001
  if (!validTimezone(input.timezone)) throw new SchedulingValidationError("timezone must be an IANA time zone", void 0, { timezone: input.timezone });
@@ -6243,6 +6279,7 @@ async function eraseSubject(db, input) {
6243
6279
  saveBrand,
6244
6280
  schedError,
6245
6281
  scheduleNotifications,
6282
+ scopeToOrganization,
6246
6283
  selectCalendarForBooking,
6247
6284
  sendTestWebhook,
6248
6285
  senderIdentity,
@@ -6261,5 +6298,6 @@ async function eraseSubject(db, input) {
6261
6298
  validateRoutingDestinations,
6262
6299
  validateRoutingStructure,
6263
6300
  verifyWebhookSignature,
6264
- withCalendarVisibility
6301
+ withCalendarVisibility,
6302
+ withOrganization
6265
6303
  });
package/dist/index.mjs CHANGED
@@ -1416,7 +1416,8 @@ function computeAvailableSlots(ctx, query) {
1416
1416
  );
1417
1417
  let activeRules = dateOverride ? [dateOverride] : [...weeklyRules];
1418
1418
  if (activeRules.length === 0) {
1419
- if (partialBlockConflicts.length > 0) {
1419
+ const hasConfiguredHours = rules.some((r) => !r.isBlocked);
1420
+ if (hasConfiguredHours || partialBlockConflicts.length > 0) {
1420
1421
  return { date: dateStr, calendarId, slots: [], timezone: tz };
1421
1422
  }
1422
1423
  activeRules.push({
@@ -2059,6 +2060,37 @@ function buildConfirmationBody(appointment, type, calendar) {
2059
2060
  ].filter(Boolean).join("\n");
2060
2061
  }
2061
2062
 
2063
+ // src/appointments/organization-filter.ts
2064
+ function withOrganization(where, organizationId) {
2065
+ if (organizationId === void 0) return where;
2066
+ return { AND: [where, { calendar: { organizationId } }] };
2067
+ }
2068
+ var NARROWED_METHODS = /* @__PURE__ */ new Set(["findMany", "findFirst", "count"]);
2069
+ function narrowModel(model, narrow) {
2070
+ return new Proxy(model, {
2071
+ get(target, property) {
2072
+ const value = Reflect.get(target, property, target);
2073
+ if (typeof property === "string" && NARROWED_METHODS.has(property) && typeof value === "function") {
2074
+ return (args = {}) => value.call(target, { ...args, where: narrow(args.where ?? {}) });
2075
+ }
2076
+ return typeof value === "function" ? value.bind(target) : value;
2077
+ }
2078
+ });
2079
+ }
2080
+ function scopeToOrganization(db, organizationId) {
2081
+ if (organizationId === void 0) return db;
2082
+ const appointment = narrowModel(db.appointment, (where) => withOrganization(where, organizationId));
2083
+ const schedulingCalendar = narrowModel(db.schedulingCalendar, (where) => ({ AND: [where, { organizationId }] }));
2084
+ return new Proxy(db, {
2085
+ get(target, property) {
2086
+ if (property === "appointment") return appointment;
2087
+ if (property === "schedulingCalendar") return schedulingCalendar;
2088
+ const value = Reflect.get(target, property, target);
2089
+ return typeof value === "function" ? value.bind(target) : value;
2090
+ }
2091
+ });
2092
+ }
2093
+
2062
2094
  // src/appointments/book-appointment.ts
2063
2095
  import { Prisma as Prisma5 } from "@prisma/client";
2064
2096
 
@@ -3317,20 +3349,19 @@ async function rescheduleAppointment(db, input, callbacks) {
3317
3349
  }
3318
3350
 
3319
3351
  // 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
- });
3352
+ async function getAppointment(db, appointmentId, options = {}) {
3353
+ const include = {
3354
+ calendar: { select: { name: true } },
3355
+ type: { select: { name: true } }
3356
+ };
3357
+ 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
3358
  if (!appointment) {
3329
3359
  throw schedError("SCHED_300", { appointmentId });
3330
3360
  }
3331
3361
  return mapToDetails(appointment);
3332
3362
  }
3333
- async function listAppointments(db, options = {}) {
3363
+ async function listAppointments(unscopedDb, options = {}) {
3364
+ const db = scopeToOrganization(unscopedDb, options.organizationId);
3334
3365
  const where = {};
3335
3366
  if (options.calendarId) where.calendarId = options.calendarId;
3336
3367
  if (options.status) where.status = options.status;
@@ -3408,13 +3439,13 @@ var STATUS_ORDER = {
3408
3439
  CANCELLED: 4
3409
3440
  };
3410
3441
  async function getGroupSessions(db, params) {
3411
- const { startDate, endDate, calendarId, visibleCalendarIds } = params;
3442
+ const { startDate, endDate, calendarId, visibleCalendarIds, organizationId } = params;
3412
3443
  const RAW_TAKE_CAP = 1e3;
3413
- const where = withCalendarVisibility({
3444
+ const where = withOrganization(withCalendarVisibility({
3414
3445
  isGroup: true,
3415
3446
  startTime: { gte: startDate, lt: endDate },
3416
3447
  ...calendarId ? { calendarId } : {}
3417
- }, visibleCalendarIds);
3448
+ }, visibleCalendarIds), organizationId);
3418
3449
  const appointments = await db.appointment.findMany({
3419
3450
  where,
3420
3451
  include: {
@@ -3483,7 +3514,7 @@ async function getBookingAnalytics(db, options = {}) {
3483
3514
  startTime: { gte: start, lte: end }
3484
3515
  };
3485
3516
  if (options.calendarId) baseWhere.calendarId = options.calendarId;
3486
- const where = withCalendarVisibility(baseWhere, options.visibleCalendarIds);
3517
+ const where = withOrganization(withCalendarVisibility(baseWhere, options.visibleCalendarIds), options.organizationId);
3487
3518
  const appointments = await db.appointment.findMany({
3488
3519
  where,
3489
3520
  select: {
@@ -3615,7 +3646,8 @@ function weekBoundsUTC(localDateStr, tz) {
3615
3646
  const end = preciseDayEnd(computeDayBoundsUTC(toDateStr(sunday), tz).end);
3616
3647
  return { start, end };
3617
3648
  }
3618
- async function getAppointmentDashboard(db, query = {}) {
3649
+ async function getAppointmentDashboard(unscopedDb, query = {}) {
3650
+ const db = scopeToOrganization(unscopedDb, query.organizationId);
3619
3651
  const now = /* @__PURE__ */ new Date();
3620
3652
  const tz = query.timezone || DEFAULT_DASHBOARD_TIMEZONE;
3621
3653
  const localDateStr = now.toLocaleDateString("en-CA", { timeZone: tz });
@@ -3722,7 +3754,8 @@ async function getAppointmentDashboard(db, query = {}) {
3722
3754
  };
3723
3755
  }
3724
3756
  var RANGE_TAKE_CAP = 2e3;
3725
- async function getAppointmentsForRange(db, rangeStart, rangeEnd) {
3757
+ async function getAppointmentsForRange(unscopedDb, rangeStart, rangeEnd, options = {}) {
3758
+ const db = scopeToOrganization(unscopedDb, options.organizationId);
3726
3759
  const appointments = await db.appointment.findMany({
3727
3760
  where: {
3728
3761
  startTime: { gte: rangeStart, lte: rangeEnd }
@@ -3786,7 +3819,8 @@ function nextDate(date) {
3786
3819
  next.setUTCDate(next.getUTCDate() + 1);
3787
3820
  return next.toISOString().slice(0, 10);
3788
3821
  }
3789
- async function getUserDayAppointments(db, input) {
3822
+ async function getUserDayAppointments(unscopedDb, input) {
3823
+ const db = scopeToOrganization(unscopedDb, input.organizationId);
3790
3824
  if (!input.userId) throw new SchedulingValidationError("A user id is required for a day query");
3791
3825
  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
3826
  if (!validTimezone(input.timezone)) throw new SchedulingValidationError("timezone must be an IANA time zone", void 0, { timezone: input.timezone });
@@ -6069,6 +6103,7 @@ export {
6069
6103
  saveBrand,
6070
6104
  schedError,
6071
6105
  scheduleNotifications,
6106
+ scopeToOrganization,
6072
6107
  selectCalendarForBooking,
6073
6108
  sendTestWebhook,
6074
6109
  senderIdentity,
@@ -6087,5 +6122,6 @@ export {
6087
6122
  validateRoutingDestinations,
6088
6123
  validateRoutingStructure,
6089
6124
  verifyWebhookSignature,
6090
- withCalendarVisibility
6125
+ withCalendarVisibility,
6126
+ withOrganization
6091
6127
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/scheduling",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "license": "MIT",
5
5
  "description": "Scheduling engine for appointment-based businesses. API-first, no iframes.",
6
6
  "main": "./dist/index.js",