@free-intelligence/core 1.16.4 → 1.17.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.
@@ -0,0 +1,20 @@
1
+ /**
2
+ * An appointment's lifecycle: a web booking is born pending and is confirmed or cancelled;
3
+ * completed and cancelled are final; a mistaken no-show goes back to confirmed. fi-php's
4
+ * `FreeIntelligence\Appointment\Status` mirrors it, both held to contracts/appointment.vectors.json.
5
+ */
6
+ declare const APPOINTMENT_STATUSES: readonly ["pending", "confirmed", "completed", "cancelled", "no_show"];
7
+ type AppointmentStatus = (typeof APPOINTMENT_STATUSES)[number];
8
+ declare const APPOINTMENT_TRANSITIONS: Readonly<Record<AppointmentStatus, readonly AppointmentStatus[]>>;
9
+ /** Whether an appointment in `from` may move to `to`. */
10
+ declare function canTransition(from: AppointmentStatus, to: AppointmentStatus): boolean;
11
+ /**
12
+ * The statuses the front desk may set by hand. Confirming is the patient's act, and a no-show
13
+ * can only be recorded once the appointment has started.
14
+ *
15
+ * @param start the appointment's start, ISO or Date
16
+ * @param now the moment the desk looks
17
+ */
18
+ declare function deskTransitions(status: AppointmentStatus, start: string | Date, now: Date): AppointmentStatus[];
19
+
20
+ export { APPOINTMENT_STATUSES, APPOINTMENT_TRANSITIONS, type AppointmentStatus, canTransition, deskTransitions };
@@ -0,0 +1,26 @@
1
+ // src/appointment/index.ts
2
+ var APPOINTMENT_STATUSES = ["pending", "confirmed", "completed", "cancelled", "no_show"];
3
+ var APPOINTMENT_TRANSITIONS = {
4
+ pending: ["confirmed", "cancelled"],
5
+ confirmed: ["completed", "cancelled", "no_show"],
6
+ completed: [],
7
+ cancelled: [],
8
+ no_show: ["confirmed"]
9
+ };
10
+ function canTransition(from, to) {
11
+ return APPOINTMENT_TRANSITIONS[from].includes(to);
12
+ }
13
+ function deskTransitions(status, start, now) {
14
+ if (status === "pending") return ["cancelled"];
15
+ if (status === "no_show") return ["confirmed"];
16
+ if (status !== "confirmed") return [];
17
+ const started = new Date(start).getTime() <= now.getTime();
18
+ return started ? ["completed", "no_show", "cancelled"] : ["completed", "cancelled"];
19
+ }
20
+ export {
21
+ APPOINTMENT_STATUSES,
22
+ APPOINTMENT_TRANSITIONS,
23
+ canTransition,
24
+ deskTransitions
25
+ };
26
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/appointment/index.ts"],"sourcesContent":["/**\n * An appointment's lifecycle: a web booking is born pending and is confirmed or cancelled;\n * completed and cancelled are final; a mistaken no-show goes back to confirmed. fi-php's\n * `FreeIntelligence\\Appointment\\Status` mirrors it, both held to contracts/appointment.vectors.json.\n */\n\nexport const APPOINTMENT_STATUSES = ['pending', 'confirmed', 'completed', 'cancelled', 'no_show'] as const;\n\nexport type AppointmentStatus = (typeof APPOINTMENT_STATUSES)[number];\n\nexport const APPOINTMENT_TRANSITIONS: Readonly<Record<AppointmentStatus, readonly AppointmentStatus[]>> = {\n pending: ['confirmed', 'cancelled'],\n confirmed: ['completed', 'cancelled', 'no_show'],\n completed: [],\n cancelled: [],\n no_show: ['confirmed'],\n};\n\n/** Whether an appointment in `from` may move to `to`. */\nexport function canTransition(from: AppointmentStatus, to: AppointmentStatus): boolean {\n return APPOINTMENT_TRANSITIONS[from].includes(to);\n}\n\n/**\n * The statuses the front desk may set by hand. Confirming is the patient's act, and a no-show\n * can only be recorded once the appointment has started.\n *\n * @param start the appointment's start, ISO or Date\n * @param now the moment the desk looks\n */\nexport function deskTransitions(status: AppointmentStatus, start: string | Date, now: Date): AppointmentStatus[] {\n if (status === 'pending') return ['cancelled'];\n if (status === 'no_show') return ['confirmed'];\n if (status !== 'confirmed') return [];\n const started = new Date(start).getTime() <= now.getTime();\n return started ? ['completed', 'no_show', 'cancelled'] : ['completed', 'cancelled'];\n}\n"],"mappings":";AAMO,IAAM,uBAAuB,CAAC,WAAW,aAAa,aAAa,aAAa,SAAS;AAIzF,IAAM,0BAA6F;AAAA,EACxG,SAAS,CAAC,aAAa,WAAW;AAAA,EAClC,WAAW,CAAC,aAAa,aAAa,SAAS;AAAA,EAC/C,WAAW,CAAC;AAAA,EACZ,WAAW,CAAC;AAAA,EACZ,SAAS,CAAC,WAAW;AACvB;AAGO,SAAS,cAAc,MAAyB,IAAgC;AACrF,SAAO,wBAAwB,IAAI,EAAE,SAAS,EAAE;AAClD;AASO,SAAS,gBAAgB,QAA2B,OAAsB,KAAgC;AAC/G,MAAI,WAAW,UAAW,QAAO,CAAC,WAAW;AAC7C,MAAI,WAAW,UAAW,QAAO,CAAC,WAAW;AAC7C,MAAI,WAAW,YAAa,QAAO,CAAC;AACpC,QAAM,UAAU,IAAI,KAAK,KAAK,EAAE,QAAQ,KAAK,IAAI,QAAQ;AACzD,SAAO,UAAU,CAAC,aAAa,WAAW,WAAW,IAAI,CAAC,aAAa,WAAW;AACpF;","names":[]}
@@ -66,6 +66,31 @@ declare function daysBetween(from: CalendarDate, to: CalendarDate): number;
66
66
  /** As JavaScript counts it: 0 is Sunday. */
