@astratra/booking 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Astratra
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,173 @@
1
+ # @astratra/booking
2
+
3
+ Prise de rendez-vous : calcul des créneaux libres et réservation **sans
4
+ double réservation**. Pour l'accueil d'une entreprise (module Accueil de
5
+ Cortex), un salon (Barber Clean), une salle de réunion, un cours collectif.
6
+
7
+ Aucune dépendance. Les fuseaux horaires passent par `Intl`, inclus dans Node.
8
+
9
+ ## Le problème
10
+
11
+ « Afficher les créneaux libres » cache plusieurs pièges :
12
+
13
+ - **les fuseaux et les changements d'heure** : 09:00 à Paris vaut 08:00 UTC
14
+ en hiver et 07:00 UTC en été ; la nuit du changement, une heure n'existe
15
+ pas ou existe deux fois ;
16
+ - **les tampons** : le nettoyage après une coupe bloque le fauteuil, sans
17
+ être une prestation ;
18
+ - **la concurrence** : deux clients cliquent sur le dernier créneau à la même
19
+ seconde ; un seul doit l'obtenir, même avec quatre processus serveur.
20
+
21
+ ## Ressources et prestations
22
+
23
+ Une **ressource** est ce qui se réserve : une personne, une salle, un siège.
24
+ Ses horaires s'écrivent en heure murale de **son** fuseau.
25
+
26
+ ```js
27
+ const barbier = {
28
+ id: 'barbier-1',
29
+ timeZone: 'Africa/Kinshasa',
30
+ country: 'CD', // ses jours fériés ferment la ressource
31
+ capacity: 1, // places en même temps (cours collectif : 12)
32
+ weekly: {
33
+ monday: [['09:00', '12:00'], ['14:00', '18:00']],
34
+ saturday: [['09:00', '13:00']]
35
+ },
36
+ exceptions: [
37
+ { from: '2026-08-01', to: '2026-08-15', reason: 'congés' }, // période fermée, bornes incluses
38
+ { date: '2026-12-24', intervals: [['09:00', '13:00']] }, // horaires spéciaux
39
+ { date: '2026-06-30', intervals: [['10:00', '12:00']] }, // ouvert un jour férié
40
+ { date: '2026-07-03', closed: true }
41
+ ]
42
+ };
43
+
44
+ const coupe = {
45
+ id: 'coupe',
46
+ duration: 30, // minutes
47
+ bufferBefore: 0,
48
+ bufferAfter: 10, // nettoyage
49
+ step: 15, // un créneau tous les quarts d'heure (la durée par défaut)
50
+ minNotice: 120, // pas de réservation à moins de 2 h
51
+ horizon: 30 // pas au-delà de 30 jours
52
+ };
53
+ ```
54
+
55
+ ## Calculer les créneaux (sans base)
56
+
57
+ ```js
58
+ const { computeSlots } = require('@astratra/booking');
59
+
60
+ const creneaux = computeSlots({
61
+ resources: [barbier],
62
+ service: coupe,
63
+ from: '2026-06-29T00:00:00Z',
64
+ to: '2026-07-06T00:00:00Z',
65
+ bookings, // rendez-vous déjà pris
66
+ busy, // indisponibilités externes { resourceId, start, end } (agenda, réunion)
67
+ mode: 'each', // each | any | all
68
+ timeZone: 'Africa/Lubumbashi' // fuseau d'affichage de `local` (celui de la 1re ressource sinon)
69
+ });
70
+ // → [{ start: '2026-06-29T08:00:00.000Z', end: '…', resourceIds: ['barbier-1'], available: 1,
71
+ // local: { date: '2026-06-29', time: '09:00', offset: '+01:00' } }, …]
72
+ ```
73
+
74
+ - `each` : un créneau par ressource ;
75
+ - `any` : au moins une ressource libre (« n'importe quel coiffeur ») ;
76
+ - `all` : toutes libres en même temps (coiffeur **et** fauteuil, expert à
77
+ Kinshasa **et** salle à Lubumbashi).
78
+
79
+ ## Les règles, qui ne changent pas
80
+
81
+ 1. La prestation tient dans une plage d'ouverture. Les tampons ne servent qu'à
82
+ écarter les autres rendez-vous et peuvent déborder l'horaire.
83
+ 2. Deux rendez-vous se gênent si leurs plages **tampons compris** se
84
+ chevauchent ; chacun garde les tampons de sa propre prestation.
85
+ 3. Un créneau est réservable s'il reste au moins `seats` places sur toute sa
86
+ durée, tampons compris.
87
+ 4. Préavis : début au plus tôt `minNotice` minutes après maintenant. Horizon :
88
+ début au plus tard `horizon` jours après.
89
+ 5. Priorité pour un jour : exception datée > période fermée > jour férié >
90
+ horaires de la semaine.
91
+ 6. Changement d'heure, tranché comme Temporal : une heure inexistante
92
+ (02:30 au printemps) avance d'autant (03:30) ; une heure ambiguë (02:30 à
93
+ l'automne) prend la première. Une plage 01:00–04:00 dure donc 2 h la nuit
94
+ du passage à l'heure d'été et 4 h la nuit du retour.
95
+
96
+ ## Réserver, annuler, reporter
97
+
98
+ ```js
99
+ const { createBookingService, createPostgresBookingStore } = require('@astratra/booking');
100
+
101
+ const reservations = createBookingService({
102
+ store: createPostgresBookingStore({ pool }),
103
+ resources: [barbier, barbier2, fauteuil], // ou async (id) => ressource
104
+ services: { coupe }
105
+ });
106
+
107
+ await reservations.getSlots({ resourceIds: ['barbier-1'], service: 'coupe', from, to });
108
+ const rdv = await reservations.book({ resourceIds: ['barbier-1'], service: 'coupe', start, data: { clientId } });
109
+ await reservations.book({ anyOf: ['barbier-1', 'barbier-2'], service: 'coupe', start }); // le premier libre
110
+ await reservations.book({ resourceIds: ['barbier-1', 'fauteuil-1'], service: 'coupe', start }); // les deux ensemble
111
+ await reservations.reschedule(rdv.id, { start: autreDebut }); // l'ancien horaire part dans `history`
112
+ await reservations.cancel(rdv.id, { reason: 'client malade' }); // les places se libèrent aussitôt
113
+ ```
114
+
115
+ `book` et `reschedule` relisent les rendez-vous **sous verrou**, recalculent
116
+ le créneau avec les mêmes règles que `getSlots`, puis écrivent. Erreurs
117
+ (`BookingError`, champ `code`) :
118
+
119
+ | Code | Sens |
120
+ | --- | --- |
121
+ | `SLOT_TAKEN` | le créneau existe mais n'a plus assez de places |
122
+ | `SLOT_UNAVAILABLE` | jamais proposé : hors horaires, hors grille, préavis, horizon, fermeture |
123
+ | `BOOKING_NOT_FOUND` | rendez-vous inconnu |
124
+ | `BOOKING_CANCELLED` | on ne reporte pas un rendez-vous annulé |
125
+ | `RESOURCE_NOT_FOUND` | ressource inconnue |
126
+
127
+ Un report reprend la prestation du rendez-vous par son id dans `services` ;
128
+ si elle n'y est pas, passe `service` à `reschedule`.
129
+
130
+ ## Stockage
131
+
132
+ | Fabrique | Exclusivité |
133
+ | --- | --- |
134
+ | `createMemoryBookingStore()` | file d'attente par ressource (un seul processus : tests, outils) |
135
+ | `createPostgresBookingStore({ pool, prefix })` | transaction + `SELECT … FOR UPDATE` sur une ligne de verrou par ressource |
136
+ | `createMongoBookingStore({ db, prefix, leaseMs, waitMs })` | bail : un document de verrou par ressource (`_id` unique), repris s'il expire ; marche sans jeu de réplicas |
137
+
138
+ Plusieurs ressources se verrouillent toujours dans le même ordre : deux
139
+ réservations croisées ne s'attendent jamais l'une l'autre.
140
+
141
+ Pour une autre base, fournis `listBookings(resourceId, from, to)`,
142
+ `getBooking(id)` et `transaction(resourceIds, travail)`, où `travail(tx)`
143
+ s'exécute en exclusivité sur ces ressources et n'écrit rien s'il lève.
144
+
145
+ ## Jours fériés
146
+
147
+ ```js
148
+ const { getPublicHolidays, HOLIDAY_COUNTRIES } = require('@astratra/booking');
149
+ getPublicHolidays('CD', 2026); // [{ date: '2026-01-01', id: 'new-year', name: 'Nouvel An' }, …]
150
+ ```
151
+
152
+ Pays fournis : RDC (`CD`), France (`FR`), Belgique (`BE`). Ce sont des
153
+ données : un autre pays (ou une liste officielle qui change) se passe en
154
+ `calendars: { CG: (annee) => [...] }` à `computeSlots` ou au service. Vérifie
155
+ la liste de ton pays avant la mise en production : un décret peut ajouter un
156
+ jour.
157
+
158
+ ## Tests
159
+
160
+ `npm test` : une semaine de créneaux avec jour férié, congé, horaires
161
+ spéciaux et tampons ; préavis et horizon ; Paris aux deux changements d'heure ;
162
+ Kinshasa et Lubumbashi ensemble ; capacité ; réservation, double
163
+ réservation refusée (20 demandes simultanées, une seule passe), annulation,
164
+ report, sur la mémoire, PostgreSQL (pg-mem) et MongoDB (mongodb-memory-server).
165
+
166
+ PostgreSQL réel (vrais verrous) : `ASTRATRA_TEST_PG_URL=postgresql:///base_jetable npm test`.
167
+ Les tables `essai_bookings` et `essai_locks` sont supprimées à la fin.
168
+
169
+ ## Origine
170
+
171
+ La logique s'inspire des idées de disponibilités de Cal.com (horaires
172
+ hebdomadaires, exceptions datées, tampons, préavis, horizon glissant,
173
+ places). Aucun code n'en est repris : tout est réécrit ici.
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@astratra/booking",
3
+ "version": "1.0.0",
4
+ "description": "Appointment slot engine without a database: weekly availability per resource, exceptions and public holidays, time zones and daylight saving, service duration, buffers, minimum notice, horizon, capacity, and atomic booking through an injected store (book fails on conflict), cancel and reschedule.",
5
+ "engines": {
6
+ "node": ">=20"
7
+ },
8
+ "main": "src/index.js",
9
+ "types": "src/index.d.ts",
10
+ "type": "commonjs",
11
+ "files": [
12
+ "src",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "scripts": {
17
+ "test": "jest --runInBand"
18
+ },
19
+ "jest": {
20
+ "testMatch": [
21
+ "**/__tests__/**/*.test.js"
22
+ ]
23
+ },
24
+ "keywords": [
25
+ "astratra",
26
+ "booking",
27
+ "appointments",
28
+ "availability",
29
+ "slots",
30
+ "scheduling",
31
+ "timezone"
32
+ ],
33
+ "license": "MIT",
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "devDependencies": {
38
+ "jest": "30.4.2",
39
+ "mongodb-memory-server": "^10.2.0",
40
+ "mongoose": "^8.17.0",
41
+ "pg": "^8.13.1",
42
+ "pg-mem": "^3.0.5"
43
+ }
44
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Jours fériés par pays (code ISO 3166-1 alpha-2).
3
+ *
4
+ * Ce sont des DONNÉES : chaque pays est une fonction année → liste de dates.
5
+ * Un pays absent se fournit par l'application (`calendars`), et une liste
6
+ * officielle qui change (un décret ajoute un jour) se corrige ici sans
7
+ * toucher au calcul des créneaux. `name` est le nom officiel dans la langue
8
+ * du pays, `id` une clé stable pour la traduction.
9
+ */
10
+
11
+ const { addDays } = require('./time');
12
+
13
+ const pad = (n) => String(n).padStart(2, '0');
14
+
15
+ /** Dimanche de Pâques (calendrier grégorien, algorithme dit « anonyme »). */
16
+ function easterSunday(year) {
17
+ const a = year % 19;
18
+ const b = Math.floor(year / 100);
19
+ const c = year % 100;
20
+ const d = Math.floor(b / 4);
21
+ const e = b % 4;
22
+ const f = Math.floor((b + 8) / 25);
23
+ const g = Math.floor((b - f + 1) / 3);
24
+ const h = (19 * a + b - d - g + 15) % 30;
25
+ const i = Math.floor(c / 4);
26
+ const k = c % 4;
27
+ const l = (32 + 2 * e + 2 * i - h - k) % 7;
28
+ const m = Math.floor((a + 11 * h + 22 * l) / 451);
29
+ const mois = Math.floor((h + l - 7 * m + 114) / 31);
30
+ const jour = ((h + l - 7 * m + 114) % 31) + 1;
31
+ return `${year}-${pad(mois)}-${pad(jour)}`;
32
+ }
33
+
34
+ const fixe = (year, mmjj, id, name) => ({ date: `${year}-${mmjj}`, id, name });
35
+ const paques = (year, decalage, id, name) => ({ date: addDays(easterSunday(year), decalage), id, name });
36
+
37
+ const CALENDRIERS = {
38
+ // République démocratique du Congo (liste complétée en 2023 : 6 avril et 2 août).
39
+ CD: (year) => [
40
+ fixe(year, '01-01', 'new-year', 'Nouvel An'),
41
+ fixe(year, '01-04', 'independence-martyrs', 'Journée des martyrs de l’indépendance'),
42
+ fixe(year, '01-16', 'laurent-desire-kabila', 'Journée du héros national Laurent-Désiré Kabila'),
43
+ fixe(year, '01-17', 'patrice-lumumba', 'Journée du héros national Patrice Emery Lumumba'),
44
+ fixe(year, '04-06', 'simon-kimbangu', 'Journée du combat de Simon Kimbangu et de la conscience africaine'),
45
+ fixe(year, '05-01', 'labour-day', 'Fête du travail'),
46
+ fixe(year, '05-17', 'liberation-day', 'Journée de la révolution et de la libération'),
47
+ fixe(year, '06-30', 'independence-day', 'Fête de l’indépendance'),
48
+ fixe(year, '08-01', 'parents-day', 'Fête des parents'),
49
+ fixe(year, '08-02', 'genocost', 'Journée de commémoration du génocide congolais'),
50
+ fixe(year, '12-25', 'christmas', 'Noël')
51
+ ],
52
+ FR: (year) => [
53
+ fixe(year, '01-01', 'new-year', 'Jour de l’an'),
54
+ paques(year, 1, 'easter-monday', 'Lundi de Pâques'),
55
+ fixe(year, '05-01', 'labour-day', 'Fête du Travail'),
56
+ fixe(year, '05-08', 'victory-1945', 'Victoire 1945'),
57
+ paques(year, 39, 'ascension', 'Ascension'),
58
+ paques(year, 50, 'whit-monday', 'Lundi de Pentecôte'),
59
+ fixe(year, '07-14', 'national-day', 'Fête nationale'),
60
+ fixe(year, '08-15', 'assumption', 'Assomption'),
61
+ fixe(year, '11-01', 'all-saints', 'Toussaint'),
62
+ fixe(year, '11-11', 'armistice-1918', 'Armistice 1918'),
63
+ fixe(year, '12-25', 'christmas', 'Noël')
64
+ ],
65
+ BE: (year) => [
66
+ fixe(year, '01-01', 'new-year', 'Nouvel An'),
67
+ paques(year, 1, 'easter-monday', 'Lundi de Pâques'),
68
+ fixe(year, '05-01', 'labour-day', 'Fête du Travail'),
69
+ paques(year, 39, 'ascension', 'Ascension'),
70
+ paques(year, 50, 'whit-monday', 'Lundi de Pentecôte'),
71
+ fixe(year, '07-21', 'national-day', 'Fête nationale'),
72
+ fixe(year, '08-15', 'assumption', 'Assomption'),
73
+ fixe(year, '11-01', 'all-saints', 'Toussaint'),
74
+ fixe(year, '11-11', 'armistice-1918', 'Armistice'),
75
+ fixe(year, '12-25', 'christmas', 'Noël')
76
+ ]
77
+ };
78
+
79
+ /**
80
+ * @param {string} country code pays (CD, FR, BE… ou un pays de `calendars`).
81
+ * @param {number} year
82
+ * @param {Record<string, (year: number) => Array<{date: string, id?: string, name?: string}>>} [calendars]
83
+ * calendriers fournis par l'application ; ils priment sur ceux du paquet.
84
+ */
85
+ function getPublicHolidays(country, year, calendars = {}) {
86
+ const code = String(country).toUpperCase();
87
+ const calendrier = calendars[code] || CALENDRIERS[code];
88
+ if (!calendrier) throw new RangeError(`Aucun calendrier de jours fériés pour le pays ${code}.`);
89
+ return calendrier(year).slice().sort((a, b) => a.date.localeCompare(b.date));
90
+ }
91
+
92
+ const HOLIDAY_COUNTRIES = Object.keys(CALENDRIERS);
93
+
94
+ module.exports = { getPublicHolidays, easterSunday, HOLIDAY_COUNTRIES };
package/src/index.d.ts ADDED
@@ -0,0 +1,190 @@
1
+ export type Weekday = 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday' | 'sunday';
2
+ /** « HH:MM » ; « 24:00 » accepté en fin de plage. */
3
+ export type WallTime = string;
4
+ export type TimeRange = [WallTime, WallTime] | { start: WallTime; end: WallTime };
5
+ export type Instant = Date | string | number;
6
+
7
+ export type ResourceException =
8
+ | { date: string; closed: true; reason?: string }
9
+ /** Horaires spéciaux ce jour-là : remplacent ceux de la semaine (et ouvrent un jour férié). */
10
+ | { date: string; intervals: TimeRange[]; reason?: string }
11
+ /** Période fermée, bornes incluses (congés). */
12
+ | { from: string; to: string; closed?: true; reason?: string };
13
+
14
+ export interface Resource {
15
+ id: string;
16
+ /** Fuseau IANA : 'Africa/Kinshasa', 'Africa/Lubumbashi', 'Europe/Paris'… */
17
+ timeZone: string;
18
+ weekly?: Partial<Record<Weekday, TimeRange[]>>;
19
+ exceptions?: ResourceException[];
20
+ /** Places en même temps (1 par défaut). */
21
+ capacity?: number;
22
+ /** Code pays ISO : ses jours fériés ferment la ressource. */
23
+ country?: string;
24
+ /** false : la ressource travaille les jours fériés. */
25
+ holidays?: boolean;
26
+ }
27
+
28
+ export interface Service {
29
+ id?: string | null;
30
+ /** Durée de la prestation, en minutes. */
31
+ duration: number;
32
+ bufferBefore?: number;
33
+ bufferAfter?: number;
34
+ /** Écart entre deux débuts de créneau, en minutes (la durée par défaut). */
35
+ step?: number;
36
+ /** Préavis minimal, en minutes. */
37
+ minNotice?: number;
38
+ /** Horizon maximal, en jours (60 par défaut). */
39
+ horizon?: number;
40
+ }
41
+
42
+ export interface BusyBlock {
43
+ resourceId: string;
44
+ start: Instant;
45
+ end: Instant;
46
+ }
47
+
48
+ export type BookingStatus = 'confirmed' | 'cancelled';
49
+
50
+ export interface Booking {
51
+ id: string;
52
+ resourceIds: string[];
53
+ start: string;
54
+ end: string;
55
+ bufferBefore: number;
56
+ bufferAfter: number;
57
+ seats: number;
58
+ status: BookingStatus;
59
+ serviceId: string | null;
60
+ data: unknown;
61
+ history: Array<{ start: string; end: string; resourceIds: string[]; movedAt: string }>;
62
+ cancelReason: string | null;
63
+ cancelledAt: string | null;
64
+ createdAt: string;
65
+ updatedAt: string;
66
+ }
67
+
68
+ export type SlotMode = 'each' | 'any' | 'all';
69
+
70
+ export interface ZonedTime {
71
+ date: string;
72
+ time: string;
73
+ offset: string;
74
+ }
75
+
76
+ export interface Slot {
77
+ start: string;
78
+ end: string;
79
+ resourceIds: string[];
80
+ /** Places encore libres (somme en mode any, minimum en mode all). */
81
+ available: number;
82
+ /** Heure murale dans le fuseau d'affichage. */
83
+ local: ZonedTime;
84
+ }
85
+
86
+ export type HolidayCalendars = Record<string, (year: number) => Array<{ date: string; id?: string; name?: string }>>;
87
+
88
+ export interface ComputeSlotsInput {
89
+ resources: Resource[];
90
+ service: Service;
91
+ from: Instant;
92
+ to: Instant;
93
+ now?: Instant;
94
+ bookings?: Array<Pick<Booking, 'resourceIds' | 'start' | 'end'> & Partial<Booking>>;
95
+ busy?: BusyBlock[];
96
+ mode?: SlotMode;
97
+ seats?: number;
98
+ timeZone?: string;
99
+ calendars?: HolidayCalendars;
100
+ }
101
+
102
+ export function computeSlots(input: ComputeSlotsInput): Slot[];
103
+
104
+ /* ---------- Stockage ---------- */
105
+
106
+ export interface BookingTransaction {
107
+ listBookings(resourceId: string, from: string, to: string): Promise<Booking[]>;
108
+ getBooking(id: string): Promise<Booking | null>;
109
+ insert(booking: Booking): Promise<void>;
110
+ update(id: string, patch: Partial<Booking>): Promise<void>;
111
+ }
112
+
113
+ export interface BookingStore {
114
+ listBookings(resourceId: string, from: string, to: string): Promise<Booking[]>;
115
+ getBooking(id: string): Promise<Booking | null>;
116
+ /** Exécute `work` en exclusivité sur ces ressources ; rien n'est écrit s'il lève. */
117
+ transaction<T>(resourceIds: string[], work: (tx: BookingTransaction) => Promise<T>): Promise<T>;
118
+ }
119
+
120
+ export function assertBookingStore<T extends BookingStore>(store: T): T;
121
+ export function createMemoryBookingStore(): BookingStore;
122
+ export function createPostgresBookingStore(options: {
123
+ pool: { query(text: string, values?: unknown[]): Promise<{ rows: any[] }>; connect(): Promise<any> };
124
+ prefix?: string;
125
+ }): BookingStore;
126
+ export function createMongoBookingStore(options: {
127
+ db: { collection(name: string): any };
128
+ prefix?: string;
129
+ leaseMs?: number;
130
+ waitMs?: number;
131
+ }): BookingStore;
132
+
133
+ /* ---------- Service ---------- */
134
+
135
+ export type BookingErrorCode = 'SLOT_TAKEN' | 'SLOT_UNAVAILABLE' | 'BOOKING_NOT_FOUND' | 'BOOKING_CANCELLED' | 'RESOURCE_NOT_FOUND';
136
+
137
+ export class BookingError extends Error {
138
+ constructor(code: BookingErrorCode, message: string);
139
+ name: 'BookingError';
140
+ code: BookingErrorCode;
141
+ }
142
+
143
+ export interface BookingServiceOptions {
144
+ store: BookingStore;
145
+ resources: Resource[] | ((id: string) => Resource | null | undefined | Promise<Resource | null | undefined>);
146
+ services?: Record<string, Service>;
147
+ now?: () => Instant;
148
+ calendars?: HolidayCalendars;
149
+ generateId?: () => string;
150
+ }
151
+
152
+ export interface BookRequest {
153
+ /** Toutes ces ressources ensemble. */
154
+ resourceIds?: string[];
155
+ /** La première libre, dans l'ordre. */
156
+ anyOf?: string[];
157
+ service: Service | string;
158
+ start: Instant;
159
+ seats?: number;
160
+ data?: unknown;
161
+ busy?: BusyBlock[];
162
+ }
163
+
164
+ export interface BookingService {
165
+ getSlots(input: {
166
+ resourceIds: string[];
167
+ service: Service | string;
168
+ from: Instant;
169
+ to: Instant;
170
+ mode?: SlotMode;
171
+ seats?: number;
172
+ busy?: BusyBlock[];
173
+ timeZone?: string;
174
+ }): Promise<Slot[]>;
175
+ book(request: BookRequest): Promise<Booking>;
176
+ cancel(id: string, options?: { reason?: string | null }): Promise<Booking>;
177
+ reschedule(id: string, options: { start: Instant; resourceIds?: string[]; service?: Service | string; busy?: BusyBlock[] }): Promise<Booking>;
178
+ getBooking(id: string): Promise<Booking | null>;
179
+ }
180
+
181
+ export function createBookingService(options: BookingServiceOptions): BookingService;
182
+
183
+ /* ---------- Jours fériés et heures ---------- */
184
+
185
+ export function getPublicHolidays(country: string, year: number, calendars?: HolidayCalendars): Array<{ date: string; id?: string; name?: string }>;
186
+ export function easterSunday(year: number): string;
187
+ export const HOLIDAY_COUNTRIES: string[];
188
+ export function wallTimeToISO(date: string, time: WallTime, timeZone: string): string;
189
+ export function toZoned(instant: Instant, timeZone: string): ZonedTime;
190
+ export function offsetMinutes(instant: Instant, timeZone: string): number;
package/src/index.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @astratra/booking — calcul des créneaux de rendez-vous et réservation sans
3
+ * double réservation.
4
+ */
5
+
6
+ const { computeSlots } = require('./slots');
7
+ const { createBookingService, BookingError } = require('./service');
8
+ const { getPublicHolidays, easterSunday, HOLIDAY_COUNTRIES } = require('./holidays');
9
+ const { zonedToInstant, toZoned, offsetMinutes, parseTime } = require('./time');
10
+ const {
11
+ assertBookingStore,
12
+ createMemoryBookingStore,
13
+ createPostgresBookingStore,
14
+ createMongoBookingStore
15
+ } = require('./stores');
16
+
17
+ /** Heure murale « AAAA-MM-JJ » + « HH:MM » dans un fuseau → instant ISO (UTC). */
18
+ function wallTimeToISO(date, time, timeZone) {
19
+ return new Date(zonedToInstant(date, parseTime(time), timeZone)).toISOString();
20
+ }
21
+
22
+ module.exports = {
23
+ computeSlots,
24
+ createBookingService,
25
+ BookingError,
26
+ createMemoryBookingStore,
27
+ createPostgresBookingStore,
28
+ createMongoBookingStore,
29
+ assertBookingStore,
30
+ getPublicHolidays,
31
+ easterSunday,
32
+ HOLIDAY_COUNTRIES,
33
+ wallTimeToISO,
34
+ toZoned,
35
+ offsetMinutes
36
+ };