@free-intelligence/core 1.15.1 → 1.16.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.
|
@@ -58,6 +58,8 @@ 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
|
+
/** The calendar date it is in a zone at an instant: what a schedule in that zone calls today. */
|
|
62
|
+
declare function calendarDateIn(zone: string, instant?: Date): CalendarDate;
|
|
61
63
|
declare function addDays(date: CalendarDate, days: number): CalendarDate;
|
|
62
64
|
/** Whole days from `from` to `to`; negative when `to` is earlier. */
|
|
63
65
|
declare function daysBetween(from: CalendarDate, to: CalendarDate): number;
|
|
@@ -174,4 +176,4 @@ declare function hourlyCapacity(rules: SchedulingRules): number | null;
|
|
|
174
176
|
*/
|
|
175
177
|
declare function generateSlots(availability: DoctorAvailability, query: SlotQuery): BookableSlot[];
|
|
176
178
|
|
|
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 };
|
|
179
|
+
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, calendarDateIn, 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,12 @@ function isValidDate(date) {
|
|
|
105
105
|
function toCalendarDate(date) {
|
|
106
106
|
return `${date.getFullYear()}-${twoDigits(date.getMonth() + 1)}-${twoDigits(date.getDate())}`;
|
|
107
107
|
}
|
|
108
|
+
function calendarDateIn(zone, instant = /* @__PURE__ */ new Date()) {
|
|
109
|
+
const part = {};
|
|
110
|
+
const format = new Intl.DateTimeFormat("en-CA", { timeZone: zone, year: "numeric", month: "2-digit", day: "2-digit" });
|
|
111
|
+
for (const { type, value } of format.formatToParts(instant)) part[type] = value;
|
|
112
|
+
return `${part.year}-${part.month}-${part.day}`;
|
|
113
|
+
}
|
|
108
114
|
var MS_PER_DAY = 24 * 60 * 60 * 1e3;
|
|
109
115
|
function toUtc(date) {
|
|
110
116
|
if (!isValidDate(date)) throw new RangeError(`Invalid calendar date: ${date}`);
|
|
@@ -434,6 +440,7 @@ export {
|
|
|
434
440
|
addDays,
|
|
435
441
|
applyBreak,
|
|
436
442
|
availabilityFromWeek,
|
|
443
|
+
calendarDateIn,
|
|
437
444
|
complementIntervals,
|
|
438
445
|
dayOfWeek,
|
|
439
446
|
daysBetween,
|
|
@@ -1 +1 @@
|
|
|
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,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AM,QAAwB,CAAC;AAC/B,MAAI,YAAY,WAAW,cAAc,QAAQ,MAAM,EAAE,CAAC,EAAE;AAC5D,WAAS,OAAO,MAAM,QAAQ,IAAI,OAAO,QAAQ,MAAM,CAAC,GAAG;AACzD,UAAM,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"]}
|
|
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\n/** The calendar date it is in a zone at an instant: what a schedule in that zone calls today. */\nexport function calendarDateIn(zone: string, instant: Date = new Date()): CalendarDate {\n const part: Record<string, string> = {};\n const format = new Intl.DateTimeFormat('en-CA', { timeZone: zone, year: 'numeric', month: '2-digit', day: '2-digit' });\n for (const { type, value } of format.formatToParts(instant)) part[type] = value;\n return `${part.year}-${part.month}-${part.day}`;\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,IAA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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"]}
|
|
@@ -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\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,CAAC,MAAO,QAAO;AACnB,QAAM,CAAC,MAAM,OAAO,GAAG,IAAI,MAAM,MAAM,CAAC,EAAE,IAAI,MAAM;AACpD,QAAM,SAAS,IAAI,KAAK,KAAK,IAAI,MAAM,QAAQ,GAAG,GAAG,CAAC;AACtD,SAAO,OAAO,YAAY,MAAM,QAAQ,KAAK,OAAO,WAAW,MAAM;AACvE;
|
|
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\n/** The calendar date it is in a zone at an instant: what a schedule in that zone calls today. */\nexport function calendarDateIn(zone: string, instant: Date = new Date()): CalendarDate {\n const part: Record<string, string> = {};\n const format = new Intl.DateTimeFormat('en-CA', { timeZone: zone, year: 'numeric', month: '2-digit', day: '2-digit' });\n for (const { type, value } of format.formatToParts(instant)) part[type] = value;\n return `${part.year}-${part.month}-${part.day}`;\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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AAY,IAAI;AAChE,QAAM,OAAO,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
|
@@ -8,6 +8,7 @@ import {
|
|
|
8
8
|
hasBlockingErrors,
|
|
9
9
|
isValidDate,
|
|
10
10
|
suggestNextSlot,
|
|
11
|
+
calendarDateIn,
|
|
11
12
|
toCalendarDate,
|
|
12
13
|
validateAvailability,
|
|
13
14
|
weeklyHours,
|
|
@@ -127,4 +128,12 @@ describe('dates', () => {
|
|
|
127
128
|
it('reads the local day even late in the evening', () => {
|
|
128
129
|
expect(toCalendarDate(new Date(2026, 10, 25, 23, 30))).toBe('2026-11-25');
|
|
129
130
|
});
|
|
131
|
+
|
|
132
|
+
it('reads the calendar date of a zone, not of the machine', () => {
|
|
133
|
+
const instant = new Date('2026-12-01T03:30:00Z');
|
|
134
|
+
expect(calendarDateIn('America/Mexico_City', instant)).toBe('2026-11-30');
|
|
135
|
+
expect(calendarDateIn('Asia/Tokyo', instant)).toBe('2026-12-01');
|
|
136
|
+
expect(calendarDateIn('UTC')).toMatch(/^\d{4}-\d{2}-\d{2}$/);
|
|
137
|
+
expect(() => calendarDateIn('Not/AZone', instant)).toThrow(RangeError);
|
|
138
|
+
});
|
|
130
139
|
});
|
package/src/availability/time.ts
CHANGED
|
@@ -37,6 +37,14 @@ export function toCalendarDate(date: Date): CalendarDate {
|
|
|
37
37
|
return `${date.getFullYear()}-${twoDigits(date.getMonth() + 1)}-${twoDigits(date.getDate())}`;
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
/** The calendar date it is in a zone at an instant: what a schedule in that zone calls today. */
|
|
41
|
+
export function calendarDateIn(zone: string, instant: Date = new Date()): CalendarDate {
|
|
42
|
+
const part: Record<string, string> = {};
|
|
43
|
+
const format = new Intl.DateTimeFormat('en-CA', { timeZone: zone, year: 'numeric', month: '2-digit', day: '2-digit' });
|
|
44
|
+
for (const { type, value } of format.formatToParts(instant)) part[type] = value;
|
|
45
|
+
return `${part.year}-${part.month}-${part.day}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
40
48
|
const MS_PER_DAY = 24 * 60 * 60 * 1000;
|
|
41
49
|
|
|
42
50
|
function toUtc(date: CalendarDate): number {
|