@ordinatio/scheduling 0.5.1 → 0.6.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,18 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.6.1 (prepared 2026-11-16)
4
+
5
+ - **New: a business's text-message settings.** A new table, `OrganizationTextSettings` (`provider`, `fromNumber`, `enabled`, one row per organization), and `getTextSettings`, `saveTextSettings`, `deleteTextSettings`, `validateTextSettings` and `normalizeTextNumber`. The provider is `TELNYX` or `TWILIO` (a server can offer fewer with the `providers` option); the number is cleaned up to international format; every problem is reported at once as `SCHED_1500`. No provider keys are stored: the host holds the provider accounts and looks the business's settings up to choose the adapter. Saving replaces the whole row, so leaving `enabled` out sets it back to true. **After upgrading, run the new migration** (a new empty table; nothing existing changes): `20261116000000_organization_text_settings` in this package, and `20261116000000_scheduling_organization_text_settings` in a host that copies the migrations into its own database package.
6
+ - **New: the sender can be told which business a notification belongs to.** `processPendingNotifications(db, sender, { organization: true })` adds `organizationId` to the sender's context for each notification whose calendar has an organization, and `adaptersToCallbacks` hands it to the adapter as `OutboundMessage.organizationId`. It is off by default, so nothing changes for a host that does not ask. It lets one text-message adapter pick a number or provider per business.
7
+
8
+ ## 0.6.0 (prepared 2026-11-10)
9
+
10
+ - **Fix: the organization table now has the `settings` and `updatedAt` columns the cancellation policy needs.** `GET` and `PUT
11
+ /admin/policy` in `@ordinatio/scheduling-api` read and write `Organization.settings` and check `Organization.updatedAt`, but the
12
+ packaged schema had neither column, so both routes answered 500 on a database built from it. A new migration adds them
13
+ (`settings` starts as `{}` and `updatedAt` as the time of the migration for existing rows). **After upgrading, run
14
+ `prisma migrate deploy`** against your database before using those two routes.
15
+
3
16
  ## 0.5.1 (2026-10-29)
4
17
 
5
18
  - **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
package/dist/index.d.mts CHANGED
@@ -11,7 +11,7 @@ import * as _prisma_client_runtime_client from '@prisma/client/runtime/client';
11
11
  * interface (minus $transaction itself) so code inside transactions
12
12
  * is fully typed without `as any` casts.
13
13
  */
14
- type SchedulingDb = Pick<PrismaClient, 'schedulingCalendar' | 'availabilityRule' | 'appointmentType' | 'appointmentTypeCalendar' | 'appointmentCategory' | 'appointment' | 'scheduledNotification' | 'notificationTemplate' | 'servicePackage' | 'packagePurchase' | 'couponCode' | 'recurringSeries' | 'roundRobinState' | 'webhookEndpoint' | 'webhookDelivery' | 'webhookAttempt' | 'waitlistEntry' | 'routingForm' | 'dataSubjectRequest' | 'organizationBrand' | 'organization' | '$transaction' | '$executeRaw' | '$queryRaw'>;
14
+ type SchedulingDb = Pick<PrismaClient, 'schedulingCalendar' | 'availabilityRule' | 'appointmentType' | 'appointmentTypeCalendar' | 'appointmentCategory' | 'appointment' | 'scheduledNotification' | 'notificationTemplate' | 'servicePackage' | 'packagePurchase' | 'couponCode' | 'recurringSeries' | 'roundRobinState' | 'webhookEndpoint' | 'webhookDelivery' | 'webhookAttempt' | 'waitlistEntry' | 'routingForm' | 'dataSubjectRequest' | 'organizationBrand' | 'organizationTextSettings' | 'organization' | '$transaction' | '$executeRaw' | '$queryRaw'>;
15
15
  /**
16
16
  * Branded subtype of SchedulingDb for transaction clients produced by withTransaction().
17
17
  * selectCalendarForBooking() requires this type to enforce that its RoundRobinState
@@ -391,6 +391,8 @@ interface NotificationSenderContext {
391
391
  trigger?: NotificationTrigger;
392
392
  /** The organization's own sender identity, when branding is on and one is set. */
393
393
  from?: SenderIdentity;
394
+ /** The organization the notification belongs to. Only set when the caller asks for it (`organization: true`). */
395
+ organizationId?: string;
394
396
  }
395
397
  /**
396
398
  * Returned by the sender when it deliberately does not deliver the notification.
@@ -1409,6 +1411,8 @@ interface OutboundMessage {
1409
1411
  trigger?: NotificationTrigger;
1410
1412
  /** The organization's own sender identity, when it has one. An adapter that cannot send as it uses its default sender. */
1411
1413
  from?: SenderIdentity;
1414
+ /** The organization this message belongs to, when the host asked for it. Lets one adapter pick a number or provider per business. */
1415
+ organizationId?: string;
1412
1416
  }