67
67
  declare function dayOfWeek(date: CalendarDate): number;
68
68
 
69
+ /** The zone a clinic keeps when it names none. */
70
+ declare const DEFAULT_CLINIC_ZONE = "America/Mexico_City";
71
+ /**
72
+ * The clinic's IANA zone: the default when none is given, the value itself when it is a zone.
73
+ *
74
+ * @throws RangeError when `value` is not an IANA zone, so a typo in configuration fails loudly
75
+ */
76
+ declare function clinicZone(value?: string | null): string;
77
+ /** How a calendar day reads: `long` "Martes, 15 de diciembre", `short` "Mar, 15 de dic de 2026", `plain` "15 de diciembre de 2026", `month` "Diciembre de 2026". */
78
+ type CalendarDateStyle = 'long' | 'short' | 'plain' | 'month';
79
+ /**
80
+ * A calendar day in Mexican Spanish, capitalized. The day is a wall date, so no zone moves it.
81
+ *
82
+ * @param date `YYYY-MM-DD`
83
+ * @param style see {@link CalendarDateStyle}
84
+ */
85
+ declare function formatCalendarDate(date: CalendarDate, style: CalendarDateStyle): string;
86
+ /**
87
+ * An instant as the clinic's clock reads it: "mar 15 de dic, 10:30 a.m.".
88
+ *
89
+ * @param instant an ISO string or a Date
90
+ * @param zone the clinic's IANA zone, see {@link clinicZone}
91
+ */
92
+ declare function formatClinicDateTime(instant: string | Date, zone: string): string;
93
+
69
94
  declare function slotsOverlap(a: WeeklySlot, b: WeeklySlot): boolean;
70
95
  declare function validateAvailability(availability: DoctorAvailability): AvailabilityError[];
71
96
  declare function hasBlockingErrors(errors: AvailabilityError[]): boolean;
