@free-intelligence/core 1.12.1 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/dist/availability/index.d.ts +101 -56
- package/dist/availability/index.js +192 -0
- package/dist/availability/index.js.map +1 -1
- package/dist/membership/index.d.ts +24 -0
- package/dist/membership/index.js +63 -0
- package/dist/membership/index.js.map +1 -0
- package/dist/types-BThgyft4.d.ts +57 -0
- package/package.json +5 -1
- package/src/availability/day.test.ts +333 -0
- package/src/availability/day.ts +132 -0
- package/src/availability/index.ts +4 -1
- package/src/availability/intervals.ts +47 -0
- package/src/availability/slots.ts +91 -0
- package/src/availability/time.ts +22 -0
- package/src/membership/index.ts +3 -0
- package/src/membership/membership.test.ts +98 -0
- package/src/membership/term.ts +44 -0
- package/src/membership/types.ts +15 -0
package/README.md
CHANGED
|
@@ -18,7 +18,8 @@ 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
|
+
| `@free-intelligence/core/membership` | A paid membership's term, renewal chaining, status (`active`, `upcoming`, `cancelled`, `expired`, `refunded`) and renewal notice window. |
|
|
22
23
|
|
|
23
24
|
## Install
|
|
24
25
|
|
|
@@ -1,58 +1,5 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
/** `YYYY-MM-DD`. */
|
|
4
|
-
type CalendarDate = string;
|
|
5
|
-
interface WeeklySlot {
|
|
6
|
-
/** As JavaScript counts it: 0 is Sunday. */
|
|
7
|
-
day: number;
|
|
8
|
-
start: TimeOfDay;
|
|
9
|
-
end: TimeOfDay;
|
|
10
|
-
label?: string;
|
|
11
|
-
}
|
|
12
|
-
/** Replaces the weekly pattern on one date. Without `fullDayClosed` it carries its own hours. */
|
|
13
|
-
interface DateOverride {
|
|
14
|
-
date: CalendarDate;
|
|
15
|
-
start?: TimeOfDay;
|
|
16
|
-
end?: TimeOfDay;
|
|
17
|
-
fullDayClosed: boolean;
|
|
18
|
-
reason?: string;
|
|
19
|
-
}
|
|
20
|
-
/** Durations are minutes. */
|
|
21
|
-
interface SchedulingRules {
|
|
22
|
-
breakStart?: TimeOfDay;
|
|
23
|
-
breakEnd?: TimeOfDay;
|
|
24
|
-
minSlotDuration?: number;
|
|
25
|
-
maxPatientsPerHour?: number;
|
|
26
|
-
bufferBetweenAppointments?: number;
|
|
27
|
-
}
|
|
28
|
-
interface DoctorAvailability {
|
|
29
|
-
version: number;
|
|
30
|
-
weeklySchedule: WeeklySlot[];
|
|
31
|
-
overrides: DateOverride[];
|
|
32
|
-
rules: SchedulingRules;
|
|
33
|
-
}
|
|
34
|
-
type AvailabilityErrorType = 'overlap' | 'invalid_time' | 'end_before_start' | 'duplicate_date';
|
|
35
|
-
interface AvailabilityError {
|
|
36
|
-
type: AvailabilityErrorType;
|
|
37
|
-
day?: number;
|
|
38
|
-
date?: CalendarDate;
|
|
39
|
-
/** Position in that day's list, when the error belongs to one slot. */
|
|
40
|
-
slotIndex?: number;
|
|
41
|
-
message: string;
|
|
42
|
-
severity: 'error' | 'warning';
|
|
43
|
-
}
|
|
44
|
-
/** Editing keeps the slots of a day that was switched off, so switching it back restores them. */
|
|
45
|
-
interface DaySchedule {
|
|
46
|
-
isWorking: boolean;
|
|
47
|
-
slots: WeeklySlot[];
|
|
48
|
-
}
|
|
49
|
-
type WeekSchedule = Record<number, DaySchedule>;
|
|
50
|
-
interface AvailabilityTemplate {
|
|
51
|
-
id: string;
|
|
52
|
-
name: string;
|
|
53
|
-
description: string;
|
|
54
|
-
weeklySchedule: WeeklySlot[];
|
|
55
|
-
}
|
|
1
|
+
import { S as SchedulingRules, D as DoctorAvailability, A as AvailabilityTemplate, T as TimeOfDay, C as CalendarDate, W as WeeklySlot, a as AvailabilityError, b as WeekSchedule, c as DateOverride } from '../types-BThgyft4.js';
|
|
2
|
+
export { d as AvailabilityErrorType, e as DaySchedule } from '../types-BThgyft4.js';
|
|
56
3
|
|
|
57
4
|
declare const AVAILABILITY_VERSION = 1;
|
|
58
5
|
declare const DAYS_OF_WEEK: readonly [{
|
|
@@ -111,6 +58,11 @@ declare function isEndAfterStart(start: TimeOfDay, end: TimeOfDay): boolean;
|
|
|
111
58
|
declare function isValidDate(date: string): boolean;
|
|
112
59
|
/** Local calendar date; `toISOString` would roll to tomorrow in the evening west of Greenwich. */
|
|
113
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;
|
|
114
66
|
|
|
115
67
|
declare function slotsOverlap(a: WeeklySlot, b: WeeklySlot): boolean;
|
|
116
68
|
declare function validateAvailability(availability: DoctorAvailability): AvailabilityError[];
|
|
@@ -129,4 +81,97 @@ declare function suggestNextSlot(day: number, existing: WeeklySlot[]): WeeklySlo
|
|
|
129
81
|
declare function weeklyHours(availability: DoctorAvailability): number;
|
|
130
82
|
declare function workingDays(availability: DoctorAvailability): number[];
|
|
131
83
|
|
|
132
|
-
|
|
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,O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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,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,QAAQ,MAAM,IAA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AM,MAAM,WAAW,cAAc,MAAM,SAAS;AACpD,UAAM,WAAW,eAAe,IAAI;AACpC,eAAW,UAAU,WAAW,IAAI,SAAS,KAAK,GAAG;AACnD,eAAS,QAAQ,OAAO,OAAO,QAAQ,YAAY,OAAO,KAAK,SAAS,WAAW,QAAQ;AACzF,cAAM,QAAQ,EAAE,OAAO,WAAW,OAAO,KAAK,WAAW,QAAQ,SAAS;AAC1E,YAAI,MAAM,QAAQ,UAAW;AAC7B,YAAI,QAAQ,KAAK,CAAC,UAAU,iBAAiB,OAAO,KAAK,CAAC,EAAG;AAC7D,YAAI,KAAK,KAAK,CAAC,UAAU,iBAAiB,OAAO,KAAK,CAAC,EAAG;AAC1D,YAAI,aAAa,SAAS,cAAc,IAAI,OAAO,MAAM,KAAK,CAAC,KAAK,MAAM,SAAU;AACpF,cAAM,KAAK,EAAE,MAAM,OAAO,KAAK,QAAQ,SAAS,CAAC;AAAA,MACnD;AAAA,IACF;AACA,gBAAY,IAAI;AAAA,EAClB;AACA,SAAO;AACT;","names":["hours","MINUTES_PER_DAY"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { C as CalendarDate } from '../types-BThgyft4.js';
|
|
2
|
+
|
|
3
|
+
/** Inclusive on both ends: a member is covered on `start` and on `end`. */
|
|
4
|
+
interface MembershipTerm {
|
|
5
|
+
start: CalendarDate;
|
|
6
|
+
end: CalendarDate;
|
|
7
|
+
}
|
|
8
|
+
/** `cancelled` keeps coverage until `end`; `refunded` removes it at once. */
|
|
9
|
+
interface MembershipRecord extends MembershipTerm {
|
|
10
|
+
cancelled: boolean;
|
|
11
|
+
refunded: boolean;
|
|
12
|
+
}
|
|
13
|
+
type MembershipStatus = 'active' | 'upcoming' | 'cancelled' | 'expired' | 'refunded';
|
|
14
|
+
|
|
15
|
+
/** Same day of the month, clamped to the last day when the target month is shorter. */
|
|
16
|
+
declare function addMonths(date: CalendarDate, months: number): CalendarDate;
|
|
17
|
+
/** Renewing before the current term ends chains the new one to the next day, so no paid day is lost. */
|
|
18
|
+
declare function membershipTerm(months: number, today: CalendarDate, currentEnd?: CalendarDate | null): MembershipTerm;
|
|
19
|
+
/** Negative once `end` has passed. */
|
|
20
|
+
declare function daysRemaining(end: CalendarDate, today: CalendarDate): number;
|
|
21
|
+
declare function membershipStatus(membership: MembershipRecord, today: CalendarDate): MembershipStatus;
|
|
22
|
+
declare function isRenewalNoticeDue(end: CalendarDate, today: CalendarDate, noticeDays: number): boolean;
|
|
23
|
+
|
|
24
|
+
export { type MembershipRecord, type MembershipStatus, type MembershipTerm, addMonths, daysRemaining, isRenewalNoticeDue, membershipStatus, membershipTerm };
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// src/availability/time.ts
|
|
2
|
+
var MINUTES_PER_DAY = 24 * 60;
|
|
3
|
+
var DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
4
|
+
function isValidDate(date) {
|
|
5
|
+
const match = DATE_PATTERN.exec(date);
|
|
6
|
+
if (!match) return false;
|
|
7
|
+
const [year, month, day] = match.slice(1).map(Number);
|
|
8
|
+
const parsed = new Date(Date.UTC(year, month - 1, day));
|
|
9
|
+
return parsed.getUTCMonth() === month - 1 && parsed.getUTCDate() === day;
|
|
10
|
+
}
|
|
11
|
+
var MS_PER_DAY = 24 * 60 * 60 * 1e3;
|
|
12
|
+
function toUtc(date) {
|
|
13
|
+
if (!isValidDate(date)) throw new RangeError(`Invalid calendar date: ${date}`);
|
|
14
|
+
const [year, month, day] = date.split("-").map(Number);
|
|
15
|
+
return Date.UTC(year, month - 1, day);
|
|
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
|
+
};
|
|
30
|
+
var fromUtc = (time) => new Date(time).toISOString().slice(0, 10);
|
|
31
|
+
function addMonths(date, months) {
|
|
32
|
+
const from = new Date(toUtc2(date));
|
|
33
|
+
const total = from.getUTCFullYear() * 12 + from.getUTCMonth() + months;
|
|
34
|
+
const year = Math.floor(total / 12);
|
|
35
|
+
const month = total - year * 12;
|
|
36
|
+
const lastDay = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
|
|
37
|
+
return fromUtc(Date.UTC(year, month, Math.min(from.getUTCDate(), lastDay)));
|
|
38
|
+
}
|
|
39
|
+
function membershipTerm(months, today, currentEnd) {
|
|
40
|
+
const start = currentEnd && currentEnd >= today ? addDays(currentEnd, 1) : today;
|
|
41
|
+
return { start, end: addDays(addMonths(start, months), -1) };
|
|
42
|
+
}
|
|
43
|
+
function daysRemaining(end, today) {
|
|
44
|
+
return daysBetween(today, end);
|
|
45
|
+
}
|
|
46
|
+
function membershipStatus(membership, today) {
|
|
47
|
+
if (membership.refunded) return "refunded";
|
|
48
|
+
if (membership.end < today) return "expired";
|
|
49
|
+
if (membership.cancelled) return "cancelled";
|
|
50
|
+
return membership.start > today ? "upcoming" : "active";
|
|
51
|
+
}
|
|
52
|
+
function isRenewalNoticeDue(end, today, noticeDays) {
|
|
53
|
+
const days = daysRemaining(end, today);
|
|
54
|
+
return days >= 0 && days <= noticeDays;
|
|
55
|
+
}
|
|
56
|
+
export {
|
|
57
|
+
addMonths,
|
|
58
|
+
daysRemaining,
|
|
59
|
+
isRenewalNoticeDue,
|
|
60
|
+
membershipStatus,
|
|
61
|
+
membershipTerm
|
|
62
|
+
};
|
|
63
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +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\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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