@free-intelligence/core 1.12.1 → 1.14.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/README.md +2 -1
- package/dist/availability/index.d.ts +101 -56
- package/dist/availability/index.js +192 -0
- package/dist/availability/index.js.map +1 -1
- package/dist/membership/index.d.ts +24 -0
- package/dist/membership/index.js +63 -0
- package/dist/membership/index.js.map +1 -0
- package/dist/types-BThgyft4.d.ts +57 -0
- package/package.json +5 -1
- package/src/availability/day.test.ts +333 -0
- package/src/availability/day.ts +132 -0
- package/src/availability/index.ts +4 -1
- package/src/availability/intervals.ts +47 -0
- package/src/availability/slots.ts +91 -0
- package/src/availability/time.ts +22 -0
- package/src/membership/index.ts +3 -0
- package/src/membership/membership.test.ts +98 -0
- package/src/membership/term.ts +44 -0
- package/src/membership/types.ts +15 -0
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** `HH:mm`, 24 h. */
|
|
2
|
+
type TimeOfDay = string;
|
|
3
|
+
/** `YYYY-MM-DD`. */
|
|
4
|
+
type CalendarDate = string;
|
|
5
|
+
interface WeeklySlot {
|
|
6
|
+
/** As JavaScript counts it: 0 is Sunday. */
|
|
7
|
+
day: number;
|
|
8
|
+
start: TimeOfDay;
|
|
9
|
+
end: TimeOfDay;
|
|
10
|
+
label?: string;
|
|
11
|
+
}
|
|
12
|
+
/** Replaces the weekly pattern on one date. Without `fullDayClosed` it carries its own hours. */
|
|
13
|
+
interface DateOverride {
|
|
14
|
+
date: CalendarDate;
|
|
15
|
+
start?: TimeOfDay;
|
|
16
|
+
end?: TimeOfDay;
|
|
17
|
+
fullDayClosed: boolean;
|
|
18
|
+
reason?: string;
|
|
19
|
+
}
|
|
20
|
+
/** Durations are minutes. */
|
|
21
|
+
interface SchedulingRules {
|
|
22
|
+
breakStart?: TimeOfDay;
|
|
23
|
+
breakEnd?: TimeOfDay;
|
|
24
|
+
minSlotDuration?: number;
|
|
25
|
+
maxPatientsPerHour?: number;
|
|
26
|
+
bufferBetweenAppointments?: number;
|
|
27
|
+
}
|
|
28
|
+
interface DoctorAvailability {
|
|
29
|
+
version: number;
|
|
30
|
+
weeklySchedule: WeeklySlot[];
|
|
31
|
+
overrides: DateOverride[];
|
|
32
|
+
rules: SchedulingRules;
|
|
33
|
+
}
|
|
34
|
+
type AvailabilityErrorType = 'overlap' | 'invalid_time' | 'end_before_start' | 'duplicate_date';
|
|
35
|
+
interface AvailabilityError {
|
|
36
|
+
type: AvailabilityErrorType;
|
|
37
|
+
day?: number;
|
|
38
|
+
date?: CalendarDate;
|
|
39
|
+
/** Position in that day's list, when the error belongs to one slot. */
|
|
40
|
+
slotIndex?: number;
|
|
41
|
+
message: string;
|
|
42
|
+
severity: 'error' | 'warning';
|
|
43
|
+
}
|
|
44
|
+
/** Editing keeps the slots of a day that was switched off, so switching it back restores them. */
|
|
45
|
+
interface DaySchedule {
|
|
46
|
+
isWorking: boolean;
|
|
47
|
+
slots: WeeklySlot[];
|
|
48
|
+
}
|
|
49
|
+
type WeekSchedule = Record<number, DaySchedule>;
|
|
50
|
+
interface AvailabilityTemplate {
|
|
51
|
+
id: string;
|
|
52
|
+
name: string;
|
|
53
|
+
description: string;
|
|
54
|
+
weeklySchedule: WeeklySlot[];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type { AvailabilityTemplate as A, CalendarDate as C, DoctorAvailability as D, SchedulingRules as S, TimeOfDay as T, WeeklySlot as W, AvailabilityError as a, WeekSchedule as b, DateOverride as c, AvailabilityErrorType as d, DaySchedule as e };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@free-intelligence/core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.14.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "https://github.com/BernardUriza/free-intelligence",
|
|
@@ -20,6 +20,10 @@
|
|
|
20
20
|
"./availability": {
|
|
21
21
|
"types": "./dist/availability/index.d.ts",
|
|
22
22
|
"import": "./dist/availability/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./membership": {
|
|
25
|
+
"types": "./dist/membership/index.d.ts",
|
|
26
|
+
"import": "./dist/membership/index.js"
|
|
23
27
|
}
|
|
24
28
|
},
|
|
25
29
|
"files": [
|
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import {
|
|
3
|
+
addDays,
|
|
4
|
+
applyBreak,
|
|
5
|
+
complementIntervals,
|
|
6
|
+
dayOfWeek,
|
|
7
|
+
daysBetween,
|
|
8
|
+
findConflict,
|
|
9
|
+
fromLocalMinutes,
|
|
10
|
+
generateSlots,
|
|
11
|
+
hourlyCapacity,
|
|
12
|
+
hoursForDate,
|
|
13
|
+
intervalsOverlap,
|
|
14
|
+
isSchedulable,
|
|
15
|
+
mergeIntervals,
|
|
16
|
+
resolveDay,
|
|
17
|
+
resolveDayWindows,
|
|
18
|
+
slotBuffer,
|
|
19
|
+
slotDuration,
|
|
20
|
+
subtractInterval,
|
|
21
|
+
toLocalMinutes,
|
|
22
|
+
type DoctorAvailability,
|
|
23
|
+
} from './index';
|
|
24
|
+
|
|
25
|
+
const availability = (changes: Partial<DoctorAvailability>): DoctorAvailability => ({
|
|
26
|
+
version: 1,
|
|
27
|
+
weeklySchedule: [],
|
|
28
|
+
overrides: [],
|
|
29
|
+
rules: {},
|
|
30
|
+
...changes,
|
|
31
|
+
});
|
|
32
|
+
const MONDAY = '2025-01-06';
|
|
33
|
+
const at = (date: string, time: string) => {
|
|
34
|
+
const [hours, minutes] = time.split(':').map(Number);
|
|
35
|
+
return toLocalMinutes(date, hours * 60 + minutes);
|
|
36
|
+
};
|
|
37
|
+
const starts = (slots: { start: number }[]) => slots.map(({ start }) => start);
|
|
38
|
+
|
|
39
|
+
describe('calendar dates', () => {
|
|
40
|
+
it('moves across months and years, and counts weekdays from Sunday', () => {
|
|
41
|
+
expect(addDays('2026-12-31', 1)).toBe('2027-01-01');
|
|
42
|
+
expect(addDays('2028-03-01', -1)).toBe('2028-02-29');
|
|
43
|
+
expect(daysBetween('2026-11-25', '2026-12-10')).toBe(15);
|
|
44
|
+
expect(dayOfWeek(MONDAY)).toBe(1);
|
|
45
|
+
expect(dayOfWeek('2025-01-05')).toBe(0);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('rejects a date that does not exist', () => {
|
|
49
|
+
expect(() => addDays('2026-02-30', 1)).toThrow(RangeError);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
describe('intervals', () => {
|
|
54
|
+
it('overlap when they share time, not when they only touch', () => {
|
|
55
|
+
expect(intervalsOverlap({ start: 0, end: 10 }, { start: 9, end: 20 })).toBe(true);
|
|
56
|
+
expect(intervalsOverlap({ start: 0, end: 10 }, { start: 10, end: 20 })).toBe(false);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('merge overlapping and touching ones, in order', () => {
|
|
60
|
+
expect(
|
|
61
|
+
mergeIntervals([
|
|
62
|
+
{ start: 600, end: 720 },
|
|
63
|
+
{ start: 300, end: 400 },
|
|
64
|
+
{ start: 400, end: 500 },
|
|
65
|
+
{ start: 450, end: 480 },
|
|
66
|
+
]),
|
|
67
|
+
).toEqual([
|
|
68
|
+
{ start: 300, end: 500 },
|
|
69
|
+
{ start: 600, end: 720 },
|
|
70
|
+
]);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('subtract a cut from the middle, an edge, or nothing', () => {
|
|
74
|
+
const windows = [{ start: 540, end: 1080 }];
|
|
75
|
+
expect(subtractInterval(windows, { start: 780, end: 840 })).toEqual([
|
|
76
|
+
{ start: 540, end: 780 },
|
|
77
|
+
{ start: 840, end: 1080 },
|
|
78
|
+
]);
|
|
79
|
+
expect(subtractInterval(windows, { start: 500, end: 600 })).toEqual([{ start: 600, end: 1080 }]);
|
|
80
|
+
expect(subtractInterval(windows, { start: 0, end: 1440 })).toEqual([]);
|
|
81
|
+
expect(subtractInterval(windows, { start: 1080, end: 1100 })).toEqual(windows);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('complement inside bounds', () => {
|
|
85
|
+
expect(complementIntervals([{ start: 540, end: 1020 }], { start: 0, end: 1440 })).toEqual([
|
|
86
|
+
{ start: 0, end: 540 },
|
|
87
|
+
{ start: 1020, end: 1440 },
|
|
88
|
+
]);
|
|
89
|
+
expect(complementIntervals([], { start: 0, end: 1440 })).toEqual([{ start: 0, end: 1440 }]);
|
|
90
|
+
expect(complementIntervals([{ start: 0, end: 1440 }], { start: 0, end: 1440 })).toEqual([]);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it('find the first conflict, and reject an interval that does not advance', () => {
|
|
94
|
+
const existing = [
|
|
95
|
+
{ start: 0, end: 30, id: 7 },
|
|
96
|
+
{ start: 60, end: 90, id: 9 },
|
|
97
|
+
];
|
|
98
|
+
expect(findConflict(existing, { start: 80, end: 100 })).toEqual({ start: 60, end: 90, id: 9 });
|
|
99
|
+
expect(findConflict(existing, { start: 30, end: 60 })).toBeNull();
|
|
100
|
+
expect(() => findConflict(existing, { start: 10, end: 10 })).toThrow(RangeError);
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
describe('hoursForDate', () => {
|
|
105
|
+
const schedule = availability({
|
|
106
|
+
weeklySchedule: [
|
|
107
|
+
{ day: 1, start: '09:00', end: '13:00', label: 'Morning' },
|
|
108
|
+
{ day: 1, start: '16:00', end: '20:00' },
|
|
109
|
+
],
|
|
110
|
+
overrides: [
|
|
111
|
+
{ date: '2025-01-13', fullDayClosed: true, reason: 'Congress' },
|
|
112
|
+
{ date: '2025-01-20', fullDayClosed: false, start: '10:00', end: '11:00' },
|
|
113
|
+
{ date: '2025-01-27', fullDayClosed: false },
|
|
114
|
+
],
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it('uses the weekly slots of that weekday', () => {
|
|
118
|
+
expect(hoursForDate(schedule, MONDAY)).toMatchObject({
|
|
119
|
+
source: 'weekly',
|
|
120
|
+
closed: false,
|
|
121
|
+
hours: [
|
|
122
|
+
{ start: '09:00', end: '13:00' },
|
|
123
|
+
{ start: '16:00', end: '20:00' },
|
|
124
|
+
],
|
|
125
|
+
});
|
|
126
|
+
expect(hoursForDate(schedule, MONDAY).slots[0].label).toBe('Morning');
|
|
127
|
+
expect(hoursForDate(schedule, '2025-01-07')).toMatchObject({ source: 'weekly', closed: true, hours: [] });
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
it('lets an override replace the weekly pattern on its date', () => {
|
|
131
|
+
expect(hoursForDate(schedule, '2025-01-13')).toMatchObject({ source: 'override', closed: true, hours: [] });
|
|
132
|
+
expect(hoursForDate(schedule, '2025-01-13').overrides[0].reason).toBe('Congress');
|
|
133
|
+
expect(hoursForDate(schedule, '2025-01-20')).toMatchObject({
|
|
134
|
+
source: 'override',
|
|
135
|
+
closed: false,
|
|
136
|
+
hours: [{ start: '10:00', end: '11:00' }],
|
|
137
|
+
});
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
it('treats an override without hours as a closed day', () => {
|
|
141
|
+
expect(hoursForDate(schedule, '2025-01-27')).toMatchObject({ source: 'override', closed: true, hours: [] });
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
describe('resolveDay', () => {
|
|
146
|
+
it('merges overlapping or touching weekly slots into canonical windows', () => {
|
|
147
|
+
const result = resolveDay(
|
|
148
|
+
availability({
|
|
149
|
+
weeklySchedule: [
|
|
150
|
+
{ day: 1, start: '09:00', end: '13:00' },
|
|
151
|
+
{ day: 1, start: '13:00', end: '17:00' },
|
|
152
|
+
],
|
|
153
|
+
}),
|
|
154
|
+
MONDAY,
|
|
155
|
+
);
|
|
156
|
+
expect(result.mergesApplied).toBe(true);
|
|
157
|
+
expect(result.windows).toEqual([{ start: 540, end: 1020, source: 'weekly' }]);
|
|
158
|
+
expect(result.totalMinutes).toBe(8 * 60);
|
|
159
|
+
expect(result.nonWorking).toHaveLength(2);
|
|
160
|
+
expect(result.fullDayOff).toBe(false);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
it('returns a full day off when the date override is closed', () => {
|
|
164
|
+
const result = resolveDay(
|
|
165
|
+
availability({
|
|
166
|
+
weeklySchedule: [{ day: 2, start: '08:00', end: '16:00' }],
|
|
167
|
+
overrides: [{ date: '2025-01-07', fullDayClosed: true }],
|
|
168
|
+
}),
|
|
169
|
+
'2025-01-07',
|
|
170
|
+
);
|
|
171
|
+
expect(result.fullDayOff).toBe(true);
|
|
172
|
+
expect(result.windows).toEqual([]);
|
|
173
|
+
expect(result.nonWorking).toEqual([{ start: 0, end: 1440 }]);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
it('is a full day off on a weekday without slots', () => {
|
|
177
|
+
expect(resolveDay(availability({ weeklySchedule: [{ day: 1, start: '09:00', end: '13:00' }] }), '2025-01-07')).toMatchObject({
|
|
178
|
+
fullDayOff: true,
|
|
179
|
+
windows: [],
|
|
180
|
+
totalMinutes: 0,
|
|
181
|
+
});
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it('carries a cross-midnight shift into the next day, even when that day has no slots', () => {
|
|
185
|
+
const night = availability({ weeklySchedule: [{ day: 3, start: '22:00', end: '02:00' }] });
|
|
186
|
+
const wednesday = resolveDay(night, '2025-01-08');
|
|
187
|
+
expect(wednesday.windows).toEqual([{ start: 1320, end: 1440, source: 'weekly' }]);
|
|
188
|
+
expect(wednesday.spilloverNext).toEqual([{ start: 0, end: 120 }]);
|
|
189
|
+
|
|
190
|
+
const thursday = resolveDay(night, '2025-01-09', wednesday.spilloverNext);
|
|
191
|
+
expect(thursday.windows).toEqual([{ start: 0, end: 120, source: 'spillover' }]);
|
|
192
|
+
expect(thursday.fullDayOff).toBe(false);
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
it('drops the spillover when an override closes the next day', () => {
|
|
196
|
+
const night = availability({
|
|
197
|
+
weeklySchedule: [{ day: 3, start: '22:00', end: '02:00' }],
|
|
198
|
+
overrides: [{ date: '2025-01-09', fullDayClosed: true }],
|
|
199
|
+
});
|
|
200
|
+
const thursday = resolveDay(night, '2025-01-09', resolveDay(night, '2025-01-08').spilloverNext);
|
|
201
|
+
expect(thursday.fullDayOff).toBe(true);
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
it('reads 24:00 as the end of the day and seconds as their minute', () => {
|
|
205
|
+
expect(resolveDayWindows([{ start: '18:00:00', end: '24:00' }]).windows).toEqual([
|
|
206
|
+
{ start: 1080, end: 1440, source: 'weekly' },
|
|
207
|
+
]);
|
|
208
|
+
expect(resolveDayWindows([{ start: '18:00', end: '24:00' }]).spilloverNext).toEqual([]);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
it('rejects hours it cannot read', () => {
|
|
212
|
+
expect(() => resolveDayWindows([{ start: '24:00', end: '02:00' }])).toThrow(RangeError);
|
|
213
|
+
expect(() => resolveDayWindows([{ start: '9', end: '13:00' }])).toThrow(RangeError);
|
|
214
|
+
expect(() => resolveDayWindows([{ start: '09:00', end: '' }])).toThrow(RangeError);
|
|
215
|
+
});
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
describe('applyBreak', () => {
|
|
219
|
+
const windows = [{ start: 540, end: 1080 }];
|
|
220
|
+
|
|
221
|
+
it('takes the break out of the windows', () => {
|
|
222
|
+
expect(applyBreak(windows, { breakStart: '13:00', breakEnd: '14:00' })).toEqual([
|
|
223
|
+
{ start: 540, end: 780 },
|
|
224
|
+
{ start: 840, end: 1080 },
|
|
225
|
+
]);
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
it('ignores a break that is incomplete, unreadable or inverted', () => {
|
|
229
|
+
expect(applyBreak(windows, { breakStart: '13:00' })).toEqual(windows);
|
|
230
|
+
expect(applyBreak(windows, { breakStart: '13:00', breakEnd: '25:00' })).toEqual(windows);
|
|
231
|
+
expect(applyBreak(windows, { breakStart: '14:00', breakEnd: '13:00' })).toEqual(windows);
|
|
232
|
+
});
|
|
233
|
+
});
|
|
234
|
+
|
|
235
|
+
describe('isSchedulable', () => {
|
|
236
|
+
it('needs weekly hours, or a dated opening from today on', () => {
|
|
237
|
+
expect(isSchedulable(availability({}), MONDAY)).toBe(false);
|
|
238
|
+
expect(isSchedulable(availability({ weeklySchedule: [{ day: 1, start: '09:00', end: '13:00' }] }), MONDAY)).toBe(true);
|
|
239
|
+
expect(isSchedulable(availability({ weeklySchedule: [{ day: 1, start: '13:00', end: '09:00' }] }), MONDAY)).toBe(false);
|
|
240
|
+
const dated = (date: string) => availability({ overrides: [{ date, fullDayClosed: false, start: '10:00', end: '11:00' }] });
|
|
241
|
+
expect(isSchedulable(dated(MONDAY), MONDAY)).toBe(true);
|
|
242
|
+
expect(isSchedulable(dated('2025-01-05'), MONDAY)).toBe(false);
|
|
243
|
+
expect(isSchedulable(availability({ overrides: [{ date: MONDAY, fullDayClosed: true }] }), MONDAY)).toBe(false);
|
|
244
|
+
});
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
describe('slot rules', () => {
|
|
248
|
+
it('fall back to safe values', () => {
|
|
249
|
+
expect(slotDuration({})).toBe(15);
|
|
250
|
+
expect(slotDuration({ minSlotDuration: 2 })).toBe(5);
|
|
251
|
+
expect(slotBuffer({})).toBe(0);
|
|
252
|
+
expect(slotBuffer({ bufferBetweenAppointments: -5 })).toBe(0);
|
|
253
|
+
expect(hourlyCapacity({})).toBeNull();
|
|
254
|
+
expect(hourlyCapacity({ maxPatientsPerHour: 0 })).toBe(1);
|
|
255
|
+
});
|
|
256
|
+
|
|
257
|
+
it('convert a date and minute to local minutes and back', () => {
|
|
258
|
+
expect(toLocalMinutes('1970-01-02', 30)).toBe(1470);
|
|
259
|
+
expect(fromLocalMinutes(at(MONDAY, '09:30'))).toEqual({ date: MONDAY, minute: 570 });
|
|
260
|
+
});
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
describe('generateSlots', () => {
|
|
264
|
+
const morning = availability({
|
|
265
|
+
weeklySchedule: [{ day: 1, start: '09:00', end: '11:00' }],
|
|
266
|
+
rules: { minSlotDuration: 30 },
|
|
267
|
+
});
|
|
268
|
+
const day = { from: MONDAY, to: MONDAY };
|
|
269
|
+
|
|
270
|
+
it('steps through each window by the slot duration', () => {
|
|
271
|
+
expect(generateSlots(morning, day)).toEqual([
|
|
272
|
+
{ date: MONDAY, start: 540, end: 570 },
|
|
273
|
+
{ date: MONDAY, start: 570, end: 600 },
|
|
274
|
+
{ date: MONDAY, start: 600, end: 630 },
|
|
275
|
+
{ date: MONDAY, start: 630, end: 660 },
|
|
276
|
+
]);
|
|
277
|
+
});
|
|
278
|
+
|
|
279
|
+
it('covers every date of the range and skips days off', () => {
|
|
280
|
+
const slots = generateSlots(morning, { from: '2025-01-05', to: '2025-01-13' });
|
|
281
|
+
expect([...new Set(slots.map((slot) => slot.date))]).toEqual([MONDAY, '2025-01-13']);
|
|
282
|
+
expect(generateSlots(morning, { from: '2025-01-13', to: MONDAY })).toEqual([]);
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
it('leaves the buffer between slots and around appointments', () => {
|
|
286
|
+
const buffered = availability({ ...morning, rules: { minSlotDuration: 30, bufferBetweenAppointments: 10 } });
|
|
287
|
+
expect(starts(generateSlots(buffered, day))).toEqual([540, 580, 620]);
|
|
288
|
+
const appointments = [{ start: at(MONDAY, '09:40'), end: at(MONDAY, '10:10') }];
|
|
289
|
+
expect(starts(generateSlots(buffered, { ...day, appointments }))).toEqual([540, 620]);
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
it('skips what overlaps an appointment or busy time, without buffer for busy time', () => {
|
|
293
|
+
const appointments = [{ start: at(MONDAY, '09:30'), end: at(MONDAY, '10:00') }];
|
|
294
|
+
expect(starts(generateSlots(morning, { ...day, appointments }))).toEqual([540, 600, 630]);
|
|
295
|
+
const busy = [{ start: at(MONDAY, '10:15'), end: at(MONDAY, '10:20') }];
|
|
296
|
+
expect(starts(generateSlots(morning, { ...day, busy }))).toEqual([540, 570, 630]);
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
it('offers nothing before notBefore', () => {
|
|
300
|
+
expect(starts(generateSlots(morning, { ...day, notBefore: at(MONDAY, '09:45') }))).toEqual([600, 630]);
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
it('closes an hour that already holds its limit of appointments', () => {
|
|
304
|
+
const capped = availability({ ...morning, rules: { minSlotDuration: 15, maxPatientsPerHour: 2 } });
|
|
305
|
+
const appointments = [
|
|
306
|
+
{ start: at(MONDAY, '09:00'), end: at(MONDAY, '09:15') },
|
|
307
|
+
{ start: at(MONDAY, '09:15'), end: at(MONDAY, '09:30') },
|
|
308
|
+
];
|
|
309
|
+
expect(starts(generateSlots(capped, { ...day, appointments }))).toEqual([600, 615, 630, 645]);
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
it('takes out the break and honours overrides', () => {
|
|
313
|
+
const withBreak = availability({
|
|
314
|
+
weeklySchedule: [{ day: 1, start: '12:00', end: '15:00' }],
|
|
315
|
+
overrides: [
|
|
316
|
+
{ date: '2025-01-13', fullDayClosed: true },
|
|
317
|
+
{ date: '2025-01-20', fullDayClosed: false, start: '08:00', end: '09:00' },
|
|
318
|
+
],
|
|
319
|
+
rules: { minSlotDuration: 60, breakStart: '13:00', breakEnd: '14:00' },
|
|
320
|
+
});
|
|
321
|
+
expect(starts(generateSlots(withBreak, day))).toEqual([720, 840]);
|
|
322
|
+
expect(generateSlots(withBreak, { from: '2025-01-13', to: '2025-01-13' })).toEqual([]);
|
|
323
|
+
expect(starts(generateSlots(withBreak, { from: '2025-01-20', to: '2025-01-20' }))).toEqual([480]);
|
|
324
|
+
});
|
|
325
|
+
|
|
326
|
+
it('offers the hours a night shift spills into the next morning', () => {
|
|
327
|
+
const night = availability({
|
|
328
|
+
weeklySchedule: [{ day: 3, start: '23:00', end: '01:00' }],
|
|
329
|
+
rules: { minSlotDuration: 60 },
|
|
330
|
+
});
|
|
331
|
+
expect(generateSlots(night, { from: '2025-01-09', to: '2025-01-09' })).toEqual([{ date: '2025-01-09', start: 0, end: 60 }]);
|
|
332
|
+
});
|
|
333
|
+
});
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { complementIntervals, mergeIntervals, subtractInterval, type Interval } from './intervals';
|
|
2
|
+
import { MINUTES_PER_DAY, dayOfWeek, isEndAfterStart, isValidTime, timeToMinutes } from './time';
|
|
3
|
+
import type { CalendarDate, DateOverride, DoctorAvailability, SchedulingRules, TimeOfDay, WeeklySlot } from './types';
|
|
4
|
+
|
|
5
|
+
type Schedule = Pick<DoctorAvailability, 'weeklySchedule' | 'overrides'>;
|
|
6
|
+
|
|
7
|
+
const CLOCK_PATTERN = /^([01]\d|2[0-3]):([0-5]\d)(?::[0-5]\d)?$/;
|
|
8
|
+
const END_OF_DAY_PATTERN = /^24:00(?::00)?$/;
|
|
9
|
+
const WHOLE_DAY: Interval = { start: 0, end: MINUTES_PER_DAY };
|
|
10
|
+
|
|
11
|
+
/** `end` may be `24:00`; an `end` at or before `start` runs past midnight into the next day. */
|
|
12
|
+
export interface DayHours {
|
|
13
|
+
start: TimeOfDay;
|
|
14
|
+
end: TimeOfDay;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export type DayWindowSource = 'override' | 'weekly' | 'spillover';
|
|
18
|
+
|
|
19
|
+
/** Minutes from that day's midnight. */
|
|
20
|
+
export interface DayWindow extends Interval {
|
|
21
|
+
source: DayWindowSource;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The hours that govern one date, before any merging: an override replaces the weekly pattern. */
|
|
25
|
+
export interface DateHours {
|
|
26
|
+
date: CalendarDate;
|
|
27
|
+
source: 'override' | 'weekly';
|
|
28
|
+
/** An override closed the day or left its hours blank, or the weekday has no slots. */
|
|
29
|
+
closed: boolean;
|
|
30
|
+
hours: DayHours[];
|
|
31
|
+
overrides: DateOverride[];
|
|
32
|
+
slots: WeeklySlot[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface DayWindows {
|
|
36
|
+
/** Merged, sorted and clipped to the day. */
|
|
37
|
+
windows: DayWindow[];
|
|
38
|
+
nonWorking: Interval[];
|
|
39
|
+
/** What runs past midnight, in minutes of the next day. */
|
|
40
|
+
spilloverNext: Interval[];
|
|
41
|
+
mergesApplied: boolean;
|
|
42
|
+
totalMinutes: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface DayResolution extends DayWindows {
|
|
46
|
+
date: CalendarDate;
|
|
47
|
+
fullDayOff: boolean;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function clockToMinutes(time: string, role: 'start' | 'end'): number {
|
|
51
|
+
if (role === 'end' && END_OF_DAY_PATTERN.test(time)) return MINUTES_PER_DAY;
|
|
52
|
+
const match = CLOCK_PATTERN.exec(time);
|
|
53
|
+
if (!match) throw new RangeError(`Invalid ${role} time: "${time}" (expected HH:mm)`);
|
|
54
|
+
return Number(match[1]) * 60 + Number(match[2]);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function hoursForDate({ weeklySchedule, overrides }: Schedule, date: CalendarDate): DateHours {
|
|
58
|
+
const dated = overrides.filter((override) => override.date === date);
|
|
59
|
+
if (dated.length > 0) {
|
|
60
|
+
const closed = dated.some((override) => override.fullDayClosed || !override.start || !override.end);
|
|
61
|
+
const hours = closed ? [] : dated.map(({ start, end }) => ({ start: start as TimeOfDay, end: end as TimeOfDay }));
|
|
62
|
+
return { date, source: 'override', closed, hours, overrides: dated, slots: [] };
|
|
63
|
+
}
|
|
64
|
+
const weekday = dayOfWeek(date);
|
|
65
|
+
const slots = weeklySchedule.filter((slot) => slot.day === weekday);
|
|
66
|
+
const hours = slots.map(({ start, end }) => ({ start, end }));
|
|
67
|
+
return { date, source: 'weekly', closed: slots.length === 0, hours, overrides: [], slots };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Turns a day's hours, plus what the previous day spilled over midnight, into canonical windows. */
|
|
71
|
+
export function resolveDayWindows(
|
|
72
|
+
hours: readonly DayHours[],
|
|
73
|
+
source: Exclude<DayWindowSource, 'spillover'> = 'weekly',
|
|
74
|
+
spilloverFromPrev: readonly Interval[] = [],
|
|
75
|
+
): DayWindows {
|
|
76
|
+
const windows: DayWindow[] = [];
|
|
77
|
+
const spilloverNext: Interval[] = [];
|
|
78
|
+
for (const entry of hours) {
|
|
79
|
+
const start = clockToMinutes(entry.start, 'start');
|
|
80
|
+
const clockEnd = clockToMinutes(entry.end, 'end');
|
|
81
|
+
const end = clockEnd > start ? clockEnd : clockEnd + MINUTES_PER_DAY;
|
|
82
|
+
windows.push({ start, end: Math.min(end, MINUTES_PER_DAY), source });
|
|
83
|
+
if (end > MINUTES_PER_DAY) spilloverNext.push({ start: 0, end: end - MINUTES_PER_DAY });
|
|
84
|
+
}
|
|
85
|
+
for (const { start, end } of spilloverFromPrev) {
|
|
86
|
+
const clipped = { start: Math.max(start, 0), end: Math.min(end, MINUTES_PER_DAY) };
|
|
87
|
+
if (clipped.end > clipped.start) windows.push({ ...clipped, source: 'spillover' });
|
|
88
|
+
}
|
|
89
|
+
const merged = mergeIntervals(windows);
|
|
90
|
+
return {
|
|
91
|
+
windows: merged,
|
|
92
|
+
nonWorking: complementIntervals(merged, WHOLE_DAY),
|
|
93
|
+
spilloverNext,
|
|
94
|
+
mergesApplied: merged.length !== windows.length,
|
|
95
|
+
totalMinutes: merged.reduce((total, window) => total + window.end - window.start, 0),
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A closing override wins over a shift that spilled in from the night before; a weekday without slots does not. */
|
|
100
|
+
export function resolveDay(
|
|
101
|
+
schedule: Schedule,
|
|
102
|
+
date: CalendarDate,
|
|
103
|
+
spilloverFromPrev: readonly Interval[] = [],
|
|
104
|
+
): DayResolution {
|
|
105
|
+
const { source, closed, hours } = hoursForDate(schedule, date);
|
|
106
|
+
if (source === 'override' && closed) {
|
|
107
|
+
return {
|
|
108
|
+
date,
|
|
109
|
+
windows: [],
|
|
110
|
+
nonWorking: [WHOLE_DAY],
|
|
111
|
+
spilloverNext: [],
|
|
112
|
+
mergesApplied: false,
|
|
113
|
+
totalMinutes: 0,
|
|
114
|
+
fullDayOff: true,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
const resolved = resolveDayWindows(hours, source, spilloverFromPrev);
|
|
118
|
+
return { date, ...resolved, fullDayOff: resolved.windows.length === 0 };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Takes the daily break out of the windows; a break without both valid ends changes nothing. */
|
|
122
|
+
export function applyBreak<T extends Interval>(windows: readonly T[], { breakStart, breakEnd }: SchedulingRules): T[] {
|
|
123
|
+
if (!breakStart || !breakEnd || !isValidTime(breakStart) || !isValidTime(breakEnd)) return [...windows];
|
|
124
|
+
if (!isEndAfterStart(breakStart, breakEnd)) return [...windows];
|
|
125
|
+
return subtractInterval(windows, { start: timeToMinutes(breakStart), end: timeToMinutes(breakEnd) });
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Whether anything can be booked from `today` on: some weekly hours, or a dated opening still ahead. */
|
|
129
|
+
export function isSchedulable({ weeklySchedule, overrides }: Schedule, today: CalendarDate): boolean {
|
|
130
|
+
if (weeklySchedule.some((slot) => timeToMinutes(slot.end) > timeToMinutes(slot.start))) return true;
|
|
131
|
+
return overrides.some((o) => o.date >= today && !o.fullDayClosed && Boolean(o.start) && Boolean(o.end));
|
|
132
|
+
}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
/** A professional's weekly hours, date exceptions and
|
|
1
|
+
/** A professional's weekly hours, date exceptions, booking rules, day resolution and bookable slots: data and pure functions. */
|
|
2
2
|
export * from './types';
|
|
3
3
|
export * from './defaults';
|
|
4
4
|
export * from './time';
|
|
5
5
|
export * from './validation';
|
|
6
6
|
export * from './week';
|
|
7
|
+
export * from './intervals';
|
|
8
|
+
export * from './day';
|
|
9
|
+
export * from './slots';
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** Half-open `[start, end)` on any numeric axis: minutes of a day, minutes since an epoch, seconds. */
|
|
2
|
+
export interface Interval {
|
|
3
|
+
start: number;
|
|
4
|
+
end: number;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export function intervalsOverlap(a: Interval, b: Interval): boolean {
|
|
8
|
+
return a.start < b.end && b.start < a.end;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Sorted by start; intervals that overlap or touch become one and keep the earlier one's other fields. */
|
|
12
|
+
export function mergeIntervals<T extends Interval>(intervals: readonly T[]): T[] {
|
|
13
|
+
const merged: T[] = [];
|
|
14
|
+
for (const interval of [...intervals].sort((a, b) => a.start - b.start)) {
|
|
15
|
+
const last = merged[merged.length - 1];
|
|
16
|
+
if (last && interval.start <= last.end) merged[merged.length - 1] = { ...last, end: Math.max(last.end, interval.end) };
|
|
17
|
+
else merged.push(interval);
|
|
18
|
+
}
|
|
19
|
+
return merged;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function subtractInterval<T extends Interval>(intervals: readonly T[], cut: Interval): T[] {
|
|
23
|
+
return intervals.flatMap((interval) => {
|
|
24
|
+
if (!intervalsOverlap(interval, cut)) return [interval];
|
|
25
|
+
const before = cut.start > interval.start ? [{ ...interval, end: cut.start }] : [];
|
|
26
|
+
const after = cut.end < interval.end ? [{ ...interval, start: cut.end }] : [];
|
|
27
|
+
return [...before, ...after];
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** What `bounds` has left once the intervals are taken out. */
|
|
32
|
+
export function complementIntervals(intervals: readonly Interval[], bounds: Interval): Interval[] {
|
|
33
|
+
const gaps: Interval[] = [];
|
|
34
|
+
let cursor = bounds.start;
|
|
35
|
+
for (const { start, end } of mergeIntervals(intervals)) {
|
|
36
|
+
if (start > cursor) gaps.push({ start: cursor, end: Math.min(start, bounds.end) });
|
|
37
|
+
cursor = Math.max(cursor, end);
|
|
38
|
+
}
|
|
39
|
+
if (cursor < bounds.end) gaps.push({ start: cursor, end: bounds.end });
|
|
40
|
+
return gaps.filter((gap) => gap.end > gap.start);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The first existing interval the candidate overlaps, or `null` when it is free. */
|
|
44
|
+
export function findConflict<T extends Interval>(existing: readonly T[], candidate: Interval): T | null {
|
|
45
|
+
if (!(candidate.end > candidate.start)) throw new RangeError('An interval must end after it starts');
|
|
46
|
+
return existing.find((interval) => intervalsOverlap(interval, candidate)) ?? null;
|
|
47
|
+
}
|