@@ -176,4 +201,4 @@ declare function hourlyCapacity(rules: SchedulingRules): number | null;
176
201
  */
177
202
  declare function generateSlots(availability: DoctorAvailability, query: SlotQuery): BookableSlot[];
178
203
 
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 };
204
+ export { AVAILABILITY_TEMPLATES, AVAILABILITY_VERSION, AvailabilityError, AvailabilityTemplate, type BookableSlot, COMMON_EXCEPTION_REASONS, CalendarDate, type CalendarDateStyle, DAYS_OF_WEEK, DEFAULT_BREAK_END, DEFAULT_BREAK_START, DEFAULT_CLINIC_ZONE, 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, clinicZone, complementIntervals, dayOfWeek, daysBetween, emptyAvailability, findConflict, findGaps, formatCalendarDate, formatClinicDateTime, 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 };
@@ -127,6 +127,42 @@ function dayOfWeek(date) {
127
127
  return new Date(toUtc(date)).getUTCDay();
128
128
  }
129
129
 
130
+ // src/availability/format.ts
131
+ var DEFAULT_CLINIC_ZONE = "America/Mexico_City";
132
+ var LOCALE = "es-MX";
133
+ function clinicZone(value) {
134
+ const zone = value?.trim();
135
+ if (!zone) return DEFAULT_CLINIC_ZONE;
136
+ try {
137
+ new Intl.DateTimeFormat(LOCALE, { timeZone: zone });
138
+ } catch {
139
+ throw new RangeError(`"${zone}" is not an IANA time zone`);
140
+ }
141
+ return zone;
142
+ }
143
+ var DATE_STYLES = {
144
+ long: { weekday: "long", day: "numeric", month: "long" },
145
+ short: { weekday: "short", day: "numeric", month: "short", year: "numeric" },
146
+ plain: { day: "numeric", month: "long", year: "numeric" },
147
+ month: { month: "long", year: "numeric" }
148
+ };
149
+ var capitalize = (text) => text.charAt(0).toUpperCase() + text.slice(1);
150
+ function formatCalendarDate(date, style) {
151
+ const [year, month, day] = date.split("-").map(Number);
152
+ const noon = new Date(Date.UTC(year, month - 1, day, 12));
153
+ return capitalize(new Intl.DateTimeFormat(LOCALE, { ...DATE_STYLES[style], timeZone: "UTC" }).format(noon));
154
+ }
155
+ function formatClinicDateTime(instant, zone) {
156
+ return new Date(instant).toLocaleString(LOCALE, {
157
+ weekday: "short",
158
+ day: "numeric",
159
+ month: "short",
160
+ hour: "2-digit",
161
+ minute: "2-digit",
162
+ timeZone: zone
163
+ });
164
+ }
165
+
130
166
  // src/availability/validation.ts
131
167
  var MIN_SLOT_DURATION = 5;
