@ordinatio/scheduling 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts DELETED
@@ -1,2835 +0,0 @@
1
- import * as _prisma_client from '@prisma/client';
2
- import { PrismaClient, Prisma } from '@prisma/client';
3
- import * as _ordinatio_errors from '@ordinatio/errors';
4
- import { ErrorRegistry } from '@ordinatio/errors';
5
- import * as _prisma_client_runtime_client from '@prisma/client/runtime/client';
6
-
7
- /** Minimal Prisma interface for scheduling operations.
8
- *
9
- * Includes all model delegates used by the package plus a typed
10
- * $transaction method. The transaction callback receives the same
11
- * interface (minus $transaction itself) so code inside transactions
12
- * is fully typed without `as any` casts.
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' | 'organizationTextSettings' | 'organizationApiKey' | 'organization' | '$transaction' | '$executeRaw' | '$queryRaw'>;
15
- /**
16
- * Branded subtype of SchedulingDb for transaction clients produced by withTransaction().
17
- * selectCalendarForBooking() requires this type to enforce that its RoundRobinState
18
- * upsert is always atomic with the appointment create — both must be in the same
19
- * SERIALIZABLE transaction. Passing the root db would silently break that guarantee.
20
- */
21
- type TxClient = SchedulingDb & {
22
- readonly _isTx: true;
23
- };
24
-
25
- type CalendarType = 'STAFF' | 'LOCATION' | 'RESOURCE';
26
- type AssignmentStrategy = 'NONE' | 'ROUND_ROBIN' | 'LOAD_BALANCED';
27
- interface CreateCalendarInput {
28
- organizationId?: string;
29
- name: string;
30
- slug: string;
31
- type: CalendarType;
32
- timezone?: string;
33
- staffName?: string;
34
- staffEmail?: string;
35
- staffAvatar?: string;
36
- /**
37
- * Explicit staff link — set only via an admin action, never auto-derived.
38
- * CALLER RESPONSIBILITY, not enforced by this package: the caller MUST
39
- * verify `userId` belongs to the target organization before passing it
40
- * here (e.g. `validateCalendarStaffUserId()`, apps/web/src/lib/scheduling/
41
- * calendar-staff-link.ts) — this package cannot perform that check itself,
42
- * since it requires the shared SYSTEM database's OrganizationMembership
43
- * table, not the tenant-scoped `db` this package receives. Skipping that
44
- * check silently persists a cross-org staff link with no error.
45
- */
46
- userId?: string | null;
47
- slotGranularityMinutes?: number;
48
- }
49
- interface UpdateCalendarInput {
50
- name?: string;
51
- type?: CalendarType;
52
- timezone?: string;
53
- isActive?: boolean;
54
- staffName?: string | null;
55
- staffEmail?: string | null;
56
- staffAvatar?: string | null;
57
- /**
58
- * Explicit staff link — set only via an admin action, never auto-derived.
59
- * CALLER RESPONSIBILITY, not enforced by this package: the caller MUST
60
- * verify `userId` belongs to the target organization before passing it
61
- * here (e.g. `validateCalendarStaffUserId()`, apps/web/src/lib/scheduling/
62
- * calendar-staff-link.ts) — this package cannot perform that check itself,
63
- * since it requires the shared SYSTEM database's OrganizationMembership
64
- * table, not the tenant-scoped `db` this package receives. Skipping that
65
- * check silently persists a cross-org staff link with no error.
66
- */
67
- userId?: string | null;
68
- location?: string | null;
69
- googleCalendarId?: string;
70
- outlookCalendarId?: string;
71
- syncDirection?: 'one-way' | 'two-way';
72
- slotGranularityMinutes?: number;
73
- }
74
- interface AddTimeBlockInput {
75
- date: Date;
76
- startTime: string;
77
- endTime: string;
78
- reason?: string;
79
- }
80
-
81
- interface AvailabilityRuleInput {
82
- calendarId: string;
83
- dayOfWeek?: number | null;
84
- startTime: string;
85
- endTime: string;
86
- specificDate?: Date | null;
87
- isBlocked?: boolean;
88
- blockReason?: string;
89
- maxPerDay?: number | null;
90
- bufferBefore?: number;
91
- bufferAfter?: number;
92
- minNotice?: number;
93
- maxAdvanceBooking?: number;
94
- }
95
- interface TimeSlot {
96
- start: Date;
97
- end: Date;
98
- calendarId: string;
99
- available: boolean;
100
- seatsTotal?: number | null;
101
- seatsBooked?: number;
102
- seatsAvailable?: number | null;
103
- }
104
- interface AvailabilityQuery {
105
- calendarId: string;
106
- date: Date;
107
- localDate?: string;
108
- duration: number;
109
- timezone?: string;
110
- excludeAppointmentId?: string;
111
- groupBooking?: {
112
- typeId: string;
113
- maxSeats: number | null;
114
- } | null;
115
- }
116
- interface AvailabilityResult {
117
- date: string;
118
- calendarId: string;
119
- slots: TimeSlot[];
120
- timezone: string;
121
- }
122
- interface TeamAvailabilityQuery {
123
- typeId: string;
124
- date: Date;
125
- localDate?: string;
126
- duration: number;
127
- timezone?: string;
128
- }
129
- interface TeamAvailabilityResult {
130
- date: string;
131
- slots: Array<{
132
- start: Date;
133
- end: Date;
134
- available: boolean;
135
- seatsTotal?: number | null;
136
- seatsBooked?: number;
137
- seatsAvailable?: number | null;
138
- }>;
139
- timezone: string;
140
- }
141
-
142
- type AppointmentLocationType = 'IN_PERSON' | 'TRAVEL_TO_CLIENT' | 'VIRTUAL' | 'PHONE';
143
- interface CreateAppointmentTypeInput {
144
- name: string;
145
- slug: string;
146
- description?: string | null;
147
- duration: number;
148
- color?: string;
149
- price?: number | null;
150
- deposit?: number | null;
151
- currency?: string;
152
- isGroup?: boolean;
153
- maxSeats?: number | null;
154
- intakeForm?: IntakeFormField[] | null;
155
- requiresPayment?: boolean;
156
- requiresApproval?: boolean;
157
- allowReschedule?: boolean;
158
- allowCancel?: boolean;
159
- cancelDeadlineHrs?: number;
160
- reminder1MinsBefore?: number;
161
- reminder2MinsBefore?: number;
162
- followupMinsAfter?: number;
163
- organizationId?: string;
164
- categoryId?: string | null;
165
- location?: string | null;
166
- locationType?: AppointmentLocationType;
167
- calendarIds?: string[];
168
- assignmentStrategy?: AssignmentStrategy;
169
- }
170
- interface IntakeFormField {
171
- id: string;
172
- type: 'text' | 'email' | 'phone' | 'textarea' | 'select' | 'checkbox' | 'radio' | 'date' | 'number';
173
- label: string;
174
- placeholder?: string;
175
- required: boolean;
176
- options?: string[];
177
- showIf?: {
178
- fieldId: string;
179
- operator: 'equals' | 'not_equals' | 'contains' | 'is_empty' | 'is_not_empty';
180
- value: string;
181
- };
182
- }
183
- type AppointmentStatus = 'PENDING' | 'CONFIRMED' | 'COMPLETED' | 'CANCELLED' | 'NO_SHOW';
184
- interface BookAppointmentInput {
185
- calendarId?: string;
186
- preferredCalendarId?: string;
187
- typeId: string;
188
- startTime: Date;
189
- timezone: string;
190
- clientName: string;
191
- clientEmail: string;
192
- clientPhone?: string;
193
- clientId?: string;
194
- intakeResponses?: Record<string, unknown>;
195
- staffNotes?: string;
196
- paymentId?: string;
197
- paymentStatus?: string;
198
- paymentAmount?: number;
199
- depositAmount?: number;
200
- paymentProvider?: string;
201
- couponCode?: string;
202
- discountAmount?: number;
203
- location?: string | null;
204
- }
205
- interface RescheduleInput {
206
- appointmentId: string;
207
- newStartTime: Date;
208
- reason?: string;
209
- }
210
- interface CancelInput {
211
- appointmentId: string;
212
- cancelledBy: 'client' | 'staff' | 'system';
213
- reason?: string;
214
- }
215
- interface AppointmentWithDetails {
216
- id: string;
217
- calendarId: string;
218
- calendarName: string;
219
- staffName: string | null;
220
- typeId: string;
221
- typeName: string;
222
- startTime: Date;
223
- endTime: Date;
224
- duration: number;
225
- timezone: string;
226
- status: AppointmentStatus;
227
- clientName: string;
228
- clientEmail: string;
229
- clientPhone: string | null;
230
- intakeResponses: Record<string, unknown> | null;
231
- staffNotes: string | null;
232
- location: string | null;
233
- paymentId: string | null;
234
- paymentStatus: string | null;
235
- paymentAmount: number | null;
236
- depositAmount: number | null;
237
- paymentProvider: string | null;
238
- couponCode: string | null;
239
- discountAmount: number | null;
240
- isGroup: boolean;
241
- manageToken: string;
242
- createdAt: Date;
243
- }
244
- /** Rich appointment data for dashboard/management views */
245
- interface AppointmentDashboardItem {
246
- id: string;
247
- calendarId: string;
248
- typeId: string;
249
- startTime: Date;
250
- endTime: Date;
251
- duration: number;
252
- timezone: string;
253
- status: string;
254
- clientName: string;
255
- clientEmail: string;
256
- clientPhone: string | null;
257
- clientId: string | null;
258
- staffNotes: string | null;
259
- location: string | null;
260
- manageToken: string;
261
- type: {
262
- name: string;
263
- color: string;
264
- duration: number;
265
- locationType: AppointmentLocationType;
266
- };
267
- calendar: {
268
- name: string;
269
- staffName: string | null;
270
- };
271
- intakeResponses: Record<string, unknown> | null;
272
- createdAt: Date;
273
- updatedAt: Date;
274
- cancelledAt: Date | null;
275
- rescheduledFrom: Date | null;
276
- isGroup: boolean;
277
- }
278
- /** Stats returned by the dashboard query */
279
- interface AppointmentDashboardStats {
280
- todayTotal: number;
281
- todayConfirmed: number;
282
- weekTotal: number;
283
- cancellationRate: number;
284
- }
285
- /** Complete dashboard data bundle */
286
- interface AppointmentDashboardData {
287
- today: AppointmentDashboardItem[];
288
- week: AppointmentDashboardItem[];
289
- /** Bookings after the current week, soonest first, capped. */
290
- upcoming: AppointmentDashboardItem[];
291
- /** All upcoming bookings the viewer may see, including those past the list cap. */
292
- upcomingTotal: number;
293
- history: AppointmentDashboardItem[];
294
- stats: AppointmentDashboardStats;
295
- historyTotal: number;
296
- historyPages: number;
297
- }
298
- /** Analytics for a date-range lookback window */
299
- interface BookingAnalytics {
300
- period: {
301
- start: Date;
302
- end: Date;
303
- days: number;
304
- };
305
- totals: {
306
- booked: number;
307
- completed: number;
308
- cancelled: number;
309
- noShows: number;
310
- pending: number;
311
- };
312
- rates: {
313
- completionRate: number;
314
- cancellationRate: number;
315
- noShowRate: number;
316
- };
317
- revenue: {
318
- total: number;
319
- avg: number;
320
- currency: string;
321
- };
322
- peakHours: Array<{
323
- hour: number;
324
- count: number;
325
- }>;
326
- peakDays: Array<{
327
- dayOfWeek: number;
328
- count: number;
329
- }>;
330
- heatmap: Array<{
331
- dayOfWeek: number;
332
- hour: number;
333
- count: number;
334
- }>;
335
- byType: Array<{
336
- typeId: string;
337
- typeName: string;
338
- count: number;
339
- color: string;
340
- totalRevenue: number;
341
- avgRevenue: number;
342
- }>;
343
- dailyTrend: Array<{
344
- date: string;
345
- count: number;
346
- }>;
347
- funnel: Array<{
348
- stage: string;
349
- count: number;
350
- }>;
351
- }
352
-
353
- type NotificationChannel = 'EMAIL' | 'SMS';
354
- type NotificationTrigger = 'CONFIRMATION' | 'REMINDER_24H' | 'REMINDER_1H' | 'FOLLOWUP' | 'CANCELLATION' | 'RESCHEDULE' | 'REMINDER_MANUAL';
355
- interface NotificationContext {
356
- clientName: string;
357
- clientEmail: string;
358
- clientPhone?: string;
359
- serviceName: string;
360
- dateTime: string;
361
- duration: string;
362
- calendarName: string;
363
- staffName?: string;
364
- location?: string;
365
- manageUrl?: string;
366
- icalUrl?: string;
367
- meetingUrl?: string;
368
- rescheduleUrl?: string;
369
- cancelUrl?: string;
370
- customFields?: Record<string, string>;
371
- }
372
- /** Retry configuration for notification processing */
373
- interface RetryConfig {
374
- /** Maximum retry attempts before marking as DEAD_LETTER (default: 3) */
375
- maxRetries?: number;
376
- /** Base backoff in minutes — doubles each retry: 5, 10, 20 (default: 5) */
377
- baseBackoffMinutes?: number;
378
- }
379
- /** Who a message should appear to come from. The sender may ignore what its provider cannot do. */
380
- interface SenderIdentity {
381
- /** The display name. */
382
- name?: string;
383
- /** The sending address, on a domain the host has confirmed. When absent, send from the provider's default address. */
384
- email?: string;
385
- /** Where replies go. */
386
- replyTo?: string;
387
- }
388
- /** Context passed to the sender with each notification */
389
- interface NotificationSenderContext {
390
- /** The scheduling trigger that produced this notification */
391
- trigger?: NotificationTrigger;
392
- /** The organization's own sender identity, when branding is on and one is set. */
393
- from?: SenderIdentity;
394
- /** The organization the notification belongs to. Only set when the caller asks for it (`organization: true`). */
395
- organizationId?: string;
396
- }
397
- /**
398
- * Returned by the sender when it deliberately does not deliver the notification.
399
- * Engine writes SKIPPED status and records the reason for the audit trail.
400
- */
401
- interface NotificationSenderResult {
402
- skipped: true;
403
- /** Human-readable reason written to errorMessage — e.g. 'contact-opted-out' */
404
- reason?: string;
405
- }
406
- /** Injected by the app — sends the actual email/SMS */
407
- type NotificationSender = (channel: NotificationChannel, to: string, subject: string, body: string, context?: NotificationSenderContext) => Promise<NotificationSenderResult | void>;
408
-
409
- interface PaymentResult {
410
- success: boolean;
411
- paymentId?: string;
412
- error?: string;
413
- }
414
- /** Injected by the app — processes the actual payment */
415
- type PaymentProcessor = (amount: number, currency: string, clientEmail: string, description: string) => Promise<PaymentResult>;
416
-
417
- interface CancellationFeeConfig {
418
- enabled: boolean;
419
- amount: number | null | undefined;
420
- feeType: 'FLAT' | 'PERCENTAGE';
421
- }
422
- interface OrgCancellationPolicy {
423
- defaultAllowCancel: boolean;
424
- defaultCancelDeadlineHrs: number;
425
- noShowFee: CancellationFeeConfig;
426
- lateCancelFee: CancellationFeeConfig;
427
- requireCardOnFile: boolean;
428
- }
429
- interface SchedulingCallbacks {
430
- /** Send an email or SMS */
431
- sendNotification?: NotificationSender;
432
- /** Process a payment */
433
- processPayment?: PaymentProcessor;
434
- /** Log an activity */
435
- onActivity?: (action: string, description: string, metadata?: Record<string, unknown>) => Promise<void>;
436
- /** Emit an event for automation */
437
- onEvent?: (event: {
438
- type: string;
439
- data: Record<string, unknown>;
440
- }) => Promise<void>;
441
- }
442
-
443
- declare const SCHEDULING_ERRORS: ErrorRegistry;
444
-
445
- declare const schedError: (code: string, context?: Record<string, unknown>) => _ordinatio_errors.OrdinatioError;
446
- /**
447
- * Shared base for scheduling's legacy Error-subclass exceptions.
448
- *
449
- * Rule 8 (Task #26): carries the full OrdinatioError diagnostic shape (code, ref,
450
- * timestamp, severity, recoverable, diagnosis, context) alongside the plain `.message`
451
- * every existing catch site already reads — `instanceof` checks and `.message` reads
452
- * throughout the codebase (including routes owned by other windows in this wave) keep
453
- * working unchanged. `code` and `context` are optional specifically so unmigrated call
454
- * sites (`new SchedulingValidationError('some message')`) still compile and now get a
455
- * generic-but-real ref/timestamp via the subclass's fallback code, rather than a hard break.
456
- */
457
- declare abstract class SchedulingDiagnosticError extends Error {
458
- readonly code: string;
459
- readonly ref: string;
460
- readonly timestamp: string;
461
- readonly severity: string;
462
- readonly recoverable: boolean;
463
- readonly diagnosis: readonly string[];
464
- readonly context: Record<string, unknown>;
465
- constructor(name: string, message: string, code: string, context: Record<string, unknown> | undefined);
466
- }
467
- /**
468
- * Validation error for scheduling operations.
469
- * Thrown when input fails business rule validation (not schema validation).
470
- * API routes check instanceof to return 400 instead of 500.
471
- *
472
- * Used across all scheduling CRUD modules — not just availability.
473
- */
474
- declare class SchedulingValidationError extends SchedulingDiagnosticError {
475
- constructor(message: string, code?: string, context?: Record<string, unknown>);
476
- }
477
- /**
478
- * Not-found error for scheduling operations.
479
- * Thrown when a resource doesn't exist or doesn't belong
480
- * to the expected parent. API routes return 404.
481
- */
482
- declare class SchedulingNotFoundError extends SchedulingDiagnosticError {
483
- constructor(message: string, code?: string, context?: Record<string, unknown>);
484
- }
485
-
486
- type CancellationFeeResult = {
487
- feeType: 'none' | 'late_cancel' | 'no_show';
488
- feeAmountCents: number;
489
- refundAmountCents: number;
490
- };
491
- declare function calculateCancellationFee(params: {
492
- paidAmountCents: number;
493
- startTime: Date;
494
- cancelledAt: Date;
495
- cancelDeadlineHrs: number;
496
- cancelledBy: 'client' | 'staff' | 'system';
497
- policy: OrgCancellationPolicy;
498
- }): CancellationFeeResult;
499
-
500
- /**
501
- * Task #17: create + slug-uniqueness is atomic via the DB's own unique constraint
502
- * rather than a check-then-create pre-flight query — the old find-then-create had a
503
- * TOCTOU window where two concurrent requests for the same slug could both pass the
504
- * pre-check and both attempt to create. Task #70: the constraint is now per-org
505
- * (`@@unique([organizationId, slug])`, not a bare `slug @unique`) — P2002 still fires
506
- * on any violation either way, so this function's behavior is unchanged.
507
- */
508
- declare function createCalendar(db: SchedulingDb, input: CreateCalendarInput): Promise<{
509
- id: string;
510
- organizationId: string | null;
511
- name: string;
512
- slug: string;
513
- type: string;
514
- timezone: string;
515
- isActive: boolean;
516
- googleCalendarId: string | null;
517
- outlookCalendarId: string | null;
518
- icloudCalendarUrl: string | null;
519
- syncDirection: string;
520
- syncToken: string | null;
521
- outlookSyncToken: string | null;
522
- outlookAccessToken: string | null;
523
- outlookRefreshToken: string | null;
524
- outlookTokenExpiresAt: Date | null;
525
- lastSyncAt: Date | null;
526
- watchChannelId: string | null;
527
- watchResourceId: string | null;
528
- watchExpiry: Date | null;
529
- watchToken: string | null;
530
- staffName: string | null;
531
- staffEmail: string | null;
532
- staffAvatar: string | null;
533
- userId: string | null;
534
- theme: Prisma.JsonValue | null;
535
- bookingPageConfig: Prisma.JsonValue | null;
536
- location: string | null;
537
- slotGranularityMinutes: number;
538
- createdAt: Date;
539
- updatedAt: Date;
540
- }>;
541
- /**
542
- * Task #17: org-scoped by design — calendarId is an internal ID that could belong to
543
- * any organization, so every caller MUST pass the caller's own organizationId. A
544
- * cross-org calendarId resolves to null (404), same as a nonexistent one — this must
545
- * never leak whether the ID exists outside the caller's org.
546
- */
547
- declare function getCalendar(db: SchedulingDb, calendarId: string, organizationId: string): Promise<{
548
- rules: {
549
- startTime: string;
550
- id: string;
551
- createdAt: Date;
552
- dayOfWeek: number | null;
553
- calendarId: string;
554
- endTime: string;
555
- specificDate: Date | null;
556
- isBlocked: boolean;
557
- blockReason: string | null;
558
- maxPerDay: number | null;
559
- bufferBefore: number;
560
- bufferAfter: number;
561
- minNotice: number;
562
- maxAdvanceBooking: number;
563
- }[];
564
- } & {
565
- id: string;
566
- organizationId: string | null;
567
- name: string;
568
- slug: string;
569
- type: string;
570
- timezone: string;
571
- isActive: boolean;
572
- googleCalendarId: string | null;
573
- outlookCalendarId: string | null;
574
- icloudCalendarUrl: string | null;
575
- syncDirection: string;
576
- syncToken: string | null;
577
- outlookSyncToken: string | null;
578
- outlookAccessToken: string | null;
579
- outlookRefreshToken: string | null;
580
- outlookTokenExpiresAt: Date | null;
581
- lastSyncAt: Date | null;
582
- watchChannelId: string | null;
583
- watchResourceId: string | null;
584
- watchExpiry: Date | null;
585
- watchToken: string | null;
586
- staffName: string | null;
587
- staffEmail: string | null;
588
- staffAvatar: string | null;
589
- userId: string | null;
590
- theme: Prisma.JsonValue | null;
591
- bookingPageConfig: Prisma.JsonValue | null;
592
- location: string | null;
593
- slotGranularityMinutes: number;
594
- createdAt: Date;
595
- updatedAt: Date;
596
- }>;
597
- /** Task #17: organizationId is now required — was previously unscoped (returned every org's calendars). */
598
- declare function listCalendars(db: SchedulingDb, organizationId: string, activeOnly?: boolean): Promise<{
599
- id: string;
600
- organizationId: string | null;
601
- name: string;
602
- slug: string;
603
- type: string;
604
- timezone: string;
605
- isActive: boolean;
606
- googleCalendarId: string | null;
607
- outlookCalendarId: string | null;
608
- icloudCalendarUrl: string | null;
609
- syncDirection: string;
610
- syncToken: string | null;
611
- outlookSyncToken: string | null;
612
- outlookAccessToken: string | null;
613
- outlookRefreshToken: string | null;
614
- outlookTokenExpiresAt: Date | null;
615
- lastSyncAt: Date | null;
616
- watchChannelId: string | null;
617
- watchResourceId: string | null;
618
- watchExpiry: Date | null;
619
- watchToken: string | null;
620
- staffName: string | null;
621
- staffEmail: string | null;
622
- staffAvatar: string | null;
623
- userId: string | null;
624
- theme: Prisma.JsonValue | null;
625
- bookingPageConfig: Prisma.JsonValue | null;
626
- location: string | null;
627
- slotGranularityMinutes: number;
628
- createdAt: Date;
629
- updatedAt: Date;
630
- }[]>;
631
- /**
632
- * Task #17: org-scoped — see getCalendar's doc comment for the cross-org-leak rationale.
633
- *
634
- * Task #70 remediation (deduction #3): the write + a FRESH isActive read now share the
635
- * same SERIALIZABLE transaction (one retry on P2034), matching archiveCalendar()'s house
636
- * pattern above. `wasActive` is read here, immediately before the write, not from a
637
- * request-start pre-check — which can be stale by the time this transaction commits.
638
- * Callers deciding whether to release a PublicBookingDirectory claim on an
639
- * isActive:true->false transition MUST use the returned wasActive, AND re-check isActive
640
- * again immediately before the release call itself — PublicBookingDirectory lives in a
641
- * physically separate SYSTEM database from this calendar's TENANT database, so no single
642
- * transaction (this one included) can make the release itself atomic with this write.
643
- */
644
- declare function updateCalendar(db: SchedulingDb, calendarId: string, organizationId: string, input: UpdateCalendarInput): Promise<{
645
- calendar: {
646
- id: string;
647
- organizationId: string | null;
648
- name: string;
649
- slug: string;
650
- type: string;
651
- timezone: string;
652
- isActive: boolean;
653
- googleCalendarId: string | null;
654
- outlookCalendarId: string | null;
655
- icloudCalendarUrl: string | null;
656
- syncDirection: string;
657
- syncToken: string | null;
658
- outlookSyncToken: string | null;
659
- outlookAccessToken: string | null;
660
- outlookRefreshToken: string | null;
661
- outlookTokenExpiresAt: Date | null;
662
- lastSyncAt: Date | null;
663
- watchChannelId: string | null;
664
- watchResourceId: string | null;
665
- watchExpiry: Date | null;
666
- watchToken: string | null;
667
- staffName: string | null;
668
- staffEmail: string | null;
669
- staffAvatar: string | null;
670
- userId: string | null;
671
- theme: Prisma.JsonValue | null;
672
- bookingPageConfig: Prisma.JsonValue | null;
673
- location: string | null;
674
- slotGranularityMinutes: number;
675
- createdAt: Date;
676
- updatedAt: Date;
677
- };
678
- wasActive: boolean;
679
- }>;
680
- /**
681
- * Hard delete — permanently removes the calendar row. Org-scoped — see getCalendar's
682
- * doc comment. NOTE: this is NOT what `DELETE /admin/calendars/[id]` does today — that
683
- * route soft-deletes (archives) via `archiveCalendar` below, preserving appointment
684
- * history. This function exists for genuine permanent removal (e.g. an admin cleanup
685
- * script), which has no "last active calendar" concern since it isn't gated on isActive.
686
- */
687
- declare function deleteCalendar(db: SchedulingDb, calendarId: string, organizationId: string): Promise<{
688
- id: string;
689
- organizationId: string | null;
690
- name: string;
691
- slug: string;
692
- type: string;
693
- timezone: string;
694
- isActive: boolean;
695
- googleCalendarId: string | null;
696
- outlookCalendarId: string | null;
697
- icloudCalendarUrl: string | null;
698
- syncDirection: string;
699
- syncToken: string | null;
700
- outlookSyncToken: string | null;
701
- outlookAccessToken: string | null;
702
- outlookRefreshToken: string | null;
703
- outlookTokenExpiresAt: Date | null;
704
- lastSyncAt: Date | null;
705
- watchChannelId: string | null;
706
- watchResourceId: string | null;
707
- watchExpiry: Date | null;
708
- watchToken: string | null;
709
- staffName: string | null;
710
- staffEmail: string | null;
711
- staffAvatar: string | null;
712
- userId: string | null;
713
- theme: Prisma.JsonValue | null;
714
- bookingPageConfig: Prisma.JsonValue | null;
715
- location: string | null;
716
- slotGranularityMinutes: number;
717
- createdAt: Date;
718
- updatedAt: Date;
719
- }>;
720
- /**
721
- * Soft-delete (archive) a calendar, refusing to archive the org's last active calendar.
722
- *
723
- * Task #17: the count-then-update was previously two separate queries with no lock
724
- * between them — two concurrent archive requests for two DIFFERENT active calendars
725
- * could both read activeCount > 1 before either commits, and both proceed, leaving
726
- * zero active calendars (which breaks the booking widget for the whole org). Fixed by
727
- * re-counting inside a SERIALIZABLE transaction: Postgres guarantees one of two
728
- * conflicting transactions fails with a serialization error (P2034) rather than both
729
- * succeeding, so we retry once on that specific error — same pattern already used by
730
- * bookAppointment/rescheduleAppointment in appointments/crud.ts.
731
- */
732
- declare function archiveCalendar(db: SchedulingDb, calendarId: string, organizationId: string): Promise<{
733
- id: string;
734
- organizationId: string | null;
735
- name: string;
736
- slug: string;
737
- type: string;
738
- timezone: string;
739
- isActive: boolean;
740
- googleCalendarId: string | null;
741
- outlookCalendarId: string | null;
742
- icloudCalendarUrl: string | null;
743
- syncDirection: string;
744
- syncToken: string | null;
745
- outlookSyncToken: string | null;
746
- outlookAccessToken: string | null;
747
- outlookRefreshToken: string | null;
748
- outlookTokenExpiresAt: Date | null;
749
- lastSyncAt: Date | null;
750
- watchChannelId: string | null;
751
- watchResourceId: string | null;
752
- watchExpiry: Date | null;
753
- watchToken: string | null;
754
- staffName: string | null;
755
- staffEmail: string | null;
756
- staffAvatar: string | null;
757
- userId: string | null;
758
- theme: Prisma.JsonValue | null;
759
- bookingPageConfig: Prisma.JsonValue | null;
760
- location: string | null;
761
- slotGranularityMinutes: number;
762
- createdAt: Date;
763
- updatedAt: Date;
764
- }>;
765
-
766
- /**
767
- * Get available time slots for a calendar on a specific date.
768
- *
769
- * @param db - Database client
770
- * @param query - Calendar ID, date, and duration
771
- * @returns Available slots for the requested date
772
- */
773
- declare function getAvailableSlots(db: SchedulingDb, query: AvailabilityQuery): Promise<AvailabilityResult>;
774
- /**
775
- * Get available dates for a calendar within a date range.
776
- * Returns which dates have at least one available slot.
777
- *
778
- * Pass groupBooking for group appointment types so co-participant bookings
779
- * on a date do not suppress that date from the result.
780
- *
781
- * Task #40: previously called getAvailableSlots per day (3 queries/day — ~180 queries
782
- * for a 60-day range). Now fetches the calendar, all availability rules, and all
783
- * appointments across the WHOLE range exactly once, then computes each day's slots in
784
- * memory via computeAvailableSlots — 3 queries total regardless of range length.
785
- */
786
- declare function getAvailableDates(db: SchedulingDb, calendarId: string, startDate: Date, endDate: Date, duration: number, groupBooking?: {
787
- typeId: string;
788
- maxSeats: number | null;
789
- } | null): Promise<string[]>;
790
- /**
791
- * Check if a specific time slot is available.
792
- *
793
- * For group appointment types, pass groupBooking so co-participant appointments
794
- * at the same slot are not treated as conflicts. Without this, a group slot
795
- * with any existing booking would always appear unavailable.
796
- */
797
- declare function isSlotAvailable(db: SchedulingDb, calendarId: string, startTime: Date, duration: number, excludeAppointmentId?: string, groupBooking?: {
798
- typeId: string;
799
- maxSeats: number | null;
800
- } | null): Promise<boolean>;
801
-
802
- /**
803
- * List all availability rules for a calendar.
804
- * Returns weekly rules sorted by day, then date overrides sorted by date.
805
- */
806
- declare function listAvailabilityRules(db: SchedulingDb, calendarId: string, options?: {
807
- limit?: number;
808
- offset?: number;
809
- }): Promise<{
810
- rules: {
811
- startTime: string;
812
- id: string;
813
- createdAt: Date;
814
- dayOfWeek: number | null;
815
- calendarId: string;
816
- endTime: string;
817
- specificDate: Date | null;
818
- isBlocked: boolean;
819
- blockReason: string | null;
820
- maxPerDay: number | null;
821
- bufferBefore: number;
822
- bufferAfter: number;
823
- minNotice: number;
824
- maxAdvanceBooking: number;
825
- }[];
826
- total: number;
827
- hasMore: boolean;
828
- }>;
829
- /**
830
- * Set the weekly availability for a calendar.
831
- * Replaces ALL existing weekly rules (not date overrides).
832
- * This is an atomic operation — old rules are deleted, new ones created.
833
- *
834
- * @param rules - Array of rules, one per active day. Days not included are closed.
835
- */
836
- declare function setWeeklyAvailability(db: SchedulingDb, calendarId: string, rules: Array<{
837
- dayOfWeek: number;
838
- startTime: string;
839
- endTime: string;
840
- bufferBefore?: number;
841
- bufferAfter?: number;
842
- minNotice?: number;
843
- maxAdvanceBooking?: number;
844
- maxPerDay?: number | null;
845
- }>): Promise<{
846
- startTime: string;
847
- id: string;
848
- createdAt: Date;
849
- dayOfWeek: number | null;
850
- calendarId: string;
851
- endTime: string;
852
- specificDate: Date | null;
853
- isBlocked: boolean;
854
- blockReason: string | null;
855
- maxPerDay: number | null;
856
- bufferBefore: number;
857
- bufferAfter: number;
858
- minNotice: number;
859
- maxAdvanceBooking: number;
860
- }[]>;
861
- /**
862
- * Add a date-specific override (e.g., holiday closure, special hours).
863
- */
864
- declare function addDateOverride(db: SchedulingDb, calendarId: string, input: {
865
- date: Date;
866
- isBlocked: boolean;
867
- blockReason?: string;
868
- startTime?: string;
869
- endTime?: string;
870
- }): Promise<{
871
- startTime: string;
872
- id: string;
873
- createdAt: Date;
874
- dayOfWeek: number | null;
875
- calendarId: string;
876
- endTime: string;
877
- specificDate: Date | null;
878
- isBlocked: boolean;
879
- blockReason: string | null;
880
- maxPerDay: number | null;
881
- bufferBefore: number;
882
- bufferAfter: number;
883
- minNotice: number;
884
- maxAdvanceBooking: number;
885
- }>;
886
- /**
887
- * Add a partial-day time block (e.g., lunch break, internal meeting).
888
- *
889
- * Unlike addDateOverride, stores the REAL startTime/endTime so the engine
890
- * injects them as conflict windows rather than blocking the entire day.
891
- * Multiple blocks per day are allowed — no find-and-replace behavior.
892
- *
893
- * Convention: addDateOverride stores '00:00'/'00:00' for full-day closures (Rule G).
894
- * addTimeBlock NEVER stores that pair — startTime < endTime validation rules it out.
895
- */
896
- declare function addTimeBlock(db: SchedulingDb, calendarId: string, input: {
897
- date: Date;
898
- startTime: string;
899
- endTime: string;
900
- reason?: string;
901
- }): Promise<{
902
- startTime: string;
903
- id: string;
904
- createdAt: Date;
905
- dayOfWeek: number | null;
906
- calendarId: string;
907
- endTime: string;
908
- specificDate: Date | null;
909
- isBlocked: boolean;
910
- blockReason: string | null;
911
- maxPerDay: number | null;
912
- bufferBefore: number;
913
- bufferAfter: number;
914
- minNotice: number;
915
- maxAdvanceBooking: number;
916
- }>;
917
- /**
918
- * Remove a date override. Verifies the rule belongs to the
919
- * specified calendar before deleting — prevents cross-calendar
920
- * data manipulation.
921
- */
922
- declare function removeDateOverride(db: SchedulingDb, calendarId: string, ruleId: string): Promise<{
923
- startTime: string;
924
- id: string;
925
- createdAt: Date;
926
- dayOfWeek: number | null;
927
- calendarId: string;
928
- endTime: string;
929
- specificDate: Date | null;
930
- isBlocked: boolean;
931
- blockReason: string | null;
932
- maxPerDay: number | null;
933
- bufferBefore: number;
934
- bufferAfter: number;
935
- minNotice: number;
936
- maxAdvanceBooking: number;
937
- }>;
938
-
939
- declare function createAppointmentType(db: SchedulingDb, input: CreateAppointmentTypeInput): Promise<{
940
- cancelDeadlineHrs: number;
941
- id: string;
942
- organizationId: string | null;
943
- name: string;
944
- slug: string;
945
- isActive: boolean;
946
- location: string | null;
947
- createdAt: Date;
948
- updatedAt: Date;
949
- duration: number;
950
- maxSeats: number | null;
951
- isGroup: boolean;
952
- description: string | null;
953
- locationType: _prisma_client.$Enums.AppointmentLocationType;
954
- color: string;
955
- price: Prisma.Decimal | null;
956
- deposit: Prisma.Decimal | null;
957
- currency: string;
958
- assignmentStrategy: string;
959
- intakeForm: Prisma.JsonValue | null;
960
- requiresPayment: boolean;
961
- requiresApproval: boolean;
962
- allowReschedule: boolean;
963
- allowCancel: boolean;
964
- reminder1MinsBefore: number;
965
- reminder2MinsBefore: number;
966
- followupMinsAfter: number;
967
- sortOrder: number;
968
- categoryId: string | null;
969
- }>;
970
- declare function getAppointmentType(db: SchedulingDb, typeId: string): Promise<{
971
- calendars: ({
972
- calendar: {
973
- id: string;
974
- organizationId: string | null;
975
- name: string;
976
- slug: string;
977
- type: string;
978
- timezone: string;
979
- isActive: boolean;
980
- googleCalendarId: string | null;
981
- outlookCalendarId: string | null;
982
- icloudCalendarUrl: string | null;
983
- syncDirection: string;
984
- syncToken: string | null;
985
- outlookSyncToken: string | null;
986
- outlookAccessToken: string | null;
987
- outlookRefreshToken: string | null;
988
- outlookTokenExpiresAt: Date | null;
989
- lastSyncAt: Date | null;
990
- watchChannelId: string | null;
991
- watchResourceId: string | null;
992
- watchExpiry: Date | null;
993
- watchToken: string | null;
994
- staffName: string | null;
995
- staffEmail: string | null;
996
- staffAvatar: string | null;
997
- userId: string | null;
998
- theme: Prisma.JsonValue | null;
999
- bookingPageConfig: Prisma.JsonValue | null;
1000
- location: string | null;
1001
- slotGranularityMinutes: number;
1002
- createdAt: Date;
1003
- updatedAt: Date;
1004
- };
1005
- } & {
1006
- calendarId: string;
1007
- appointmentTypeId: string;
1008
- })[];
1009
- } & {
1010
- cancelDeadlineHrs: number;
1011
- id: string;
1012
- organizationId: string | null;
1013
- name: string;
1014
- slug: string;
1015
- isActive: boolean;
1016
- location: string | null;
1017
- createdAt: Date;
1018
- updatedAt: Date;
1019
- duration: number;
1020
- maxSeats: number | null;
1021
- isGroup: boolean;
1022
- description: string | null;
1023
- locationType: _prisma_client.$Enums.AppointmentLocationType;
1024
- color: string;
1025
- price: Prisma.Decimal | null;
1026
- deposit: Prisma.Decimal | null;
1027
- currency: string;
1028
- assignmentStrategy: string;
1029
- intakeForm: Prisma.JsonValue | null;
1030
- requiresPayment: boolean;
1031
- requiresApproval: boolean;
1032
- allowReschedule: boolean;
1033
- allowCancel: boolean;
1034
- reminder1MinsBefore: number;
1035
- reminder2MinsBefore: number;
1036
- followupMinsAfter: number;
1037
- sortOrder: number;
1038
- categoryId: string | null;
1039
- }>;
1040
- declare function listAppointmentTypes(db: SchedulingDb, options?: {
1041
- calendarId?: string;
1042
- activeOnly?: boolean;
1043
- }): Promise<({
1044
- calendars: ({
1045
- calendar: {
1046
- id: string;
1047
- name: string;
1048
- };
1049
- } & {
1050
- calendarId: string;
1051
- appointmentTypeId: string;
1052
- })[];
1053
- } & {
1054
- cancelDeadlineHrs: number;
1055
- id: string;
1056
- organizationId: string | null;
1057
- name: string;
1058
- slug: string;
1059
- isActive: boolean;
1060
- location: string | null;
1061
- createdAt: Date;
1062
- updatedAt: Date;
1063
- duration: number;
1064
- maxSeats: number | null;
1065
- isGroup: boolean;
1066
- description: string | null;
1067
- locationType: _prisma_client.$Enums.AppointmentLocationType;
1068
- color: string;
1069
- price: Prisma.Decimal | null;
1070
- deposit: Prisma.Decimal | null;
1071
- currency: string;
1072
- assignmentStrategy: string;
1073
- intakeForm: Prisma.JsonValue | null;
1074
- requiresPayment: boolean;
1075
- requiresApproval: boolean;
1076
- allowReschedule: boolean;
1077
- allowCancel: boolean;
1078
- reminder1MinsBefore: number;
1079
- reminder2MinsBefore: number;
1080
- followupMinsAfter: number;
1081
- sortOrder: number;
1082
- categoryId: string | null;
1083
- })[]>;
1084
- declare function updateAppointmentType(db: SchedulingDb, typeId: string, organizationId: string, input: Partial<CreateAppointmentTypeInput> & {
1085
- isActive?: boolean;
1086
- }): Promise<{
1087
- type: {
1088
- cancelDeadlineHrs: number;
1089
- id: string;
1090
- organizationId: string | null;
1091
- name: string;
1092
- slug: string;
1093
- isActive: boolean;
1094
- location: string | null;
1095
- createdAt: Date;
1096
- updatedAt: Date;
1097
- duration: number;
1098
- maxSeats: number | null;
1099
- isGroup: boolean;
1100
- description: string | null;
1101
- locationType: _prisma_client.$Enums.AppointmentLocationType;
1102
- color: string;
1103
- price: Prisma.Decimal | null;
1104
- deposit: Prisma.Decimal | null;
1105
- currency: string;
1106
- assignmentStrategy: string;
1107
- intakeForm: Prisma.JsonValue | null;
1108
- requiresPayment: boolean;
1109
- requiresApproval: boolean;
1110
- allowReschedule: boolean;
1111
- allowCancel: boolean;
1112
- reminder1MinsBefore: number;
1113
- reminder2MinsBefore: number;
1114
- followupMinsAfter: number;
1115
- sortOrder: number;
1116
- categoryId: string | null;
1117
- };
1118
- wasActive: boolean;
1119
- }>;
1120
-
1121
- /**
1122
- * Book a new appointment.
1123
- *
1124
- * Validates availability, creates the appointment,
1125
- * and triggers confirmation notification.
1126
- */
1127
- declare function bookAppointment(db: SchedulingDb, input: BookAppointmentInput, callbacks?: SchedulingCallbacks): Promise<AppointmentWithDetails>;
1128
-
1129
- /**
1130
- * Cancel an appointment.
1131
- *
1132
- * Org-scoping precondition: `appointmentId` is trusted as-is — this function performs
1133
- * no organizationId check of its own. Real callers (confirmed 2026-07-05, re-verified
1134
- * against a full grep of every call site) use one of four distinct trust boundaries
1135
- * instead, and the caller MUST use one of them:
1136
- * 1. Org-membership: session-authenticated staff routes resolve `db` via
1137
- * `requireSchedulingAuth()`/`getTenantContext()` (tenant-scoped physical database)
1138
- * AND additionally call `verifyAppointmentOwnership()` — e.g. staff cancel/no-show.
1139
- * 2. Capability token: public self-service routes (e.g. `manage/route.ts`) look the
1140
- * appointment up by its own unguessable `manageToken` instead of a session — the
1141
- * token itself is the authorization, so these legitimately pass the raw system
1142
- * `prisma` client (single-tenant deployment; there is currently only one physical
1143
- * database, so this is not yet a cross-tenant leak, but it is NOT the org-membership
1144
- * pattern and would need re-architecting before a second tenant is onboarded).
1145
- * 3. Internal secret: worker-to-worker routes (e.g. `cancel-sync/route.ts`) authenticate
1146
- * via `INTERNAL_API_SECRET`, not a user session, and also currently pass the raw
1147
- * system `prisma` client for the same single-tenant reason as #2.
1148
- * 4. Same-request provenance: `appointments/route.ts`'s public booking POST handler
1149
- * self-cancels an appointment it JUST created earlier in the same request (coupon
1150
- * exhausted by a concurrent booking after the appointment was already inserted) —
1151
- * the `appointmentId` here was never attacker-supplied, it's a value this same
1152
- * function call stack generated moments earlier. Also raw `prisma`, same
1153
- * single-tenant caveat as #2/#3.
1154
- * Do not assume "not org-membership-scoped" means "unscoped" — verify which of these 4
1155
- * patterns actually applies to a given caller before trusting it.
1156
- */
1157
- declare function cancelAppointment(db: SchedulingDb, input: CancelInput, callbacks?: SchedulingCallbacks): Promise<AppointmentWithDetails>;
1158
-
1159
- interface MarkNoShowInput {
1160
- appointmentId: string;
1161
- reason?: string;
1162
- }
1163
- /**
1164
- * Mark an appointment as a no-show.
1165
- *
1166
- * Org-scoping precondition: no organizationId check is performed here. Its one real
1167
- * caller today (`apps/web/.../[id]/no-show/route.ts`) uses org-membership scoping —
1168
- * `requireSchedulingAuth()`/`getTenantContext()` for a tenant-resolved `db` handle AND
1169
- * `verifyAppointmentOwnership()` (see `cancelAppointment`'s doc for the other two trust
1170
- * boundaries a future caller of this function might legitimately use instead).
1171
- */
1172
- declare function markNoShow(db: SchedulingDb, input: MarkNoShowInput, callbacks?: SchedulingCallbacks): Promise<AppointmentWithDetails>;
1173
-
1174
- /**
1175
- * Reschedule an appointment to a new time.
1176
- *
1177
- * Org-scoping precondition: no organizationId check is performed here. Real callers
1178
- * today use 2 of the 3 trust boundaries documented on `cancelAppointment`: org-membership
1179
- * (`apps/web/.../[id]/reschedule/route.ts`, via `requireSchedulingAuth()` +
1180
- * `verifyAppointmentOwnership()`) and capability token (`manage/route.ts`'s PATCH handler,
1181
- * via the appointment's own unguessable `manageToken` — no internal-secret caller exists
1182
- * for this function today).
1183
- */
1184
- declare function rescheduleAppointment(db: SchedulingDb, input: RescheduleInput, callbacks?: SchedulingCallbacks): Promise<AppointmentWithDetails>;
1185
-
1186
- /**
1187
- * Get a single appointment by ID.
1188
- *
1189
- * Pass `organizationId` and an appointment of another organization is reported as not found. Without it no organization
1190
- * check is made here: the caller must already have verified ownership or be passing a database handle that holds one business.
1191
- */
1192
- declare function getAppointment(db: SchedulingDb, appointmentId: string, options?: {
1193
- organizationId?: string;
1194
- }): Promise<AppointmentWithDetails>;
1195
- /**
1196
- * List appointments with filters.
1197
- *
1198
- * Org-scoping precondition: no organizationId check is performed here; the caller
1199
- * must already have verified ownership or be passing a tenant-resolved `db` handle.
1200
- * UNLIKE the other functions in this file, this one currently has NO production caller
1201
- * anywhere in apps/web (confirmed via repo-wide grep, 2026-07-05) — it exists only as a
1202
- * barrel-exported public package API (`packages/ordinatio-scheduling/src/index.ts`). Any
1203
- * future caller MUST resolve `db` via `getTenantContext()`/`requireSchedulingAuth()` (or
1204
- * equivalent ownership verification) before invoking this — there is no runtime guard
1205
- * here to catch a caller that skips this.
1206
- */
1207
- declare function listAppointments(unscopedDb: SchedulingDb, options?: {
1208
- /** Only this organization's appointments. Leave it out when the database holds one business. */
1209
- organizationId?: string;
1210
- calendarId?: string;
1211
- status?: string;
1212
- clientEmail?: string;
1213
- startDate?: Date;
1214
- endDate?: Date;
1215
- limit?: number;
1216
- offset?: number;
1217
- }): Promise<{
1218
- appointments: AppointmentWithDetails[];
1219
- total: number;
1220
- }>;
1221
-
1222
- interface GroupCapacityResult {
1223
- seatsTotal: number | null;
1224
- seatsBooked: number;
1225
- seatsAvailable: number | null;
1226
- isFull: boolean;
1227
- }
1228
- /**
1229
- * Return the current seat availability for a specific group event slot.
1230
- *
1231
- * Counts PENDING and CONFIRMED appointments for the given
1232
- * typeId + calendarId + exact startTime. Throws SCHED_308 if
1233
- * the type is not a group type.
1234
- *
1235
- * Caller is responsible for ensuring startTime is in UTC.
1236
- */
1237
- declare function getGroupCapacity(db: SchedulingDb, params: {
1238
- typeId: string;
1239
- calendarId: string;
1240
- startTime: Date;
1241
- }): Promise<GroupCapacityResult>;
1242
-
1243
- interface GroupSessionAttendee {
1244
- id: string;
1245
- clientName: string;
1246
- clientEmail: string;
1247
- clientPhone: string | null;
1248
- clientId: string | null;
1249
- status: 'PENDING' | 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NO_SHOW';
1250
- }
1251
- interface GroupSession {
1252
- typeId: string;
1253
- typeName: string;
1254
- typeColor: string;
1255
- maxSeats: number | null;
1256
- calendarId: string;
1257
- calendarName: string;
1258
- staffName: string | null;
1259
- startTime: Date;
1260
- endTime: Date;
1261
- seatsBooked: number;
1262
- seatsAvailable: number | null;
1263
- isFull: boolean;
1264
- attendees: GroupSessionAttendee[];
1265
- }
1266
- interface GroupSessionsResult {
1267
- sessions: GroupSession[];
1268
- /**
1269
- * Task #31: true when the raw appointment fetch hit the 1000-row cap — some
1270
- * sessions/attendees in this range may be missing. The cap exists to prevent a
1271
- * runaway query; this flag lets the caller surface "showing partial results"
1272
- * instead of silently dropping sessions with zero signal.
1273
- */
1274
- hasMore: boolean;
1275
- }
1276
- declare function getGroupSessions(db: SchedulingDb, params: {
1277
- startDate: Date;
1278
- endDate: Date;
1279
- calendarId?: string;
1280
- /** Task #83 — omitted means unrestricted, byte-identical to before. See visibility-filter.ts. */
1281
- visibleCalendarIds?: string[];
1282
- /** Only this organization's classes count. Leave it out when the database holds one business. */
1283
- organizationId?: string;
1284
- }): Promise<GroupSessionsResult>;
1285
-
1286
- /**
1287
- * Aggregate booking analytics for a lookback window.
1288
- * Fetches all appointments in one query, computes all metrics in JS.
1289
- * No N+1 queries — suitable for 30–90 day windows at normal volume.
1290
- */
1291
- declare function getBookingAnalytics(db: SchedulingDb, options?: {
1292
- calendarId?: string;
1293
- days?: number;
1294
- visibleCalendarIds?: string[];
1295
- /** Only this organization's appointments count. Leave it out when the database holds one business. */
1296
- organizationId?: string;
1297
- }): Promise<BookingAnalytics>;
1298
-
1299
- interface DashboardQuery {
1300
- /** Only this organization's appointments. Leave it out when the database holds one business. */
1301
- organizationId?: string;
1302
- /** Search by client name, email, or phone */
1303
- search?: string;
1304
- /** Filter history by status */
1305
- status?: string;
1306
- /** History page number (1-based) */
1307
- page?: number;
1308
- /** Override page size (default 20) */
1309
- pageSize?: number;
1310
- /**
1311
- * IANA timezone the "today"/"week" boundaries are computed in. Defaults to
1312
- * DEFAULT_DASHBOARD_TIMEZONE. Treated as trusted, like AvailabilityQuery's own
1313
- * `timezone` field — localToUTC() throws (not null-safe) on an unrecognized
1314
- * zone. No caller currently passes an untrusted value; validate first if one
1315
- * ever does.
1316
- */
1317
- timezone?: string;
1318
- /**
1319
- * Task #83 — omitted means unrestricted (byte-identical to pre-Task-#83
1320
- * behavior); when present, narrows every query below to appointments whose
1321
- * calendar is in this list OR whose calendar is unlinked (`userId: null`,
1322
- * always visible — see visibility-filter.ts's own doc comment for why).
1323
- * Callers resolve this from resolveSchedulingGroupScope() +
1324
- * resolveVisibleCalendarIds() (apps/web/src/lib/scheduling/group-scope.ts)
1325
- * before calling this function — this package never resolves a scope
1326
- * itself.
1327
- */
1328
- visibleCalendarIds?: string[];
1329
- }
1330
- /**
1331
- * Fetch all data needed for the appointments dashboard in one call.
1332
- *
1333
- * Runs 10 parallel queries:
1334
- * - Today's appointments (chronological, excluding cancelled)
1335
- * - This week's remaining appointments
1336
- * - Today stats (total + cancelled)
1337
- * - Week stats (total + cancelled)
1338
- * - History (paginated, searchable, filterable)
1339
- * - History count
1340
- * - Upcoming (after this week, soonest first, capped)
1341
- * - Upcoming count (all of them, so a capped list can say so)
1342
- */
1343
- declare function getAppointmentDashboard(unscopedDb: SchedulingDb, query?: DashboardQuery): Promise<AppointmentDashboardData>;
1344
- interface AppointmentsForRangeResult {
1345
- appointments: AppointmentDashboardItem[];
1346
- /**
1347
- * Task #31: true when the fetch hit the take cap — some appointments in this range
1348
- * may be missing. Previously this query had NO take limit at all (unbounded — the
1349
- * opposite problem from the other truncation gaps this task fixes): a busy range on
1350
- * a large org could trigger a full, uncapped table scan.
1351
- */
1352
- hasMore: boolean;
1353
- }
1354
- /**
1355
- * Fetch all appointments within an arbitrary date range.
1356
- * Used by calendar views (day/week/month).
1357
- * Includes all statuses (cancelled shown greyed out in the UI).
1358
- */
1359
- declare function getAppointmentsForRange(unscopedDb: SchedulingDb, rangeStart: Date, rangeEnd: Date, options?: {
1360
- organizationId?: string;
1361
- }): Promise<AppointmentsForRangeResult>;
1362
-
1363
- declare const USER_DAY_LIMIT = 200;
1364
- interface UserDayInput {
1365
- /** Only this organization's appointments and calendars. Leave it out when the database holds one business. */
1366
- organizationId?: string;
1367
- /** The staff member whose day it is (the id stored in SchedulingCalendar.userId). */
1368
- userId: string;
1369
- /** The local calendar day, 'YYYY-MM-DD', in `timezone`. */
1370
- date: string;
1371
- /** IANA time zone that defines where the day starts and ends, e.g. 'America/Detroit'. */
1372
- timezone: string;
1373
- /** Calendars the caller may see; omit when unrestricted. Same meaning as in the other package queries. */
1374
- visibleCalendarIds?: string[];
1375
- /** Cancelled appointments are left out unless this is true. */
1376
- includeCancelled?: boolean;
1377
- }
1378
- interface DayAppointment {
1379
- id: string;
1380
- calendarId: string;
1381
- calendarName: string;
1382
- typeId: string;
1383
- typeName: string;
1384
- startTime: Date;
1385
- endTime: Date;
1386
- duration: number;
1387
- timezone: string;
1388
- status: string;
1389
- clientName: string;
1390
- /** The host application's client record, when the appointment is linked to one. */
1391
- clientId: string | null;
1392
- isGroup: boolean;
1393
- }
1394
- interface UserDayResult {
1395
- appointments: DayAppointment[];
1396
- /** True when the day holds more than USER_DAY_LIMIT appointments and the rest were left out. */
1397
- hasMore: boolean;
1398
- /** Calendars linked to this user that the caller can see; 0 means "nothing linked", not "free day". */
1399
- linkedCalendarCount: number;
1400
- }
1401
- declare function getUserDayAppointments(unscopedDb: SchedulingDb, input: UserDayInput): Promise<UserDayResult>;
1402
-
1403
- interface Clock {
1404
- now(): Date;
1405
- }
1406
- interface OutboundMessage {
1407
- channel: NotificationChannel;
1408
- to: string;
1409
- subject: string;
1410
- body: string;
1411
- trigger?: NotificationTrigger;
1412
- /** The organization's own sender identity, when it has one. An adapter that cannot send as it uses its default sender. */
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;
1416
- }
1417
- type SendResult = {
1418
- status: 'SENT';
1419
- id?: string;
1420
- } | {
1421
- status: 'SKIPPED';
1422
- reason?: string;
1423
- };
1424
- interface NotificationAdapter {
1425
- /** Must not report SENT for a message it did not hand to a provider. */
1426
- send(message: OutboundMessage): Promise<SendResult>;
1427
- }
1428
- interface ChargeRequest {
1429
- /** Major units (dollars, not cents), the same unit the engine uses everywhere. */
1430
- amount: number;
1431
- currency: string;
1432
- clientEmail: string;
1433
- description: string;
1434
- /** Charging twice with the same key must not charge twice: it returns the first payment. */
1435
- idempotencyKey?: string;
1436
- metadata?: Record<string, string>;
1437
- }
1438
- /** A payment that needs the client to do something (for example a bank check) comes back as REQUIRES_ACTION. */
1439
- type ChargeResult = PaymentResult & {
1440
- status?: 'SUCCEEDED' | 'REQUIRES_ACTION';
1441
- clientSecret?: string;
1442
- /** IN_PROGRESS: another request with this key is still running. CANCELED: the saved payment for this key was canceled, so retry with a new key. KEY_REUSED: the key was already used with different details. */
1443
- code?: 'IN_PROGRESS' | 'CANCELED' | 'KEY_REUSED';
1444
- };
1445
- interface PaymentCheck {
1446
- paid: boolean;
1447
- /** Major units. Left out when the adapter cannot convert the payment's currency safely. */
1448
- amount?: number;
1449
- currency?: string;
1450
- /** The provider's own status word, or one of 'refunded', 'not_found', 'refund_state_unknown' where the adapter has to say so itself. */
1451
- status?: string;
1452
- /** What the payment was created for, so a payment cannot be reused for a different booking. */
1453
- metadata?: Record<string, string>;
1454
- }
1455
- interface RefundOptions {
1456
- /** Major units. Omit to refund whatever is left. A partial refund must come with an idempotencyKey. */
1457
- amount?: number;
1458
- /**
1459
- * Makes a retry of the same refund safe. Required for a partial refund: without it, a retry after an
1460
- * unknown outcome could refund twice, so the adapter must refuse. After a failed refund, retry with a new key.
1461
- */
1462
- idempotencyKey?: string;
1463
- }
1464
- interface RefundResult {
1465
- success: boolean;
1466
- refundId?: string;
1467
- error?: string;
1468
- /** Major units this call refunded, as the provider reports it. Left out when the currency cannot be converted safely. */
1469
- amount?: number;
1470
- /** PENDING means the provider accepted it but has not finished; the final outcome comes later. */
1471
- status?: 'SUCCEEDED' | 'PENDING';
1472
- /**
1473
- * Why a refusal happened. ALREADY_REFUNDED means nothing is left to refund; it is only the same as success
1474
- * for a full refund. IN_PROGRESS: another request with this key is still running. REPLAYED_FAILURE: the
1475
- * provider returned a saved copy of an earlier failed attempt, so retry once with a new key.
1476
- * KEY_REUSED: the key was already used with different details, so nothing was refunded.
1477
- */
1478
- code?: 'ALREADY_REFUNDED' | 'IN_PROGRESS' | 'REPLAYED_FAILURE' | 'KEY_REUSED';
1479
- /** The provider's id for the request, for support tickets. */
1480
- requestId?: string;
1481
- }
1482
- /** An expected refusal (zero charge, unknown payment, over-refund) may be returned as a failure or thrown. */
1483
- interface PaymentAdapter {
1484
- charge(request: ChargeRequest): Promise<ChargeResult>;
1485
- /** Server-side check that a payment id was really paid, never trusting the browser. A fully refunded payment is reported as not paid. */
1486
- verify(paymentId: string): Promise<PaymentCheck>;
1487
- /**
1488
- * No amount refunds whatever is left. A partial refund is allowed but needs an idempotencyKey; a refund
1489
- * of more than what is left, or of a payment with nothing left, must report failure.
1490
- */
1491
- refund(paymentId: string, options?: RefundOptions): Promise<RefundResult>;
1492
- }
1493
- interface CalendarEvent {
1494
- appointmentId: string;
1495
- calendarId: string;
1496
- title: string;
1497
- startTime: Date;
1498
- endTime: Date;
1499
- timezone: string;
1500
- }
1501
- interface CalendarEventRef {
1502
- appointmentId: string;
1503
- /** The calendar the event was last written to, needed when an appointment moves between calendars. */
1504
- calendarId?: string;
1505
- /** The provider's own id, as returned by upsertEvent. */
1506
- externalId?: string;
1507
- }
1508
- interface CalendarSyncAdapter {
1509
- /** One event per appointment id: calling again moves or renames it. */
1510
- upsertEvent(event: CalendarEvent): Promise<{
1511
- externalId?: string;
1512
- }>;
1513
- /** Removing an event that is already gone is not an error. */
1514
- removeEvent(ref: CalendarEventRef): Promise<void>;
1515
- }
1516
- interface AuthContext {
1517
- userId: string;
1518
- organizationId: string;
1519
- roles: string[];
1520
- }
1521
- interface AuthAdapter {
1522
- /** Returns null for missing or invalid credentials; never throws for a bad token. */
1523
- resolve(headers: Record<string, string | undefined>): Promise<AuthContext | null>;
1524
- }
1525
- interface SchedulingAdapters {
1526
- clock: Clock;
1527
- notifications: NotificationAdapter;
1528
- payments: PaymentAdapter;
1529
- calendarSync: CalendarSyncAdapter;
1530
- auth: AuthAdapter;
1531
- }
1532
-
1533
- interface InMemoryOptions {
1534
- now?: Date;
1535
- /** Bearer token to the context it signs in as. */
1536
- users?: Record<string, AuthContext>;
1537
- }
1538
- interface InMemoryRecords {
1539
- sent: OutboundMessage[];
1540
- charges: ChargeRequest[];
1541
- refunds: Array<{
1542
- paymentId: string;
1543
- amount?: number;
1544
- }>;
1545
- calendarEvents: Map<string, CalendarEvent>;
1546
- }
1547
- interface InMemoryClockControl {
1548
- set(date: Date): void;
1549
- advance(ms: number): void;
1550
- }
1551
- declare function createInMemoryAdapters(options?: InMemoryOptions): {
1552
- adapters: SchedulingAdapters;
1553
- records: InMemoryRecords;
1554
- clock: InMemoryClockControl;
1555
- };
1556
-
1557
- type PassThrough = Pick<SchedulingCallbacks, 'onActivity' | 'onEvent'>;
1558
- declare function adaptersToCallbacks(adapters: Pick<SchedulingAdapters, 'notifications' | 'payments'>, passThrough?: PassThrough): SchedulingCallbacks;
1559
-
1560
- declare function checkClockContract(clock: Clock): Promise<string[]>;
1561
- declare function checkNotificationContract(adapter: NotificationAdapter): Promise<string[]>;
1562
- interface PaymentContractOptions {
1563
- /**
1564
- * For a payment the client confirms in the browser (charge returns REQUIRES_ACTION): confirm it here,
1565
- * for example with the provider's test card. Without it the paid-payment checks cannot run, and the
1566
- * check reports that as a failure instead of passing silently.
1567
- */
1568
- completePayment?: (charge: ChargeResult) => Promise<void>;
1569
- }
1570
- declare function checkPaymentContract(adapter: PaymentAdapter, options?: PaymentContractOptions): Promise<string[]>;
1571
- declare function checkCalendarSyncContract(adapter: CalendarSyncAdapter): Promise<string[]>;
1572
- declare function checkAuthContract(adapter: AuthAdapter, validHeaders?: Record<string, string | undefined>): Promise<string[]>;
1573
-
1574
- /**
1575
- * Composes an OR fragment — `{ calendarId: { in: visibleCalendarIds } } OR
1576
- * { calendar: { userId: null } }` — into an existing Prisma `where` object.
1577
- *
1578
- * An unlinked calendar (`userId: null`) is always visible regardless of
1579
- * scope, matching group-scope.ts's own documented deviation for this exact
1580
- * reason (a calendar isn't part of the group system until an admin opts it
1581
- * in via the staff-picker) — this function exists specifically so all 3
1582
- * call sites encode that rule identically instead of each hand-rolling it.
1583
- *
1584
- * If `where` already has a top-level `OR` (e.g. dashboard.ts's search
1585
- * filter), naively assigning a second `OR` key would silently overwrite the
1586
- * first — Prisma `where` objects are plain JS objects, later keys win. This
1587
- * combines both via `AND` instead so neither filter is lost.
1588
- *
1589
- * Does NOT defend against `where.AND` already being present — none of this
1590
- * package's 3 current call sites use `AND`, so that case can't arise today;
1591
- * a future caller that does would need this function extended, not
1592
- * silently mis-combined.
1593
- */
1594
- declare function withCalendarVisibility(where: Record<string, unknown>, visibleCalendarIds: string[] | undefined): Record<string, unknown>;
1595
-
1596
- /**
1597
- * Limits a Prisma `where` on appointments to one organization, through the appointment's calendar.
1598
- *
1599
- * The package does not assume the database handle it is given is already limited to one business: a host that keeps
1600
- * several businesses in one database passes the organization here and nothing from another business can come back.
1601
- * Left out, the `where` is returned unchanged (the same object), for a host that gives each business its own database.
1602
- * Wrapped in `AND` so it combines with any `OR` or `calendar` condition already in the `where`.
1603
- */
1604
- declare function withOrganization(where: Record<string, unknown>, organizationId: string | undefined): Record<string, unknown>;
1605
- /**
1606
- * The same database handle, but every appointment query is limited to one organization (through the calendar) and every
1607
- * calendar query to the organization itself. For the package's read functions that run several queries, so none of them can be
1608
- * left unscoped by accident. Given no organization the handle is returned as it is.
1609
- */
1610
- declare function scopeToOrganization(db: SchedulingDb, organizationId: string | undefined): SchedulingDb;
1611
-
1612
- declare function renderTemplate(template: string, context: NotificationContext, channel?: NotificationChannel): string;
1613
- /**
1614
- * Build notification context from an appointment + related data.
1615
- */
1616
- declare function buildNotificationContext(appointment: {
1617
- clientName: string;
1618
- clientEmail: string;
1619
- clientPhone?: string | null;
1620
- startTime: Date;
1621
- duration: number;
1622
- timezone: string;
1623
- location?: string | null;
1624
- meetingUrl?: string | null;
1625
- manageToken?: string;
1626
- status?: string;
1627
- intakeResponses?: Record<string, unknown> | null;
1628
- type: {
1629
- name: string;
1630
- intakeForm?: unknown;
1631
- location?: string | null;
1632
- locationType?: AppointmentLocationType | null;
1633
- };
1634
- calendar: {
1635
- name: string;
1636
- staffName?: string | null;
1637
- location?: string | null;
1638
- };
1639
- }, baseUrl?: string): NotificationContext;
1640
-
1641
- /**
1642
- * Find and process all pending notifications that are ready to send.
1643
- * Single source of truth for notification processing — the worker
1644
- * delegates to this function with an injected sender.
1645
- *
1646
- * Includes retry with exponential backoff:
1647
- * - On failure: retryCount incremented, scheduledFor pushed forward
1648
- * - Backoff: baseMinutes * 2^retryCount (default 5, 10, 20 minutes)
1649
- * - After maxRetries (default 3): marked DEAD_LETTER permanently
1650
- */
1651
- declare function processPendingNotifications(db: SchedulingDb, sender: NotificationSender, options?: {
1652
- batchSize?: number;
1653
- retry?: RetryConfig;
1654
- workerId?: string;
1655
- staleThresholdMs?: number;
1656
- maxOverdueMs?: number;
1657
- /** Queue a `reminder.sent` webhook for each reminder that was sent. Off by default; needs the webhook tables. */
1658
- webhooks?: boolean;
1659
- /** Send each message with its organization's sender identity (name, address, reply-to). Off by default; needs the brand table. */
1660
- brand?: boolean;
1661
- /** Tell the sender which organization each notification belongs to (`organizationId` in its context). Off by default. */
1662
- organization?: boolean;
1663
- }): Promise<{
1664
- sent: number;
1665
- failed: number;
1666
- deadLettered: number;
1667
- skipped: number;
1668
- }>;
1669
-
1670
- /**
1671
- * Schedule all notifications for a newly booked appointment.
1672
- * Creates ScheduledNotification records for immediate + future delivery.
1673
- */
1674
- declare function scheduleNotifications(db: SchedulingDb, appointmentId: string, baseUrl?: string, options?: {
1675
- excludeTriggers?: NotificationTrigger[];
1676
- brand?: boolean;
1677
- }): Promise<number | undefined>;
1678
- /**
1679
- * Cancel all pending notifications for an appointment.
1680
- * Called when an appointment is cancelled.
1681
- */
1682
- declare function cancelPendingNotifications(db: SchedulingDb, appointmentId: string): Promise<_prisma_client.Prisma.BatchPayload>;
1683
- /**
1684
- * Queue an immediate notification for delivery (e.g., cancellation notice).
1685
- *
1686
- * Creates PENDING notification records with scheduledFor = now.
1687
- * The worker's processPendingNotifications picks them up on the next
1688
- * poll cycle (≤30s) with full retry/backoff/dead-letter support.
1689
- *
1690
- * Previously called sendImmediateNotification — renamed to make the
1691
- * async queue-based behavior explicit.
1692
- */
1693
- declare function queueImmediateNotification(db: SchedulingDb, appointmentId: string, trigger: NotificationTrigger, baseUrl?: string, options?: {
1694
- brand?: boolean;
1695
- }): Promise<void>;
1696
- /**
1697
- * Queue an immediate email notification to the calendar's staff member.
1698
- * Silently skips if: appointment not found, no staffEmail on the calendar,
1699
- * or no active STAFF templates exist for the trigger.
1700
- * Failure must NEVER block the caller — always wrap call sites in try/catch.
1701
- */
1702
- declare function queueStaffNotification(db: SchedulingDb, appointmentId: string, trigger: NotificationTrigger, baseUrl?: string, options?: {
1703
- brand?: boolean;
1704
- }): Promise<void>;
1705
-
1706
- /**
1707
- * List all notification templates for an org, sorted by channel then trigger.
1708
- */
1709
- declare function listNotificationTemplates(db: SchedulingDb, organizationId: string): Promise<{
1710
- id: string;
1711
- organizationId: string;
1712
- name: string;
1713
- isActive: boolean;
1714
- channel: string;
1715
- trigger: string;
1716
- subject: string | null;
1717
- body: string;
1718
- recipientType: string;
1719
- }[]>;
1720
- /**
1721
- * Get a single notification template by ID, scoped to the caller's org.
1722
- * A template belonging to a different org is treated as not found (404, not 403) —
1723
- * this must not leak whether the ID exists at all outside the caller's org.
1724
- */
1725
- declare function getNotificationTemplate(db: SchedulingDb, organizationId: string, templateId: string): Promise<{
1726
- id: string;
1727
- organizationId: string;
1728
- name: string;
1729
- isActive: boolean;
1730
- channel: string;
1731
- trigger: string;
1732
- subject: string | null;
1733
- body: string;
1734
- recipientType: string;
1735
- }>;
1736
- /**
1737
- * Create a new notification template.
1738
- * Validates that the channel/trigger combination has a meaningful body.
1739
- */
1740
- declare function createNotificationTemplate(db: SchedulingDb, organizationId: string, input: {
1741
- name: string;
1742
- channel: string;
1743
- trigger: string;
1744
- recipientType?: string;
1745
- subject?: string | null;
1746
- body: string;
1747
- isActive?: boolean;
1748
- }): Promise<{
1749
- id: string;
1750
- organizationId: string;
1751
- name: string;
1752
- isActive: boolean;
1753
- channel: string;
1754
- trigger: string;
1755
- subject: string | null;
1756
- body: string;
1757
- recipientType: string;
1758
- }>;
1759
- /**
1760
- * Update an existing notification template.
1761
- * Only updates fields that are explicitly provided.
1762
- */
1763
- declare function updateNotificationTemplate(db: SchedulingDb, organizationId: string, templateId: string, input: {
1764
- name?: string;
1765
- subject?: string | null;
1766
- body?: string;
1767
- isActive?: boolean;
1768
- }): Promise<{
1769
- id: string;
1770
- organizationId: string;
1771
- name: string;
1772
- isActive: boolean;
1773
- channel: string;
1774
- trigger: string;
1775
- subject: string | null;
1776
- body: string;
1777
- recipientType: string;
1778
- }>;
1779
- /**
1780
- * Delete a notification template permanently.
1781
- */
1782
- declare function deleteNotificationTemplate(db: SchedulingDb, organizationId: string, templateId: string): Promise<{
1783
- id: string;
1784
- organizationId: string;
1785
- name: string;
1786
- isActive: boolean;
1787
- channel: string;
1788
- trigger: string;
1789
- subject: string | null;
1790
- body: string;
1791
- recipientType: string;
1792
- }>;
1793
-
1794
- /**
1795
- * Resolve the effective location for an appointment.
1796
- *
1797
- * Chain for IN_PERSON / VIRTUAL / PHONE:
1798
- * per-appointment override → type default → calendar default → null
1799
- *
1800
- * Chain for TRAVEL_TO_CLIENT:
1801
- * per-appointment override → null
1802
- * The clothier travels to the client; type/calendar have no relevant venue.
1803
- * The per-appointment override IS the client address (set via #62 location PATCH).
1804
- *
1805
- * When locationType is omitted (backward compat), applies the 3-tier chain.
1806
- */
1807
- declare function resolveLocation(appointment: {
1808
- location?: string | null;
1809
- type?: {
1810
- location?: string | null;
1811
- locationType?: AppointmentLocationType | null;
1812
- } | null;
1813
- calendar?: {
1814
- location?: string | null;
1815
- } | null;
1816
- }): string | null;
1817
-
1818
- type RecurringFrequency = 'DAILY' | 'WEEKLY' | 'BIWEEKLY' | 'MONTHLY';
1819
- type CancelRecurringScope = 'ONE' | 'THIS_AND_FOLLOWING' | 'ALL';
1820
- declare const RECURRING_MAX_OCCURRENCES = 104;
1821
- /**
1822
- * Generate up to `count` occurrence dates starting from `start`.
1823
- *
1824
- * Each returned Date represents the UTC midnight of that occurrence day.
1825
- * Callers combine with `startTimeLocal` ("HH:MM") to produce the actual
1826
- * appointment startTime in the calendar's timezone.
1827
- *
1828
- * @param start - First occurrence day (UTC midnight)
1829
- * @param frequency - DAILY | WEEKLY | BIWEEKLY | MONTHLY
1830
- * @param count - Requested occurrences (clamped to RECURRING_MAX_OCCURRENCES;
1831
- * non-finite input — e.g. NaN — is treated as 1; fractional
1832
- * finite input is floored)
1833
- * @param endsAt - Optional upper bound, compared in UTC-midnight-day space
1834
- * (before any timezone is applied — timezone only enters
1835
- * at buildOccurrenceStartTime). Occurrences whose day
1836
- * marker is past `endsAt` are dropped.
1837
- */
1838
- declare function generateOccurrenceDates(start: Date, frequency: RecurringFrequency, count: number, endsAt?: Date): Date[];
1839
- /**
1840
- * Parse "HH:MM" into hours and minutes.
1841
- * Returns null for invalid input so callers can produce typed errors.
1842
- */
1843
- declare function parseTimeLocal(hhmm: string): {
1844
- h: number;
1845
- m: number;
1846
- } | null;
1847
- /**
1848
- * Build a UTC Date from an occurrence day (UTC midnight) and a local time string,
1849
- * DST-aware for the given IANA timezone — mirrors the single-booking conversion
1850
- * in availability/engine.ts. `timezone` defaults to 'UTC' (a zero-offset,
1851
- * DST-free zone) so callers that don't yet pass a real calendar timezone see
1852
- * byte-identical output to the old naive Date.UTC() construction.
1853
- *
1854
- * Returns null for either an invalid `startTimeLocal` or an unrecognized
1855
- * `timezone` — both are caller input errors with the same "can't build a
1856
- * slot for this" meaning to buildRecurringSlots' filter step.
1857
- */
1858
- declare function buildOccurrenceStartTime(dayUtcMidnight: Date, startTimeLocal: string, timezone?: string): Date | null;
1859
- /**
1860
- * Build all appointment startTime/endTime pairs for a recurring series.
1861
- * Pure — no DB access. `timezone` defaults to 'UTC' for backward compatibility
1862
- * with callers that don't yet pass the calendar's real timezone (see
1863
- * buildOccurrenceStartTime).
1864
- */
1865
- declare function buildRecurringSlots(firstDate: Date, frequency: RecurringFrequency, occurrences: number, startTimeLocal: string, durationMins: number, endsAt?: Date, timezone?: string): Array<{
1866
- startTime: Date;
1867
- endTime: Date;
1868
- }>;
1869
-
1870
- /**
1871
- * Generate a stable Jitsi Meet URL for a virtual appointment.
1872
- * Jitsi rooms are open by default — no account required for participants.
1873
- * URL is deterministic: same appointmentId always returns the same URL.
1874
- */
1875
- declare function buildJitsiUrl(appointmentId: string): string;
1876
- /**
1877
- * Determine whether an appointment type's location type warrants a video link.
1878
- * Returns true only for VIRTUAL meetings.
1879
- */
1880
- declare function isVirtualMeeting(locationType: string | null | undefined): boolean;
1881
-
1882
- /**
1883
- * Selects a calendar from the pool for a team booking.
1884
- *
1885
- * Requires TxClient (not root SchedulingDb) — enforced at compile time by the branded type.
1886
- * The RoundRobinState update and the appointment create must be in the same
1887
- * SERIALIZABLE transaction to prevent two concurrent bookings picking the same calendar.
1888
- */
1889
- declare function selectCalendarForBooking(db: TxClient, typeId: string, startTime: Date, duration: number): Promise<string>;
1890
-
1891
- /**
1892
- * Returns merged available slots across all calendars linked to a team appointment type.
1893
- * A slot is available if ANY calendar in the pool has it free (OR-merge, not AND).
1894
- *
1895
- * _getSlots is injectable for testing — production callers never pass it.
1896
- * Same-file ESM calls cannot be intercepted by vi.mock, so the seam is explicit.
1897
- */
1898
- declare function getTeamAvailableSlots(db: SchedulingDb, query: TeamAvailabilityQuery, _getSlots?: typeof getAvailableSlots): Promise<TeamAvailabilityResult>;
1899
-
1900
- /**
1901
- * Convert a local date + time to a UTC Date, independently of the machine's timezone.
1902
- *
1903
- * Algorithm: treat the target local time as a "naive" UTC timestamp, format that
1904
- * naive UTC in the target timezone to find the actual UTC offset at that moment,
1905
- * then subtract the offset to get the true UTC time — then REPEAT against the
1906
- * newly-adjusted candidate, because the offset measured at the naive candidate may
1907
- * not be the offset actually in effect at the true target instant (they differ by
1908
- * an hour whenever the candidate initially lands on the wrong side of a DST
1909
- * transition). A single pass here was a real, confirmed bug (Task #43): for
1910
- * America/New_York on 2026-03-08 (US spring-forward day), a single pass converted
1911
- * local '03:00' to 2026-03-08T08:00:00.000Z instead of the correct
1912
- * 2026-03-08T07:00:00.000Z (EDT, UTC-4) — it measured the still-in-effect-at-the-
1913
- * naive-candidate EST offset (UTC-5) and never rechecked after the adjustment
1914
- * crossed into EDT. Iterating corrects it for any local time that has a real,
1915
- * unambiguous UTC instant (verified 2025-2028 across every standard 1-hour US
1916
- * DST shift) — 2 passes suffice for those.
1917
- *
1918
- * DST GAP HANDLING (Task #43 audit finding, since fixed at the root — this used
1919
- * to rely on an undisclosed parity accident of a fixed loop-iteration count; see
1920
- * git history / debt.md for that prior version if you need the archaeology): a
1921
- * local time inside a DST "gap" hour (a wall-clock time that does not exist,
1922
- * e.g. 02:30 when clocks jump 2:00→3:00) makes this offset-recompute loop
1923
- * oscillate indefinitely between exactly two candidates — the pre- and
1924
- * post-transition interpretation of the same naive instant — rather than
1925
- * reaching a fixed point. The loop below DETECTS that 2-cycle explicitly (the
1926
- * newly-computed candidate equals the one seen two steps back) and resolves it
1927
- * deterministically to the LATER of the two oscillating instants — i.e. "the
1928
- * gap resolves forward, past the transition" — rather than depending on
1929
- * whichever candidate an arbitrary fixed iteration count happens to stop on.
1930
- * Verified by direct execution against every 2025-2028 US spring-forward date.
1931
- *
1932
- * DST FOLD behavior (verified by direct execution): a local time in the "fold"
1933
- * hour on a fall-back day (e.g. 01:30, which occurs twice) does NOT trigger the
1934
- * 2-cycle above — this loop converges to a genuine fixed point for fold-hour
1935
- * inputs, and that fixed point is always the FIRST occurrence (the still-in-
1936
- * DST interpretation, before the fallback). Neither the gap's "resolves
1937
- * forward" nor the fold's "resolves to first occurrence" is a business rule
1938
- * anyone has explicitly signed off on for appointment scheduling — flagged so
1939
- * a future reader doesn't have to re-derive either by testing.
1940
- *
1941
- * This is the same technique already proven in appointments/recurring.ts's own
1942
- * (separately-maintained — see debt.md) copy of this algorithm, ported here rather
1943
- * than re-derived independently. Unlike that copy, this function keeps its
1944
- * original non-null `Date` return contract: it still throws on an unrecognized
1945
- * `tz` (a `RangeError` from the underlying `Intl.DateTimeFormat` constructor),
1946
- * because every existing caller of this shared, package-barrel-exported function
1947
- * (availability/engine.ts, availability/compute-available-slots.ts,
1948
- * appointments/dashboard.ts's weekBoundsUTC(), and an app-layer caller outside
1949
- * this package) assumes a non-null `Date` back — adopting
1950
- * recurring.ts's `Date | null` graceful-invalid-timezone contract would require
1951
- * touching all of them, which is out of scope for this fix.
1952
- *
1953
- * @param dateStr - 'YYYY-MM-DD' in the target timezone
1954
- * @param timeStr - 'HH:MM' in the target timezone
1955
- * @param tz - IANA timezone name
1956
- */
1957
- declare function localToUTC(dateStr: string, timeStr: string, tz: string): Date;
1958
-
1959
- declare const WEBHOOK_EVENT_TYPES: readonly ["appointment.booked", "appointment.rescheduled", "appointment.cancelled", "appointment.no_show", "reminder.sent", "waitlist.offered"];
1960
- type WebhookEventType = (typeof WEBHOOK_EVENT_TYPES)[number];
1961
- /** Sent only by the "test" action; no endpoint subscribes to it. */
1962
- declare const WEBHOOK_TEST_EVENT = "webhook.test";
1963
- interface WebhookEnvelope {
1964
- id: string;
1965
- type: string;
1966
- createdAt: string;
1967
- organizationId: string;
1968
- data: Record<string, unknown>;
1969
- }
1970
-
1971
- declare const SIGNATURE_HEADER = "x-scheduling-signature";
1972
- declare function generateWebhookSecret(): string;
1973
- /** The header value: `t=<unix seconds>,v1=<hex hmac-sha256 of "<t>.<body>">`. */
1974
- declare function signWebhook(args: {
1975
- secret: string;
1976
- body: string;
1977
- now: Date;
1978
- }): string;
1979
- /**
1980
- * True only when the header was made with this secret for exactly this body, and its timestamp is within
1981
- * `toleranceSeconds` of now (default 5 minutes, both directions). Never throws on a malformed header.
1982
- */
1983
- declare function verifyWebhookSignature(args: {
1984
- secret: string;
1985
- header: string | null | undefined;
1986
- body: string;
1987
- toleranceSeconds?: number;
1988
- now?: Date;
1989
- }): boolean;
1990
-
1991
- interface UrlCheckOptions {
1992
- /** Allows http and addresses on this machine or a private network. For local development and tests only. */
1993
- allowInsecureTargets?: boolean;
1994
- }
1995
- type UrlCheck = {
1996
- ok: true;
1997
- url: URL;
1998
- } | {
1999
- ok: false;
2000
- reason: string;
2001
- };
2002
- /** True for loopback, private, link-local, carrier-grade NAT, multicast and unspecified addresses. */
2003
- declare function isPrivateAddress(ip: string): boolean;
2004
- declare function checkWebhookUrl(raw: string, options?: UrlCheckOptions): UrlCheck;
2005
-
2006
- interface TransportRequest {
2007
- url: URL;
2008
- headers: Record<string, string>;
2009
- body: string;
2010
- timeoutMs: number;
2011
- }
2012
- /** The status the receiver answered with. Rejects on a network failure, a timeout or a blocked target. */
2013
- type WebhookTransport = (request: TransportRequest) => Promise<{
2014
- status: number;
2015
- }>;
2016
- declare class BlockedTargetError extends Error {
2017
- constructor(hostname: string);
2018
- }
2019
- declare function createNodeTransport(options?: {
2020
- allowInsecureTargets?: boolean;
2021
- }): WebhookTransport;
2022
-
2023
- declare const MAX_ENDPOINTS_PER_ORGANIZATION = 20;
2024
- /** An endpoint as the outside world sees it. The secret is never part of it. */
2025
- interface WebhookEndpointView {
2026
- id: string;
2027
- url: string;
2028
- description: string | null;
2029
- eventTypes: string[];
2030
- isActive: boolean;
2031
- createdAt: Date;
2032
- }
2033
- declare function createWebhookEndpoint(db: SchedulingDb, input: {
2034
- organizationId: string;
2035
- url: string;
2036
- eventTypes: unknown;
2037
- description?: string | null;
2038
- }, options?: UrlCheckOptions): Promise<{
2039
- endpoint: WebhookEndpointView;
2040
- secret: string;
2041
- }>;
2042
- declare function listWebhookEndpoints(db: SchedulingDb, organizationId: string): Promise<WebhookEndpointView[]>;
2043
- /** Removes the endpoint and, with it, its deliveries and their log. */
2044
- declare function deleteWebhookEndpoint(db: SchedulingDb, organizationId: string, endpointId: string): Promise<void>;
2045
-
2046
- /** What a receiver is told about an appointment. Payment details are left out on purpose. */
2047
- declare function appointmentWebhookData(db: SchedulingDb, organizationId: string, appointmentId: string): Promise<Record<string, unknown>>;
2048
- /** Queues the event for every active endpoint of the organization that subscribes to it. Returns how many were queued. */
2049
- declare function enqueueWebhookEvent(db: SchedulingDb, input: {
2050
- organizationId: string;
2051
- type: string;
2052
- data: Record<string, unknown>;
2053
- eventId?: string;
2054
- now?: Date;
2055
- }): Promise<{
2056
- queued: number;
2057
- }>;
2058
- /**
2059
- * Queues an event for an appointment and never throws: the booking is already saved, and a webhook problem must
2060
- * not undo or hide that. The failure is logged with a reference.
2061
- */
2062
- declare function enqueueAppointmentWebhook(db: SchedulingDb, input: {
2063
- organizationId: string;
2064
- type: string;
2065
- appointmentId: string;
2066
- extra?: Record<string, unknown>;
2067
- eventId?: string;
2068
- }): Promise<void>;
2069
- /** Queues `reminder.sent` for a reminder the engine just sent. The organization comes from the appointment's calendar. */
2070
- declare function enqueueReminderSent(db: SchedulingDb, notification: {
2071
- id: string;
2072
- appointmentId: string;
2073
- channel: string;
2074
- trigger: string;
2075
- }): Promise<void>;
2076
-
2077
- /** Seconds to wait after the 1st, 2nd, ... failed try. The delivery goes to the dead-letter list after one more failure. */
2078
- declare const DEFAULT_BACKOFF_SECONDS: number[];
2079
- interface AttemptOptions {
2080
- transport?: WebhookTransport;
2081
- now?: () => Date;
2082
- timeoutMs?: number;
2083
- backoffSeconds?: number[];
2084
- /** Tries before dead-letter. Default: one more than the back-off list is long (6). */
2085
- maxAttempts?: number;
2086
- allowInsecureTargets?: boolean;
2087
- }
2088
-
2089
- interface DeliverOptions extends AttemptOptions {
2090
- /** How many deliveries one call picks up. Default 20. */
2091
- batchSize?: number;
2092
- /** How many are sent at the same moment. Default 5. */
2093
- concurrency?: number;
2094
- workerId?: string;
2095
- /** A claim older than this is taken to belong to a crashed worker and is reclaimed. Default 5 minutes. */
2096
- staleClaimMs?: number;
2097
- }
2098
- interface DeliverSummary {
2099
- succeeded: number;
2100
- retried: number;
2101
- deadLettered: number;
2102
- /** Deliveries another worker finished first. */
2103
- lostClaim: number;
2104
- }
2105
- declare function deliverDueWebhooks(db: SchedulingDb, options?: DeliverOptions): Promise<DeliverSummary>;
2106
-
2107
- interface TestSendResult {
2108
- deliveryId: string;
2109
- ok: boolean;
2110
- statusCode: number | null;
2111
- error: string | null;
2112
- }
2113
- declare function sendTestWebhook(db: SchedulingDb, input: {
2114
- organizationId: string;
2115
- endpointId: string;
2116
- }, options?: AttemptOptions): Promise<TestSendResult>;
2117
-
2118
- interface WebhookDeliveryView {
2119
- id: string;
2120
- endpointId: string;
2121
- eventId: string;
2122
- eventType: string;
2123
- status: string;
2124
- attempts: number;
2125
- nextAttemptAt: Date;
2126
- lastStatusCode: number | null;
2127
- lastError: string | null;
2128
- deliveredAt: Date | null;
2129
- createdAt: Date;
2130
- attemptLog: Array<{
2131
- attemptNumber: number;
2132
- statusCode: number | null;
2133
- error: string | null;
2134
- durationMs: number;
2135
- createdAt: Date;
2136
- }>;
2137
- }
2138
- declare function listWebhookDeliveries(db: SchedulingDb, input: {
2139
- organizationId: string;
2140
- endpointId?: string;
2141
- status?: string;
2142
- limit?: number;
2143
- offset?: number;
2144
- }): Promise<{
2145
- deliveries: WebhookDeliveryView[];
2146
- total: number;
2147
- }>;
2148
- /** Puts a dead-lettered delivery back in the queue with a fresh set of tries. The log of earlier tries stays. */
2149
- declare function retryWebhookDelivery(db: SchedulingDb, organizationId: string, deliveryId: string, now?: Date): Promise<void>;
2150
-
2151
- interface WaitlistEntryView {
2152
- id: string;
2153
- typeId: string;
2154
- calendarId: string | null;
2155
- day: string;
2156
- slotStart: Date | null;
2157
- clientName: string;
2158
- clientEmail: string;
2159
- clientPhone: string | null;
2160
- status: string;
2161
- offerSlotStart: Date | null;
2162
- offerExpiresAt: Date | null;
2163
- createdAt: Date;
2164
- }
2165
-
2166
- declare const MAX_WAITING_PER_TYPE_DAY = 50;
2167
- interface JoinWaitlistInput {
2168
- organizationId: string;
2169
- typeId: string;
2170
- /** Leave out to wait for any calendar that offers the type. */
2171
- calendarId?: string;
2172
- /** The day, YYYY-MM-DD in the calendar's timezone. */
2173
- day: string;
2174
- /** Leave out to wait for any time that day. */
2175
- slotStart?: Date;
2176
- clientName: string;
2177
- clientEmail: string;
2178
- clientPhone?: string | null;
2179
- }
2180
- declare function joinWaitlist(db: SchedulingDb, input: JoinWaitlistInput, now?: Date): Promise<{
2181
- entry: WaitlistEntryView;
2182
- token: string;
2183
- }>;
2184
-
2185
- declare const DEFAULT_OFFER_MINUTES = 30;
2186
- interface WaitlistOffer {
2187
- entry: WaitlistEntryView;
2188
- /** The client's own handle; the host puts it in the link it sends. */
2189
- token: string;
2190
- calendarId: string;
2191
- calendarName: string;
2192
- typeName: string;
2193
- startTime: Date;
2194
- /** The timezone the client chose when they joined, for writing the time in their message. */
2195
- timezone: string;
2196
- expiresAt: Date;
2197
- }
2198
- /**
2199
- * Offers the slot to the longest-waiting entry that fits it: same day, a calendar and type that match, the slot still
2200
- * free. Returns null when nobody fits or the slot already has a live offer. The offer lasts `offerMinutes`, and never
2201
- * past the start of the slot. Two callers freeing the same slot cannot both offer it: the database holds one live
2202
- * offer per slot.
2203
- */
2204
- declare function offerFreedSlot(db: SchedulingDb, input: {
2205
- organizationId: string;
2206
- calendarId: string;
2207
- startTime: Date;
2208
- offerMinutes?: number;
2209
- now?: Date;
2210
- }): Promise<WaitlistOffer | null>;
2211
- /** As offerFreedSlot, but never throws: the cancellation that freed the slot is already saved. Logs a reference. */
2212
- declare function tryOfferFreedSlot(db: SchedulingDb, input: Parameters<typeof offerFreedSlot>[1]): Promise<WaitlistOffer | null>;
2213
- /**
2214
- * Ends offers whose time ran out, and sorts out an accept that started and never finished. An accept whose booking was
2215
- * saved becomes BOOKED; one whose booking never happened goes back in line. Returns the slots that came free either way
2216
- * (a lapsed offer, or an accept that never booked), so the caller can offer each to the next person.
2217
- */
2218
- declare function expireWaitlistOffers(db: SchedulingDb, options?: {
2219
- now?: Date;
2220
- acceptTimeoutMs?: number;
2221
- }): Promise<{
2222
- lapsed: Array<{
2223
- organizationId: string;
2224
- calendarId: string;
2225
- startTime: Date;
2226
- }>;
2227
- released: number;
2228
- booked: number;
2229
- }>;
2230
-
2231
- /** A slot that someone was holding an offer for and no longer is. The caller offers it to the next person. */
2232
- interface FreedSlot {
2233
- organizationId: string;
2234
- calendarId: string;
2235
- startTime: Date;
2236
- }
2237
- declare function listWaitlist(db: SchedulingDb, input: {
2238
- organizationId: string;
2239
- status?: string;
2240
- limit?: number;
2241
- offset?: number;
2242
- }): Promise<{
2243
- entries: WaitlistEntryView[];
2244
- total: number;
2245
- }>;
2246
- /**
2247
- * Removes an entry that is not mid-accept. When it held a live offer, the slot it held is returned so the caller can
2248
- * offer it to the next person.
2249
- */
2250
- declare function removeWaitlistEntry(db: SchedulingDb, organizationId: string, entryId: string): Promise<FreedSlot | null>;
2251
- /** The client leaves by their own link. Only an entry that is waiting or holding an offer can leave; a held slot is returned. */
2252
- declare function leaveWaitlist(db: SchedulingDb, token: string): Promise<FreedSlot | null>;
2253
-
2254
- interface OfferDetails {
2255
- entryId: string;
2256
- organizationId: string;
2257
- typeId: string;
2258
- typeName: string;
2259
- calendarId: string;
2260
- calendarName: string;
2261
- startTime: Date;
2262
- timezone: string;
2263
- expiresAt: Date;
2264
- clientName: string;
2265
- clientEmail: string;
2266
- clientPhone: string | null;
2267
- }
2268
- /** What the offer is, for the page the client opens. Throws SCHED_1106 when there is none and SCHED_1107 when it lapsed. */
2269
- declare function getWaitlistOffer(db: SchedulingDb, token: string, now?: Date): Promise<OfferDetails>;
2270
- /** Claims the offer so it can be accepted once. Two clicks at the same moment: one wins, the other gets SCHED_1106. */
2271
- declare function beginWaitlistAccept(db: SchedulingDb, token: string, now?: Date): Promise<OfferDetails>;
2272
- declare function completeWaitlistAccept(db: SchedulingDb, entryId: string, appointmentId: string): Promise<void>;
2273
- /**
2274
- * What to do with an accept whose booking did not happen.
2275
- * KEEP_OFFER: a temporary failure (busy, server error): the offer stays open until it expires.
2276
- * BACK_IN_LINE: the slot was taken: the client keeps their place and waits for another opening.
2277
- * DROP: the booking can never go through for this client (a booking rule refuses them): they come off the list and the
2278
- * slot is returned, so the caller can offer it to the next person.
2279
- */
2280
- type AcceptRelease = 'KEEP_OFFER' | 'BACK_IN_LINE' | 'DROP';
2281
- declare function releaseWaitlistAccept(db: SchedulingDb, entryId: string, outcome?: AcceptRelease): Promise<FreedSlot | null>;
2282
- interface SettledBooking {
2283
- id: string;
2284
- status: string;
2285
- startTime: Date;
2286
- endTime: Date;
2287
- manageToken: string | null;
2288
- clientName: string;
2289
- clientEmail: string;
2290
- }
2291
- /**
2292
- * Call this when an accept looks like it failed. A booking can be saved and a later step (messages, calendar sync) still
2293
- * fail, so the client may already hold the slot. When they do, the entry is marked BOOKED and the booking is returned;
2294
- * when they do not, this returns null and the caller releases the accept.
2295
- */
2296
- declare function settleBookedAccept(db: SchedulingDb, entryId: string): Promise<SettledBooking | null>;
2297
-
2298
- /** The calendar day an instant falls on in `timeZone`. */
2299
- declare function localDay(instant: Date, timeZone: string): string;
2300
-
2301
- type QuestionType = 'select' | 'radio' | 'checkbox' | 'text' | 'number';
2302
- interface RoutingQuestion {
2303
- id: string;
2304
- label: string;
2305
- type: QuestionType;
2306
- required: boolean;
2307
- /** The choices of a select, radio or checkbox question. */
2308
- options?: string[];
2309
- }
2310
- type RoutingOperator = 'equals' | 'not_equals' | 'in' | 'contains' | 'not_contains' | 'gt' | 'gte' | 'lt' | 'lte' | 'is_answered' | 'is_empty';
2311
- interface RoutingCondition {
2312
- questionId: string;
2313
- operator: RoutingOperator;
2314
- /** A text, a number or a list of choices, depending on the operator. Not used by is_answered and is_empty. */
2315
- value?: string | number | string[];
2316
- }
2317
- /** Where to send the client: an appointment type, a calendar, or a type on a given calendar. At least one is set. */
2318
- interface RoutingDestination {
2319
- typeId?: string;
2320
- calendarId?: string;
2321
- }
2322
- interface RoutingRule {
2323
- id: string;
2324
- label?: string;
2325
- /** `all`: every condition must hold. `any`: one is enough. */
2326
- match: 'all' | 'any';
2327
- conditions: RoutingCondition[];
2328
- destination: RoutingDestination;
2329
- }
2330
- /** What happens when no rule matches: send the client somewhere anyway, or show a message. */
2331
- type RoutingFallback = {
2332
- kind: 'DESTINATION';
2333
- destination: RoutingDestination;
2334
- } | {
2335
- kind: 'MESSAGE';
2336
- message: string;
2337
- };
2338
- interface RoutingFormDefinition {
2339
- questions: RoutingQuestion[];
2340
- rules: RoutingRule[];
2341
- fallback: RoutingFallback;
2342
- }
2343
- type RoutingAnswers = Record<string, string | number | string[]>;
2344
- interface RoutingProblem {
2345
- /** Where in the form, such as `rules[2].conditions[0].value`. */
2346
- path: string;
2347
- message: string;
2348
- }
2349
- declare const LIMITS: {
2350
- readonly questions: 20;
2351
- readonly rules: 50;
2352
- readonly conditionsPerRule: 10;
2353
- readonly options: 50;
2354
- readonly label: 200;
2355
- readonly option: 100;
2356
- readonly message: 500;
2357
- readonly textAnswer: 1000;
2358
- readonly problems: 50;
2359
- readonly formsPerOrganization: 50;
2360
- };
2361
-
2362
- /** Which operators each kind of question allows. */
2363
- declare const OPERATORS_BY_TYPE: Record<QuestionType, RoutingOperator[]>;
2364
- type StructureResult = {
2365
- ok: true;
2366
- value: RoutingFormDefinition;
2367
- } | {
2368
- ok: false;
2369
- problems: RoutingProblem[];
2370
- };
2371
- declare function validateRoutingStructure(input: unknown): StructureResult;
2372
-
2373
- declare function validateRoutingDestinations(db: SchedulingDb, organizationId: string, definition: RoutingFormDefinition): Promise<RoutingProblem[]>;
2374
-
2375
- type AnswerCheck = {
2376
- ok: true;
2377
- answers: RoutingAnswers;
2378
- } | {
2379
- ok: false;
2380
- problems: RoutingProblem[];
2381
- };
2382
- /** Checks the answers fit the questions: required ones present, choices among the options, nothing the form did not ask. */
2383
- declare function checkAnswers(questions: RoutingQuestion[], input: unknown): AnswerCheck;
2384
- /** Every rule the answers satisfy, in the order the rules are listed. The first is the one that wins. */
2385
- declare function matchingRules(definition: Pick<RoutingFormDefinition, 'rules'>, answers: RoutingAnswers): RoutingRule[];
2386
-
2387
- interface RoutingFormView extends RoutingFormDefinition {
2388
- id: string;
2389
- name: string;
2390
- slug: string;
2391
- description: string | null;
2392
- isActive: boolean;
2393
- createdAt: Date;
2394
- updatedAt: Date;
2395
- }
2396
- interface RoutingFormSummary {
2397
- id: string;
2398
- name: string;
2399
- slug: string;
2400
- description: string | null;
2401
- isActive: boolean;
2402
- updatedAt: Date;
2403
- }
2404
- interface RoutingFormInput {
2405
- name: string;
2406
- slug: string;
2407
- description?: string | null;
2408
- isActive?: boolean;
2409
- questions: unknown;
2410
- rules: unknown;
2411
- fallback: unknown;
2412
- }
2413
- declare function createRoutingForm(db: SchedulingDb, organizationId: string, input: RoutingFormInput): Promise<RoutingFormView>;
2414
- declare function getRoutingForm(db: SchedulingDb, organizationId: string, id: string): Promise<RoutingFormView>;
2415
- declare function listRoutingForms(db: SchedulingDb, organizationId: string): Promise<RoutingFormSummary[]>;
2416
- /** Changes the given fields and checks the whole result again, since a changed question can break an existing rule. */
2417
- declare function updateRoutingForm(db: SchedulingDb, organizationId: string, id: string, patch: Partial<RoutingFormInput>): Promise<RoutingFormView>;
2418
- declare function deleteRoutingForm(db: SchedulingDb, organizationId: string, id: string): Promise<void>;
2419
-
2420
- interface PublicRoutingForm {
2421
- name: string;
2422
- slug: string;
2423
- description: string | null;
2424
- questions: RoutingQuestion[];
2425
- }
2426
- interface ResolvedDestination {
2427
- typeId: string | null;
2428
- typeSlug: string | null;
2429
- typeName: string | null;
2430
- calendarId: string | null;
2431
- calendarSlug: string | null;
2432
- calendarName: string | null;
2433
- }
2434
- interface RoutingOutcome {
2435
- /** Where to send the client, or null when the form says to show `message` instead. */
2436
- destination: ResolvedDestination | null;
2437
- message: string | null;
2438
- /** The rule that decided it, or null when the fallback did. */
2439
- matchedRuleId: string | null;
2440
- usedFallback: boolean;
2441
- }
2442
- /** The questions only. The rules and the fallback stay on the server. */
2443
- declare function getPublicRoutingForm(db: SchedulingDb, input: {
2444
- organizationId: string | null;
2445
- slug: string;
2446
- }): Promise<PublicRoutingForm>;
2447
- /** Looks the destination up now: a type or calendar switched off since the form was saved is not sent to. */
2448
- declare function resolveDestination(db: SchedulingDb, organizationId: string, destination: RoutingDestination): Promise<ResolvedDestination | null>;
2449
- /**
2450
- * Sends a client on. The first matching rule whose destination is still live wins; if none is, the fallback decides.
2451
- * A form whose fallback destination is also gone tells the client to get in touch.
2452
- */
2453
- declare function routeClient(db: SchedulingDb, input: {
2454
- organizationId: string | null;
2455
- slug: string;
2456
- answers: unknown;
2457
- }): Promise<RoutingOutcome>;
2458
- /** Staff trying a form with sample answers. Works on a form that is switched off, and lists every rule that matched. */
2459
- declare function testRoutingForm(db: SchedulingDb, input: {
2460
- organizationId: string;
2461
- id: string;
2462
- answers: unknown;
2463
- }): Promise<RoutingOutcome & {
2464
- allMatchedRuleIds: string[];
2465
- }>;
2466
-
2467
- interface ParsedSubject {
2468
- email: string | null;
2469
- clientId: string | null;
2470
- }
2471
- interface ResolvedSubject {
2472
- /** Lower-case addresses, without repeats. */
2473
- emails: string[];
2474
- clientId: string | null;
2475
- }
2476
- /** Checks the request names somebody, and in a way that cannot match more than that person. */
2477
- declare function parseSubject(input: {
2478
- email?: unknown;
2479
- clientId?: unknown;
2480
- }): ParsedSubject;
2481
- /** One digest per identifier, tied to the organization. The request record keeps these instead of the address itself. */
2482
- declare function subjectHashes(organizationId: string, subject: ResolvedSubject): string[];
2483
- /** Adds the addresses a client id stands for: those on the client's bookings and series in this organization. */
2484
- declare function resolveSubject(db: SchedulingDb, organizationId: string, parsed: ParsedSubject): Promise<ResolvedSubject>;
2485
-
2486
- declare function collectSubjectRows(db: SchedulingDb, organizationId: string, subject: ResolvedSubject): Promise<{
2487
- appointments: {
2488
- couponCode: string | null;
2489
- startTime: Date;
2490
- cancelledAt: Date | null;
2491
- cancelledBy: string | null;
2492
- id: string;
2493
- type: {
2494
- name: string;
2495
- };
2496
- timezone: string;
2497
- location: string | null;
2498
- createdAt: Date;
2499
- updatedAt: Date;
2500
- calendar: {
2501
- name: string;
2502
- };
2503
- endTime: Date;
2504
- duration: number;
2505
- clientName: string;
2506
- clientEmail: string;
2507
- clientPhone: string | null;
2508
- clientId: string | null;
2509
- status: _prisma_client.$Enums.AppointmentStatus;
2510
- cancelReason: string | null;
2511
- rescheduledFrom: Date | null;
2512
- rescheduleCount: number;
2513
- intakeResponses: _prisma_client_runtime_client.JsonValue;
2514
- paymentStatus: string | null;
2515
- paymentAmount: _prisma_client_runtime_client.Decimal | null;
2516
- depositAmount: _prisma_client_runtime_client.Decimal | null;
2517
- tipAmount: _prisma_client_runtime_client.Decimal | null;
2518
- paymentProvider: string | null;
2519
- paymentId: string | null;
2520
- balancePaymentId: string | null;
2521
- discountAmount: _prisma_client_runtime_client.Decimal | null;
2522
- cancellationFeeAmount: _prisma_client_runtime_client.Decimal | null;
2523
- refundAmount: _prisma_client_runtime_client.Decimal | null;
2524
- refundStatus: _prisma_client.$Enums.RefundStatus | null;
2525
- isGroup: boolean;
2526
- notes: string | null;
2527
- staffNotes: string | null;
2528
- meetingUrl: string | null;
2529
- recurringId: string | null;
2530
- recurringIndex: number | null;
2531
- packagePurchaseId: string | null;
2532
- }[];
2533
- notifications: never[] | {
2534
- id: string;
2535
- createdAt: Date;
2536
- status: string;
2537
- appointmentId: string;
2538
- channel: string;
2539
- trigger: string;
2540
- recipient: string;
2541
- subject: string | null;
2542
- body: string;
2543
- scheduledFor: Date;
2544
- sentAt: Date | null;
2545
- }[];
2546
- waitlistEntries: never[] | {
2547
- id: string;
2548
- timezone: string;
2549
- createdAt: Date;
2550
- calendarId: string | null;
2551
- day: string;
2552
- typeId: string;
2553
- clientName: string;
2554
- clientEmail: string;
2555
- clientPhone: string | null;
2556
- status: string;
2557
- slotStart: Date | null;
2558
- offerSlotStart: Date | null;
2559
- offerExpiresAt: Date | null;
2560
- offeredAt: Date | null;
2561
- bookedAppointmentId: string | null;
2562
- }[];
2563
- packagePurchases: never[] | {
2564
- id: string;
2565
- createdAt: Date;
2566
- clientName: string | null;
2567
- clientEmail: string;
2568
- status: _prisma_client.$Enums.PackagePurchaseStatus;
2569
- paymentId: string | null;
2570
- notes: string | null;
2571
- expiresAt: Date | null;
2572
- packageId: string;
2573
- sessionsTotal: number;
2574
- sessionsUsed: number;
2575
- purchasedAt: Date;
2576
- pricePaidCents: number | null;
2577
- }[];
2578
- recurringSeries: never[] | {
2579
- id: string;
2580
- timezone: string;
2581
- createdAt: Date;
2582
- calendarId: string;
2583
- typeId: string;
2584
- clientName: string;
2585
- clientEmail: string;
2586
- clientPhone: string | null;
2587
- clientId: string | null;
2588
- status: _prisma_client.$Enums.RecurringSeriesStatus;
2589
- notes: string | null;
2590
- frequency: _prisma_client.$Enums.RecurringFrequency;
2591
- occurrences: number;
2592
- startTimeLocal: string;
2593
- durationMins: number;
2594
- endsAt: Date | null;
2595
- }[];
2596
- webhookDeliveries: {
2597
- id: string;
2598
- eventId: string;
2599
- eventType: string;
2600
- body: string;
2601
- status: string;
2602
- createdAt: Date;
2603
- }[];
2604
- }>;
2605
- type SubjectRows = Awaited<ReturnType<typeof collectSubjectRows>>;
2606
- interface SubjectCounts {
2607
- appointments: number;
2608
- notifications: number;
2609
- waitlistEntries: number;
2610
- packagePurchases: number;
2611
- recurringSeries: number;
2612
- webhookDeliveries: number;
2613
- }
2614
-
2615
- interface SubjectExport {
2616
- format: 'ordinatio-scheduling-subject-export';
2617
- version: 1;
2618
- exportedAt: string;
2619
- organizationId: string;
2620
- subject: {
2621
- emails: string[];
2622
- clientId: string | null;
2623
- };
2624
- counts: SubjectCounts;
2625
- appointments: Array<Omit<SubjectRows['appointments'][number], 'calendar' | 'type'> & {
2626
- calendarName: string;
2627
- typeName: string;
2628
- }>;
2629
- notifications: SubjectRows['notifications'];
2630
- waitlistEntries: SubjectRows['waitlistEntries'];
2631
- packagePurchases: SubjectRows['packagePurchases'];
2632
- recurringSeries: SubjectRows['recurringSeries'];
2633
- webhookDeliveries: SubjectRows['webhookDeliveries'];
2634
- }
2635
- declare function exportSubject(db: SchedulingDb, input: {
2636
- organizationId: string;
2637
- requestedBy: string;
2638
- email?: unknown;
2639
- clientId?: unknown;
2640
- now?: Date;
2641
- }): Promise<SubjectExport>;
2642
-
2643
- declare const ERASED_NAME = "Erased client";
2644
- declare const ERASED_EMAIL = "erased@erased.invalid";
2645
- interface EraseBlockers {
2646
- upcomingAppointments: number;
2647
- liveWaitlistEntries: number;
2648
- }
2649
- interface ErasePreview {
2650
- counts: SubjectCounts;
2651
- blockers: EraseBlockers;
2652
- canErase: boolean;
2653
- warnings: string[];
2654
- }
2655
- /** What an erasure would remove and whether anything stops it. Changes and records nothing. */
2656
- declare function previewErase(db: SchedulingDb, input: {
2657
- organizationId: string;
2658
- email?: unknown;
2659
- clientId?: unknown;
2660
- now?: Date;
2661
- }): Promise<ErasePreview>;
2662
- declare function eraseSubject(db: SchedulingDb, input: {
2663
- organizationId: string;
2664
- requestedBy: string;
2665
- email?: unknown;
2666
- clientId?: unknown;
2667
- now?: Date;
2668
- }): Promise<{
2669
- counts: SubjectCounts;
2670
- }>;
2671
-
2672
- type PrivacyRequestKind = 'EXPORT' | 'ERASE';
2673
- interface PrivacyRequestView {
2674
- id: string;
2675
- kind: string;
2676
- requestedBy: string;
2677
- counts: unknown;
2678
- createdAt: Date;
2679
- }
2680
- declare function listPrivacyRequests(db: SchedulingDb, input: {
2681
- organizationId: string;
2682
- limit?: number;
2683
- offset?: number;
2684
- }): Promise<{
2685
- requests: PrivacyRequestView[];
2686
- total: number;
2687
- }>;
2688
-
2689
- interface BrandFields {
2690
- displayName: string;
2691
- logoUrl: string | null;
2692
- primaryColor: string | null;
2693
- accentColor: string | null;
2694
- backgroundColor: string | null;
2695
- textColor: string | null;
2696
- fontFamily: string | null;
2697
- footerText: string | null;
2698
- replyToEmail: string | null;
2699
- fromName: string | null;
2700
- fromEmail: string | null;
2701
- }
2702
- interface BrandView extends BrandFields {
2703
- updatedAt: Date;
2704
- }
2705
- /** What a visitor of the booking page may see: no email addresses. */
2706
- interface PublicBrand {
2707
- displayName: string;
2708
- logoUrl: string | null;
2709
- primaryColor: string | null;
2710
- accentColor: string | null;
2711
- backgroundColor: string | null;
2712
- textColor: string | null;
2713
- fontFamily: string | null;
2714
- footerText: string | null;
2715
- }
2716
- interface BrandProblem {
2717
- path: string;
2718
- message: string;
2719
- }
2720
- declare const BRAND_FIELDS: readonly ["displayName", "logoUrl", "primaryColor", "accentColor", "backgroundColor", "textColor", "fontFamily", "footerText", "replyToEmail", "fromName", "fromEmail"];
2721
-
2722
- interface ValidateBrandOptions {
2723
- /**
2724
- * Says whether the host may send mail from this domain (lower case). Without it no sending address is accepted: an
2725
- * organization must not be able to send as a domain it does not control.
2726
- */
2727
- isSendingDomainVerified?: (domain: string) => Promise<boolean>;
2728
- }
2729
- /** The stored form of the settings, or a SCHED_1400 error listing every problem. */
2730
- declare function validateBrand(input: unknown, options: ValidateBrandOptions): Promise<BrandFields>;
2731
-
2732
- declare function getBrand(db: SchedulingDb, organizationId: string): Promise<BrandView | null>;
2733
- /**
2734
- * What the booking page may show. With no organization named (a server with one organization) it is the brand of the
2735
- * only organization that has one; with several, none is chosen for the visitor.
2736
- */
2737
- declare function getPublicBrand(db: SchedulingDb, organizationId: string | null): Promise<PublicBrand | null>;
2738
- /** Saves the whole brand, replacing what was there. Throws SCHED_1400 listing every problem. */
2739
- declare function saveBrand(db: SchedulingDb, organizationId: string, input: unknown, options: ValidateBrandOptions): Promise<BrandView>;
2740
- /** Removes the brand. True when there was one. */
2741
- declare function deleteBrand(db: SchedulingDb, organizationId: string): Promise<boolean>;
2742
-
2743
- /** The sender of an organization's messages, or null when there is no brand. Only what is set is included. */
2744
- declare function senderIdentity(brand: BrandFields | null): SenderIdentity | null;
2745
- /** Values for `{{brandName}}`, `{{brandLogoUrl}}`, `{{brandColor}}` and `{{brandFooter}}`; empty text when not set. */
2746
- declare function brandTemplateFields(brand: BrandFields | null): Record<string, string>;
2747
- declare function toPublicBrand(brand: BrandFields): PublicBrand;
2748
-
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
- /** READ may only look things up; FULL may also change them. */
2783
- declare const API_KEY_ACCESS: readonly ["READ", "FULL"];
2784
- type ApiKeyAccess = (typeof API_KEY_ACCESS)[number];
2785
- declare const API_KEY_FIELDS: readonly ["name", "access"];
2786
- declare const MAX_ACTIVE_API_KEYS = 25;
2787
- declare const API_KEY_NAME_MAX = 60;
2788
- interface ApiKeyFields {
2789
- /** What the key is for, such as "Zapier". Shown in the list so the owner can tell keys apart. */
2790
- name: string;
2791
- access: ApiKeyAccess;
2792
- }
2793
- /** A key as listed: never the secret, only enough to recognise it. */
2794
- interface ApiKeyView extends ApiKeyFields {
2795
- id: string;
2796
- /** The first characters of the key, so the owner can match a list entry to a key they hold. */
2797
- prefix: string;
2798
- createdByUserId: string | null;
2799
- createdAt: Date;
2800
- lastUsedAt: Date | null;
2801
- revokedAt: Date | null;
2802
- }
2803
- /** Returned once, when a key is created. The secret cannot be read again. */
2804
- interface CreatedApiKey {
2805
- key: string;
2806
- view: ApiKeyView;
2807
- }
2808
- /** Who a valid key acts as. */
2809
- interface VerifiedApiKey {
2810
- id: string;
2811
- organizationId: string;
2812
- access: ApiKeyAccess;
2813
- createdByUserId: string | null;
2814
- }
2815
-
2816
- /** The cleaned-up request for a new key, or a SCHED_1600 error listing every problem. */
2817
- declare function validateApiKeyRequest(input: unknown): ApiKeyFields;
2818
-
2819
- /** True when the text has the shape of a key, so a request with some other credential is never looked up. */
2820
- declare function looksLikeApiKey(text: string): boolean;
2821
-
2822
- /**
2823
- * Makes a key for the business. The secret is in the result once and cannot be read again.
2824
- * Throws SCHED_1600 for a bad request and SCHED_1601 when the business already has the most keys it may have.
2825
- * The limit is checked just before the key is written, so two requests at the same moment can pass it together.
2826
- */
2827
- declare function createApiKey(db: SchedulingDb, organizationId: string, input: unknown, createdByUserId?: string): Promise<CreatedApiKey>;
2828
- /** Every key of the business, newest first, revoked ones included. Never the secret. */
2829
- declare function listApiKeys(db: SchedulingDb, organizationId: string): Promise<ApiKeyView[]>;
2830
- /** Stops a key from working. True when it was active; false for an unknown, other-business or already revoked key. */
2831
- declare function revokeApiKey(db: SchedulingDb, organizationId: string, id: string): Promise<boolean>;
2832
- /** Who a secret acts as, or null when it is not a live key. Never throws for a bad secret. */
2833
- declare function verifyApiKey(db: SchedulingDb, secret: string): Promise<VerifiedApiKey | null>;
2834
-
2835
- export { API_KEY_ACCESS, API_KEY_FIELDS, API_KEY_NAME_MAX, type AcceptRelease, type AddTimeBlockInput, type ApiKeyAccess, type ApiKeyFields, type ApiKeyView, 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, type CreatedApiKey, 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_ACTIVE_API_KEYS, 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, type VerifiedApiKey, 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, createApiKey, 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, listApiKeys, listAppointmentTypes, listAppointments, listAvailabilityRules, listCalendars, listNotificationTemplates, listPrivacyRequests, listRoutingForms, listWaitlist, listWebhookDeliveries, listWebhookEndpoints, localDay, localToUTC, looksLikeApiKey, markNoShow, matchingRules, normalizeTextNumber, offerFreedSlot, parseSubject, parseTimeLocal, previewErase, processPendingNotifications, queueImmediateNotification, queueStaffNotification, releaseWaitlistAccept, removeDateOverride, removeWaitlistEntry, renderTemplate, rescheduleAppointment, resolveDestination, resolveLocation, resolveSubject, retryWebhookDelivery, revokeApiKey, routeClient, saveBrand, saveTextSettings, schedError, scheduleNotifications, scopeToOrganization, selectCalendarForBooking, sendTestWebhook, senderIdentity, setWeeklyAvailability, settleBookedAccept, signWebhook, subjectHashes, testRoutingForm, toPublicBrand, tryOfferFreedSlot, updateAppointmentType, updateCalendar, updateNotificationTemplate, updateRoutingForm, validateApiKeyRequest, validateBrand, validateRoutingDestinations, validateRoutingStructure, validateTextSettings, verifyApiKey, verifyWebhookSignature, withCalendarVisibility, withOrganization };