@free-intelligence/core 1.13.0 → 1.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/availability/index.d.ts +99 -1
- package/dist/availability/index.js +192 -0
- package/dist/availability/index.js.map +1 -1
- package/dist/membership/index.js +15 -5
- package/dist/membership/index.js.map +1 -1
- package/package.json +1 -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/term.ts +4 -8
package/README.md
CHANGED
|
@@ -18,7 +18,7 @@ is the glassmorphism skin built on top of it.
|
|
|
18
18
|
| `AgentHook` | The transport interface a consumer implements: `{ turn, isStreaming, send, reset, abort }`. |
|
|
19
19
|
| `ChatMessage`, `ConversationSummary` | Plain message / conversation shapes shared across the surface. |
|
|
20
20
|
| conversation helpers | Pure helpers for building and merging conversation transcripts. |
|
|
21
|
-
| `@free-intelligence/core/availability` | Weekly hours, date exceptions and booking rules: types, validation and week math. |
|
|
21
|
+
| `@free-intelligence/core/availability` | Weekly hours, date exceptions and booking rules: types, validation and week math. Day resolution (`hoursForDate`, `resolveDay`: an override replaces the weekly pattern, windows merge, night shifts spill into the next day), interval algebra, `isSchedulable` and `generateSlots` (duration, buffer, appointments, busy time, hourly limit). Time-zone free: dates and minutes in, the caller converts to instants. |
|
|
22
22
|
| `@free-intelligence/core/membership` | A paid membership's term, renewal chaining, status (`active`, `upcoming`, `cancelled`, `expired`, `refunded`) and renewal notice window. |
|
|
23
23
|
|
|
24
24
|
## Install
|
|
@@ -58,6 +58,11 @@ declare function isEndAfterStart(start: TimeOfDay, end: TimeOfDay): boolean;
|
|
|
58
58
|
declare function isValidDate(date: string): boolean;
|
|
59
59
|
/** Local calendar date; `toISOString` would roll to tomorrow in the evening west of Greenwich. */
|
|
60
60
|
declare function toCalendarDate(date: Date): CalendarDate;
|
|
61
|
+
declare function addDays(date: CalendarDate, days: number): CalendarDate;
|
|
62
|
+
/** Whole days from `from` to `to`; negative when `to` is earlier. */
|
|
63
|
+
declare function daysBetween(from: CalendarDate, to: CalendarDate): number;
|
|
64
|
+
/** As JavaScript counts it: 0 is Sunday. */
|
|
65
|
+
declare function dayOfWeek(date: CalendarDate): number;
|
|
61
66
|
|
|
62
67
|
declare function slotsOverlap(a: WeeklySlot, b: WeeklySlot): boolean;
|
|
63
68
|
declare function validateAvailability(availability: DoctorAvailability): AvailabilityError[];
|
|
@@ -76,4 +81,97 @@ declare function suggestNextSlot(day: number, existing: WeeklySlot[]): WeeklySlo
|
|
|
76
81
|
declare function weeklyHours(availability: DoctorAvailability): number;
|
|
77
82
|
declare function workingDays(availability: DoctorAvailability): number[];
|
|
78
83
|
|
|
79
|
-
|
|
84
|
+
/** Half-open `[start, end)` on any numeric axis: minutes of a day, minutes since an epoch, seconds. */
|
|
85
|
+
interface Interval {
|
|
86
|
+
start: number;
|
|
87
|
+
end: number;
|
|
88
|
+
}
|
|
89
|
+
declare function intervalsOverlap(a: Interval, b: Interval): boolean;
|
|
90
|
+
/** Sorted by start; intervals that overlap or touch become one and keep the earlier one's other fields. */
|
|
91
|
+
declare function mergeIntervals<T extends Interval>(intervals: readonly T[]): T[];
|
|
92
|
+
declare function subtractInterval<T extends Interval>(intervals: readonly T[], cut: Interval): T[];
|
|
93
|
+
/** What `bounds` has left once the intervals are taken out. */
|
|
94
|
+
declare function complementIntervals(intervals: readonly Interval[], bounds: Interval): Interval[];
|
|
95
|
+
/** The first existing interval the candidate overlaps, or `null` when it is free. */
|
|
96
|
+
declare function findConflict<T extends Interval>(existing: readonly T[], candidate: Interval): T | null;
|
|
97
|
+
|
|
98
|
+
type Schedule = Pick<DoctorAvailability, 'weeklySchedule' | 'overrides'>;
|
|
99
|
+
/** `end` may be `24:00`; an `end` at or before `start` runs past midnight into the next day. */
|
|
100
|
+
interface DayHours {
|
|
101
|
+
start: TimeOfDay;
|
|
102
|
+
end: TimeOfDay;
|
|
103
|
+
}
|
|
104
|
+
type DayWindowSource = 'override' | 'weekly' | 'spillover';
|
|
105
|
+
/** Minutes from that day's midnight. */
|
|
106
|
+
interface DayWindow extends Interval {
|
|
107
|
+
source: DayWindowSource;
|
|
108
|
+
}
|
|
109
|
+
/** The hours that govern one date, before any merging: an override replaces the weekly pattern. */
|
|
110
|
+
interface DateHours {
|
|
111
|
+
date: CalendarDate;
|
|
112
|
+
source: 'override' | 'weekly';
|
|
113
|
+
/** An override closed the day or left its hours blank, or the weekday has no slots. */
|
|
114
|
+
closed: boolean;
|
|
115
|
+
hours: DayHours[];
|
|
116
|
+
overrides: DateOverride[];
|
|
117
|
+
slots: WeeklySlot[];
|
|
118
|
+
}
|
|
119
|
+
interface DayWindows {
|
|
120
|
+
/** Merged, sorted and clipped to the day. */
|
|
121
|
+
windows: DayWindow[];
|
|
122
|
+
nonWorking: Interval[];
|
|
123
|
+
/** What runs past midnight, in minutes of the next day. */
|
|
124
|
+
spilloverNext: Interval[];
|
|
125
|
+
mergesApplied: boolean;
|
|
126
|
+
totalMinutes: number;
|
|
127
|
+
}
|
|
128
|
+
interface DayResolution extends DayWindows {
|
|
129
|
+
date: CalendarDate;
|
|
130
|
+
fullDayOff: boolean;
|
|
131
|
+
}
|
|
132
|
+
declare function hoursForDate({ weeklySchedule, overrides }: Schedule, date: CalendarDate): DateHours;
|
|
133
|
+
/** Turns a day's hours, plus what the previous day spilled over midnight, into canonical windows. */
|
|
134
|
+
declare function resolveDayWindows(hours: readonly DayHours[], source?: Exclude<DayWindowSource, 'spillover'>, spilloverFromPrev?: readonly Interval[]): DayWindows;
|
|
135
|
+
/** A closing override wins over a shift that spilled in from the night before; a weekday without slots does not. */
|
|
136
|
+
declare function resolveDay(schedule: Schedule, date: CalendarDate, spilloverFromPrev?: readonly Interval[]): DayResolution;
|
|
137
|
+
/** Takes the daily break out of the windows; a break without both valid ends changes nothing. */
|
|
138
|
+
declare function applyBreak<T extends Interval>(windows: readonly T[], { breakStart, breakEnd }: SchedulingRules): T[];
|
|
139
|
+
/** Whether anything can be booked from `today` on: some weekly hours, or a dated opening still ahead. */
|
|
140
|
+
declare function isSchedulable({ weeklySchedule, overrides }: Schedule, today: CalendarDate): boolean;
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Appointments, busy time and `notBefore` are local minutes: wall-clock minutes since 1970-01-01 00:00
|
|
144
|
+
* in the schedule's own time zone. The caller owns the conversion from and to instants.
|
|
145
|
+
*/
|
|
146
|
+
interface SlotQuery {
|
|
147
|
+
/** Both ends inclusive. */
|
|
148
|
+
from: CalendarDate;
|
|
149
|
+
to: CalendarDate;
|
|
150
|
+
appointments?: readonly Interval[];
|
|
151
|
+
/** Time taken outside this schedule, such as an external calendar. The buffer does not apply to it. */
|
|
152
|
+
busy?: readonly Interval[];
|
|
153
|
+
notBefore?: number;
|
|
154
|
+
}
|
|
155
|
+
/** `start` and `end` are minutes from that date's midnight. */
|
|
156
|
+
interface BookableSlot {
|
|
157
|
+
date: CalendarDate;
|
|
158
|
+
start: number;
|
|
159
|
+
end: number;
|
|
160
|
+
}
|
|
161
|
+
declare function toLocalMinutes(date: CalendarDate, minuteOfDay?: number): number;
|
|
162
|
+
declare function fromLocalMinutes(localMinutes: number): {
|
|
163
|
+
date: CalendarDate;
|
|
164
|
+
minute: number;
|
|
165
|
+
};
|
|
166
|
+
declare function slotDuration(rules: SchedulingRules): number;
|
|
167
|
+
declare function slotBuffer(rules: SchedulingRules): number;
|
|
168
|
+
/** `null` when the rules set no hourly limit. */
|
|
169
|
+
declare function hourlyCapacity(rules: SchedulingRules): number | null;
|
|
170
|
+
/**
|
|
171
|
+
* Every slot the schedule offers in the range: one per duration plus buffer inside each working window,
|
|
172
|
+
* minus what starts before `notBefore`, what comes within the buffer of an appointment, what overlaps
|
|
173
|
+
* busy time, and what starts in an hour that already holds its limit of appointments.
|
|
174
|
+
*/
|
|
175
|
+
declare function generateSlots(availability: DoctorAvailability, query: SlotQuery): BookableSlot[];
|
|
176
|
+
|
|
177
|
+
export { AVAILABILITY_TEMPLATES, AVAILABILITY_VERSION, AvailabilityError, AvailabilityTemplate, type BookableSlot, COMMON_EXCEPTION_REASONS, CalendarDate, DAYS_OF_WEEK, DEFAULT_BREAK_END, DEFAULT_BREAK_START, DEFAULT_RULES, DEFAULT_WORK_END, DEFAULT_WORK_START, type DateHours, DateOverride, type DayHours, type DayResolution, type DayWindow, type DayWindowSource, type DayWindows, DoctorAvailability, type Interval, MINUTES_PER_DAY, SLOT_DURATION_CHOICES, type ScheduleGap, SchedulingRules, type SlotQuery, TimeOfDay, WEEKDAYS, WEEKEND, WeekSchedule, WeeklySlot, addDays, applyBreak, availabilityFromWeek, complementIntervals, dayOfWeek, daysBetween, emptyAvailability, findConflict, findGaps, fromLocalMinutes, generateSlots, groupByDay, hasBlockingErrors, hourlyCapacity, hoursForDate, intervalsOverlap, isEndAfterStart, isSchedulable, isValidDate, isValidTime, mergeIntervals, minutesToTime, resolveDay, resolveDayWindows, slotBuffer, slotDuration, slotsOverlap, subtractInterval, suggestNextSlot, timeToMinutes, toCalendarDate, toLocalMinutes, validateAvailability, weeklyHours, workingDays };
|
|
@@ -105,6 +105,21 @@ function isValidDate(date) {
|
|
|
105
105
|
function toCalendarDate(date) {
|
|
106
106
|
return `${date.getFullYear()}-${twoDigits(date.getMonth() + 1)}-${twoDigits(date.getDate())}`;
|
|
107
107
|
}
|
|
108
|
+
var MS_PER_DAY = 24 * 60 * 60 * 1e3;
|
|
109
|
+
function toUtc(date) {
|
|
110
|
+
if (!isValidDate(date)) throw new RangeError(`Invalid calendar date: ${date}`);
|
|
111
|
+
const [year, month, day] = date.split("-").map(Number);
|
|
112
|
+
return Date.UTC(year, month - 1, day);
|
|
113
|
+
}
|
|
114
|
+
function addDays(date, days) {
|
|
115
|
+
return new Date(toUtc(date) + days * MS_PER_DAY).toISOString().slice(0, 10);
|
|
116
|
+
}
|
|
117
|
+
function daysBetween(from, to) {
|
|
118
|
+
return Math.round((toUtc(to) - toUtc(from)) / MS_PER_DAY);
|
|
119
|
+
}
|
|
120
|
+
function dayOfWeek(date) {
|
|
121
|
+
return new Date(toUtc(date)).getUTCDay();
|
|
122
|
+
}
|
|
108
123
|
|
|
109
124
|
// src/availability/validation.ts
|
|
110
125
|
var MIN_SLOT_DURATION = 5;
|
|
@@ -244,6 +259,164 @@ function weeklyHours(availability) {
|
|
|
244
259
|
function workingDays(availability) {
|
|
245
260
|
return [...new Set(availability.weeklySchedule.map((slot) => slot.day))].sort();
|
|
246
261
|
}
|
|
262
|
+
|
|
263
|
+
// src/availability/intervals.ts
|
|
264
|
+
function intervalsOverlap(a, b) {
|
|
265
|
+
return a.start < b.end && b.start < a.end;
|
|
266
|
+
}
|
|
267
|
+
function mergeIntervals(intervals) {
|
|
268
|
+
const merged = [];
|
|
269
|
+
for (const interval of [...intervals].sort((a, b) => a.start - b.start)) {
|
|
270
|
+
const last = merged[merged.length - 1];
|
|
271
|
+
if (last && interval.start <= last.end) merged[merged.length - 1] = { ...last, end: Math.max(last.end, interval.end) };
|
|
272
|
+
else merged.push(interval);
|
|
273
|
+
}
|
|
274
|
+
return merged;
|
|
275
|
+
}
|
|
276
|
+
function subtractInterval(intervals, cut) {
|
|
277
|
+
return intervals.flatMap((interval) => {
|
|
278
|
+
if (!intervalsOverlap(interval, cut)) return [interval];
|
|
279
|
+
const before = cut.start > interval.start ? [{ ...interval, end: cut.start }] : [];
|
|
280
|
+
const after = cut.end < interval.end ? [{ ...interval, start: cut.end }] : [];
|
|
281
|
+
return [...before, ...after];
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
function complementIntervals(intervals, bounds) {
|
|
285
|
+
const gaps = [];
|
|
286
|
+
let cursor = bounds.start;
|
|
287
|
+
for (const { start, end } of mergeIntervals(intervals)) {
|
|
288
|
+
if (start > cursor) gaps.push({ start: cursor, end: Math.min(start, bounds.end) });
|
|
289
|
+
cursor = Math.max(cursor, end);
|
|
290
|
+
}
|
|
291
|
+
if (cursor < bounds.end) gaps.push({ start: cursor, end: bounds.end });
|
|
292
|
+
return gaps.filter((gap) => gap.end > gap.start);
|
|
293
|
+
}
|
|
294
|
+
function findConflict(existing, candidate) {
|
|
295
|
+
if (!(candidate.end > candidate.start)) throw new RangeError("An interval must end after it starts");
|
|
296
|
+
return existing.find((interval) => intervalsOverlap(interval, candidate)) ?? null;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// src/availability/day.ts
|
|
300
|
+
var CLOCK_PATTERN = /^([01]\d|2[0-3]):([0-5]\d)(?::[0-5]\d)?$/;
|
|
301
|
+
var END_OF_DAY_PATTERN = /^24:00(?::00)?$/;
|
|
302
|
+
var WHOLE_DAY = { start: 0, end: MINUTES_PER_DAY };
|
|
303
|
+
function clockToMinutes(time, role) {
|
|
304
|
+
if (role === "end" && END_OF_DAY_PATTERN.test(time)) return MINUTES_PER_DAY;
|
|
305
|
+
const match = CLOCK_PATTERN.exec(time);
|
|
306
|
+
if (!match) throw new RangeError(`Invalid ${role} time: "${time}" (expected HH:mm)`);
|
|
307
|
+
return Number(match[1]) * 60 + Number(match[2]);
|
|
308
|
+
}
|
|
309
|
+
function hoursForDate({ weeklySchedule, overrides }, date) {
|
|
310
|
+
const dated = overrides.filter((override) => override.date === date);
|
|
311
|
+
if (dated.length > 0) {
|
|
312
|
+
const closed = dated.some((override) => override.fullDayClosed || !override.start || !override.end);
|
|
313
|
+
const hours2 = closed ? [] : dated.map(({ start, end }) => ({ start, end }));
|
|
314
|
+
return { date, source: "override", closed, hours: hours2, overrides: dated, slots: [] };
|
|
315
|
+
}
|
|
316
|
+
const weekday = dayOfWeek(date);
|
|
317
|
+
const slots = weeklySchedule.filter((slot) => slot.day === weekday);
|
|
318
|
+
const hours = slots.map(({ start, end }) => ({ start, end }));
|
|
319
|
+
return { date, source: "weekly", closed: slots.length === 0, hours, overrides: [], slots };
|
|
320
|
+
}
|
|
321
|
+
function resolveDayWindows(hours, source = "weekly", spilloverFromPrev = []) {
|
|
322
|
+
const windows = [];
|
|
323
|
+
const spilloverNext = [];
|
|
324
|
+
for (const entry of hours) {
|
|
325
|
+
const start = clockToMinutes(entry.start, "start");
|
|
326
|
+
const clockEnd = clockToMinutes(entry.end, "end");
|
|
327
|
+
const end = clockEnd > start ? clockEnd : clockEnd + MINUTES_PER_DAY;
|
|
328
|
+
windows.push({ start, end: Math.min(end, MINUTES_PER_DAY), source });
|
|
329
|
+
if (end > MINUTES_PER_DAY) spilloverNext.push({ start: 0, end: end - MINUTES_PER_DAY });
|
|
330
|
+
}
|
|
331
|
+
for (const { start, end } of spilloverFromPrev) {
|
|
332
|
+
const clipped = { start: Math.max(start, 0), end: Math.min(end, MINUTES_PER_DAY) };
|
|
333
|
+
if (clipped.end > clipped.start) windows.push({ ...clipped, source: "spillover" });
|
|
334
|
+
}
|
|
335
|
+
const merged = mergeIntervals(windows);
|
|
336
|
+
return {
|
|
337
|
+
windows: merged,
|
|
338
|
+
nonWorking: complementIntervals(merged, WHOLE_DAY),
|
|
339
|
+
spilloverNext,
|
|
340
|
+
mergesApplied: merged.length !== windows.length,
|
|
341
|
+
totalMinutes: merged.reduce((total, window) => total + window.end - window.start, 0)
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
function resolveDay(schedule, date, spilloverFromPrev = []) {
|
|
345
|
+
const { source, closed, hours } = hoursForDate(schedule, date);
|
|
346
|
+
if (source === "override" && closed) {
|
|
347
|
+
return {
|
|
348
|
+
date,
|
|
349
|
+
windows: [],
|
|
350
|
+
nonWorking: [WHOLE_DAY],
|
|
351
|
+
spilloverNext: [],
|
|
352
|
+
mergesApplied: false,
|
|
353
|
+
totalMinutes: 0,
|
|
354
|
+
fullDayOff: true
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
const resolved = resolveDayWindows(hours, source, spilloverFromPrev);
|
|
358
|
+
return { date, ...resolved, fullDayOff: resolved.windows.length === 0 };
|
|
359
|
+
}
|
|
360
|
+
function applyBreak(windows, { breakStart, breakEnd }) {
|
|
361
|
+
if (!breakStart || !breakEnd || !isValidTime(breakStart) || !isValidTime(breakEnd)) return [...windows];
|
|
362
|
+
if (!isEndAfterStart(breakStart, breakEnd)) return [...windows];
|
|
363
|
+
return subtractInterval(windows, { start: timeToMinutes(breakStart), end: timeToMinutes(breakEnd) });
|
|
364
|
+
}
|
|
365
|
+
function isSchedulable({ weeklySchedule, overrides }, today) {
|
|
366
|
+
if (weeklySchedule.some((slot) => timeToMinutes(slot.end) > timeToMinutes(slot.start))) return true;
|
|
367
|
+
return overrides.some((o) => o.date >= today && !o.fullDayClosed && Boolean(o.start) && Boolean(o.end));
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// src/availability/slots.ts
|
|
371
|
+
var EPOCH = "1970-01-01";
|
|
372
|
+
var MINUTES_PER_DAY2 = 24 * 60;
|
|
373
|
+
var SHORTEST_SLOT = 5;
|
|
374
|
+
function toLocalMinutes(date, minuteOfDay = 0) {
|
|
375
|
+
return daysBetween(EPOCH, date) * MINUTES_PER_DAY2 + minuteOfDay;
|
|
376
|
+
}
|
|
377
|
+
function fromLocalMinutes(localMinutes) {
|
|
378
|
+
const days = Math.floor(localMinutes / MINUTES_PER_DAY2);
|
|
379
|
+
return { date: addDays(EPOCH, days), minute: localMinutes - days * MINUTES_PER_DAY2 };
|
|
380
|
+
}
|
|
381
|
+
function slotDuration(rules) {
|
|
382
|
+
return Math.max(SHORTEST_SLOT, Math.trunc(rules.minSlotDuration ?? DEFAULT_RULES.minSlotDuration));
|
|
383
|
+
}
|
|
384
|
+
function slotBuffer(rules) {
|
|
385
|
+
return Math.max(0, Math.trunc(rules.bufferBetweenAppointments ?? 0));
|
|
386
|
+
}
|
|
387
|
+
function hourlyCapacity(rules) {
|
|
388
|
+
const { maxPatientsPerHour } = rules;
|
|
389
|
+
return maxPatientsPerHour === void 0 || maxPatientsPerHour === null ? null : Math.max(1, Math.trunc(maxPatientsPerHour));
|
|
390
|
+
}
|
|
391
|
+
var hourOf = (localMinutes) => Math.floor(localMinutes / 60);
|
|
392
|
+
function generateSlots(availability, query) {
|
|
393
|
+
const { rules } = availability;
|
|
394
|
+
const { from, to, appointments = [], busy = [], notBefore = -Infinity } = query;
|
|
395
|
+
const duration = slotDuration(rules);
|
|
396
|
+
const buffer = slotBuffer(rules);
|
|
397
|
+
const capacity = hourlyCapacity(rules);
|
|
398
|
+
const bookedPerHour = /* @__PURE__ */ new Map();
|
|
399
|
+
for (const { start } of appointments) bookedPerHour.set(hourOf(start), (bookedPerHour.get(hourOf(start)) ?? 0) + 1);
|
|
400
|
+
const guarded = appointments.map(({ start, end }) => ({ start: start - buffer, end: end + buffer }));
|
|
401
|
+
const slots = [];
|
|
402
|
+
let spillover = resolveDay(availability, addDays(from, -1)).spilloverNext;
|
|
403
|
+
for (let date = from; date <= to; date = addDays(date, 1)) {
|
|
404
|
+
const day = resolveDay(availability, date, spillover);
|
|
405
|
+
const midnight = toLocalMinutes(date);
|
|
406
|
+
for (const window of applyBreak(day.windows, rules)) {
|
|
407
|
+
for (let start = window.start; start + duration <= window.end; start += duration + buffer) {
|
|
408
|
+
const local = { start: midnight + start, end: midnight + start + duration };
|
|
409
|
+
if (local.start < notBefore) continue;
|
|
410
|
+
if (guarded.some((taken) => intervalsOverlap(local, taken))) continue;
|
|
411
|
+
if (busy.some((taken) => intervalsOverlap(local, taken))) continue;
|
|
412
|
+
if (capacity !== null && (bookedPerHour.get(hourOf(local.start)) ?? 0) >= capacity) continue;
|
|
413
|
+
slots.push({ date, start, end: start + duration });
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
spillover = day.spilloverNext;
|
|
417
|
+
}
|
|
418
|
+
return slots;
|
|
419
|
+
}
|
|
247
420
|
export {
|
|
248
421
|
AVAILABILITY_TEMPLATES,
|
|
249
422
|
AVAILABILITY_VERSION,
|
|
@@ -258,19 +431,38 @@ export {
|
|
|
258
431
|
SLOT_DURATION_CHOICES,
|
|
259
432
|
WEEKDAYS,
|
|
260
433
|
WEEKEND,
|
|
434
|
+
addDays,
|
|
435
|
+
applyBreak,
|
|
261
436
|
availabilityFromWeek,
|
|
437
|
+
complementIntervals,
|
|
438
|
+
dayOfWeek,
|
|
439
|
+
daysBetween,
|
|
262
440
|
emptyAvailability,
|
|
441
|
+
findConflict,
|
|
263
442
|
findGaps,
|
|
443
|
+
fromLocalMinutes,
|
|
444
|
+
generateSlots,
|
|
264
445
|
groupByDay,
|
|
265
446
|
hasBlockingErrors,
|
|
447
|
+
hourlyCapacity,
|
|
448
|
+
hoursForDate,
|
|
449
|
+
intervalsOverlap,
|
|
266
450
|
isEndAfterStart,
|
|
451
|
+
isSchedulable,
|
|
267
452
|
isValidDate,
|
|
268
453
|
isValidTime,
|
|
454
|
+
mergeIntervals,
|
|
269
455
|
minutesToTime,
|
|
456
|
+
resolveDay,
|
|
457
|
+
resolveDayWindows,
|
|
458
|
+
slotBuffer,
|
|
459
|
+
slotDuration,
|
|
270
460
|
slotsOverlap,
|
|
461
|
+
subtractInterval,
|
|
271
462
|
suggestNextSlot,
|
|
272
463
|
timeToMinutes,
|
|
273
464
|
toCalendarDate,
|
|
465
|
+
toLocalMinutes,
|
|
274
466
|
validateAvailability,
|
|
275
467
|
weeklyHours,
|
|
276
468
|
workingDays
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/availability/defaults.ts","../../src/availability/time.ts","../../src/availability/validation.ts","../../src/availability/week.ts"],"sourcesContent":["import type { AvailabilityTemplate, DoctorAvailability, SchedulingRules, WeeklySlot } from './types';\n\nexport const AVAILABILITY_VERSION = 1;\n\nexport const DAYS_OF_WEEK = [\n { value: 0, label: 'Domingo', short: 'Dom', abbr: 'D' },\n { value: 1, label: 'Lunes', short: 'Lun', abbr: 'L' },\n { value: 2, label: 'Martes', short: 'Mar', abbr: 'M' },\n { value: 3, label: 'Miércoles', short: 'Mié', abbr: 'X' },\n { value: 4, label: 'Jueves', short: 'Jue', abbr: 'J' },\n { value: 5, label: 'Viernes', short: 'Vie', abbr: 'V' },\n { value: 6, label: 'Sábado', short: 'Sáb', abbr: 'S' },\n] as const;\n\nexport const WEEKDAYS = [1, 2, 3, 4, 5] as const;\nexport const WEEKEND = [0, 6] as const;\n\nexport const DEFAULT_WORK_START = '09:00';\nexport const DEFAULT_WORK_END = '18:00';\nexport const DEFAULT_BREAK_START = '13:00';\nexport const DEFAULT_BREAK_END = '14:00';\n\nexport const SLOT_DURATION_CHOICES = [15, 20, 30, 45, 60] as const;\n\nexport const DEFAULT_RULES: Readonly<SchedulingRules> = {\n minSlotDuration: 15,\n maxPatientsPerHour: 4,\n bufferBetweenAppointments: 5,\n};\n\nexport const COMMON_EXCEPTION_REASONS = [\n 'Vacaciones',\n 'Día festivo',\n 'Conferencia',\n 'Capacitación',\n 'Cita personal',\n 'Enfermedad',\n 'Emergencia familiar',\n] as const;\n\nexport function emptyAvailability(): DoctorAvailability {\n return { version: AVAILABILITY_VERSION, weeklySchedule: [], overrides: [], rules: { ...DEFAULT_RULES } };\n}\n\nconst everyDay = (days: readonly number[], ...hours: Omit<WeeklySlot, 'day'>[]): WeeklySlot[] =>\n days.flatMap((day) => hours.map((slot) => ({ day, ...slot })));\n\nexport const AVAILABILITY_TEMPLATES: AvailabilityTemplate[] = [\n {\n id: 'standard-9-5',\n name: 'Estándar 9-18 (L-V)',\n description: '9:00 - 18:00, lunes a viernes, fines de semana libres',\n weeklySchedule: everyDay(WEEKDAYS, { start: '09:00', end: '18:00' }),\n },\n {\n id: 'morning-clinic',\n name: 'Clínica Matutina (L-V)',\n description: '8:00 - 14:00, lunes a viernes',\n weeklySchedule: everyDay(WEEKDAYS, { start: '08:00', end: '14:00' }),\n },\n {\n id: 'afternoon-clinic',\n name: 'Clínica Vespertina (L-V)',\n description: '15:00 - 21:00, lunes a viernes',\n weeklySchedule: everyDay(WEEKDAYS, { start: '15:00', end: '21:00' }),\n },\n {\n id: 'split-shift',\n name: 'Turno Partido (L-V)',\n description: '9:00 - 13:00 y 16:00 - 20:00, lunes a viernes',\n weeklySchedule: everyDay(\n WEEKDAYS,\n { start: '09:00', end: '13:00', label: 'Mañana' },\n { start: '16:00', end: '20:00', label: 'Tarde' },\n ),\n },\n {\n id: 'weekend-doctor',\n name: 'Doctor de Fin de Semana',\n description: '10:00 - 14:00, sábado y domingo',\n weeklySchedule: everyDay(WEEKEND, { start: '10:00', end: '14:00' }),\n },\n {\n id: 'full-week',\n name: 'Semana Completa',\n description: '9:00 - 18:00, todos los días',\n weeklySchedule: everyDay([0, ...WEEKDAYS, 6], { start: '09:00', end: '18:00' }),\n },\n];\n","import type { CalendarDate, TimeOfDay } from './types';\n\nexport const MINUTES_PER_DAY = 24 * 60;\n\nconst TIME_PATTERN = /^([01]\\d|2[0-3]):[0-5]\\d$/;\nconst DATE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\nconst twoDigits = (value: number): string => String(value).padStart(2, '0');\n\nexport function timeToMinutes(time: TimeOfDay): number {\n const [hours, minutes] = time.split(':').map(Number);\n return hours * 60 + minutes;\n}\n\nexport function minutesToTime(minutes: number): TimeOfDay {\n return `${twoDigits(Math.floor(minutes / 60) % 24)}:${twoDigits(minutes % 60)}`;\n}\n\nexport function isValidTime(time: string): boolean {\n return TIME_PATTERN.test(time);\n}\n\nexport function isEndAfterStart(start: TimeOfDay, end: TimeOfDay): boolean {\n return timeToMinutes(end) > timeToMinutes(start);\n}\n\nexport function isValidDate(date: string): boolean {\n const match = DATE_PATTERN.exec(date);\n if (!match) return false;\n const [year, month, day] = match.slice(1).map(Number);\n const parsed = new Date(Date.UTC(year, month - 1, day));\n return parsed.getUTCMonth() === month - 1 && parsed.getUTCDate() === day;\n}\n\n/** Local calendar date; `toISOString` would roll to tomorrow in the evening west of Greenwich. */\nexport function toCalendarDate(date: Date): CalendarDate {\n return `${date.getFullYear()}-${twoDigits(date.getMonth() + 1)}-${twoDigits(date.getDate())}`;\n}\n","import { isEndAfterStart, isValidDate, isValidTime, timeToMinutes } from './time';\nimport type {\n AvailabilityError,\n DateOverride,\n DoctorAvailability,\n SchedulingRules,\n WeeklySlot,\n} from './types';\n\nconst MIN_SLOT_DURATION = 5;\n\ntype Problem = Pick<AvailabilityError, 'type' | 'message'>;\n\nfunction problemInHours(start: string, end: string): Problem | null {\n if (!isValidTime(start)) return { type: 'invalid_time', message: `Hora de inicio inválida: ${start}` };\n if (!isValidTime(end)) return { type: 'invalid_time', message: `Hora de fin inválida: ${end}` };\n if (!isEndAfterStart(start, end)) {\n return {\n type: 'end_before_start',\n message: `La hora de fin (${end}) debe ser posterior a la de inicio (${start})`,\n };\n }\n return null;\n}\n\nfunction problemInOverride(override: DateOverride): Problem | null {\n if (!isValidDate(override.date)) return { type: 'invalid_time', message: `Fecha inválida: ${override.date}` };\n if (override.fullDayClosed) return null;\n if (!override.start || !override.end) {\n return { type: 'invalid_time', message: 'Debe especificar hora de inicio y fin, o marcar como día libre' };\n }\n return problemInHours(override.start, override.end);\n}\n\nfunction problemsInRules(rules: SchedulingRules): AvailabilityError[] {\n const errors: AvailabilityError[] = [];\n const { breakStart, breakEnd, minSlotDuration, maxPatientsPerHour } = rules;\n\n if (breakStart && breakEnd) {\n const problem = problemInHours(breakStart, breakEnd);\n if (problem) errors.push({ ...problem, message: `Descanso: ${problem.message}`, severity: 'error' });\n } else if (breakStart || breakEnd) {\n errors.push({\n type: 'invalid_time',\n message: 'Debe especificar tanto inicio como fin del descanso',\n severity: 'warning',\n });\n }\n if (minSlotDuration !== undefined && minSlotDuration < MIN_SLOT_DURATION) {\n errors.push({\n type: 'invalid_time',\n message: `La duración mínima debe ser al menos ${MIN_SLOT_DURATION} minutos`,\n severity: 'error',\n });\n }\n if (maxPatientsPerHour !== undefined && maxPatientsPerHour < 1) {\n errors.push({ type: 'invalid_time', message: 'Debe permitir al menos 1 paciente por hora', severity: 'error' });\n }\n return errors;\n}\n\nexport function slotsOverlap(a: WeeklySlot, b: WeeklySlot): boolean {\n return (\n a.day === b.day &&\n timeToMinutes(a.start) < timeToMinutes(b.end) &&\n timeToMinutes(b.start) < timeToMinutes(a.end)\n );\n}\n\nfunction slotsByDay(slots: WeeklySlot[]): Map<number, WeeklySlot[]> {\n const days = new Map<number, WeeklySlot[]>();\n for (const slot of slots) days.set(slot.day, [...(days.get(slot.day) ?? []), slot]);\n return days;\n}\n\nfunction problemsInDay(day: number, slots: WeeklySlot[]): AvailabilityError[] {\n const errors: AvailabilityError[] = [];\n slots.forEach((slot, slotIndex) => {\n const problem = problemInHours(slot.start, slot.end);\n if (problem) errors.push({ ...problem, day, slotIndex, severity: 'error' });\n slots.slice(0, slotIndex).forEach((earlier) => {\n if (!slotsOverlap(earlier, slot)) return;\n errors.push({\n type: 'overlap',\n day,\n slotIndex,\n message: `Solapamiento detectado: ${earlier.start}-${earlier.end} y ${slot.start}-${slot.end}`,\n severity: 'error',\n });\n });\n });\n return errors;\n}\n\nfunction problemsInOverrides(overrides: DateOverride[]): AvailabilityError[] {\n const errors: AvailabilityError[] = [];\n const seen = new Set<string>();\n for (const override of overrides) {\n const { date } = override;\n const problem = problemInOverride(override);\n if (problem) errors.push({ ...problem, date, severity: 'error' });\n if (seen.has(date)) {\n errors.push({ type: 'duplicate_date', date, message: `Fecha duplicada: ${date}`, severity: 'error' });\n }\n seen.add(date);\n }\n return errors;\n}\n\nexport function validateAvailability(availability: DoctorAvailability): AvailabilityError[] {\n const weekly = [...slotsByDay(availability.weeklySchedule)].flatMap(([day, slots]) => problemsInDay(day, slots));\n return [...weekly, ...problemsInOverrides(availability.overrides), ...problemsInRules(availability.rules)];\n}\n\nexport function hasBlockingErrors(errors: AvailabilityError[]): boolean {\n return errors.some((error) => error.severity === 'error');\n}\n\nexport interface ScheduleGap {\n day: number;\n from: string;\n to: string;\n}\n\nexport function findGaps(slots: WeeklySlot[]): ScheduleGap[] {\n return [...slotsByDay(slots)].flatMap(([day, daySlots]) => {\n const sorted = [...daySlots].sort((a, b) => timeToMinutes(a.start) - timeToMinutes(b.start));\n return sorted.slice(1).flatMap((next, i) => {\n const previous = sorted[i];\n return isEndAfterStart(previous.end, next.start) ? [{ day, from: previous.end, to: next.start }] : [];\n });\n });\n}\n","import { AVAILABILITY_VERSION, DAYS_OF_WEEK, DEFAULT_WORK_END, DEFAULT_WORK_START } from './defaults';\nimport { MINUTES_PER_DAY, minutesToTime, timeToMinutes } from './time';\nimport type { DateOverride, DoctorAvailability, SchedulingRules, WeeklySlot, WeekSchedule } from './types';\n\nconst GAP_BEFORE_NEW_SLOT = 60;\nconst NEW_SLOT_LENGTH = 4 * 60;\nconst SHORTEST_NEW_SLOT = 30;\nconst LAST_MINUTE = MINUTES_PER_DAY - 1;\n\nexport function groupByDay(weeklySchedule: WeeklySlot[]): WeekSchedule {\n return Object.fromEntries(\n DAYS_OF_WEEK.map(({ value }) => {\n const slots = weeklySchedule\n .filter((slot) => slot.day === value)\n .sort((a, b) => timeToMinutes(a.start) - timeToMinutes(b.start));\n return [value, { isWorking: slots.length > 0, slots }];\n }),\n );\n}\n\nexport function availabilityFromWeek(\n week: WeekSchedule,\n overrides: DateOverride[],\n rules: SchedulingRules,\n): DoctorAvailability {\n const weeklySchedule = Object.values(week).flatMap((day) => (day.isWorking ? day.slots : []));\n return { version: AVAILABILITY_VERSION, weeklySchedule, overrides, rules };\n}\n\n/** `null` when the day has no room left before midnight. */\nexport function suggestNextSlot(day: number, existing: WeeklySlot[]): WeeklySlot | null {\n const last = existing[existing.length - 1];\n if (!last) return { day, start: DEFAULT_WORK_START, end: DEFAULT_WORK_END };\n const start = timeToMinutes(last.end) + GAP_BEFORE_NEW_SLOT;\n const end = Math.min(start + NEW_SLOT_LENGTH, LAST_MINUTE);\n if (!(end - start >= SHORTEST_NEW_SLOT)) return null;\n return { day, start: minutesToTime(start), end: minutesToTime(end) };\n}\n\nexport function weeklyHours(availability: DoctorAvailability): number {\n const minutes = availability.weeklySchedule.reduce(\n (total, slot) => total + timeToMinutes(slot.end) - timeToMinutes(slot.start),\n 0,\n );\n return minutes / 60;\n}\n\nexport function workingDays(availability: DoctorAvailability): number[] {\n return [...new Set(availability.weeklySchedule.map((slot) => slot.day))].sort();\n}\n"],"mappings":";AAEO,IAAM,uBAAuB;AAE7B,IAAM,eAAe;AAAA,EAC1B,EAAE,OAAO,GAAG,OAAO,WAAW,OAAO,OAAO,MAAM,IAAI;AAAA,EACtD,EAAE,OAAO,GAAG,OAAO,SAAS,OAAO,OAAO,MAAM,IAAI;AAAA,EACpD,EAAE,OAAO,GAAG,OAAO,UAAU,OAAO,OAAO,MAAM,IAAI;AAAA,EACrD,EAAE,OAAO,GAAG,OAAO,gBAAa,OAAO,UAAO,MAAM,IAAI;AAAA,EACxD,EAAE,OAAO,GAAG,OAAO,UAAU,OAAO,OAAO,MAAM,IAAI;AAAA,EACrD,EAAE,OAAO,GAAG,OAAO,WAAW,OAAO,OAAO,MAAM,IAAI;AAAA,EACtD,EAAE,OAAO,GAAG,OAAO,aAAU,OAAO,UAAO,MAAM,IAAI;AACvD;AAEO,IAAM,WAAW,CAAC,GAAG,GAAG,GAAG,GAAG,CAAC;AAC/B,IAAM,UAAU,CAAC,GAAG,CAAC;AAErB,IAAM,qBAAqB;AAC3B,IAAM,mBAAmB;AACzB,IAAM,sBAAsB;AAC5B,IAAM,oBAAoB;AAE1B,IAAM,wBAAwB,CAAC,IAAI,IAAI,IAAI,IAAI,EAAE;AAEjD,IAAM,gBAA2C;AAAA,EACtD,iBAAiB;AAAA,EACjB,oBAAoB;AAAA,EACpB,2BAA2B;AAC7B;AAEO,IAAM,2BAA2B;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,oBAAwC;AACtD,SAAO,EAAE,SAAS,sBAAsB,gBAAgB,CAAC,GAAG,WAAW,CAAC,GAAG,OAAO,EAAE,GAAG,cAAc,EAAE;AACzG;AAEA,IAAM,WAAW,CAAC,SAA4B,UAC5C,KAAK,QAAQ,CAAC,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E,QAAQ,CAAC,QAAS,IAAI,YAAY,IAAI,QAAQ,CAAC,CAAE;AAC5F,SAAO,EAAE,SAAS,sBAAsB,gBAAgB,WAAW,MAAM;AAC3E;AAGO,SAAS,gBAAgB,KAAa,UAA2C;AACtF,QAAM,OAAO,SAAS,SAAS,SAAS,CAAC;AACzC,MAAI,CAAC,KAAM,QAAO,EAAE,KAAK,OAAO,oBAAoB,KAAK,iBAAiB;AAC1E,QAAM,QAAQ,cAAc,KAAK,GAAG,IAAI;AACxC,QAAM,MAAM,KAAK,IAAI,QAAQ,iBAAiB,WAAW;AACzD,MAAI,EAAE,MAAM,SAAS,mBAAoB,QAAO;AAChD,SAAO,EAAE,KAAK,OAAO,cAAc,KAAK,GAAG,KAAK,cAAc,GAAG,EAAE;AACrE;AAEO,SAAS,YAAY,cAA0C;AACpE,QAAM,UAAU,aAAa,eAAe;AAAA,IAC1C,CAAC,OAAO,SAAS,QAAQ,cAAc,KAAK,GAAG,IAAI,cAAc,KAAK,KAAK;AAAA,IAC3E;AAAA,EACF;AACA,SAAO,UAAU;AACnB;AAEO,SAAS,YAAY,cAA4C;AACtE,SAAO,CAAC,GAAG,IAAI,IAAI,aAAa,eAAe,IAAI,CAAC,SAAS,KAAK,GAAG,CAAC,CAAC,EAAE,KAAK;AAChF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/availability/defaults.ts","../../src/availability/time.ts","../../src/availability/validation.ts","../../src/availability/week.ts","../../src/availability/intervals.ts","../../src/availability/day.ts","../../src/availability/slots.ts"],"sourcesContent":["import type { AvailabilityTemplate, DoctorAvailability, SchedulingRules, WeeklySlot } from './types';\n\nexport const AVAILABILITY_VERSION = 1;\n\nexport const DAYS_OF_WEEK = [\n { value: 0, label: 'Domingo', short: 'Dom', abbr: 'D' },\n { value: 1, label: 'Lunes', short: 'Lun', abbr: 'L' },\n { value: 2, label: 'Martes', short: 'Mar', abbr: 'M' },\n { value: 3, label: 'Miércoles', short: 'Mié', abbr: 'X' },\n { value: 4, label: 'Jueves', short: 'Jue', abbr: 'J' },\n { value: 5, label: 'Viernes', short: 'Vie', abbr: 'V' },\n { value: 6, label: 'Sábado', short: 'Sáb', abbr: 'S' },\n] as const;\n\nexport const WEEKDAYS = [1, 2, 3, 4, 5] as const;\nexport const WEEKEND = [0, 6] as const;\n\nexport const DEFAULT_WORK_START = '09:00';\nexport const DEFAULT_WORK_END = '18:00';\nexport const DEFAULT_BREAK_START = '13:00';\nexport const DEFAULT_BREAK_END = '14:00';\n\nexport const SLOT_DURATION_CHOICES = [15, 20, 30, 45, 60] as const;\n\nexport const DEFAULT_RULES: Readonly<SchedulingRules> = {\n minSlotDuration: 15,\n maxPatientsPerHour: 4,\n bufferBetweenAppointments: 5,\n};\n\nexport const COMMON_EXCEPTION_REASONS = [\n 'Vacaciones',\n 'Día festivo',\n 'Conferencia',\n 'Capacitación',\n 'Cita personal',\n 'Enfermedad',\n 'Emergencia familiar',\n] as const;\n\nexport function emptyAvailability(): DoctorAvailability {\n return { version: AVAILABILITY_VERSION, weeklySchedule: [], overrides: [], rules: { ...DEFAULT_RULES } };\n}\n\nconst everyDay = (days: readonly number[], ...hours: Omit<WeeklySlot, 'day'>[]): WeeklySlot[] =>\n days.flatMap((day) => hours.map((slot) => ({ day, ...slot })));\n\nexport const AVAILABILITY_TEMPLATES: AvailabilityTemplate[] = [\n {\n id: 'standard-9-5',\n name: 'Estándar 9-18 (L-V)',\n description: '9:00 - 18:00, lunes a viernes, fines de semana libres',\n weeklySchedule: everyDay(WEEKDAYS, { start: '09:00', end: '18:00' }),\n },\n {\n id: 'morning-clinic',\n name: 'Clínica Matutina (L-V)',\n description: '8:00 - 14:00, lunes a viernes',\n weeklySchedule: everyDay(WEEKDAYS, { start: '08:00', end: '14:00' }),\n },\n {\n id: 'afternoon-clinic',\n name: 'Clínica Vespertina (L-V)',\n description: '15:00 - 21:00, lunes a viernes',\n weeklySchedule: everyDay(WEEKDAYS, { start: '15:00', end: '21:00' }),\n },\n {\n id: 'split-shift',\n name: 'Turno Partido (L-V)',\n description: '9:00 - 13:00 y 16:00 - 20:00, lunes a viernes',\n weeklySchedule: everyDay(\n WEEKDAYS,\n { start: '09:00', end: '13:00', label: 'Mañana' },\n { start: '16:00', end: '20:00', label: 'Tarde' },\n ),\n },\n {\n id: 'weekend-doctor',\n name: 'Doctor de Fin de Semana',\n description: '10:00 - 14:00, sábado y domingo',\n weeklySchedule: everyDay(WEEKEND, { start: '10:00', end: '14:00' }),\n },\n {\n id: 'full-week',\n name: 'Semana Completa',\n description: '9:00 - 18:00, todos los días',\n weeklySchedule: everyDay([0, ...WEEKDAYS, 6], { start: '09:00', end: '18:00' }),\n },\n];\n","import type { CalendarDate, TimeOfDay } from './types';\n\nexport const MINUTES_PER_DAY = 24 * 60;\n\nconst TIME_PATTERN = /^([01]\\d|2[0-3]):[0-5]\\d$/;\nconst DATE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\nconst twoDigits = (value: number): string => String(value).padStart(2, '0');\n\nexport function timeToMinutes(time: TimeOfDay): number {\n const [hours, minutes] = time.split(':').map(Number);\n return hours * 60 + minutes;\n}\n\nexport function minutesToTime(minutes: number): TimeOfDay {\n return `${twoDigits(Math.floor(minutes / 60) % 24)}:${twoDigits(minutes % 60)}`;\n}\n\nexport function isValidTime(time: string): boolean {\n return TIME_PATTERN.test(time);\n}\n\nexport function isEndAfterStart(start: TimeOfDay, end: TimeOfDay): boolean {\n return timeToMinutes(end) > timeToMinutes(start);\n}\n\nexport function isValidDate(date: string): boolean {\n const match = DATE_PATTERN.exec(date);\n if (!match) return false;\n const [year, month, day] = match.slice(1).map(Number);\n const parsed = new Date(Date.UTC(year, month - 1, day));\n return parsed.getUTCMonth() === month - 1 && parsed.getUTCDate() === day;\n}\n\n/** Local calendar date; `toISOString` would roll to tomorrow in the evening west of Greenwich. */\nexport function toCalendarDate(date: Date): CalendarDate {\n return `${date.getFullYear()}-${twoDigits(date.getMonth() + 1)}-${twoDigits(date.getDate())}`;\n}\n\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\nfunction toUtc(date: CalendarDate): number {\n if (!isValidDate(date)) throw new RangeError(`Invalid calendar date: ${date}`);\n const [year, month, day] = date.split('-').map(Number);\n return Date.UTC(year, month - 1, day);\n}\n\nexport function addDays(date: CalendarDate, days: number): CalendarDate {\n return new Date(toUtc(date) + days * MS_PER_DAY).toISOString().slice(0, 10);\n}\n\n/** Whole days from `from` to `to`; negative when `to` is earlier. */\nexport function daysBetween(from: CalendarDate, to: CalendarDate): number {\n return Math.round((toUtc(to) - toUtc(from)) / MS_PER_DAY);\n}\n\n/** As JavaScript counts it: 0 is Sunday. */\nexport function dayOfWeek(date: CalendarDate): number {\n return new Date(toUtc(date)).getUTCDay();\n}\n","import { isEndAfterStart, isValidDate, isValidTime, timeToMinutes } from './time';\nimport type {\n AvailabilityError,\n DateOverride,\n DoctorAvailability,\n SchedulingRules,\n WeeklySlot,\n} from './types';\n\nconst MIN_SLOT_DURATION = 5;\n\ntype Problem = Pick<AvailabilityError, 'type' | 'message'>;\n\nfunction problemInHours(start: string, end: string): Problem | null {\n if (!isValidTime(start)) return { type: 'invalid_time', message: `Hora de inicio inválida: ${start}` };\n if (!isValidTime(end)) return { type: 'invalid_time', message: `Hora de fin inválida: ${end}` };\n if (!isEndAfterStart(start, end)) {\n return {\n type: 'end_before_start',\n message: `La hora de fin (${end}) debe ser posterior a la de inicio (${start})`,\n };\n }\n return null;\n}\n\nfunction problemInOverride(override: DateOverride): Problem | null {\n if (!isValidDate(override.date)) return { type: 'invalid_time', message: `Fecha inválida: ${override.date}` };\n if (override.fullDayClosed) return null;\n if (!override.start || !override.end) {\n return { type: 'invalid_time', message: 'Debe especificar hora de inicio y fin, o marcar como día libre' };\n }\n return problemInHours(override.start, override.end);\n}\n\nfunction problemsInRules(rules: SchedulingRules): AvailabilityError[] {\n const errors: AvailabilityError[] = [];\n const { breakStart, breakEnd, minSlotDuration, maxPatientsPerHour } = rules;\n\n if (breakStart && breakEnd) {\n const problem = problemInHours(breakStart, breakEnd);\n if (problem) errors.push({ ...problem, message: `Descanso: ${problem.message}`, severity: 'error' });\n } else if (breakStart || breakEnd) {\n errors.push({\n type: 'invalid_time',\n message: 'Debe especificar tanto inicio como fin del descanso',\n severity: 'warning',\n });\n }\n if (minSlotDuration !== undefined && minSlotDuration < MIN_SLOT_DURATION) {\n errors.push({\n type: 'invalid_time',\n message: `La duración mínima debe ser al menos ${MIN_SLOT_DURATION} minutos`,\n severity: 'error',\n });\n }\n if (maxPatientsPerHour !== undefined && maxPatientsPerHour < 1) {\n errors.push({ type: 'invalid_time', message: 'Debe permitir al menos 1 paciente por hora', severity: 'error' });\n }\n return errors;\n}\n\nexport function slotsOverlap(a: WeeklySlot, b: WeeklySlot): boolean {\n return (\n a.day === b.day &&\n timeToMinutes(a.start) < timeToMinutes(b.end) &&\n timeToMinutes(b.start) < timeToMinutes(a.end)\n );\n}\n\nfunction slotsByDay(slots: WeeklySlot[]): Map<number, WeeklySlot[]> {\n const days = new Map<number, WeeklySlot[]>();\n for (const slot of slots) days.set(slot.day, [...(days.get(slot.day) ?? []), slot]);\n return days;\n}\n\nfunction problemsInDay(day: number, slots: WeeklySlot[]): AvailabilityError[] {\n const errors: AvailabilityError[] = [];\n slots.forEach((slot, slotIndex) => {\n const problem = problemInHours(slot.start, slot.end);\n if (problem) errors.push({ ...problem, day, slotIndex, severity: 'error' });\n slots.slice(0, slotIndex).forEach((earlier) => {\n if (!slotsOverlap(earlier, slot)) return;\n errors.push({\n type: 'overlap',\n day,\n slotIndex,\n message: `Solapamiento detectado: ${earlier.start}-${earlier.end} y ${slot.start}-${slot.end}`,\n severity: 'error',\n });\n });\n });\n return errors;\n}\n\nfunction problemsInOverrides(overrides: DateOverride[]): AvailabilityError[] {\n const errors: AvailabilityError[] = [];\n const seen = new Set<string>();\n for (const override of overrides) {\n const { date } = override;\n const problem = problemInOverride(override);\n if (problem) errors.push({ ...problem, date, severity: 'error' });\n if (seen.has(date)) {\n errors.push({ type: 'duplicate_date', date, message: `Fecha duplicada: ${date}`, severity: 'error' });\n }\n seen.add(date);\n }\n return errors;\n}\n\nexport function validateAvailability(availability: DoctorAvailability): AvailabilityError[] {\n const weekly = [...slotsByDay(availability.weeklySchedule)].flatMap(([day, slots]) => problemsInDay(day, slots));\n return [...weekly, ...problemsInOverrides(availability.overrides), ...problemsInRules(availability.rules)];\n}\n\nexport function hasBlockingErrors(errors: AvailabilityError[]): boolean {\n return errors.some((error) => error.severity === 'error');\n}\n\nexport interface ScheduleGap {\n day: number;\n from: string;\n to: string;\n}\n\nexport function findGaps(slots: WeeklySlot[]): ScheduleGap[] {\n return [...slotsByDay(slots)].flatMap(([day, daySlots]) => {\n const sorted = [...daySlots].sort((a, b) => timeToMinutes(a.start) - timeToMinutes(b.start));\n return sorted.slice(1).flatMap((next, i) => {\n const previous = sorted[i];\n return isEndAfterStart(previous.end, next.start) ? [{ day, from: previous.end, to: next.start }] : [];\n });\n });\n}\n","import { AVAILABILITY_VERSION, DAYS_OF_WEEK, DEFAULT_WORK_END, DEFAULT_WORK_START } from './defaults';\nimport { MINUTES_PER_DAY, minutesToTime, timeToMinutes } from './time';\nimport type { DateOverride, DoctorAvailability, SchedulingRules, WeeklySlot, WeekSchedule } from './types';\n\nconst GAP_BEFORE_NEW_SLOT = 60;\nconst NEW_SLOT_LENGTH = 4 * 60;\nconst SHORTEST_NEW_SLOT = 30;\nconst LAST_MINUTE = MINUTES_PER_DAY - 1;\n\nexport function groupByDay(weeklySchedule: WeeklySlot[]): WeekSchedule {\n return Object.fromEntries(\n DAYS_OF_WEEK.map(({ value }) => {\n const slots = weeklySchedule\n .filter((slot) => slot.day === value)\n .sort((a, b) => timeToMinutes(a.start) - timeToMinutes(b.start));\n return [value, { isWorking: slots.length > 0, slots }];\n }),\n );\n}\n\nexport function availabilityFromWeek(\n week: WeekSchedule,\n overrides: DateOverride[],\n rules: SchedulingRules,\n): DoctorAvailability {\n const weeklySchedule = Object.values(week).flatMap((day) => (day.isWorking ? day.slots : []));\n return { version: AVAILABILITY_VERSION, weeklySchedule, overrides, rules };\n}\n\n/** `null` when the day has no room left before midnight. */\nexport function suggestNextSlot(day: number, existing: WeeklySlot[]): WeeklySlot | null {\n const last = existing[existing.length - 1];\n if (!last) return { day, start: DEFAULT_WORK_START, end: DEFAULT_WORK_END };\n const start = timeToMinutes(last.end) + GAP_BEFORE_NEW_SLOT;\n const end = Math.min(start + NEW_SLOT_LENGTH, LAST_MINUTE);\n if (!(end - start >= SHORTEST_NEW_SLOT)) return null;\n return { day, start: minutesToTime(start), end: minutesToTime(end) };\n}\n\nexport function weeklyHours(availability: DoctorAvailability): number {\n const minutes = availability.weeklySchedule.reduce(\n (total, slot) => total + timeToMinutes(slot.end) - timeToMinutes(slot.start),\n 0,\n );\n return minutes / 60;\n}\n\nexport function workingDays(availability: DoctorAvailability): number[] {\n return [...new Set(availability.weeklySchedule.map((slot) => slot.day))].sort();\n}\n","/** Half-open `[start, end)` on any numeric axis: minutes of a day, minutes since an epoch, seconds. */\nexport interface Interval {\n start: number;\n end: number;\n}\n\nexport function intervalsOverlap(a: Interval, b: Interval): boolean {\n return a.start < b.end && b.start < a.end;\n}\n\n/** Sorted by start; intervals that overlap or touch become one and keep the earlier one's other fields. */\nexport function mergeIntervals<T extends Interval>(intervals: readonly T[]): T[] {\n const merged: T[] = [];\n for (const interval of [...intervals].sort((a, b) => a.start - b.start)) {\n const last = merged[merged.length - 1];\n if (last && interval.start <= last.end) merged[merged.length - 1] = { ...last, end: Math.max(last.end, interval.end) };\n else merged.push(interval);\n }\n return merged;\n}\n\nexport function subtractInterval<T extends Interval>(intervals: readonly T[], cut: Interval): T[] {\n return intervals.flatMap((interval) => {\n if (!intervalsOverlap(interval, cut)) return [interval];\n const before = cut.start > interval.start ? [{ ...interval, end: cut.start }] : [];\n const after = cut.end < interval.end ? [{ ...interval, start: cut.end }] : [];\n return [...before, ...after];\n });\n}\n\n/** What `bounds` has left once the intervals are taken out. */\nexport function complementIntervals(intervals: readonly Interval[], bounds: Interval): Interval[] {\n const gaps: Interval[] = [];\n let cursor = bounds.start;\n for (const { start, end } of mergeIntervals(intervals)) {\n if (start > cursor) gaps.push({ start: cursor, end: Math.min(start, bounds.end) });\n cursor = Math.max(cursor, end);\n }\n if (cursor < bounds.end) gaps.push({ start: cursor, end: bounds.end });\n return gaps.filter((gap) => gap.end > gap.start);\n}\n\n/** The first existing interval the candidate overlaps, or `null` when it is free. */\nexport function findConflict<T extends Interval>(existing: readonly T[], candidate: Interval): T | null {\n if (!(candidate.end > candidate.start)) throw new RangeError('An interval must end after it starts');\n return existing.find((interval) => intervalsOverlap(interval, candidate)) ?? null;\n}\n","import { complementIntervals, mergeIntervals, subtractInterval, type Interval } from './intervals';\nimport { MINUTES_PER_DAY, dayOfWeek, isEndAfterStart, isValidTime, timeToMinutes } from './time';\nimport type { CalendarDate, DateOverride, DoctorAvailability, SchedulingRules, TimeOfDay, WeeklySlot } from './types';\n\ntype Schedule = Pick<DoctorAvailability, 'weeklySchedule' | 'overrides'>;\n\nconst CLOCK_PATTERN = /^([01]\\d|2[0-3]):([0-5]\\d)(?::[0-5]\\d)?$/;\nconst END_OF_DAY_PATTERN = /^24:00(?::00)?$/;\nconst WHOLE_DAY: Interval = { start: 0, end: MINUTES_PER_DAY };\n\n/** `end` may be `24:00`; an `end` at or before `start` runs past midnight into the next day. */\nexport interface DayHours {\n start: TimeOfDay;\n end: TimeOfDay;\n}\n\nexport type DayWindowSource = 'override' | 'weekly' | 'spillover';\n\n/** Minutes from that day's midnight. */\nexport interface DayWindow extends Interval {\n source: DayWindowSource;\n}\n\n/** The hours that govern one date, before any merging: an override replaces the weekly pattern. */\nexport interface DateHours {\n date: CalendarDate;\n source: 'override' | 'weekly';\n /** An override closed the day or left its hours blank, or the weekday has no slots. */\n closed: boolean;\n hours: DayHours[];\n overrides: DateOverride[];\n slots: WeeklySlot[];\n}\n\nexport interface DayWindows {\n /** Merged, sorted and clipped to the day. */\n windows: DayWindow[];\n nonWorking: Interval[];\n /** What runs past midnight, in minutes of the next day. */\n spilloverNext: Interval[];\n mergesApplied: boolean;\n totalMinutes: number;\n}\n\nexport interface DayResolution extends DayWindows {\n date: CalendarDate;\n fullDayOff: boolean;\n}\n\nfunction clockToMinutes(time: string, role: 'start' | 'end'): number {\n if (role === 'end' && END_OF_DAY_PATTERN.test(time)) return MINUTES_PER_DAY;\n const match = CLOCK_PATTERN.exec(time);\n if (!match) throw new RangeError(`Invalid ${role} time: \"${time}\" (expected HH:mm)`);\n return Number(match[1]) * 60 + Number(match[2]);\n}\n\nexport function hoursForDate({ weeklySchedule, overrides }: Schedule, date: CalendarDate): DateHours {\n const dated = overrides.filter((override) => override.date === date);\n if (dated.length > 0) {\n const closed = dated.some((override) => override.fullDayClosed || !override.start || !override.end);\n const hours = closed ? [] : dated.map(({ start, end }) => ({ start: start as TimeOfDay, end: end as TimeOfDay }));\n return { date, source: 'override', closed, hours, overrides: dated, slots: [] };\n }\n const weekday = dayOfWeek(date);\n const slots = weeklySchedule.filter((slot) => slot.day === weekday);\n const hours = slots.map(({ start, end }) => ({ start, end }));\n return { date, source: 'weekly', closed: slots.length === 0, hours, overrides: [], slots };\n}\n\n/** Turns a day's hours, plus what the previous day spilled over midnight, into canonical windows. */\nexport function resolveDayWindows(\n hours: readonly DayHours[],\n source: Exclude<DayWindowSource, 'spillover'> = 'weekly',\n spilloverFromPrev: readonly Interval[] = [],\n): DayWindows {\n const windows: DayWindow[] = [];\n const spilloverNext: Interval[] = [];\n for (const entry of hours) {\n const start = clockToMinutes(entry.start, 'start');\n const clockEnd = clockToMinutes(entry.end, 'end');\n const end = clockEnd > start ? clockEnd : clockEnd + MINUTES_PER_DAY;\n windows.push({ start, end: Math.min(end, MINUTES_PER_DAY), source });\n if (end > MINUTES_PER_DAY) spilloverNext.push({ start: 0, end: end - MINUTES_PER_DAY });\n }\n for (const { start, end } of spilloverFromPrev) {\n const clipped = { start: Math.max(start, 0), end: Math.min(end, MINUTES_PER_DAY) };\n if (clipped.end > clipped.start) windows.push({ ...clipped, source: 'spillover' });\n }\n const merged = mergeIntervals(windows);\n return {\n windows: merged,\n nonWorking: complementIntervals(merged, WHOLE_DAY),\n spilloverNext,\n mergesApplied: merged.length !== windows.length,\n totalMinutes: merged.reduce((total, window) => total + window.end - window.start, 0),\n };\n}\n\n/** A closing override wins over a shift that spilled in from the night before; a weekday without slots does not. */\nexport function resolveDay(\n schedule: Schedule,\n date: CalendarDate,\n spilloverFromPrev: readonly Interval[] = [],\n): DayResolution {\n const { source, closed, hours } = hoursForDate(schedule, date);\n if (source === 'override' && closed) {\n return {\n date,\n windows: [],\n nonWorking: [WHOLE_DAY],\n spilloverNext: [],\n mergesApplied: false,\n totalMinutes: 0,\n fullDayOff: true,\n };\n }\n const resolved = resolveDayWindows(hours, source, spilloverFromPrev);\n return { date, ...resolved, fullDayOff: resolved.windows.length === 0 };\n}\n\n/** Takes the daily break out of the windows; a break without both valid ends changes nothing. */\nexport function applyBreak<T extends Interval>(windows: readonly T[], { breakStart, breakEnd }: SchedulingRules): T[] {\n if (!breakStart || !breakEnd || !isValidTime(breakStart) || !isValidTime(breakEnd)) return [...windows];\n if (!isEndAfterStart(breakStart, breakEnd)) return [...windows];\n return subtractInterval(windows, { start: timeToMinutes(breakStart), end: timeToMinutes(breakEnd) });\n}\n\n/** Whether anything can be booked from `today` on: some weekly hours, or a dated opening still ahead. */\nexport function isSchedulable({ weeklySchedule, overrides }: Schedule, today: CalendarDate): boolean {\n if (weeklySchedule.some((slot) => timeToMinutes(slot.end) > timeToMinutes(slot.start))) return true;\n return overrides.some((o) => o.date >= today && !o.fullDayClosed && Boolean(o.start) && Boolean(o.end));\n}\n","import { applyBreak, resolveDay } from './day';\nimport { DEFAULT_RULES } from './defaults';\nimport { intervalsOverlap, type Interval } from './intervals';\nimport { addDays, daysBetween } from './time';\nimport type { CalendarDate, DoctorAvailability, SchedulingRules } from './types';\n\nconst EPOCH: CalendarDate = '1970-01-01';\nconst MINUTES_PER_DAY = 24 * 60;\nconst SHORTEST_SLOT = 5;\n\n/**\n * Appointments, busy time and `notBefore` are local minutes: wall-clock minutes since 1970-01-01 00:00\n * in the schedule's own time zone. The caller owns the conversion from and to instants.\n */\nexport interface SlotQuery {\n /** Both ends inclusive. */\n from: CalendarDate;\n to: CalendarDate;\n appointments?: readonly Interval[];\n /** Time taken outside this schedule, such as an external calendar. The buffer does not apply to it. */\n busy?: readonly Interval[];\n notBefore?: number;\n}\n\n/** `start` and `end` are minutes from that date's midnight. */\nexport interface BookableSlot {\n date: CalendarDate;\n start: number;\n end: number;\n}\n\nexport function toLocalMinutes(date: CalendarDate, minuteOfDay = 0): number {\n return daysBetween(EPOCH, date) * MINUTES_PER_DAY + minuteOfDay;\n}\n\nexport function fromLocalMinutes(localMinutes: number): { date: CalendarDate; minute: number } {\n const days = Math.floor(localMinutes / MINUTES_PER_DAY);\n return { date: addDays(EPOCH, days), minute: localMinutes - days * MINUTES_PER_DAY };\n}\n\nexport function slotDuration(rules: SchedulingRules): number {\n return Math.max(SHORTEST_SLOT, Math.trunc(rules.minSlotDuration ?? (DEFAULT_RULES.minSlotDuration as number)));\n}\n\nexport function slotBuffer(rules: SchedulingRules): number {\n return Math.max(0, Math.trunc(rules.bufferBetweenAppointments ?? 0));\n}\n\n/** `null` when the rules set no hourly limit. */\nexport function hourlyCapacity(rules: SchedulingRules): number | null {\n const { maxPatientsPerHour } = rules;\n return maxPatientsPerHour === undefined || maxPatientsPerHour === null ? null : Math.max(1, Math.trunc(maxPatientsPerHour));\n}\n\nconst hourOf = (localMinutes: number): number => Math.floor(localMinutes / 60);\n\n/**\n * Every slot the schedule offers in the range: one per duration plus buffer inside each working window,\n * minus what starts before `notBefore`, what comes within the buffer of an appointment, what overlaps\n * busy time, and what starts in an hour that already holds its limit of appointments.\n */\nexport function generateSlots(availability: DoctorAvailability, query: SlotQuery): BookableSlot[] {\n const { rules } = availability;\n const { from, to, appointments = [], busy = [], notBefore = -Infinity } = query;\n const duration = slotDuration(rules);\n const buffer = slotBuffer(rules);\n const capacity = hourlyCapacity(rules);\n\n const bookedPerHour = new Map<number, number>();\n for (const { start } of appointments) bookedPerHour.set(hourOf(start), (bookedPerHour.get(hourOf(start)) ?? 0) + 1);\n const guarded = appointments.map(({ start, end }) => ({ start: start - buffer, end: end + buffer }));\n\n const slots: BookableSlot[] = [];\n let spillover = resolveDay(availability, addDays(from, -1)).spilloverNext;\n for (let date = from; date <= to; date = addDays(date, 1)) {\n const day = resolveDay(availability, date, spillover);\n const midnight = toLocalMinutes(date);\n for (const window of applyBreak(day.windows, rules)) {\n for (let start = window.start; start + duration <= window.end; start += duration + buffer) {\n const local = { start: midnight + start, end: midnight + start + duration };\n if (local.start < notBefore) continue;\n if (guarded.some((taken) => intervalsOverlap(local, taken))) continue;\n if (busy.some((taken) => intervalsOverlap(local, taken))) continue;\n if (capacity !== null && (bookedPerHour.get(hourOf(local.start)) ?? 0) >= capacity) continue;\n slots.push({ date, start, end: start + duration });\n }\n }\n spillover = day.spilloverNext;\n }\n return slots;\n}\n"],"mappings":";AAEO,IAAM,uBAAuB;AAE7B,IAAM,eAAe;AAAA,EAC1B,EAAE,OAAO,GAAG,OAAO,WAAW,OAAO,OAAO,MAAM,IAAI;AAAA,EACtD,EAAE,OAAO,GAAG,OAAO,SAAS,OAAO,OAAO,MAAM,IAAI;AAAA,EACpD,EAAE,OAAO,GAAG,OAAO,UAAU,OAAO,OAAO,MAAM,IAAI;AAAA,EACrD,EAAE,OAAO,GAAG,OAAO,gBAAa,OAAO,UAAO,MAAM,IAAI;AAAA,EACxD,EAAE,OAAO,GAAG,OAAO,UAAU,OAAO,OAAO,MAAM,IAAI;AAAA,EACrD,EAAE,OAAO,GAAG,OAAO,WAAW,OAAO,OAAO,MAAM,IAAI;AAAA,EACtD,EAAE,OAAO,GAAG,OAAO,aAAU,OAAO,UAAO,MAAM,IAAI;AACvD;AAEO,IAAM,WAAW,CAAC,GAAG,GAAG,GAAG,GAAG,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ES_PER_DAY"]}
|
package/dist/membership/index.js
CHANGED
|
@@ -8,18 +8,28 @@ function isValidDate(date) {
|
|
|
8
8
|
const parsed = new Date(Date.UTC(year, month - 1, day));
|
|
9
9
|
return parsed.getUTCMonth() === month - 1 && parsed.getUTCDate() === day;
|
|
10
10
|
}
|
|
11
|
-
|
|
12
|
-
// src/membership/term.ts
|
|
13
11
|
var MS_PER_DAY = 24 * 60 * 60 * 1e3;
|
|
14
12
|
function toUtc(date) {
|
|
15
13
|
if (!isValidDate(date)) throw new RangeError(`Invalid calendar date: ${date}`);
|
|
16
14
|
const [year, month, day] = date.split("-").map(Number);
|
|
17
15
|
return Date.UTC(year, month - 1, day);
|
|
18
16
|
}
|
|
17
|
+
function addDays(date, days) {
|
|
18
|
+
return new Date(toUtc(date) + days * MS_PER_DAY).toISOString().slice(0, 10);
|
|
19
|
+
}
|
|
20
|
+
function daysBetween(from, to) {
|
|
21
|
+
return Math.round((toUtc(to) - toUtc(from)) / MS_PER_DAY);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// src/membership/term.ts
|
|
25
|
+
var toUtc2 = (date) => {
|
|
26
|
+
if (!isValidDate(date)) throw new RangeError(`Invalid calendar date: ${date}`);
|
|
27
|
+
const [year, month, day] = date.split("-").map(Number);
|
|
28
|
+
return Date.UTC(year, month - 1, day);
|
|
29
|
+
};
|
|
19
30
|
var fromUtc = (time) => new Date(time).toISOString().slice(0, 10);
|
|
20
|
-
var addDays = (date, days) => fromUtc(toUtc(date) + days * MS_PER_DAY);
|
|
21
31
|
function addMonths(date, months) {
|
|
22
|
-
const from = new Date(
|
|
32
|
+
const from = new Date(toUtc2(date));
|
|
23
33
|
const total = from.getUTCFullYear() * 12 + from.getUTCMonth() + months;
|
|
24
34
|
const year = Math.floor(total / 12);
|
|
25
35
|
const month = total - year * 12;
|
|
@@ -31,7 +41,7 @@ function membershipTerm(months, today, currentEnd) {
|
|
|
31
41
|
return { start, end: addDays(addMonths(start, months), -1) };
|
|
32
42
|
}
|
|
33
43
|
function daysRemaining(end, today) {
|
|
34
|
-
return
|
|
44
|
+
return daysBetween(today, end);
|
|
35
45
|
}
|
|
36
46
|
function membershipStatus(membership, today) {
|
|
37
47
|
if (membership.refunded) return "refunded";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/availability/time.ts","../../src/membership/term.ts"],"sourcesContent":["import type { CalendarDate, TimeOfDay } from './types';\n\nexport const MINUTES_PER_DAY = 24 * 60;\n\nconst TIME_PATTERN = /^([01]\\d|2[0-3]):[0-5]\\d$/;\nconst DATE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\nconst twoDigits = (value: number): string => String(value).padStart(2, '0');\n\nexport function timeToMinutes(time: TimeOfDay): number {\n const [hours, minutes] = time.split(':').map(Number);\n return hours * 60 + minutes;\n}\n\nexport function minutesToTime(minutes: number): TimeOfDay {\n return `${twoDigits(Math.floor(minutes / 60) % 24)}:${twoDigits(minutes % 60)}`;\n}\n\nexport function isValidTime(time: string): boolean {\n return TIME_PATTERN.test(time);\n}\n\nexport function isEndAfterStart(start: TimeOfDay, end: TimeOfDay): boolean {\n return timeToMinutes(end) > timeToMinutes(start);\n}\n\nexport function isValidDate(date: string): boolean {\n const match = DATE_PATTERN.exec(date);\n if (!match) return false;\n const [year, month, day] = match.slice(1).map(Number);\n const parsed = new Date(Date.UTC(year, month - 1, day));\n return parsed.getUTCMonth() === month - 1 && parsed.getUTCDate() === day;\n}\n\n/** Local calendar date; `toISOString` would roll to tomorrow in the evening west of Greenwich. */\nexport function toCalendarDate(date: Date): CalendarDate {\n return `${date.getFullYear()}-${twoDigits(date.getMonth() + 1)}-${twoDigits(date.getDate())}`;\n}\n","import { isValidDate } from '../availability/time';\nimport type { CalendarDate } from '../availability/types';\nimport type { MembershipRecord, MembershipStatus, MembershipTerm } from './types';\n\nconst
|
|
1
|
+
{"version":3,"sources":["../../src/availability/time.ts","../../src/membership/term.ts"],"sourcesContent":["import type { CalendarDate, TimeOfDay } from './types';\n\nexport const MINUTES_PER_DAY = 24 * 60;\n\nconst TIME_PATTERN = /^([01]\\d|2[0-3]):[0-5]\\d$/;\nconst DATE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\nconst twoDigits = (value: number): string => String(value).padStart(2, '0');\n\nexport function timeToMinutes(time: TimeOfDay): number {\n const [hours, minutes] = time.split(':').map(Number);\n return hours * 60 + minutes;\n}\n\nexport function minutesToTime(minutes: number): TimeOfDay {\n return `${twoDigits(Math.floor(minutes / 60) % 24)}:${twoDigits(minutes % 60)}`;\n}\n\nexport function isValidTime(time: string): boolean {\n return TIME_PATTERN.test(time);\n}\n\nexport function isEndAfterStart(start: TimeOfDay, end: TimeOfDay): boolean {\n return timeToMinutes(end) > timeToMinutes(start);\n}\n\nexport function isValidDate(date: string): boolean {\n const match = DATE_PATTERN.exec(date);\n if (!match) return false;\n const [year, month, day] = match.slice(1).map(Number);\n const parsed = new Date(Date.UTC(year, month - 1, day));\n return parsed.getUTCMonth() === month - 1 && parsed.getUTCDate() === day;\n}\n\n/** Local calendar date; `toISOString` would roll to tomorrow in the evening west of Greenwich. */\nexport function toCalendarDate(date: Date): CalendarDate {\n return `${date.getFullYear()}-${twoDigits(date.getMonth() + 1)}-${twoDigits(date.getDate())}`;\n}\n\nconst MS_PER_DAY = 24 * 60 * 60 * 1000;\n\nfunction toUtc(date: CalendarDate): number {\n if (!isValidDate(date)) throw new RangeError(`Invalid calendar date: ${date}`);\n const [year, month, day] = date.split('-').map(Number);\n return Date.UTC(year, month - 1, day);\n}\n\nexport function addDays(date: CalendarDate, days: number): CalendarDate {\n return new Date(toUtc(date) + days * MS_PER_DAY).toISOString().slice(0, 10);\n}\n\n/** Whole days from `from` to `to`; negative when `to` is earlier. */\nexport function daysBetween(from: CalendarDate, to: CalendarDate): number {\n return Math.round((toUtc(to) - toUtc(from)) / MS_PER_DAY);\n}\n\n/** As JavaScript counts it: 0 is Sunday. */\nexport function dayOfWeek(date: CalendarDate): number {\n return new Date(toUtc(date)).getUTCDay();\n}\n","import { addDays, daysBetween, isValidDate } from '../availability/time';\nimport type { CalendarDate } from '../availability/types';\nimport type { MembershipRecord, MembershipStatus, MembershipTerm } from './types';\n\nconst toUtc = (date: CalendarDate): number => {\n if (!isValidDate(date)) throw new RangeError(`Invalid calendar date: ${date}`);\n const [year, month, day] = date.split('-').map(Number);\n return Date.UTC(year, month - 1, day);\n};\n\nconst fromUtc = (time: number): CalendarDate => new Date(time).toISOString().slice(0, 10);\n\n/** Same day of the month, clamped to the last day when the target month is shorter. */\nexport function addMonths(date: CalendarDate, months: number): CalendarDate {\n const from = new Date(toUtc(date));\n const total = from.getUTCFullYear() * 12 + from.getUTCMonth() + months;\n const year = Math.floor(total / 12);\n const month = total - year * 12;\n const lastDay = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();\n return fromUtc(Date.UTC(year, month, Math.min(from.getUTCDate(), lastDay)));\n}\n\n/** Renewing before the current term ends chains the new one to the next day, so no paid day is lost. */\nexport function membershipTerm(months: number, today: CalendarDate, currentEnd?: CalendarDate | null): MembershipTerm {\n const start = currentEnd && currentEnd >= today ? addDays(currentEnd, 1) : today;\n return { start, end: addDays(addMonths(start, months), -1) };\n}\n\n/** Negative once `end` has passed. */\nexport function daysRemaining(end: CalendarDate, today: CalendarDate): number {\n return daysBetween(today, end);\n}\n\nexport function membershipStatus(membership: MembershipRecord, today: CalendarDate): MembershipStatus {\n if (membership.refunded) return 'refunded';\n if (membership.end < today) return 'expired';\n if (membership.cancelled) return 'cancelled';\n return membership.start > today ? 'upcoming' : 'active';\n}\n\nexport function isRenewalNoticeDue(end: CalendarDate, today: CalendarDate, noticeDays: number): boolean {\n const days = daysRemaining(end, today);\n return days >= 0 && days <= noticeDays;\n}\n"],"mappings":";AAEO,IAAM,kBAAkB,KAAK;AAGpC,IAAM,eAAe;AAqBd,SAAS,YAAY,MAAuB;AACjD,QAAM,QAAQ,aAAa,KAAK,IAAI;AACpC,MAAI,CAA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AAO,KAAK,MAAM,QAAQ,EAAE;AAClC,QAAM,QAAQ,QAAQ,OAAO;AAC7B,QAAM,UAAU,IAAI,KAAK,KAAK,IAAI,MAAM,QAAQ,GAAG,CAAC,CAAC,EAAE,WAAW;AAClE,SAAO,QAAQ,KAAK,IAAI,MAAM,OAAO,KAAK,IAAI,KAAK,WAAW,GAAG,OAAO,CAAC,CAAC;AAC5E;AAGO,SAAS,eAAe,QAAgB,OAAqB,YAAkD;AACpH,QAAM,QAAQ,cAAc,cAAc,QAAQ,QAAQ,YAAY,CAAC,IAAI;AAC3E,SAAO,EAAE,OAAO,KAAK,QAAQ,UAAU,OAAO,MAAM,GAAG,EAAE,EAAE;AAC7D;AAGO,SAAS,cAAc,KAAmB,OAA6B;AAC5E,SAAO,YAAY,OAAO,GAAG;AAC/B;AAEO,SAAS,iBAAiB,YAA8B,OAAuC;AACpG,MAAI,WAAW,SAAU,QAAO;AAChC,MAAI,WAAW,MAAM,MAAO,QAAO;AACnC,MAAI,WAAW,UAAW,QAAO;AACjC,SAAO,WAAW,QAAQ,QAAQ,aAAa;AACjD;AAEO,SAAS,mBAAmB,KAAmB,OAAqB,YAA6B;AACtG,QAAM,OAAO,cAAc,KAAK,KAAK;AACrC,SAAO,QAAQ,KAAK,QAAQ;AAC9B;","names":["toUtc"]}
|
package/package.json
CHANGED
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { applyBreak, resolveDay } from './day';
|
|
2
|
+
import { DEFAULT_RULES } from './defaults';
|
|
3
|
+
import { intervalsOverlap, type Interval } from './intervals';
|
|
4
|
+
import { addDays, daysBetween } from './time';
|
|
5
|
+
import type { CalendarDate, DoctorAvailability, SchedulingRules } from './types';
|
|
6
|
+
|
|
7
|
+
const EPOCH: CalendarDate = '1970-01-01';
|
|
8
|
+
const MINUTES_PER_DAY = 24 * 60;
|
|
9
|
+
const SHORTEST_SLOT = 5;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Appointments, busy time and `notBefore` are local minutes: wall-clock minutes since 1970-01-01 00:00
|
|
13
|
+
* in the schedule's own time zone. The caller owns the conversion from and to instants.
|
|
14
|
+
*/
|
|
15
|
+
export interface SlotQuery {
|
|
16
|
+
/** Both ends inclusive. */
|
|
17
|
+
from: CalendarDate;
|
|
18
|
+
to: CalendarDate;
|
|
19
|
+
appointments?: readonly Interval[];
|
|
20
|
+
/** Time taken outside this schedule, such as an external calendar. The buffer does not apply to it. */
|
|
21
|
+
busy?: readonly Interval[];
|
|
22
|
+
notBefore?: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** `start` and `end` are minutes from that date's midnight. */
|
|
26
|
+
export interface BookableSlot {
|
|
27
|
+
date: CalendarDate;
|
|
28
|
+
start: number;
|
|
29
|
+
end: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function toLocalMinutes(date: CalendarDate, minuteOfDay = 0): number {
|
|
33
|
+
return daysBetween(EPOCH, date) * MINUTES_PER_DAY + minuteOfDay;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function fromLocalMinutes(localMinutes: number): { date: CalendarDate; minute: number } {
|
|
37
|
+
const days = Math.floor(localMinutes / MINUTES_PER_DAY);
|
|
38
|
+
return { date: addDays(EPOCH, days), minute: localMinutes - days * MINUTES_PER_DAY };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function slotDuration(rules: SchedulingRules): number {
|
|
42
|
+
return Math.max(SHORTEST_SLOT, Math.trunc(rules.minSlotDuration ?? (DEFAULT_RULES.minSlotDuration as number)));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function slotBuffer(rules: SchedulingRules): number {
|
|
46
|
+
return Math.max(0, Math.trunc(rules.bufferBetweenAppointments ?? 0));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** `null` when the rules set no hourly limit. */
|
|
50
|
+
export function hourlyCapacity(rules: SchedulingRules): number | null {
|
|
51
|
+
const { maxPatientsPerHour } = rules;
|
|
52
|
+
return maxPatientsPerHour === undefined || maxPatientsPerHour === null ? null : Math.max(1, Math.trunc(maxPatientsPerHour));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const hourOf = (localMinutes: number): number => Math.floor(localMinutes / 60);
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Every slot the schedule offers in the range: one per duration plus buffer inside each working window,
|
|
59
|
+
* minus what starts before `notBefore`, what comes within the buffer of an appointment, what overlaps
|
|
60
|
+
* busy time, and what starts in an hour that already holds its limit of appointments.
|
|
61
|
+
*/
|
|
62
|
+
export function generateSlots(availability: DoctorAvailability, query: SlotQuery): BookableSlot[] {
|
|
63
|
+
const { rules } = availability;
|
|
64
|
+
const { from, to, appointments = [], busy = [], notBefore = -Infinity } = query;
|
|
65
|
+
const duration = slotDuration(rules);
|
|
66
|
+
const buffer = slotBuffer(rules);
|
|
67
|
+
const capacity = hourlyCapacity(rules);
|
|
68
|
+
|
|
69
|
+
const bookedPerHour = new Map<number, number>();
|
|
70
|
+
for (const { start } of appointments) bookedPerHour.set(hourOf(start), (bookedPerHour.get(hourOf(start)) ?? 0) + 1);
|
|
71
|
+
const guarded = appointments.map(({ start, end }) => ({ start: start - buffer, end: end + buffer }));
|
|
72
|
+
|
|
73
|
+
const slots: BookableSlot[] = [];
|
|
74
|
+
let spillover = resolveDay(availability, addDays(from, -1)).spilloverNext;
|
|
75
|
+
for (let date = from; date <= to; date = addDays(date, 1)) {
|
|
76
|
+
const day = resolveDay(availability, date, spillover);
|
|
77
|
+
const midnight = toLocalMinutes(date);
|
|
78
|
+
for (const window of applyBreak(day.windows, rules)) {
|
|
79
|
+
for (let start = window.start; start + duration <= window.end; start += duration + buffer) {
|
|
80
|
+
const local = { start: midnight + start, end: midnight + start + duration };
|
|
81
|
+
if (local.start < notBefore) continue;
|
|
82
|
+
if (guarded.some((taken) => intervalsOverlap(local, taken))) continue;
|
|
83
|
+
if (busy.some((taken) => intervalsOverlap(local, taken))) continue;
|
|
84
|
+
if (capacity !== null && (bookedPerHour.get(hourOf(local.start)) ?? 0) >= capacity) continue;
|
|
85
|
+
slots.push({ date, start, end: start + duration });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
spillover = day.spilloverNext;
|
|
89
|
+
}
|
|
90
|
+
return slots;
|
|
91
|
+
}
|
package/src/availability/time.ts
CHANGED
|
@@ -36,3 +36,25 @@ export function isValidDate(date: string): boolean {
|
|
|
36
36
|
export function toCalendarDate(date: Date): CalendarDate {
|
|
37
37
|
return `${date.getFullYear()}-${twoDigits(date.getMonth() + 1)}-${twoDigits(date.getDate())}`;
|
|
38
38
|
}
|
|
39
|
+
|
|
40
|
+
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
|
41
|
+
|
|
42
|
+
function toUtc(date: CalendarDate): number {
|
|
43
|
+
if (!isValidDate(date)) throw new RangeError(`Invalid calendar date: ${date}`);
|
|
44
|
+
const [year, month, day] = date.split('-').map(Number);
|
|
45
|
+
return Date.UTC(year, month - 1, day);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function addDays(date: CalendarDate, days: number): CalendarDate {
|
|
49
|
+
return new Date(toUtc(date) + days * MS_PER_DAY).toISOString().slice(0, 10);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Whole days from `from` to `to`; negative when `to` is earlier. */
|
|
53
|
+
export function daysBetween(from: CalendarDate, to: CalendarDate): number {
|
|
54
|
+
return Math.round((toUtc(to) - toUtc(from)) / MS_PER_DAY);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** As JavaScript counts it: 0 is Sunday. */
|
|
58
|
+
export function dayOfWeek(date: CalendarDate): number {
|
|
59
|
+
return new Date(toUtc(date)).getUTCDay();
|
|
60
|
+
}
|
package/src/membership/term.ts
CHANGED
|
@@ -1,19 +1,15 @@
|
|
|
1
|
-
import { isValidDate } from '../availability/time';
|
|
1
|
+
import { addDays, daysBetween, isValidDate } from '../availability/time';
|
|
2
2
|
import type { CalendarDate } from '../availability/types';
|
|
3
3
|
import type { MembershipRecord, MembershipStatus, MembershipTerm } from './types';
|
|
4
4
|
|
|
5
|
-
const
|
|
6
|
-
|
|
7
|
-
function toUtc(date: CalendarDate): number {
|
|
5
|
+
const toUtc = (date: CalendarDate): number => {
|
|
8
6
|
if (!isValidDate(date)) throw new RangeError(`Invalid calendar date: ${date}`);
|
|
9
7
|
const [year, month, day] = date.split('-').map(Number);
|
|
10
8
|
return Date.UTC(year, month - 1, day);
|
|
11
|
-
}
|
|
9
|
+
};
|
|
12
10
|
|
|
13
11
|
const fromUtc = (time: number): CalendarDate => new Date(time).toISOString().slice(0, 10);
|
|
14
12
|
|
|
15
|
-
const addDays = (date: CalendarDate, days: number): CalendarDate => fromUtc(toUtc(date) + days * MS_PER_DAY);
|
|
16
|
-
|
|
17
13
|
/** Same day of the month, clamped to the last day when the target month is shorter. */
|
|
18
14
|
export function addMonths(date: CalendarDate, months: number): CalendarDate {
|
|
19
15
|
const from = new Date(toUtc(date));
|
|
@@ -32,7 +28,7 @@ export function membershipTerm(months: number, today: CalendarDate, currentEnd?:
|
|
|
32
28
|
|
|
33
29
|
/** Negative once `end` has passed. */
|
|
34
30
|
export function daysRemaining(end: CalendarDate, today: CalendarDate): number {
|
|
35
|
-
return
|
|
31
|
+
return daysBetween(today, end);
|
|
36
32
|
}
|
|
37
33
|
|
|
38
34
|
export function membershipStatus(membership: MembershipRecord, today: CalendarDate): MembershipStatus {
|