@free-intelligence/core 1.12.1 → 1.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,91 @@
1
+ import { applyBreak, resolveDay } from './day';
2
+ import { DEFAULT_RULES } from './defaults';
3
+ import { intervalsOverlap, type Interval } from './intervals';
4
+ import { addDays, daysBetween } from './time';
5
+ import type { CalendarDate, DoctorAvailability, SchedulingRules } from './types';
6
+
7
+ const EPOCH: CalendarDate = '1970-01-01';
8
+ const MINUTES_PER_DAY = 24 * 60;
9
+ const SHORTEST_SLOT = 5;
10
+
11
+ /**
12
+ * Appointments, busy time and `notBefore` are local minutes: wall-clock minutes since 1970-01-01 00:00
13
+ * in the schedule's own time zone. The caller owns the conversion from and to instants.
14
+ */
15
+ export interface SlotQuery {
16
+ /** Both ends inclusive. */
17
+ from: CalendarDate;
18
+ to: CalendarDate;
19
+ appointments?: readonly Interval[];
20
+ /** Time taken outside this schedule, such as an external calendar. The buffer does not apply to it. */
21
+ busy?: readonly Interval[];
22
+ notBefore?: number;
23
+ }
24
+
25
+ /** `start` and `end` are minutes from that date's midnight. */
26
+ export interface BookableSlot {
27
+ date: CalendarDate;
28
+ start: number;
29
+ end: number;
30
+ }
31
+
32
+ export function toLocalMinutes(date: CalendarDate, minuteOfDay = 0): number {
33
+ return daysBetween(EPOCH, date) * MINUTES_PER_DAY + minuteOfDay;
34
+ }
35
+
36
+ export function fromLocalMinutes(localMinutes: number): { date: CalendarDate; minute: number } {
37
+ const days = Math.floor(localMinutes / MINUTES_PER_DAY);
38
+ return { date: addDays(EPOCH, days), minute: localMinutes - days * MINUTES_PER_DAY };
39
+ }
40
+
41
+ export function slotDuration(rules: SchedulingRules): number {
42
+ return Math.max(SHORTEST_SLOT, Math.trunc(rules.minSlotDuration ?? (DEFAULT_RULES.minSlotDuration as number)));
43
+ }
44
+
45
+ export function slotBuffer(rules: SchedulingRules): number {
46
+ return Math.max(0, Math.trunc(rules.bufferBetweenAppointments ?? 0));
47
+ }
48
+
49
+ /** `null` when the rules set no hourly limit. */
50
+ export function hourlyCapacity(rules: SchedulingRules): number | null {
51
+ const { maxPatientsPerHour } = rules;
52
+ return maxPatientsPerHour === undefined || maxPatientsPerHour === null ? null : Math.max(1, Math.trunc(maxPatientsPerHour));
53
+ }
54
+
55
+ const hourOf = (localMinutes: number): number => Math.floor(localMinutes / 60);
56
+
57
+ /**
58
+ * Every slot the schedule offers in the range: one per duration plus buffer inside each working window,
59
+ * minus what starts before `notBefore`, what comes within the buffer of an appointment, what overlaps
60
+ * busy time, and what starts in an hour that already holds its limit of appointments.
61
+ */
62
+ export function generateSlots(availability: DoctorAvailability, query: SlotQuery): BookableSlot[] {
63
+ const { rules } = availability;
64
+ const { from, to, appointments = [], busy = [], notBefore = -Infinity } = query;
65
+ const duration = slotDuration(rules);
66
+ const buffer = slotBuffer(rules);
67
+ const capacity = hourlyCapacity(rules);
68
+
69
+ const bookedPerHour = new Map<number, number>();
70
+ for (const { start } of appointments) bookedPerHour.set(hourOf(start), (bookedPerHour.get(hourOf(start)) ?? 0) + 1);
71
+ const guarded = appointments.map(({ start, end }) => ({ start: start - buffer, end: end + buffer }));
72
+
73
+ const slots: BookableSlot[] = [];
74
+ let spillover = resolveDay(availability, addDays(from, -1)).spilloverNext;
75
+ for (let date = from; date <= to; date = addDays(date, 1)) {
76
+ const day = resolveDay(availability, date, spillover);
77
+ const midnight = toLocalMinutes(date);
78
+ for (const window of applyBreak(day.windows, rules)) {
79
+ for (let start = window.start; start + duration <= window.end; start += duration + buffer) {
80
+ const local = { start: midnight + start, end: midnight + start + duration };
81
+ if (local.start < notBefore) continue;
82
+ if (guarded.some((taken) => intervalsOverlap(local, taken))) continue;
83
+ if (busy.some((taken) => intervalsOverlap(local, taken))) continue;
84
+ if (capacity !== null && (bookedPerHour.get(hourOf(local.start)) ?? 0) >= capacity) continue;
85
+ slots.push({ date, start, end: start + duration });
86
+ }
87
+ }
88
+ spillover = day.spilloverNext;
89
+ }
90
+ return slots;
91
+ }
@@ -36,3 +36,25 @@ export function isValidDate(date: string): boolean {
36
36
  export function toCalendarDate(date: Date): CalendarDate {
37
37
  return `${date.getFullYear()}-${twoDigits(date.getMonth() + 1)}-${twoDigits(date.getDate())}`;
38
38
  }
39
+
40
+ const MS_PER_DAY = 24 * 60 * 60 * 1000;
41
+
42
+ function toUtc(date: CalendarDate): number {
43
+ if (!isValidDate(date)) throw new RangeError(`Invalid calendar date: ${date}`);
44
+ const [year, month, day] = date.split('-').map(Number);
45
+ return Date.UTC(year, month - 1, day);
46
+ }
47
+
48
+ export function addDays(date: CalendarDate, days: number): CalendarDate {
49
+ return new Date(toUtc(date) + days * MS_PER_DAY).toISOString().slice(0, 10);
50
+ }
51
+
52
+ /** Whole days from `from` to `to`; negative when `to` is earlier. */
53
+ export function daysBetween(from: CalendarDate, to: CalendarDate): number {
54
+ return Math.round((toUtc(to) - toUtc(from)) / MS_PER_DAY);
55
+ }
56
+
57
+ /** As JavaScript counts it: 0 is Sunday. */
58
+ export function dayOfWeek(date: CalendarDate): number {
59
+ return new Date(toUtc(date)).getUTCDay();
60
+ }
@@ -0,0 +1,3 @@
1
+ /** A paid membership's term, status and renewal notice: data and pure functions. */
2
+ export * from './types';
3
+ export * from './term';
@@ -0,0 +1,98 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ addMonths,
4
+ daysRemaining,
5
+ isRenewalNoticeDue,
6
+ membershipStatus,
7
+ membershipTerm,
8
+ type MembershipRecord,
9
+ } from './index';
10
+
11
+ const membership = (changes: Partial<MembershipRecord>): MembershipRecord => ({
12
+ start: '2026-01-01',
13
+ end: '2026-12-31',
14
+ cancelled: false,
15
+ refunded: false,
16
+ ...changes,
17
+ });
18
+
19
+ describe('addMonths', () => {
20
+ it('keeps the day of the month', () => {
21
+ expect(addMonths('2026-11-25', 12)).toBe('2027-11-25');
22
+ expect(addMonths('2026-11-25', 2)).toBe('2027-01-25');
23
+ });
24
+
25
+ it('clamps to the last day of a shorter month', () => {
26
+ expect(addMonths('2026-01-31', 1)).toBe('2026-02-28');
27
+ expect(addMonths('2028-01-31', 1)).toBe('2028-02-29');
28
+ expect(addMonths('2024-02-29', 12)).toBe('2025-02-28');
29
+ expect(addMonths('2026-08-31', 1)).toBe('2026-09-30');
30
+ });
31
+
32
+ it('rejects a date that does not exist', () => {
33
+ expect(() => addMonths('2026-02-30', 1)).toThrow(RangeError);
34
+ expect(() => addMonths('25/11/2026', 1)).toThrow(RangeError);
35
+ });
36
+ });
37
+
38
+ describe('membershipTerm', () => {
39
+ it('starts today and ends the day before the anniversary', () => {
40
+ expect(membershipTerm(12, '2026-11-25')).toEqual({ start: '2026-11-25', end: '2027-11-24' });
41
+ expect(membershipTerm(6, '2026-08-31', null)).toEqual({ start: '2026-08-31', end: '2027-02-27' });
42
+ });
43
+
44
+ it('chains a renewal to the day after the current end', () => {
45
+ expect(membershipTerm(12, '2026-11-25', '2027-11-24')).toEqual({ start: '2027-11-25', end: '2028-11-24' });
46
+ expect(membershipTerm(12, '2026-11-25', '2026-11-25')).toEqual({ start: '2026-11-26', end: '2027-11-25' });
47
+ });
48
+
49
+ it('starts today when the previous term already ended', () => {
50
+ expect(membershipTerm(12, '2027-12-01', '2027-11-24')).toEqual({ start: '2027-12-01', end: '2028-11-30' });
51
+ });
52
+ });
53
+
54
+ describe('daysRemaining', () => {
55
+ it('counts calendar days and goes negative after the end', () => {
56
+ expect(daysRemaining('2026-11-25', '2026-11-25')).toBe(0);
57
+ expect(daysRemaining('2026-12-10', '2026-11-25')).toBe(15);
58
+ expect(daysRemaining('2026-11-24', '2026-11-25')).toBe(-1);
59
+ expect(daysRemaining('2027-11-24', '2026-11-25')).toBe(364);
60
+ });
61
+ });
62
+
63
+ describe('membershipStatus', () => {
64
+ const today = '2026-11-25';
65
+
66
+ it('is active through its last day', () => {
67
+ expect(membershipStatus(membership({}), today)).toBe('active');
68
+ expect(membershipStatus(membership({ end: today }), today)).toBe('active');
69
+ });
70
+
71
+ it('expires the day after its end, cancelled or not', () => {
72
+ expect(membershipStatus(membership({ end: '2026-11-24' }), today)).toBe('expired');
73
+ expect(membershipStatus(membership({ end: '2026-11-01', cancelled: true }), today)).toBe('expired');
74
+ });
75
+
76
+ it('is upcoming before its start', () => {
77
+ expect(membershipStatus(membership({ start: '2026-12-01', end: '2027-11-30' }), today)).toBe('upcoming');
78
+ });
79
+
80
+ it('stays cancelled until its end', () => {
81
+ expect(membershipStatus(membership({ cancelled: true }), today)).toBe('cancelled');
82
+ });
83
+
84
+ it('is refunded whatever its dates or cancellation say', () => {
85
+ expect(membershipStatus(membership({ refunded: true }), today)).toBe('refunded');
86
+ expect(membershipStatus(membership({ end: '2026-11-01', cancelled: true, refunded: true }), today)).toBe('refunded');
87
+ expect(membershipStatus(membership({ start: '2026-12-01', end: '2027-11-30', refunded: true }), today)).toBe('refunded');
88
+ });
89
+ });
90
+
91
+ describe('isRenewalNoticeDue', () => {
92
+ it('is due inside the notice window and never after the end', () => {
93
+ expect(isRenewalNoticeDue('2026-12-10', '2026-11-25', 15)).toBe(true);
94
+ expect(isRenewalNoticeDue('2026-12-11', '2026-11-25', 15)).toBe(false);
95
+ expect(isRenewalNoticeDue('2026-11-25', '2026-11-25', 15)).toBe(true);
96
+ expect(isRenewalNoticeDue('2026-11-24', '2026-11-25', 15)).toBe(false);
97
+ });
98
+ });
@@ -0,0 +1,44 @@
1
+ import { addDays, daysBetween, isValidDate } from '../availability/time';
2
+ import type { CalendarDate } from '../availability/types';
3
+ import type { MembershipRecord, MembershipStatus, MembershipTerm } from './types';
4
+
5
+ const toUtc = (date: CalendarDate): number => {
6
+ if (!isValidDate(date)) throw new RangeError(`Invalid calendar date: ${date}`);
7
+ const [year, month, day] = date.split('-').map(Number);
8
+ return Date.UTC(year, month - 1, day);
9
+ };
10
+
11
+ const fromUtc = (time: number): CalendarDate => new Date(time).toISOString().slice(0, 10);
12
+
13
+ /** Same day of the month, clamped to the last day when the target month is shorter. */
14
+ export function addMonths(date: CalendarDate, months: number): CalendarDate {
15
+ const from = new Date(toUtc(date));
16
+ const total = from.getUTCFullYear() * 12 + from.getUTCMonth() + months;
17
+ const year = Math.floor(total / 12);
18
+ const month = total - year * 12;
19
+ const lastDay = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
20
+ return fromUtc(Date.UTC(year, month, Math.min(from.getUTCDate(), lastDay)));
21
+ }
22
+
23
+ /** Renewing before the current term ends chains the new one to the next day, so no paid day is lost. */
24
+ export function membershipTerm(months: number, today: CalendarDate, currentEnd?: CalendarDate | null): MembershipTerm {
25
+ const start = currentEnd && currentEnd >= today ? addDays(currentEnd, 1) : today;
26
+ return { start, end: addDays(addMonths(start, months), -1) };
27
+ }
28
+
29
+ /** Negative once `end` has passed. */
30
+ export function daysRemaining(end: CalendarDate, today: CalendarDate): number {
31
+ return daysBetween(today, end);
32
+ }
33
+
34
+ export function membershipStatus(membership: MembershipRecord, today: CalendarDate): MembershipStatus {
35
+ if (membership.refunded) return 'refunded';
36
+ if (membership.end < today) return 'expired';
37
+ if (membership.cancelled) return 'cancelled';
38
+ return membership.start > today ? 'upcoming' : 'active';
39
+ }
40
+
41
+ export function isRenewalNoticeDue(end: CalendarDate, today: CalendarDate, noticeDays: number): boolean {
42
+ const days = daysRemaining(end, today);
43
+ return days >= 0 && days <= noticeDays;
44
+ }
@@ -0,0 +1,15 @@
1
+ import type { CalendarDate } from '../availability/types';
2
+
3
+ /** Inclusive on both ends: a member is covered on `start` and on `end`. */
4
+ export interface MembershipTerm {
5
+ start: CalendarDate;
6
+ end: CalendarDate;
7
+ }
8
+
9
+ /** `cancelled` keeps coverage until `end`; `refunded` removes it at once. */
10
+ export interface MembershipRecord extends MembershipTerm {
11
+ cancelled: boolean;
12
+ refunded: boolean;
13
+ }
14
+
15
+ export type MembershipStatus = 'active' | 'upcoming' | 'cancelled' | 'expired' | 'refunded';