1413
1417
  type SendResult = {
1414
1418
  status: 'SENT';
@@ -1654,6 +1658,8 @@ declare function processPendingNotifications(db: SchedulingDb, sender: Notificat
1654
1658
  webhooks?: boolean;
1655
1659
  /** Send each message with its organization's sender identity (name, address, reply-to). Off by default; needs the brand table. */
1656
1660
  brand?: boolean;
1661
+ /** Tell the sender which organization each notification belongs to (`organizationId` in its context). Off by default. */
1662
+ organization?: boolean;
1657
1663
  }): Promise<{
1658
1664
  sent: number;
1659
1665
  failed: number;
@@ -2740,4 +2746,37 @@ declare function senderIdentity(brand: BrandFields | null): SenderIdentity | nul
2740
2746
  declare function brandTemplateFields(brand: BrandFields | null): Record<string, string>;
2741
2747
  declare function toPublicBrand(brand: BrandFields): PublicBrand;
2742
2748
 
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 };
2749
+ declare const TEXT_PROVIDERS: readonly ["TELNYX", "TWILIO"];
2750
+ type TextProvider = (typeof TEXT_PROVIDERS)[number];
2751
+ interface TextSettingsFields {
2752
+ provider: TextProvider;
2753
+ /** International format, such as +13135550100. */
2754
+ fromNumber: string;
2755
+ /** False pauses texting for the business without losing its number. */
2756
+ enabled: boolean;
2757
+ }
2758
+ interface TextSettingsView extends TextSettingsFields {
2759
+ updatedAt: Date;
2760
+ }
2761
+ interface TextSettingsProblem {
2762
+ path: string;
2763
+ message: string;
2764
+ }
2765
+ declare const TEXT_SETTINGS_FIELDS: readonly ["provider", "fromNumber", "enabled"];
2766
+
2767
+ /** International format, or null. Ten digits are read as a US number. */
2768
+ declare function normalizeTextNumber(raw: string): string | null;
2769
+ interface ValidateTextSettingsOptions {
2770
+ /** The providers this server has accounts for. Default: all known providers. */
2771
+ providers?: readonly TextProvider[];
2772
+ }
2773
+ /** The stored form of the settings, or a SCHED_1500 error listing every problem. */
2774
+ declare function validateTextSettings(input: unknown, options?: ValidateTextSettingsOptions): TextSettingsFields;
2775
+
2776
+ declare function getTextSettings(db: SchedulingDb, organizationId: string): Promise<TextSettingsView | null>;
2777
+ /** Saves the whole settings, replacing what was there. Throws SCHED_1500 listing every problem. */
2778
+ declare function saveTextSettings(db: SchedulingDb, organizationId: string, input: unknown, options?: ValidateTextSettingsOptions): Promise<TextSettingsView>;
2779
+ /** Removes the settings. True when there were some. */
2780
+ declare function deleteTextSettings(db: SchedulingDb, organizationId: string): Promise<boolean>;
2781
+
2782
+ 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, TEXT_PROVIDERS, TEXT_SETTINGS_FIELDS, type TeamAvailabilityQuery, type TeamAvailabilityResult, type TestSendResult, type TextProvider, type TextSettingsFields, type TextSettingsProblem, type TextSettingsView, type TimeSlot, type TransportRequest, USER_DAY_LIMIT, type UpdateCalendarInput, type UrlCheckOptions, type UserDayInput, type UserDayResult, type ValidateBrandOptions, type ValidateTextSettingsOptions, 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, deleteTextSettings, 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, getTextSettings, getUserDayAppointments, getWaitlistOffer, isPrivateAddress, isSlotAvailable, isVirtualMeeting, joinWaitlist, leaveWaitlist, listAppointmentTypes, listAppointments, listAvailabilityRules, listCalendars, listNotificationTemplates, listPrivacyRequests, listRoutingForms, listWaitlist, listWebhookDeliveries, listWebhookEndpoints, localDay, localToUTC, markNoShow, matchingRules, normalizeTextNumber, offerFreedSlot, parseSubject, parseTimeLocal, previewErase, processPendingNotifications, queueImmediateNotification, queueStaffNotification, releaseWaitlistAccept, removeDateOverride, removeWaitlistEntry, renderTemplate, rescheduleAppointment, resolveDestination, resolveLocation, resolveSubject, retryWebhookDelivery, routeClient, saveBrand, saveTextSettings, schedError, scheduleNotifications, scopeToOrganization, selectCalendarForBooking, sendTestWebhook, senderIdentity, setWeeklyAvailability, settleBookedAccept, signWebhook, subjectHashes, testRoutingForm, toPublicBrand, tryOfferFreedSlot, updateAppointmentType, updateCalendar, updateNotificationTemplate, updateRoutingForm, validateBrand, validateRoutingDestinations, validateRoutingStructure, validateTextSettings, verifyWebhookSignature, withCalendarVisibility, withOrganization };
package/dist/index.d.ts CHANGED
@@ -11,7 +11,7 @@ import * as _prisma_client_runtime_client from '@prisma/client/runtime/client';
11
11
  * interface (minus $transaction itself) so code inside transactions
12
12
  * is fully typed without `as any` casts.
13
13
  */
14
- type SchedulingDb = Pick<PrismaClient, 'schedulingCalendar' | 'availabilityRule' | 'appointmentType' | 'appointmentTypeCalendar' | 'appointmentCategory' | 'appointment' | 'scheduledNotification' | 'notificationTemplate' | 'servicePackage' | 'packagePurchase' | 'couponCode' | 'recurringSeries' | 'roundRobinState' | 'webhookEndpoint' | 'webhookDelivery' | 'webhookAttempt' | 'waitlistEntry' | 'routingForm' | 'dataSubjectRequest' | 'organizationBrand' | 'organization' | '$transaction' | '$executeRaw' | '$queryRaw'>;
14
+ type SchedulingDb = Pick<PrismaClient, 'schedulingCalendar' | 'availabilityRule' | 'appointmentType' | 'appointmentTypeCalendar' | 'appointmentCategory' | 'appointment' | 'scheduledNotification' | 'notificationTemplate' | 'servicePackage' | 'packagePurchase' | 'couponCode' | 'recurringSeries' | 'roundRobinState' | 'webhookEndpoint' | 'webhookDelivery' | 'webhookAttempt' | 'waitlistEntry' | 'routingForm' | 'dataSubjectRequest' | 'organizationBrand' | 'organizationTextSettings' | 'organization' | '$transaction' | '$executeRaw' | '$queryRaw'>;
15
15
  /**
16
16
  * Branded subtype of SchedulingDb for transaction clients produced by withTransaction().
17
17
  * selectCalendarForBooking() requires this type to enforce that its RoundRobinState
@@ -391,6 +391,8 @@ interface NotificationSenderContext {
391
391
  trigger?: NotificationTrigger;
392
392
  /** The organization's own sender identity, when branding is on and one is set. */