132
168
  function problemInHours(start, end) {
@@ -430,6 +466,7 @@ export {
430
466
  DAYS_OF_WEEK,
431
467
  DEFAULT_BREAK_END,
432
468
  DEFAULT_BREAK_START,
469
+ DEFAULT_CLINIC_ZONE,
433
470
  DEFAULT_RULES,
434
471
  DEFAULT_WORK_END,
435
472
  DEFAULT_WORK_START,
@@ -441,12 +478,15 @@ export {
441
478
  applyBreak,
442
479
  availabilityFromWeek,
443
480
  calendarDateIn,
481
+ clinicZone,
444
482
  complementIntervals,
445
483
  dayOfWeek,
446
484
  daysBetween,
447
485
  emptyAvailability,
448
486
  findConflict,
449
487
  findGaps,
488
+ formatCalendarDate,
489
+ formatClinicDateTime,
450
490
  fromLocalMinutes,
451
491
  generateSlots,
452
492
  groupByDay,
@@ -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\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,OAA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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/format.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 type { CalendarDate } from './types';\n\n/** The zone a clinic keeps when it names none. */\nexport const DEFAULT_CLINIC_ZONE = 'America/Mexico_City';\n\nconst LOCALE = 'es-MX';\n\n/**\n * The clinic's IANA zone: the default when none is given, the value itself when it is a zone.\n *\n * @throws RangeError when `value` is not an IANA zone, so a typo in configuration fails loudly\n */\nexport function clinicZone(value?: string | null): string {\n const zone = value?.trim();\n if (!zone) return DEFAULT_CLINIC_ZONE;\n try {\n new Intl.DateTimeFormat(LOCALE, { timeZone: zone });\n } catch {\n throw new RangeError(`\"${zone}\" is not an IANA time zone`);\n }\n return zone;\n}\n\n/** How a calendar day reads: `long` \"Martes, 15 de diciembre\", `short` \"Mar, 15 de dic de 2026\", `plain` \"15 de diciembre de 2026\", `month` \"Diciembre de 2026\". */\nexport type CalendarDateStyle = 'long' | 'short' | 'plain' | 'month';\n\nconst DATE_STYLES: Record<CalendarDateStyle, Intl.DateTimeFormatOptions> = {\n long: { weekday: 'long', day: 'numeric', month: 'long' },\n short: { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' },\n plain: { day: 'numeric', month: 'long', year: 'numeric' },\n month: { month: 'long', year: 'numeric' },\n};\n\nconst capitalize = (text: string) => text.charAt(0).toUpperCase() + text.slice(1);\n\n/**\n * A calendar day in Mexican Spanish, capitalized. The day is a wall date, so no zone moves it.\n *\n * @param date `YYYY-MM-DD`\n * @param style see {@link CalendarDateStyle}\n */\nexport function formatCalendarDate(date: CalendarDate, style: CalendarDateStyle): string {\n const [year, month, day] = date.split('-').map(Number);\n const noon = new Date(Date.UTC(year, month - 1, day, 12));\n return capitalize(new Intl.DateTimeFormat(LOCALE, { ...DATE_STYLES[style], timeZone: 'UTC' }).format(noon));\n}\n\n/**\n * An instant as the clinic's clock reads it: \"mar 15 de dic, 10:30 a.m.\".\n *\n * @param instant an ISO string or a Date\n * @param zone the clinic's IANA zone, see {@link clinicZone}\n */\nexport function formatClinicDateTime(instant: string | Date, zone: string): string {\n return new Date(instant).toLocaleString(LOCALE, {\n weekday: 'short',\n day: 'numeric',\n month: 'short',\n hour: '2-digit',\n minute: '2-digit',\n timeZone: zone,\n });\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,WA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AAK,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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@free-intelligence/core",
3
- "version": "1.16.4",
3
+ "version": "1.17.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/BernardUriza/free-intelligence",
@@ -24,6 +24,10 @@
24
24
  "./membership": {
25
25
  "types": "./dist/membership/index.d.ts",
26
26
  "import": "./dist/membership/index.js"
27
+ },
28
+ "./appointment": {
29
+ "types": "./dist/appointment/index.d.ts",
30
+ "import": "./dist/appointment/index.js"
27
31
  }
28
32
  },
29
33
  "files": [
@@ -0,0 +1,34 @@
1
+ /** contracts/appointment.vectors.json: the lifecycle as data for fi-php's mirror. `UPDATE_VECTORS=1` refreshes `desk`. */
2
+
3
+ import { readFileSync, writeFileSync } from 'node:fs';
4
+ import { dirname, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { describe, expect, it } from 'vitest';
7
+ import { canTransition, deskTransitions, type AppointmentStatus } from './index';
8
+
9
+ const path = resolve(dirname(fileURLToPath(import.meta.url)), '../../contracts/appointment.vectors.json');
10
+ const vectors = JSON.parse(readFileSync(path, 'utf8')) as {
11
+ transitions: { name: string; from: AppointmentStatus; to: AppointmentStatus; expected: boolean }[];
12
+ desk: { name: string; status: AppointmentStatus; start: string; now: string; expected: AppointmentStatus[] | null }[];
13
+ };
14
+ const desk = (c: (typeof vectors.desk)[number]) => deskTransitions(c.status, c.start, new Date(c.now));
15
+ if (process.env.UPDATE_VECTORS === '1') {
16
+ for (const c of vectors.desk) c.expected = desk(c);
17
+ writeFileSync(path, JSON.stringify(vectors, null, 1) + '\n');
18
+ }
19
+
20
+ describe('canTransition', () => {
21
+ it.each(vectors.transitions.map((c) => [c.name, c] as const))('%s', (_name, c) => {
22
+ expect(canTransition(c.from, c.to)).toBe(c.expected);
23
+ });
24
+ });
25
+
26
+ describe('deskTransitions', () => {
27
+ it.each(vectors.desk.map((c) => [c.name, c] as const))('%s', (_name, c) => {
28
+ expect(desk(c)).toEqual(c.expected);
29
+ });
30
+
31
+ it('only offers transitions the lifecycle allows', () => {
32
+ for (const c of vectors.desk) for (const to of desk(c)) expect(canTransition(c.status, to)).toBe(true);
33
+ });
34
+ });
@@ -0,0 +1,37 @@
1
+ /**
2
+ * An appointment's lifecycle: a web booking is born pending and is confirmed or cancelled;
3
+ * completed and cancelled are final; a mistaken no-show goes back to confirmed. fi-php's
4
+ * `FreeIntelligence\Appointment\Status` mirrors it, both held to contracts/appointment.vectors.json.
5
+ */
6
+
7
+ export const APPOINTMENT_STATUSES = ['pending', 'confirmed', 'completed', 'cancelled', 'no_show'] as const;
8
+
9
+ export type AppointmentStatus = (typeof APPOINTMENT_STATUSES)[number];
10
+
11
+ export const APPOINTMENT_TRANSITIONS: Readonly<Record<AppointmentStatus, readonly AppointmentStatus[]>> = {
12
+ pending: ['confirmed', 'cancelled'],
13
+ confirmed: ['completed', 'cancelled', 'no_show'],
14
+ completed: [],
15
+ cancelled: [],
16
+ no_show: ['confirmed'],
17
+ };
18
+
19
+ /** Whether an appointment in `from` may move to `to`. */
20
+ export function canTransition(from: AppointmentStatus, to: AppointmentStatus): boolean {
21
+ return APPOINTMENT_TRANSITIONS[from].includes(to);
22
+ }
23
+
24
+ /**
25
+ * The statuses the front desk may set by hand. Confirming is the patient's act, and a no-show
26
+ * can only be recorded once the appointment has started.
27
+ *
28
+ * @param start the appointment's start, ISO or Date
29
+ * @param now the moment the desk looks
30
+ */
31
+ export function deskTransitions(status: AppointmentStatus, start: string | Date, now: Date): AppointmentStatus[] {
32
+ if (status === 'pending') return ['cancelled'];
33
+ if (status === 'no_show') return ['confirmed'];
34
+ if (status !== 'confirmed') return [];
35
+ const started = new Date(start).getTime() <= now.getTime();
36
+ return started ? ['completed', 'no_show', 'cancelled'] : ['completed', 'cancelled'];
37
+ }
@@ -0,0 +1,37 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { DEFAULT_CLINIC_ZONE, clinicZone, formatCalendarDate, formatClinicDateTime } from './format';
3
+
4
+ describe('clinicZone', () => {
5
+ it('defaults when the value is missing or blank', () => {
6
+ expect(clinicZone()).toBe(DEFAULT_CLINIC_ZONE);
7
+ expect(clinicZone(null)).toBe(DEFAULT_CLINIC_ZONE);
8
+ expect(clinicZone(' ')).toBe(DEFAULT_CLINIC_ZONE);
9
+ });
10
+
11
+ it('keeps a real zone and refuses a typo', () => {
12
+ expect(clinicZone(' America/Tijuana ')).toBe('America/Tijuana');
13
+ expect(() => clinicZone('America/Mexico_Cty')).toThrow(RangeError);
14
+ });
15
+ });
16
+
17
+ describe('formatCalendarDate', () => {
18
+ it.each([
19
+ ['long', 'Martes, 15 de diciembre'],
20
+ ['short', 'Mar, 15 de dic de 2026'],
21
+ ['plain', '15 de diciembre de 2026'],
22
+ ['month', 'Diciembre de 2026'],
23
+ ] as const)('%s', (style, text) => {
24
+ expect(formatCalendarDate('2026-12-15', style)).toBe(text);
25
+ });
26
+
27
+ it('a first of the month stays on its day', () => {
28
+ expect(formatCalendarDate('2026-11-01', 'long')).toBe('Domingo, 1 de noviembre');
29
+ });
30
+ });
31
+
32
+ describe('formatClinicDateTime', () => {
33
+ it('reads the instant on the clinic clock', () => {
34
+ expect(formatClinicDateTime('2026-12-15T16:30:00Z', 'America/Mexico_City')).toBe('mar 15 de dic, 10:30 a.m.');
35
+ expect(formatClinicDateTime(new Date('2026-12-15T16:30:00Z'), 'America/Tijuana')).toBe('mar 15 de dic, 08:30 a.m.');
36
+ });
37
+ });
@@ -0,0 +1,63 @@
1
+ import type { CalendarDate } from './types';
2
+
3
+ /** The zone a clinic keeps when it names none. */
4
+ export const DEFAULT_CLINIC_ZONE = 'America/Mexico_City';
5
+
6
+ const LOCALE = 'es-MX';
7
+
8
+ /**
9
+ * The clinic's IANA zone: the default when none is given, the value itself when it is a zone.
10
+ *
11
+ * @throws RangeError when `value` is not an IANA zone, so a typo in configuration fails loudly
12
+ */
13
+ export function clinicZone(value?: string | null): string {
14
+ const zone = value?.trim();
15
+ if (!zone) return DEFAULT_CLINIC_ZONE;
16
+ try {
17
+ new Intl.DateTimeFormat(LOCALE, { timeZone: zone });
18
+ } catch {
19
+ throw new RangeError(`"${zone}" is not an IANA time zone`);
20
+ }
21
+ return zone;
22
+ }
23
+
24
+ /** How a calendar day reads: `long` "Martes, 15 de diciembre", `short` "Mar, 15 de dic de 2026", `plain` "15 de diciembre de 2026", `month` "Diciembre de 2026". */
25
+ export type CalendarDateStyle = 'long' | 'short' | 'plain' | 'month';
26
+
27
+ const DATE_STYLES: Record<CalendarDateStyle, Intl.DateTimeFormatOptions> = {
28
+ long: { weekday: 'long', day: 'numeric', month: 'long' },
29
+ short: { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' },
30
+ plain: { day: 'numeric', month: 'long', year: 'numeric' },
31
+ month: { month: 'long', year: 'numeric' },
32
+ };
33
+
34
+ const capitalize = (text: string) => text.charAt(0).toUpperCase() + text.slice(1);
35
+
36
+ /**
37
+ * A calendar day in Mexican Spanish, capitalized. The day is a wall date, so no zone moves it.
38
+ *
39
+ * @param date `YYYY-MM-DD`
40
+ * @param style see {@link CalendarDateStyle}
41
+ */
42
+ export function formatCalendarDate(date: CalendarDate, style: CalendarDateStyle): string {
43
+ const [year, month, day] = date.split('-').map(Number);
44
+ const noon = new Date(Date.UTC(year, month - 1, day, 12));
45
+ return capitalize(new Intl.DateTimeFormat(LOCALE, { ...DATE_STYLES[style], timeZone: 'UTC' }).format(noon));
46
+ }
47
+
48
+ /**
49
+ * An instant as the clinic's clock reads it: "mar 15 de dic, 10:30 a.m.".
50
+ *
51
+ * @param instant an ISO string or a Date
52
+ * @param zone the clinic's IANA zone, see {@link clinicZone}
53
+ */
54
+ export function formatClinicDateTime(instant: string | Date, zone: string): string {
55
+ return new Date(instant).toLocaleString(LOCALE, {
56
+ weekday: 'short',
57
+ day: 'numeric',
58
+ month: 'short',
59
+ hour: '2-digit',
60
+ minute: '2-digit',
61
+ timeZone: zone,
62
+ });
63
+ }
@@ -2,6 +2,7 @@
2
2
  export * from './types';
3
3
  export * from './defaults';
4
4
  export * from './time';
5
+ export * from './format';
5
6
  export * from './validation';
6
7
  export * from './week';
7
8
  export * from './intervals';
@@ -0,0 +1,58 @@
1
+ /**
2
+ * contracts/availability.vectors.json, availability-day.vectors.json and membership.vectors.json:
3
+ * the rules as data, so fi-php's mirror is held to the same results. `UPDATE_VECTORS=1 vitest run`
4
+ * rewrites `expected` from src; without it, any drift between src and the vectors is red.
5
+ */
6
+
7
+ import { readFileSync, writeFileSync } from 'node:fs';
8
+ import { dirname, resolve } from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
10
+ import { describe, expect, it } from 'vitest';
11
+ import * as availability from './index';
12
+ import { findGaps, validateAvailability, type DoctorAvailability } from './index';
13
+ import { addMonths, daysRemaining, isRenewalNoticeDue, membershipStatus, membershipTerm } from '../membership';
14
+
15
+ const contracts = resolve(dirname(fileURLToPath(import.meta.url)), '../../contracts');
16
+ const update = process.env.UPDATE_VECTORS === '1';
17
+
18
+ type Vectors<C> = { description: string; cases: (C & { name: string; expected: unknown })[] };
19
+
20
+ function check<C>(file: string, compute: (c: C) => unknown) {
21
+ const path = resolve(contracts, file);
22
+ const vectors: Vectors<C> = JSON.parse(readFileSync(path, 'utf8'));
23
+ if (update) {
24
+ for (const c of vectors.cases) c.expected = compute(c);
25
+ writeFileSync(path, JSON.stringify(vectors, null, 1) + '\n');
26
+ }
27
+ describe(file, () => {
28
+ it.each(vectors.cases.map((c) => [c.name, c] as const))('%s', (_name, c) => {
29
+ expect(compute(c)).toEqual(c.expected);
30
+ });
31
+ });
32
+ }
33
+
34
+ check<{ availability: DoctorAvailability }>('availability.vectors.json', (c) => ({
35
+ errors: validateAvailability(c.availability),
36
+ gaps: findGaps(c.availability.weeklySchedule),
37
+ }));
38
+
39
+ check<{ operation: string; args: unknown[] }>('availability-day.vectors.json', (c) => {
40
+ const operation = (availability as unknown as Record<string, (...args: unknown[]) => unknown>)[c.operation];
41
+ if (typeof operation !== 'function') throw new Error(`core has no ${c.operation}`);
42
+ try {
43
+ return { result: operation(...structuredClone(c.args)) };
44
+ } catch (error) {
45
+ if (!(error instanceof RangeError)) throw error;
46
+ return { error: { name: error.name, message: error.message } };
47
+ }
48
+ });
49
+
50
+ type MembershipCase = { operation: string } & Record<string, any>;
51
+ const membership: Record<string, (c: MembershipCase) => unknown> = {
52
+ addMonths: (c) => addMonths(c.date, c.months),
53
+ membershipTerm: (c) => membershipTerm(c.months, c.today, c.currentEnd),
54
+ daysRemaining: (c) => daysRemaining(c.end, c.today),
55
+ membershipStatus: (c) => membershipStatus({ start: c.start, end: c.end, cancelled: c.cancelled, refunded: c.refunded }, c.today),
56
+ isRenewalNoticeDue: (c) => isRenewalNoticeDue(c.end, c.today, c.noticeDays),
57
+ };
58
+ check<MembershipCase>('membership.vectors.json', (c) => membership[c.operation](c));