@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/src/service.js ADDED
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Service de réservation : créneaux, réservation atomique, annulation, report.
3
+ *
4
+ * Toute écriture passe par `store.transaction` : on relit les rendez-vous de
5
+ * la ressource SOUS VERROU, on recalcule le créneau demandé avec les mêmes
6
+ * règles que `getSlots`, puis on écrit. Deux personnes qui cliquent sur le
7
+ * même dernier créneau à la même milliseconde : une seule l'obtient, l'autre
8
+ * reçoit `SLOT_TAKEN`.
9
+ */
10
+
11
+ const { randomUUID } = require('node:crypto');
12
+ const { computeSlots, normaliserService } = require('./slots');
13
+ const { assertBookingStore } = require('./stores');
14
+ const { toInstant, MINUTE } = require('./time');
15
+
16
+ const JOUR_MS = 24 * 60 * MINUTE;
17
+
18
+ class BookingError extends Error {
19
+ /**
20
+ * @param {'SLOT_TAKEN'|'SLOT_UNAVAILABLE'|'BOOKING_NOT_FOUND'|'BOOKING_CANCELLED'|'RESOURCE_NOT_FOUND'} code
21
+ */
22
+ constructor(code, message) {
23
+ super(message);
24
+ this.name = 'BookingError';
25
+ this.code = code;
26
+ }
27
+ }
28
+
29
+ /**
30
+ * @param {object} options
31
+ * @param {object} options.store voir `stores.js`.
32
+ * @param {Array|((id: string) => object|null|Promise<object|null>)} options.resources
33
+ * les ressources, ou une fonction qui en rend une par id.
34
+ * @param {Record<string, object>} [options.services] prestations par id, si
35
+ * l'application préfère passer `service: 'coupe'` plutôt que l'objet.
36
+ * @param {() => Date|number} [options.now]
37
+ * @param {object} [options.calendars] calendriers de jours fériés en plus.
38
+ */
39
+ function createBookingService({ store, resources, services = {}, now = () => Date.now(), calendars, generateId = randomUUID } = {}) {
40
+ assertBookingStore(store);
41
+ const parId = Array.isArray(resources) ? new Map(resources.map((r) => [String(r.id), r])) : null;
42
+ if (!parId && typeof resources !== 'function') throw new TypeError('resources doit être une liste ou une fonction.');
43
+
44
+ async function ressource(id) {
45
+ const trouvee = parId ? parId.get(String(id)) : await resources(String(id));
46
+ if (!trouvee) throw new BookingError('RESOURCE_NOT_FOUND', `Ressource inconnue : ${id}`);
47
+ return trouvee;
48
+ }
49
+
50
+ function prestation(service) {
51
+ const objet = typeof service === 'string' ? services[service] && { id: service, ...services[service] } : service;
52
+ if (!objet) throw new TypeError(`Prestation inconnue : ${service} (passe l’objet, ou déclare-la dans services).`);
53
+ return objet;
54
+ }
55
+
56
+ /* Les rendez-vous qui peuvent gêner [from, to) : on élargit d'une journée
57
+ pour attraper ceux dont seuls les tampons débordent. */
58
+ async function rendezVous(source, resourceIds, from, to) {
59
+ const debut = new Date(from - JOUR_MS).toISOString();
60
+ const fin = new Date(to + JOUR_MS).toISOString();
61
+ const vus = new Map();
62
+ for (const id of resourceIds) {
63
+ for (const b of await source.listBookings(id, debut, fin)) vus.set(b.id, b);
64
+ }
65
+ return [...vus.values()];
66
+ }
67
+
68
+ async function getSlots({ resourceIds, service, from, to, mode = 'each', seats = 1, busy = [], timeZone } = {}) {
69
+ if (!Array.isArray(resourceIds) || !resourceIds.length) throw new TypeError('resourceIds doit contenir au moins un id.');
70
+ const liste = await Promise.all(resourceIds.map(ressource));
71
+ const debut = toInstant(from, 'from');
72
+ const fin = toInstant(to, 'to');
73
+ return computeSlots({
74
+ resources: liste,
75
+ service: prestation(service),
76
+ from: debut,
77
+ to: fin,
78
+ now: now(),
79
+ bookings: await rendezVous(store, resourceIds, debut, fin),
80
+ busy,
81
+ mode,
82
+ seats,
83
+ timeZone,
84
+ calendars
85
+ });
86
+ }
87
+
88
+ /**
89
+ * Vérifie, sous verrou, qu'un créneau est encore offert à `start` pour
90
+ * TOUTES ces ressources. `ignorer` : le rendez-vous qu'on déplace.
91
+ */
92
+ async function verifier(tx, liste, service, start, seats, busy, ignorer) {
93
+ const instant = toInstant(start, 'start');
94
+ const tous = (await rendezVous(tx, liste.map((r) => r.id), instant, instant + 1)).filter((b) => b.id !== ignorer);
95
+ const options = { resources: liste, service, from: instant, to: instant + 1, now: now(), busy, mode: 'all', seats, calendars };
96
+ const creneau = computeSlots({ ...options, bookings: tous }).find((c) => Date.parse(c.start) === instant);
97
+ if (creneau) return creneau;
98
+ // Le créneau existe-t-il sans les autres rendez-vous ? Alors il vient d'être pris.
99
+ const sansRdv = computeSlots({ ...options, bookings: [] }).some((c) => Date.parse(c.start) === instant);
100
+ throw sansRdv
101
+ ? new BookingError('SLOT_TAKEN', 'Ce créneau vient d’être réservé.')
102
+ : new BookingError('SLOT_UNAVAILABLE', 'Ce créneau n’est pas proposé (horaires, préavis, horizon ou fermeture).');
103
+ }
104
+
105
+ async function reserverSur(resourceIds, { service, start, seats = 1, data = null, busy = [] }) {
106
+ const liste = await Promise.all(resourceIds.map(ressource));
107
+ const objet = prestation(service);
108
+ const regles = normaliserService(objet);
109
+ return store.transaction(resourceIds, async (tx) => {
110
+ const creneau = await verifier(tx, liste, objet, start, seats, busy);
111
+ const horodatage = new Date(toInstant(now(), 'now')).toISOString();
112
+ const booking = {
113
+ id: generateId(),
114
+ resourceIds: resourceIds.map(String),
115
+ start: creneau.start,
116
+ end: creneau.end,
117
+ bufferBefore: regles.bufferBefore,
118
+ bufferAfter: regles.bufferAfter,
119
+ seats,
120
+ status: 'confirmed',
121
+ serviceId: regles.id,
122
+ data,
123
+ history: [],
124
+ cancelReason: null,
125
+ cancelledAt: null,
126
+ createdAt: horodatage,
127
+ updatedAt: horodatage
128
+ };
129
+ await tx.insert(booking);
130
+ return booking;
131
+ });
132
+ }
133
+
134
+ /**
135
+ * Réserve. `resourceIds` : toutes ces ressources ensemble (coiffeur ET
136
+ * fauteuil). `anyOf` : la première ressource libre de la liste, dans
137
+ * l'ordre (« n'importe quel coiffeur »).
138
+ */
139
+ async function book({ resourceIds, anyOf, ...demande } = {}) {
140
+ if (anyOf) {
141
+ if (!Array.isArray(anyOf) || !anyOf.length) throw new TypeError('anyOf doit contenir au moins un id.');
142
+ let derniere;
143
+ for (const id of anyOf) {
144
+ try {
145
+ return await reserverSur([id], demande);
146
+ } catch (erreur) {
147
+ if (!(erreur instanceof BookingError) || !['SLOT_TAKEN', 'SLOT_UNAVAILABLE'].includes(erreur.code)) throw erreur;
148
+ // Une ressource prise prime sur une ressource fermée pour expliquer le refus.
149
+ if (!derniere || erreur.code === 'SLOT_TAKEN') derniere = erreur;
150
+ }
151
+ }
152
+ throw derniere;
153
+ }
154
+ if (!Array.isArray(resourceIds) || !resourceIds.length) throw new TypeError('resourceIds ou anyOf est requis.');
155
+ return reserverSur(resourceIds, demande);
156
+ }
157
+
158
+ async function existant(id) {
159
+ const booking = await store.getBooking(id);
160
+ if (!booking) throw new BookingError('BOOKING_NOT_FOUND', `Rendez-vous introuvable : ${id}`);
161
+ return booking;
162
+ }
163
+
164
+ /** Annule : les places se libèrent aussitôt. Annuler deux fois ne change rien. */
165
+ async function cancel(id, { reason = null } = {}) {
166
+ const { resourceIds } = await existant(id);
167
+ return store.transaction(resourceIds, async (tx) => {
168
+ const booking = await tx.getBooking(id);
169
+ if (booking.status === 'cancelled') return booking;
170
+ const horodatage = new Date(toInstant(now(), 'now')).toISOString();
171
+ const patch = { status: 'cancelled', cancelReason: reason, cancelledAt: horodatage, updatedAt: horodatage };
172
+ await tx.update(id, patch);
173
+ return { ...booking, ...patch };
174
+ });
175
+ }
176
+
177
+ /**
178
+ * Reporte à `start`, sur les mêmes ressources ou d'autres. Le rendez-vous
179
+ * ne se gêne pas lui-même : passer de 10:00 à 10:15 sur une prestation
180
+ * d'une heure est permis. L'ancien horaire part dans `history`.
181
+ */
182
+ async function reschedule(id, { start, resourceIds, service, busy = [] } = {}) {
183
+ const actuel = await existant(id);
184
+ const cibles = (resourceIds || actuel.resourceIds).map(String);
185
+ const liste = await Promise.all(cibles.map(ressource));
186
+ // La grille des créneaux dépend de la prestation (pas, tampons) : on la
187
+ // reprend telle quelle, sans la deviner depuis le rendez-vous.
188
+ const objet = prestation(service ?? actuel.serviceId);
189
+ const regles = normaliserService(objet);
190
+ return store.transaction([...actuel.resourceIds, ...cibles], async (tx) => {
191
+ const booking = await tx.getBooking(id);
192
+ if (booking.status === 'cancelled') throw new BookingError('BOOKING_CANCELLED', 'Un rendez-vous annulé ne se reporte pas.');
193
+ const creneau = await verifier(tx, liste, objet, start, booking.seats, busy, id);
194
+ const horodatage = new Date(toInstant(now(), 'now')).toISOString();
195
+ const patch = {
196
+ resourceIds: cibles,
197
+ start: creneau.start,
198
+ end: creneau.end,
199
+ bufferBefore: regles.bufferBefore,
200
+ bufferAfter: regles.bufferAfter,
201
+ serviceId: regles.id,
202
+ history: [...(booking.history || []), { start: booking.start, end: booking.end, resourceIds: booking.resourceIds, movedAt: horodatage }],
203
+ updatedAt: horodatage
204
+ };
205
+ await tx.update(id, patch);
206
+ return { ...booking, ...patch };
207
+ });
208
+ }
209
+
210
+ return { getSlots, book, cancel, reschedule, getBooking: (id) => store.getBooking(id) };
211
+ }
212
+
213
+ module.exports = { createBookingService, BookingError };
package/src/slots.js ADDED
@@ -0,0 +1,270 @@
1
+ /**
2
+ * Calcul des créneaux libres, sans base de données : on lui donne les
3
+ * ressources, la prestation, les rendez-vous déjà pris et l'instant présent,
4
+ * il rend les créneaux réservables.
5
+ *
6
+ * Une ressource est ce qui se réserve : une personne, une salle, un siège de
7
+ * barbier. Elle a ses horaires hebdomadaires en heure murale DE SON fuseau,
8
+ * ses exceptions (congés, horaires spéciaux), son pays (jours fériés) et sa
9
+ * capacité (nombre de places en même temps).
10
+ *
11
+ * Règles :
12
+ * 1. La prestation elle-même doit tenir dans une plage d'ouverture. Les
13
+ * tampons avant/après ne servent qu'à écarter les autres rendez-vous :
14
+ * un nettoyage de 10 min après le dernier client peut déborder l'horaire.
15
+ * 2. Deux rendez-vous se gênent si leurs plages TAMPONS COMPRIS se
16
+ * chevauchent ; chacun garde les tampons de sa propre prestation.
17
+ * 3. Un créneau est réservable s'il reste au moins `seats` places sur toute
18
+ * sa durée (tampons compris).
19
+ * 4. Préavis : le créneau commence au plus tôt `minNotice` minutes après
20
+ * maintenant. Horizon : il commence au plus tard `horizon` jours après.
21
+ * 5. Priorité des règles d'un jour : exception datée > congés (période) >
22
+ * jour férié > horaires de la semaine. Une exception datée avec des
23
+ * horaires ouvre donc un jour férié ou un dimanche.
24
+ */
25
+
26
+ const {
27
+ MINUTE,
28
+ JOURS,
29
+ assertTimeZone,
30
+ parseTime,
31
+ addDays,
32
+ weekday,
33
+ zonedToInstant,
34
+ toZoned,
35
+ toInstant,
36
+ verifierDate
37
+ } = require('./time');
38
+ const { getPublicHolidays } = require('./holidays');
39
+
40
+ const JOUR_MS = 24 * 60 * MINUTE;
41
+ const MODES = ['each', 'any', 'all'];
42
+
43
+ function entierPositif(valeur, champ, { zero = false } = {}) {
44
+ if (!Number.isInteger(valeur) || valeur < (zero ? 0 : 1)) {
45
+ throw new TypeError(`${champ} doit être un entier ${zero ? 'positif ou nul' : 'strictement positif'} (reçu : ${valeur}).`);
46
+ }
47
+ return valeur;
48
+ }
49
+
50
+ /** Plages « HH:MM » → minutes, triées et fusionnées quand elles se touchent. */
51
+ function normaliserPlages(plages, champ) {
52
+ const liste = (plages || []).map((plage) => {
53
+ const [debut, fin] = Array.isArray(plage) ? plage : [plage.start, plage.end];
54
+ const d = parseTime(debut);
55
+ const f = parseTime(fin);
56
+ if (f <= d) throw new TypeError(`${champ} : la plage ${debut}–${fin} finit avant de commencer.`);
57
+ return [d, f];
58
+ });
59
+ return fusionner(liste);
60
+ }
61
+
62
+ function fusionner(plages) {
63
+ const liste = plages.map((plage) => [...plage]).sort((a, b) => a[0] - b[0]);
64
+ const fusion = [];
65
+ for (const plage of liste) {
66
+ const derniere = fusion[fusion.length - 1];
67
+ if (derniere && plage[0] <= derniere[1]) derniere[1] = Math.max(derniere[1], plage[1]);
68
+ else fusion.push(plage);
69
+ }
70
+ return fusion;
71
+ }
72
+
73
+ function normaliserRessource(ressource) {
74
+ if (!ressource || ressource.id == null) throw new TypeError('Chaque ressource doit avoir un id.');
75
+ assertTimeZone(ressource.timeZone);
76
+ const weekly = {};
77
+ for (const [jour, plages] of Object.entries(ressource.weekly || {})) {
78
+ if (!JOURS.includes(jour)) throw new TypeError(`Jour inconnu dans weekly : ${jour} (attendu : ${JOURS.join(', ')}).`);
79
+ weekly[jour] = normaliserPlages(plages, `weekly.${jour}`);
80
+ }
81
+ const exceptions = (ressource.exceptions || []).map((exception) => {
82
+ if (exception.date) verifierDate(exception.date);
83
+ else if (exception.from && exception.to) {
84
+ verifierDate(exception.from);
85
+ verifierDate(exception.to);
86
+ if (exception.intervals) throw new TypeError('Une période (from/to) ne peut que fermer : donne des horaires date par date.');
87
+ } else throw new TypeError('Une exception a soit `date`, soit `from` et `to`.');
88
+ return {
89
+ ...exception,
90
+ closed: exception.closed === true || !exception.intervals,
91
+ intervals: exception.intervals ? normaliserPlages(exception.intervals, `exception ${exception.date}`) : []
92
+ };
93
+ });
94
+ return {
95
+ id: String(ressource.id),
96
+ timeZone: ressource.timeZone,
97
+ capacity: entierPositif(ressource.capacity ?? 1, 'capacity'),
98
+ country: ressource.country ? String(ressource.country).toUpperCase() : null,
99
+ holidays: ressource.holidays !== false,
100
+ weekly,
101
+ exceptions
102
+ };
103
+ }
104
+
105
+ function normaliserService(service = {}) {
106
+ const duration = entierPositif(service.duration, 'service.duration');
107
+ return {
108
+ id: service.id ?? null,
109
+ duration,
110
+ bufferBefore: entierPositif(service.bufferBefore ?? 0, 'service.bufferBefore', { zero: true }),
111
+ bufferAfter: entierPositif(service.bufferAfter ?? 0, 'service.bufferAfter', { zero: true }),
112
+ step: entierPositif(service.step ?? duration, 'service.step'),
113
+ minNotice: entierPositif(service.minNotice ?? 0, 'service.minNotice', { zero: true }),
114
+ horizon: entierPositif(service.horizon ?? 60, 'service.horizon')
115
+ };
116
+ }
117
+
118
+ /** Plages d'ouverture d'une ressource pour une date civile, en minutes murales. */
119
+ function plagesDuJour(ressource, date, feries) {
120
+ const datees = ressource.exceptions.filter((e) => e.date === date);
121
+ if (datees.length) {
122
+ if (datees.some((e) => e.closed)) return [];
123
+ return fusionner(datees.flatMap((e) => e.intervals));
124
+ }
125
+ if (ressource.exceptions.some((e) => e.from && e.from <= date && date <= e.to)) return [];
126
+ if (ressource.holidays && ressource.country && feries(ressource.country, date)) return [];
127
+ return ressource.weekly[weekday(date)] || [];
128
+ }
129
+
130
+ /** Cache des jours fériés (pays, année) pour un calcul. */
131
+ function creerFeries(calendars) {
132
+ const cache = new Map();
133
+ return (pays, date) => {
134
+ const annee = Number(date.slice(0, 4));
135
+ const cle = `${pays}:${annee}`;
136
+ if (!cache.has(cle)) cache.set(cle, new Set(getPublicHolidays(pays, annee, calendars).map((f) => f.date)));
137
+ return cache.get(cle).has(date);
138
+ };
139
+ }
140
+
141
+ /**
142
+ * Occupations d'une ressource : rendez-vous actifs (tampons compris) et
143
+ * indisponibilités externes, qui prennent toute la capacité.
144
+ */
145
+ function occupations(ressourceId, bookings, busy) {
146
+ const liste = [];
147
+ for (const b of bookings) {
148
+ if (b.status === 'cancelled' || !(b.resourceIds || []).map(String).includes(ressourceId)) continue;
149
+ liste.push({
150
+ debut: toInstant(b.start, 'booking.start') - (b.bufferBefore || 0) * MINUTE,
151
+ fin: toInstant(b.end, 'booking.end') + (b.bufferAfter || 0) * MINUTE,
152
+ places: b.seats ?? 1
153
+ });
154
+ }
155
+ for (const bloc of busy) {
156
+ if (String(bloc.resourceId) !== ressourceId) continue;
157
+ liste.push({ debut: toInstant(bloc.start, 'busy.start'), fin: toInstant(bloc.end, 'busy.end'), places: Infinity });
158
+ }
159
+ return liste;
160
+ }
161
+
162
+ /** Places prises au pire moment de [debut, fin). */
163
+ function placesPrises(liste, debut, fin) {
164
+ const chevauchent = liste.filter((o) => o.debut < fin && debut < o.fin);
165
+ let maximum = 0;
166
+ for (const point of [debut, ...chevauchent.map((o) => o.debut).filter((t) => t > debut)]) {
167
+ const total = chevauchent.reduce((somme, o) => (o.debut <= point && point < o.fin ? somme + o.places : somme), 0);
168
+ maximum = Math.max(maximum, total);
169
+ }
170
+ return maximum;
171
+ }
172
+
173
+ /** Créneaux d'UNE ressource : [{ debut, fin, restantes }]. */
174
+ function creneauxRessource(ressource, service, fenetre, bookings, busy, feries) {
175
+ const occupe = occupations(ressource.id, bookings, busy);
176
+ const resultat = [];
177
+ // Une journée de marge de chaque côté : un fuseau éloigné décale les dates.
178
+ let date = toZoned(fenetre.debut - JOUR_MS, ressource.timeZone).date;
179
+ const derniere = toZoned(fenetre.fin + JOUR_MS, ressource.timeZone).date;
180
+ for (; date <= derniere; date = addDays(date, 1)) {
181
+ for (const [debutMin, finMin] of plagesDuJour(ressource, date, feries)) {
182
+ const ouverture = zonedToInstant(date, debutMin, ressource.timeZone);
183
+ const fermeture = zonedToInstant(date, finMin, ressource.timeZone);
184
+ for (let debut = ouverture; debut + service.duration * MINUTE <= fermeture; debut += service.step * MINUTE) {
185
+ if (debut < fenetre.debut || debut >= fenetre.fin) continue;
186
+ const fin = debut + service.duration * MINUTE;
187
+ const prises = placesPrises(occupe, debut - service.bufferBefore * MINUTE, fin + service.bufferAfter * MINUTE);
188
+ resultat.push({ debut, fin, restantes: Math.max(0, ressource.capacity - prises) });
189
+ }
190
+ }
191
+ }
192
+ return resultat;
193
+ }
194
+
195
+ /**
196
+ * @param {object} input
197
+ * @param {Array} input.resources
198
+ * @param {object} input.service { duration, bufferBefore?, bufferAfter?, step?, minNotice?, horizon? }
199
+ * @param {Date|string|number} input.from début de la fenêtre demandée.
200
+ * @param {Date|string|number} input.to fin de la fenêtre (exclue).
201
+ * @param {Date|string|number} [input.now]
202
+ * @param {Array} [input.bookings] rendez-vous connus { resourceIds, start, end, bufferBefore, bufferAfter, seats, status }.
203
+ * @param {Array} [input.busy] indisponibilités externes { resourceId, start, end }.
204
+ * @param {'each'|'any'|'all'} [input.mode='each']
205
+ * each : un créneau par ressource ; any : au moins une ressource libre ;
206
+ * all : toutes les ressources libres en même temps (coiffeur ET fauteuil).
207
+ * @param {number} [input.seats=1] places demandées.
208
+ * @param {string} [input.timeZone] fuseau d'affichage de `local` (celui de la 1re ressource sinon).
209
+ * @param {object} [input.calendars] calendriers de jours fériés en plus.
210
+ */
211
+ function computeSlots({
212
+ resources,
213
+ service,
214
+ from,
215
+ to,
216
+ now = Date.now(),
217
+ bookings = [],
218
+ busy = [],
219
+ mode = 'each',
220
+ seats = 1,
221
+ timeZone,
222
+ calendars
223
+ } = {}) {
224
+ if (!Array.isArray(resources) || !resources.length) throw new TypeError('resources doit contenir au moins une ressource.');
225
+ if (!MODES.includes(mode)) throw new TypeError(`mode inconnu : ${mode} (attendu : ${MODES.join(', ')}).`);
226
+ entierPositif(seats, 'seats');
227
+ const ressources = resources.map(normaliserRessource);
228
+ const prestation = normaliserService(service);
229
+ const affichage = timeZone || ressources[0].timeZone;
230
+ assertTimeZone(affichage);
231
+
232
+ const maintenant = toInstant(now, 'now');
233
+ const fenetre = {
234
+ debut: Math.max(toInstant(from, 'from'), maintenant + prestation.minNotice * MINUTE),
235
+ fin: Math.min(toInstant(to, 'to'), maintenant + prestation.horizon * JOUR_MS)
236
+ };
237
+ if (fenetre.fin <= fenetre.debut) return [];
238
+
239
+ const feries = creerFeries(calendars);
240
+ const parDebut = new Map();
241
+ for (const ressource of ressources) {
242
+ for (const c of creneauxRessource(ressource, prestation, fenetre, bookings, busy, feries)) {
243
+ if (!parDebut.has(c.debut)) parDebut.set(c.debut, []);
244
+ parDebut.get(c.debut).push({ ressource: ressource.id, fin: c.fin, restantes: c.restantes });
245
+ }
246
+ }
247
+
248
+ const sortie = (debut, fin, resourceIds, available) => ({
249
+ start: new Date(debut).toISOString(),
250
+ end: new Date(fin).toISOString(),
251
+ resourceIds,
252
+ available,
253
+ local: toZoned(debut, affichage)
254
+ });
255
+
256
+ const creneaux = [];
257
+ for (const debut of [...parDebut.keys()].sort((a, b) => a - b)) {
258
+ const libres = parDebut.get(debut).filter((c) => c.restantes >= seats);
259
+ if (mode === 'each') {
260
+ for (const c of libres) creneaux.push(sortie(debut, c.fin, [c.ressource], c.restantes));
261
+ } else if (mode === 'any' && libres.length) {
262
+ creneaux.push(sortie(debut, libres[0].fin, libres.map((c) => c.ressource), libres.reduce((s, c) => s + c.restantes, 0)));
263
+ } else if (mode === 'all' && libres.length === ressources.length) {
264
+ creneaux.push(sortie(debut, libres[0].fin, libres.map((c) => c.ressource), Math.min(...libres.map((c) => c.restantes))));
265
+ }
266
+ }
267
+ return creneaux;
268
+ }
269
+
270
+ module.exports = { computeSlots, normaliserRessource, normaliserService };