393
393
  from?: SenderIdentity;
394
+ /** The organization the notification belongs to. Only set when the caller asks for it (`organization: true`). */
395
+ organizationId?: string;
394
396
  }
395
397
  /**
396
398
  * Returned by the sender when it deliberately does not deliver the notification.
@@ -1409,6 +1411,8 @@ interface OutboundMessage {
1409
1411
  trigger?: NotificationTrigger;
1410
1412
  /** The organization's own sender identity, when it has one. An adapter that cannot send as it uses its default sender. */
1411
1413
  from?: SenderIdentity;
1414
+ /** The organization this message belongs to, when the host asked for it. Lets one adapter pick a number or provider per business. */
1415
+ organizationId?: string;
1412
1416
  }
1413
1417
  type SendResult = {
1414
1418
  status: 'SENT';
@@ -1654,6 +1658,8 @@ declare function processPendingNotifications(db: SchedulingDb, sender: Notificat
1654
1658
  webhooks?: boolean;
1655
1659
  /** Send each message with its organization's sender identity (name, address, reply-to). Off by default; needs the brand table. */
1656
1660
  brand?: boolean;
1661
+ /** Tell the sender which organization each notification belongs to (`organizationId` in its context). Off by default. */
1662
+ organization?: boolean;
1657
1663
  }): Promise<{
1658
1664
  sent: number;
1659
1665
  failed: number;
@@ -2740,4 +2746,37 @@ declare function senderIdentity(brand: BrandFields | null): SenderIdentity | nul
2740
2746
  declare function brandTemplateFields(brand: BrandFields | null): Record<string, string>;
2741
2747
  declare function toPublicBrand(brand: BrandFields): PublicBrand;
2742
2748
 
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 };
2749
+ declare const TEXT_PROVIDERS: readonly ["TELNYX", "TWILIO"];
2750
+ type TextProvider = (typeof TEXT_PROVIDERS)[number];
2751
+ interface TextSettingsFields {
2752
+ provider: TextProvider;
2753
+ /** International format, such as +13135550100. */
2754
+ fromNumber: string;
2755
+ /** False pauses texting for the business without losing its number. */
2756
+ enabled: boolean;
2757
+ }
2758
+ interface TextSettingsView extends TextSettingsFields {
2759
+ updatedAt: Date;
2760
+ }
2761
+ interface TextSettingsProblem {
2762
+ path: string;
2763
+ message: string;
2764
+ }
2765
+ declare const TEXT_SETTINGS_FIELDS: readonly ["provider", "fromNumber", "enabled"];
2766
+
2767
+ /** International format, or null. Ten digits are read as a US number. */
2768
+ declare function normalizeTextNumber(raw: string): string | null;
2769
+ interface ValidateTextSettingsOptions {
2770
+ /** The providers this server has accounts for. Default: all known providers. */
2771
+ providers?: readonly TextProvider[];
2772
+ }
2773
+ /** The stored form of the settings, or a SCHED_1500 error listing every problem. */
2774
+ declare function validateTextSettings(input: unknown, options?: ValidateTextSettingsOptions): TextSettingsFields;
2775
+
2776
+ declare function getTextSettings(db: SchedulingDb, organizationId: string): Promise<TextSettingsView | null>;
2777
+ /** Saves the whole settings, replacing what was there. Throws SCHED_1500 listing every problem. */
2778
+ declare function saveTextSettings(db: SchedulingDb, organizationId: string, input: unknown, options?: ValidateTextSettingsOptions): Promise<TextSettingsView>;
2779
+ /** Removes the settings. True when there were some. */
2780
+ declare function deleteTextSettings(db: SchedulingDb, organizationId: string): Promise<boolean>;
2781
+
2782
+ 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, TEXT_PROVIDERS, TEXT_SETTINGS_FIELDS, type TeamAvailabilityQuery, type TeamAvailabilityResult, type TestSendResult, type TextProvider, type TextSettingsFields, type TextSettingsProblem, type TextSettingsView, type TimeSlot, type TransportRequest, USER_DAY_LIMIT, type UpdateCalendarInput, type UrlCheckOptions, type UserDayInput, type UserDayResult, type ValidateBrandOptions, type ValidateTextSettingsOptions, 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, deleteTextSettings, 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, getTextSettings, getUserDayAppointments, getWaitlistOffer, isPrivateAddress, isSlotAvailable, isVirtualMeeting, joinWaitlist, leaveWaitlist, listAppointmentTypes, listAppointments, listAvailabilityRules, listCalendars, listNotificationTemplates, listPrivacyRequests, listRoutingForms, listWaitlist, listWebhookDeliveries, listWebhookEndpoints, localDay, localToUTC, markNoShow, matchingRules, normalizeTextNumber, offerFreedSlot, parseSubject, parseTimeLocal, previewErase, processPendingNotifications, queueImmediateNotification, queueStaffNotification, releaseWaitlistAccept, removeDateOverride, removeWaitlistEntry, renderTemplate, rescheduleAppointment, resolveDestination, resolveLocation, resolveSubject, retryWebhookDelivery, routeClient, saveBrand, saveTextSettings, schedError, scheduleNotifications, scopeToOrganization, selectCalendarForBooking, sendTestWebhook, senderIdentity, setWeeklyAvailability, settleBookedAccept, signWebhook, subjectHashes, testRoutingForm, toPublicBrand, tryOfferFreedSlot, updateAppointmentType, updateCalendar, updateNotificationTemplate, updateRoutingForm, validateBrand, validateRoutingDestinations, validateRoutingStructure, validateTextSettings, verifyWebhookSignature, withCalendarVisibility, withOrganization };
package/dist/index.js CHANGED
@@ -45,6 +45,8 @@ __export(index_exports, {
45
45
  SIGNATURE_HEADER: () => SIGNATURE_HEADER,
46
46
  SchedulingNotFoundError: () => SchedulingNotFoundError,
47
47
  SchedulingValidationError: () => SchedulingValidationError,
48
+ TEXT_PROVIDERS: () => TEXT_PROVIDERS,
49
+ TEXT_SETTINGS_FIELDS: () => TEXT_SETTINGS_FIELDS,
48
50
  USER_DAY_LIMIT: () => USER_DAY_LIMIT,
49
51
  WEBHOOK_EVENT_TYPES: () => WEBHOOK_EVENT_TYPES,
50
52
  WEBHOOK_TEST_EVENT: () => WEBHOOK_TEST_EVENT,
@@ -82,6 +84,7 @@ __export(index_exports, {
82
84
  deleteCalendar: () => deleteCalendar,
83
85
  deleteNotificationTemplate: () => deleteNotificationTemplate,
84
86
  deleteRoutingForm: () => deleteRoutingForm,
87
+ deleteTextSettings: () => deleteTextSettings,
85
88
  deleteWebhookEndpoint: () => deleteWebhookEndpoint,
86
89
  deliverDueWebhooks: () => deliverDueWebhooks,
87
90
  enqueueAppointmentWebhook: () => enqueueAppointmentWebhook,
@@ -108,6 +111,7 @@ __export(index_exports, {
108
111
  getPublicRoutingForm: () => getPublicRoutingForm,
109
112
  getRoutingForm: () => getRoutingForm,
110
113
  getTeamAvailableSlots: () => getTeamAvailableSlots,
114
+ getTextSettings: () => getTextSettings,
111
115
  getUserDayAppointments: () => getUserDayAppointments,
112
116
  getWaitlistOffer: () => getWaitlistOffer,
113
117
  isPrivateAddress: () => isPrivateAddress,
@@ -129,6 +133,7 @@ __export(index_exports, {
129
133
  localToUTC: () => localToUTC,
130
134
  markNoShow: () => markNoShow,
131
135
  matchingRules: () => matchingRules,
136
+ normalizeTextNumber: () => normalizeTextNumber,
132
137
  offerFreedSlot: () => offerFreedSlot,
133
138
  parseSubject: () => parseSubject,
134
139
  parseTimeLocal: () => parseTimeLocal,
@@ -147,6 +152,7 @@ __export(index_exports, {
147
152
  retryWebhookDelivery: () => retryWebhookDelivery,
148
153
  routeClient: () => routeClient,
149
154
  saveBrand: () => saveBrand,
155
+ saveTextSettings: () => saveTextSettings,
150
156
  schedError: () => schedError,
151
157
  scheduleNotifications: () => scheduleNotifications,
152
158
  scopeToOrganization: () => scopeToOrganization,
@@ -167,6 +173,7 @@ __export(index_exports, {
167
173
  validateBrand: () => validateBrand,
168
174
  validateRoutingDestinations: () => validateRoutingDestinations,
169
175
  validateRoutingStructure: () => validateRoutingStructure,
176
+ validateTextSettings: () => validateTextSettings,
170
177
  verifyWebhookSignature: () => verifyWebhookSignature,
171
178
  withCalendarVisibility: () => withCalendarVisibility,
172
179
  withOrganization: () => withOrganization
@@ -1310,6 +1317,22 @@ var BRAND_ERRORS = {
1310
1317
  }
1311
1318
  };
1312
1319
 
1320
+ // src/errors/registry-text-settings.ts
1321
+ var TEXT_SETTINGS_ERRORS = {
1322
+ SCHED_1500: {
1323
+ code: "SCHED_1500",
1324
+ file: "text-settings/",
1325
+ function: "validateTextSettings",
1326
+ severity: "warning",
1327
+ recoverable: true,
1328
+ description: "The text-message settings are not valid",
1329
+ diagnosis: [
1330
+ "Read the list of problems in the error context: each names the field and what is wrong",
1331
+ "The provider must be one the server offers; the number is a phone number such as +13135550100"
1332
+ ]
1333
+ }
1334
+ };
1335
+
1313
1336
  // src/errors/registry.ts
1314
1337
  var SCHEDULING_ERRORS = {
1315
1338
  ...CALENDARS_AVAILABILITY_ERRORS,
@@ -1324,7 +1347,8 @@ var SCHEDULING_ERRORS = {
1324
1347
  ...WAITLIST_ERRORS,
1325
1348
  ...ROUTING_ERRORS,
1326
1349
  ...PRIVACY_ERRORS,
1327
- ...BRAND_ERRORS
1350
+ ...BRAND_ERRORS,
1351
+ ...TEXT_SETTINGS_ERRORS
1328
1352
  };
1329
1353
 
1330
1354
  // src/errors/diagnostic-error.ts
@@ -2958,7 +2982,7 @@ async function processPendingNotifications(db, sender, options) {
2958
2982
  if (claimed.length === 0) return { sent: 0, failed: 0, deadLettered: 0, skipped: 0 };
2959
2983
  const pending = await db.scheduledNotification.findMany({
2960
2984
  where: { id: { in: claimed.map((c) => c.id) } },
2961
- ...options?.brand ? { include: { appointment: { select: { calendar: { select: { organizationId: true } } } } } } : {}
2985
+ ...options?.brand || options?.organization ? { include: { appointment: { select: { calendar: { select: { organizationId: true } } } } } } : {}
2962
2986
  });
2963
2987
  const senders = options?.brand ? await loadSenders(db, pending) : null;
2964
2988
  let sent = 0;
@@ -2974,7 +2998,8 @@ async function processPendingNotifications(db, sender, options) {
2974
2998
  notification.body,
2975
2999
  {
2976
3000
  trigger: notification.trigger,
2977
- ...senderFor(senders, notification)
3001
+ ...senderFor(senders, notification),
3002
+ ...options?.organization ? organizationOf(notification) : {}
2978
3003
  }
2979
3004
  );
2980
3005
  if (result?.skipped) {
@@ -3040,6 +3065,10 @@ async function loadSenders(db, rows) {
3040
3065
  }
3041
3066
  return senders;
3042
3067
  }
3068
+ function organizationOf(row) {
3069
+ const organizationId = row.appointment?.calendar?.organizationId;
3070
+ return organizationId ? { organizationId } : {};
3071
+ }
3043
3072
  function senderFor(senders, row) {
3044
3073
  const organizationId = row.appointment?.calendar?.organizationId;
3045
3074
  const from = senders && organizationId ? senders.get(organizationId) : void 0;
@@ -4145,7 +4174,7 @@ function adaptersToCallbacks(adapters, passThrough = {}) {
4145
4174
  return {
4146
4175
  ...passThrough,
4147
4176
  sendNotification: async (channel, to, subject, body, context) => {
4148
- const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger, ...context?.from ? { from: context.from } : {} });
4177
+ const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger, ...context?.from ? { from: context.from } : {}, ...context?.organizationId ? { organizationId: context.organizationId } : {} });
4149
4178
  if (result.status === "SKIPPED") return { skipped: true, reason: result.reason };
4150
4179
  return void 0;
4151
4180
  },
@@ -6158,6 +6187,66 @@ async function eraseSubject(db, input) {
6158
6187
  return { counts };
6159
6188
  }, { timeout: 12e4 });
6160
6189
  }
6190
+
6191
+ // src/text-settings/types.ts
6192
+ var TEXT_PROVIDERS = ["TELNYX", "TWILIO"];
6193
+ var TEXT_SETTINGS_FIELDS = ["provider", "fromNumber", "enabled"];
6194
+
6195
+ // src/text-settings/validate.ts
6196
+ function normalizeTextNumber(raw) {
6197
+ const digits = raw.trim().replace(/[\s().-]/g, "");
6198
+ if (/^\+[1-9]\d{7,14}$/.test(digits)) return digits;
6199
+ if (/^\d{10}$/.test(digits)) return `+1${digits}`;
6200
+ if (/^1\d{10}$/.test(digits)) return `+${digits}`;
6201
+ return null;
6202
+ }
6203
+ function validateTextSettings(input, options = {}) {
6204
+ const problems = [];
6205
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
6206
+ throw new SchedulingValidationError("The text-message settings are not valid", "SCHED_1500", { errors: [{ path: "", message: "Must be an object" }] });
6207
+ }
6208
+ const given = input;
6209
+ for (const key of Object.keys(given)) if (!TEXT_SETTINGS_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
6210
+ const offered = options.providers ?? TEXT_PROVIDERS;
6211
+ let provider = TEXT_PROVIDERS[0];
6212
+ if (typeof given.provider !== "string" || given.provider === "") problems.push({ path: "provider", message: "Required" });
6213
+ else if (!TEXT_PROVIDERS.includes(given.provider) || !offered.includes(given.provider)) {
6214
+ problems.push({ path: "provider", message: `Must be one of: ${offered.join(", ")}` });
6215
+ } else provider = given.provider;
6216
+ let fromNumber = "";
6217
+ if (typeof given.fromNumber !== "string" || given.fromNumber.trim() === "") problems.push({ path: "fromNumber", message: "Required" });
6218
+ else {
6219
+ const normalized = normalizeTextNumber(given.fromNumber);
6220
+ if (normalized === null) problems.push({ path: "fromNumber", message: "Must be a phone number such as +13135550100" });
6221
+ else fromNumber = normalized;
6222
+ }
6223
+ let enabled = true;
6224
+ if (given.enabled !== void 0) {
6225
+ if (typeof given.enabled === "boolean") enabled = given.enabled;
6226
+ else problems.push({ path: "enabled", message: "Must be true or false" });
6227
+ }
6228
+ if (problems.length > 0) throw new SchedulingValidationError("The text-message settings are not valid", "SCHED_1500", { errors: problems });
6229
+ return { provider, fromNumber, enabled };
6230
+ }
6231
+
6232
+ // src/text-settings/crud.ts
6233
+ var SELECT2 = { provider: true, fromNumber: true, enabled: true, updatedAt: true };
6234
+ async function getTextSettings(db, organizationId) {
6235
+ return db.organizationTextSettings.findUnique({ where: { organizationId }, select: SELECT2 });
6236
+ }
6237
+ async function saveTextSettings(db, organizationId, input, options = {}) {
6238
+ const fields = validateTextSettings(input, options);
6239
+ return db.organizationTextSettings.upsert({
6240
+ where: { organizationId },
6241
+ create: { organizationId, ...fields },
6242
+ update: { ...fields },
6243
+ select: SELECT2
6244
+ });
6245
+ }
6246
+ async function deleteTextSettings(db, organizationId) {
6247
+ const { count } = await db.organizationTextSettings.deleteMany({ where: { organizationId } });
6248
+ return count > 0;
6249
+ }
6161
6250
  // Annotate the CommonJS export names for ESM import in node:
6162
6251
  0 && (module.exports = {
6163
6252
  BRAND_FIELDS,
@@ -6175,6 +6264,8 @@ async function eraseSubject(db, input) {
6175
6264
  SIGNATURE_HEADER,
6176
6265
  SchedulingNotFoundError,
6177
6266
  SchedulingValidationError,
6267
+ TEXT_PROVIDERS,
6268
+ TEXT_SETTINGS_FIELDS,
6178
6269
  USER_DAY_LIMIT,
6179
6270
  WEBHOOK_EVENT_TYPES,
6180
6271
  WEBHOOK_TEST_EVENT,
@@ -6212,6 +6303,7 @@ async function eraseSubject(db, input) {
6212
6303
  deleteCalendar,
6213
6304
  deleteNotificationTemplate,
6214
6305
  deleteRoutingForm,
6306
+ deleteTextSettings,
6215
6307
  deleteWebhookEndpoint,
6216
6308
  deliverDueWebhooks,
6217
6309
  enqueueAppointmentWebhook,
@@ -6238,6 +6330,7 @@ async function eraseSubject(db, input) {
6238
6330
  getPublicRoutingForm,
6239
6331
  getRoutingForm,
6240
6332
  getTeamAvailableSlots,
6333
+ getTextSettings,
6241
6334
  getUserDayAppointments,
6242
6335
  getWaitlistOffer,
6243
6336
  isPrivateAddress,
@@ -6259,6 +6352,7 @@ async function eraseSubject(db, input) {
6259
6352
  localToUTC,
6260
6353
  markNoShow,
6261
6354
  matchingRules,
6355
+ normalizeTextNumber,
6262
6356
  offerFreedSlot,
6263
6357
  parseSubject,
6264
6358
  parseTimeLocal,
@@ -6277,6 +6371,7 @@ async function eraseSubject(db, input) {
6277
6371
  retryWebhookDelivery,
6278
6372
  routeClient,
6279
6373
  saveBrand,
6374
+ saveTextSettings,
6280
6375
  schedError,
6281
6376
  scheduleNotifications,
6282
6377
  scopeToOrganization,
@@ -6297,6 +6392,7 @@ async function eraseSubject(db, input) {
6297
6392
  validateBrand,
6298
6393
  validateRoutingDestinations,
6299
6394
  validateRoutingStructure,
6395
+ validateTextSettings,
6300
6396
  verifyWebhookSignature,
6301
6397
  withCalendarVisibility,
6302
6398
  withOrganization
package/dist/index.mjs CHANGED
@@ -1135,6 +1135,22 @@ var BRAND_ERRORS = {
1135
1135
  }
1136
1136
  };
1137
1137
 
1138
+ // src/errors/registry-text-settings.ts
1139
+ var TEXT_SETTINGS_ERRORS = {
1140
+ SCHED_1500: {
1141
+ code: "SCHED_1500",
1142
+ file: "text-settings/",
1143
+ function: "validateTextSettings",
1144
+ severity: "warning",
1145
+ recoverable: true,
1146
+ description: "The text-message settings are not valid",
1147
+ diagnosis: [
1148
+ "Read the list of problems in the error context: each names the field and what is wrong",
1149
+ "The provider must be one the server offers; the number is a phone number such as +13135550100"
1150
+ ]
1151
+ }
1152
+ };
1153
+
1138
1154
  // src/errors/registry.ts
1139
1155
  var SCHEDULING_ERRORS = {
1140
1156
  ...CALENDARS_AVAILABILITY_ERRORS,
@@ -1149,7 +1165,8 @@ var SCHEDULING_ERRORS = {
1149
1165
  ...WAITLIST_ERRORS,
1150
1166
  ...ROUTING_ERRORS,
1151
1167
  ...PRIVACY_ERRORS,
1152
- ...BRAND_ERRORS
1168
+ ...BRAND_ERRORS,
1169
+ ...TEXT_SETTINGS_ERRORS
1153
1170
  };
1154
1171
 
1155
1172
  // src/errors/diagnostic-error.ts
@@ -2783,7 +2800,7 @@ async function processPendingNotifications(db, sender, options) {
2783
2800
  if (claimed.length === 0) return { sent: 0, failed: 0, deadLettered: 0, skipped: 0 };
2784
2801
  const pending = await db.scheduledNotification.findMany({
2785
2802
  where: { id: { in: claimed.map((c) => c.id) } },
2786
- ...options?.brand ? { include: { appointment: { select: { calendar: { select: { organizationId: true } } } } } } : {}
2803
+ ...options?.brand || options?.organization ? { include: { appointment: { select: { calendar: { select: { organizationId: true } } } } } } : {}
2787
2804
  });
2788
2805
  const senders = options?.brand ? await loadSenders(db, pending) : null;
2789
2806
  let sent = 0;
@@ -2799,7 +2816,8 @@ async function processPendingNotifications(db, sender, options) {
2799
2816
  notification.body,
2800
2817
  {
2801
2818
  trigger: notification.trigger,
2802
- ...senderFor(senders, notification)
2819
+ ...senderFor(senders, notification),
2820
+ ...options?.organization ? organizationOf(notification) : {}
2803
2821
  }
2804
2822
  );
2805
2823
  if (result?.skipped) {
@@ -2865,6 +2883,10 @@ async function loadSenders(db, rows) {
2865
2883
  }
2866
2884
  return senders;
2867
2885
  }
2886
+ function organizationOf(row) {
2887
+ const organizationId = row.appointment?.calendar?.organizationId;
2888
+ return organizationId ? { organizationId } : {};
2889
+ }
2868
2890
  function senderFor(senders, row) {
2869
2891
  const organizationId = row.appointment?.calendar?.organizationId;
2870
2892
  const from = senders && organizationId ? senders.get(organizationId) : void 0;
@@ -3970,7 +3992,7 @@ function adaptersToCallbacks(adapters, passThrough = {}) {
3970
3992
  return {
3971
3993
  ...passThrough,
3972
3994
  sendNotification: async (channel, to, subject, body, context) => {
3973
- const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger, ...context?.from ? { from: context.from } : {} });
3995
+ const result = await adapters.notifications.send({ channel, to, subject, body, trigger: context?.trigger, ...context?.from ? { from: context.from } : {}, ...context?.organizationId ? { organizationId: context.organizationId } : {} });
3974
3996
  if (result.status === "SKIPPED") return { skipped: true, reason: result.reason };
3975
3997
  return void 0;
3976
3998
  },
@@ -5983,6 +6005,66 @@ async function eraseSubject(db, input) {
5983
6005
  return { counts };
5984
6006
  }, { timeout: 12e4 });
5985
6007
  }
6008
+
6009
+ // src/text-settings/types.ts
6010
+ var TEXT_PROVIDERS = ["TELNYX", "TWILIO"];
6011
+ var TEXT_SETTINGS_FIELDS = ["provider", "fromNumber", "enabled"];
6012
+
6013
+ // src/text-settings/validate.ts
6014
+ function normalizeTextNumber(raw) {
6015
+ const digits = raw.trim().replace(/[\s().-]/g, "");
6016
+ if (/^\+[1-9]\d{7,14}$/.test(digits)) return digits;
6017
+ if (/^\d{10}$/.test(digits)) return `+1${digits}`;
6018
+ if (/^1\d{10}$/.test(digits)) return `+${digits}`;
6019
+ return null;
6020
+ }
6021
+ function validateTextSettings(input, options = {}) {
6022
+ const problems = [];
6023
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
6024
+ throw new SchedulingValidationError("The text-message settings are not valid", "SCHED_1500", { errors: [{ path: "", message: "Must be an object" }] });
6025
+ }
6026
+ const given = input;
6027
+ for (const key of Object.keys(given)) if (!TEXT_SETTINGS_FIELDS.includes(key)) problems.push({ path: key, message: "Unknown field" });
6028
+ const offered = options.providers ?? TEXT_PROVIDERS;
6029
+ let provider = TEXT_PROVIDERS[0];
6030
+ if (typeof given.provider !== "string" || given.provider === "") problems.push({ path: "provider", message: "Required" });
6031
+ else if (!TEXT_PROVIDERS.includes(given.provider) || !offered.includes(given.provider)) {
6032
+ problems.push({ path: "provider", message: `Must be one of: ${offered.join(", ")}` });
6033
+ } else provider = given.provider;
6034
+ let fromNumber = "";
6035
+ if (typeof given.fromNumber !== "string" || given.fromNumber.trim() === "") problems.push({ path: "fromNumber", message: "Required" });
6036
+ else {
6037
+ const normalized = normalizeTextNumber(given.fromNumber);
6038
+ if (normalized === null) problems.push({ path: "fromNumber", message: "Must be a phone number such as +13135550100" });
6039
+ else fromNumber = normalized;
6040
+ }
6041
+ let enabled = true;
6042
+ if (given.enabled !== void 0) {
6043
+ if (typeof given.enabled === "boolean") enabled = given.enabled;
6044
+ else problems.push({ path: "enabled", message: "Must be true or false" });
6045
+ }
6046
+ if (problems.length > 0) throw new SchedulingValidationError("The text-message settings are not valid", "SCHED_1500", { errors: problems });
6047
+ return { provider, fromNumber, enabled };
6048
+ }
6049
+
6050
+ // src/text-settings/crud.ts
6051
+ var SELECT2 = { provider: true, fromNumber: true, enabled: true, updatedAt: true };
6052
+ async function getTextSettings(db, organizationId) {
6053
+ return db.organizationTextSettings.findUnique({ where: { organizationId }, select: SELECT2 });
6054
+ }
6055
+ async function saveTextSettings(db, organizationId, input, options = {}) {
6056
+ const fields = validateTextSettings(input, options);
6057
+ return db.organizationTextSettings.upsert({
6058
+ where: { organizationId },
6059
+ create: { organizationId, ...fields },
6060
+ update: { ...fields },
6061
+ select: SELECT2
6062
+ });
6063
+ }
6064
+ async function deleteTextSettings(db, organizationId) {
6065
+ const { count } = await db.organizationTextSettings.deleteMany({ where: { organizationId } });
6066
+ return count > 0;
6067
+ }
5986
6068
  export {
5987
6069
  BRAND_FIELDS,
5988
6070
  BlockedTargetError,
@@ -5999,6 +6081,8 @@ export {
5999
6081
  SIGNATURE_HEADER,
6000
6082
  SchedulingNotFoundError,
6001
6083
  SchedulingValidationError,
6084
+ TEXT_PROVIDERS,
6085
+ TEXT_SETTINGS_FIELDS,
6002
6086
  USER_DAY_LIMIT,
6003
6087
  WEBHOOK_EVENT_TYPES,
6004
6088
  WEBHOOK_TEST_EVENT,
@@ -6036,6 +6120,7 @@ export {
6036
6120
  deleteCalendar,
6037
6121
  deleteNotificationTemplate,
6038
6122
  deleteRoutingForm,
6123
+ deleteTextSettings,
6039
6124
  deleteWebhookEndpoint,
6040
6125
  deliverDueWebhooks,
6041
6126
  enqueueAppointmentWebhook,
@@ -6062,6 +6147,7 @@ export {
6062
6147
  getPublicRoutingForm,
6063
6148
  getRoutingForm,
6064
6149
  getTeamAvailableSlots,
6150
+ getTextSettings,
6065
6151
  getUserDayAppointments,
6066
6152
  getWaitlistOffer,
6067
6153
  isPrivateAddress,
@@ -6083,6 +6169,7 @@ export {
6083
6169
  localToUTC,
6084
6170
  markNoShow,
6085
6171
  matchingRules,
6172
+ normalizeTextNumber,
6086
6173
  offerFreedSlot,
6087
6174
  parseSubject,
6088
6175
  parseTimeLocal,
@@ -6101,6 +6188,7 @@ export {
6101
6188
  retryWebhookDelivery,
6102
6189
  routeClient,
6103
6190
  saveBrand,
6191
+ saveTextSettings,
6104
6192
  schedError,
6105
6193
  scheduleNotifications,
6106
6194
  scopeToOrganization,
@@ -6121,6 +6209,7 @@ export {
6121
6209
  validateBrand,
6122
6210
  validateRoutingDestinations,
6123
6211
  validateRoutingStructure,
6212
+ validateTextSettings,
6124
6213
  verifyWebhookSignature,
6125
6214
  withCalendarVisibility,
6126
6215
  withOrganization
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ordinatio/scheduling",
3
- "version": "0.5.1",
3
+ "version": "0.6.1",
4
4
  "license": "MIT",
5
5
  "description": "Scheduling engine for appointment-based businesses. API-first, no iframes.",
6
6
  "main": "./dist/index.js",
@@ -0,0 +1,3 @@
1
+ -- AlterTable
2
+ ALTER TABLE "Organization" ADD COLUMN "settings" JSONB NOT NULL DEFAULT '{}',
3
+ ADD COLUMN "updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP;
@@ -0,0 +1,18 @@
1
+ -- CreateTable
2
+ CREATE TABLE "OrganizationTextSettings" (
3
+ "id" TEXT NOT NULL,
4
+ "organizationId" TEXT NOT NULL,
5
+ "provider" TEXT NOT NULL,
6
+ "fromNumber" TEXT NOT NULL,
7
+ "enabled" BOOLEAN NOT NULL DEFAULT true,
8
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
9
+ "updatedAt" TIMESTAMP(3) NOT NULL,
10
+
11
+ CONSTRAINT "OrganizationTextSettings_pkey" PRIMARY KEY ("id")
12
+ );
13
+
14
+ -- CreateIndex
15
+ CREATE UNIQUE INDEX "OrganizationTextSettings_organizationId_key" ON "OrganizationTextSettings"("organizationId");
16
+
17
+ -- AddForeignKey
18
+ ALTER TABLE "OrganizationTextSettings" ADD CONSTRAINT "OrganizationTextSettings_organizationId_fkey" FOREIGN KEY ("organizationId") REFERENCES "Organization"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -19,7 +19,11 @@ datasource db {
19
19
  model Organization {
20
20
  id String @id @default(cuid())
21
21
  name String
22
+ // Organization-wide settings kept as one JSON object; the cancellation policy lives under "cancellationPolicy".
23
+ settings Json @default("{}")
22
24
  createdAt DateTime @default(now())
25
+ // Moves on every change, which the policy route uses to refuse a save made from an out-of-date read.
26
+ updatedAt DateTime @default(now()) @updatedAt
23
27
 
24
28
  appointmentTypes AppointmentType[]
25
29
  servicePackages ServicePackage[]
@@ -32,6 +36,7 @@ model Organization {
32
36
  routingForms RoutingForm[]
33
37
  dataSubjectRequests DataSubjectRequest[]
34
38
  brand OrganizationBrand?
39
+ textSettings OrganizationTextSettings?
35
40
  }
36
41
 
37
42
  // ===== BEGIN SHARED SCHEDULING MODELS (copied verbatim into the host schema by packages/database/scripts/sync-scheduling-schema.ts) =====
@@ -539,6 +544,18 @@ model OrganizationBrand {
539
544
  updatedAt DateTime @updatedAt
540
545
  }
541
546
 
547
+ /// Which text-message provider and sending number a business uses. No keys are stored here: the host holds the provider accounts.
548
+ model OrganizationTextSettings {
549
+ id String @id @default(cuid())
550
+ organizationId String @unique
551
+ organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
552
+ provider String
553
+ fromNumber String
554
+ enabled Boolean @default(true)
555
+ createdAt DateTime @default(now())
556
+ updatedAt DateTime @updatedAt
557
+ }
558
+
542
559
  model ServicePackage {
543
560
  id String @id @default(cuid())
544
561
  name String