@free-intelligence/core 1.12.1 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,6 +19,7 @@ is the glassmorphism skin built on top of it.
19
19
  | `ChatMessage`, `ConversationSummary` | Plain message / conversation shapes shared across the surface. |
20
20
  | conversation helpers | Pure helpers for building and merging conversation transcripts. |
21
21
  | `@free-intelligence/core/availability` | Weekly hours, date exceptions and booking rules: types, validation and week math. |
22
+ | `@free-intelligence/core/membership` | A paid membership's term, renewal chaining, status (`active`, `upcoming`, `cancelled`, `expired`, `refunded`) and renewal notice window. |
22
23
 
23
24
  ## Install
24
25
 
@@ -1,58 +1,5 @@
1
- /** `HH:mm`, 24 h. */
2
- type TimeOfDay = string;
3
- /** `YYYY-MM-DD`. */
4
- type CalendarDate = string;
5
- interface WeeklySlot {
6
- /** As JavaScript counts it: 0 is Sunday. */
7
- day: number;
8
- start: TimeOfDay;
9
- end: TimeOfDay;
10
- label?: string;
11
- }
12
- /** Replaces the weekly pattern on one date. Without `fullDayClosed` it carries its own hours. */
13
- interface DateOverride {
14
- date: CalendarDate;
15
- start?: TimeOfDay;
16
- end?: TimeOfDay;
17
- fullDayClosed: boolean;
18
- reason?: string;
19
- }
20
- /** Durations are minutes. */
21
- interface SchedulingRules {
22
- breakStart?: TimeOfDay;
23
- breakEnd?: TimeOfDay;
24
- minSlotDuration?: number;
25
- maxPatientsPerHour?: number;
26
- bufferBetweenAppointments?: number;
27
- }
28
- interface DoctorAvailability {
29
- version: number;
30
- weeklySchedule: WeeklySlot[];
31
- overrides: DateOverride[];
32
- rules: SchedulingRules;
33
- }
34
- type AvailabilityErrorType = 'overlap' | 'invalid_time' | 'end_before_start' | 'duplicate_date';
35
- interface AvailabilityError {
36
- type: AvailabilityErrorType;
37
- day?: number;
38
- date?: CalendarDate;
39
- /** Position in that day's list, when the error belongs to one slot. */
40
- slotIndex?: number;
41
- message: string;
42
- severity: 'error' | 'warning';
43
- }
44
- /** Editing keeps the slots of a day that was switched off, so switching it back restores them. */
45
- interface DaySchedule {
46
- isWorking: boolean;
47
- slots: WeeklySlot[];
48
- }
49
- type WeekSchedule = Record<number, DaySchedule>;
50
- interface AvailabilityTemplate {
51
- id: string;
52
- name: string;
53
- description: string;
54
- weeklySchedule: WeeklySlot[];
55
- }
1
+ import { S as SchedulingRules, D as DoctorAvailability, A as AvailabilityTemplate, T as TimeOfDay, C as CalendarDate, W as WeeklySlot, a as AvailabilityError, b as WeekSchedule, c as DateOverride } from '../types-BThgyft4.js';
2
+ export { d as AvailabilityErrorType, e as DaySchedule } from '../types-BThgyft4.js';
56
3
 
57
4
  declare const AVAILABILITY_VERSION = 1;
58
5
  declare const DAYS_OF_WEEK: readonly [{
@@ -129,4 +76,4 @@ declare function suggestNextSlot(day: number, existing: WeeklySlot[]): WeeklySlo
129
76
  declare function weeklyHours(availability: DoctorAvailability): number;
130
77
  declare function workingDays(availability: DoctorAvailability): number[];
131
78
 
132
- export { AVAILABILITY_TEMPLATES, AVAILABILITY_VERSION, type AvailabilityError, type AvailabilityErrorType, type AvailabilityTemplate, COMMON_EXCEPTION_REASONS, type CalendarDate, DAYS_OF_WEEK, DEFAULT_BREAK_END, DEFAULT_BREAK_START, DEFAULT_RULES, DEFAULT_WORK_END, DEFAULT_WORK_START, type DateOverride, type DaySchedule, type DoctorAvailability, MINUTES_PER_DAY, SLOT_DURATION_CHOICES, type ScheduleGap, type SchedulingRules, type TimeOfDay, WEEKDAYS, WEEKEND, type WeekSchedule, type WeeklySlot, availabilityFromWeek, emptyAvailability, findGaps, groupByDay, hasBlockingErrors, isEndAfterStart, isValidDate, isValidTime, minutesToTime, slotsOverlap, suggestNextSlot, timeToMinutes, toCalendarDate, validateAvailability, weeklyHours, workingDays };
79
+ export { AVAILABILITY_TEMPLATES, AVAILABILITY_VERSION, AvailabilityError, AvailabilityTemplate, COMMON_EXCEPTION_REASONS, CalendarDate, DAYS_OF_WEEK, DEFAULT_BREAK_END, DEFAULT_BREAK_START, DEFAULT_RULES, DEFAULT_WORK_END, DEFAULT_WORK_START, DateOverride, DoctorAvailability, MINUTES_PER_DAY, SLOT_DURATION_CHOICES, type ScheduleGap, SchedulingRules, TimeOfDay, WEEKDAYS, WEEKEND, WeekSchedule, WeeklySlot, availabilityFromWeek, emptyAvailability, findGaps, groupByDay, hasBlockingErrors, isEndAfterStart, isValidDate, isValidTime, minutesToTime, slotsOverlap, suggestNextSlot, timeToMinutes, toCalendarDate, validateAvailability, weeklyHours, workingDays };
@@ -0,0 +1,24 @@
1
+ import { C as CalendarDate } from '../types-BThgyft4.js';
2
+
3
+ /** Inclusive on both ends: a member is covered on `start` and on `end`. */
4
+ interface MembershipTerm {
5
+ start: CalendarDate;
6
+ end: CalendarDate;
7
+ }
8
+ /** `cancelled` keeps coverage until `end`; `refunded` removes it at once. */
9
+ interface MembershipRecord extends MembershipTerm {
10
+ cancelled: boolean;
11
+ refunded: boolean;
12
+ }
13
+ type MembershipStatus = 'active' | 'upcoming' | 'cancelled' | 'expired' | 'refunded';
14
+
15
+ /** Same day of the month, clamped to the last day when the target month is shorter. */
16
+ declare function addMonths(date: CalendarDate, months: number): CalendarDate;
17
+ /** Renewing before the current term ends chains the new one to the next day, so no paid day is lost. */
18
+ declare function membershipTerm(months: number, today: CalendarDate, currentEnd?: CalendarDate | null): MembershipTerm;
19
+ /** Negative once `end` has passed. */
20
+ declare function daysRemaining(end: CalendarDate, today: CalendarDate): number;
21
+ declare function membershipStatus(membership: MembershipRecord, today: CalendarDate): MembershipStatus;
22
+ declare function isRenewalNoticeDue(end: CalendarDate, today: CalendarDate, noticeDays: number): boolean;
23
+
24
+ export { type MembershipRecord, type MembershipStatus, type MembershipTerm, addMonths, daysRemaining, isRenewalNoticeDue, membershipStatus, membershipTerm };
@@ -0,0 +1,53 @@
1
+ // src/availability/time.ts
2
+ var MINUTES_PER_DAY = 24 * 60;
3
+ var DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
4
+ function isValidDate(date) {
5
+ const match = DATE_PATTERN.exec(date);
6
+ if (!match) return false;
7
+ const [year, month, day] = match.slice(1).map(Number);
8
+ const parsed = new Date(Date.UTC(year, month - 1, day));
9
+ return parsed.getUTCMonth() === month - 1 && parsed.getUTCDate() === day;
10
+ }
11
+
12
+ // src/membership/term.ts
13
+ var MS_PER_DAY = 24 * 60 * 60 * 1e3;
14
+ function toUtc(date) {
15
+ if (!isValidDate(date)) throw new RangeError(`Invalid calendar date: ${date}`);
16
+ const [year, month, day] = date.split("-").map(Number);
17
+ return Date.UTC(year, month - 1, day);
18
+ }
19
+ var fromUtc = (time) => new Date(time).toISOString().slice(0, 10);
20
+ var addDays = (date, days) => fromUtc(toUtc(date) + days * MS_PER_DAY);
21
+ function addMonths(date, months) {
22
+ const from = new Date(toUtc(date));
23
+ const total = from.getUTCFullYear() * 12 + from.getUTCMonth() + months;
24
+ const year = Math.floor(total / 12);
25
+ const month = total - year * 12;
26
+ const lastDay = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
27
+ return fromUtc(Date.UTC(year, month, Math.min(from.getUTCDate(), lastDay)));
28
+ }
29
+ function membershipTerm(months, today, currentEnd) {
30
+ const start = currentEnd && currentEnd >= today ? addDays(currentEnd, 1) : today;
31
+ return { start, end: addDays(addMonths(start, months), -1) };
32
+ }
33
+ function daysRemaining(end, today) {
34
+ return Math.round((toUtc(end) - toUtc(today)) / MS_PER_DAY);
35
+ }
36
+ function membershipStatus(membership, today) {
37
+ if (membership.refunded) return "refunded";
38
+ if (membership.end < today) return "expired";
39
+ if (membership.cancelled) return "cancelled";
40
+ return membership.start > today ? "upcoming" : "active";
41
+ }
42
+ function isRenewalNoticeDue(end, today, noticeDays) {
43
+ const days = daysRemaining(end, today);
44
+ return days >= 0 && days <= noticeDays;
45
+ }
46
+ export {
47
+ addMonths,
48
+ daysRemaining,
49
+ isRenewalNoticeDue,
50
+ membershipStatus,
51
+ membershipTerm
52
+ };
53
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/availability/time.ts","../../src/membership/term.ts"],"sourcesContent":["import type { CalendarDate, TimeOfDay } from './types';\n\nexport const MINUTES_PER_DAY = 24 * 60;\n\nconst TIME_PATTERN = /^([01]\\d|2[0-3]):[0-5]\\d$/;\nconst DATE_PATTERN = /^(\\d{4})-(\\d{2})-(\\d{2})$/;\n\nconst twoDigits = (value: number): string => String(value).padStart(2, '0');\n\nexport function timeToMinutes(time: TimeOfDay): number {\n const [hours, minutes] = time.split(':').map(Number);\n return hours * 60 + minutes;\n}\n\nexport function minutesToTime(minutes: number): TimeOfDay {\n return `${twoDigits(Math.floor(minutes / 60) % 24)}:${twoDigits(minutes % 60)}`;\n}\n\nexport function isValidTime(time: string): boolean {\n return TIME_PATTERN.test(time);\n}\n\nexport function isEndAfterStart(start: TimeOfDay, end: TimeOfDay): boolean {\n return timeToMinutes(end) > timeToMinutes(start);\n}\n\nexport function isValidDate(date: string): boolean {\n const match = DATE_PATTERN.exec(date);\n if (!match) return false;\n const [year, month, day] = match.slice(1).map(Number);\n const parsed = new Date(Date.UTC(year, month - 1, day));\n return parsed.getUTCMonth() === month - 1 && parsed.getUTCDate() === day;\n}\n\n/** Local calendar date; `toISOString` would roll to tomorrow in the evening west of Greenwich. */\nexport function toCalendarDate(date: Date): CalendarDate {\n return `${date.getFullYear()}-${twoDigits(date.getMonth() + 1)}-${twoDigits(date.getDate())}`;\n}\n","import { isValidDate } from '../availability/time';\nimport type { CalendarDate } from '../availability/types';\nimport type { MembershipRecord, MembershipStatus, MembershipTerm } from './types';\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\nconst fromUtc = (time: number): CalendarDate => new Date(time).toISOString().slice(0, 10);\n\nconst addDays = (date: CalendarDate, days: number): CalendarDate => fromUtc(toUtc(date) + days * MS_PER_DAY);\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 Math.round((toUtc(end) - toUtc(today)) / MS_PER_DAY);\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;;;AC5BA,IAAM,aAAa,KAAK,KAAK,KAAK;AAElC,SAAS,MAAM,MAA4B;AACzC,MAAI,CAAC,YAAY,IAAI,EAAG,OAAM,IAAI,WAAW,0BAA0B,IAAI,EAAE;AAC7E,QAAM,CAAC,MAAM,OAAO,GAAG,IAAI,KAAK,MAAM,GAAG,EAAE,IAAI,MAAM;AACrD,SAAO,KAAK,IAAI,MAAM,QAAQ,GAAG,GAAG;AACtC;AAEA,IAAM,UAAU,CAAC,SAA+B,IAAI,KAAK,IAAI,EAAE,YAAY,EAAE,MAAM,GAAG,EAAE;AAExF,IAAM,UAAU,CAAC,MAAoB,SAA+B,QAAQ,MAAM,IAAI,IAAI,OAAO,UAAU;AAGpG,SAAS,UAAU,MAAoB,QAA8B;AAC1E,QAAM,OAAO,IAAI,KAAK,MAAM,IAAI,CAAC;AACjC,QAAM,QAAQ,KAAK,eAAe,IAAI,KAAK,KAAK,YAAY,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,KAAK,OAAO,MAAM,GAAG,IAAI,MAAM,KAAK,KAAK,UAAU;AAC5D;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":[]}
@@ -0,0 +1,57 @@
1
+ /** `HH:mm`, 24 h. */
2
+ type TimeOfDay = string;
3
+ /** `YYYY-MM-DD`. */
4
+ type CalendarDate = string;
5
+ interface WeeklySlot {
6
+ /** As JavaScript counts it: 0 is Sunday. */
7
+ day: number;
8
+ start: TimeOfDay;
9
+ end: TimeOfDay;
10
+ label?: string;
11
+ }
12
+ /** Replaces the weekly pattern on one date. Without `fullDayClosed` it carries its own hours. */
13
+ interface DateOverride {
14
+ date: CalendarDate;
15
+ start?: TimeOfDay;
16
+ end?: TimeOfDay;
17
+ fullDayClosed: boolean;
18
+ reason?: string;
19
+ }
20
+ /** Durations are minutes. */
21
+ interface SchedulingRules {
22
+ breakStart?: TimeOfDay;
23
+ breakEnd?: TimeOfDay;
24
+ minSlotDuration?: number;
25
+ maxPatientsPerHour?: number;
26
+ bufferBetweenAppointments?: number;
27
+ }
28
+ interface DoctorAvailability {
29
+ version: number;
30
+ weeklySchedule: WeeklySlot[];
31
+ overrides: DateOverride[];
32
+ rules: SchedulingRules;
33
+ }
34
+ type AvailabilityErrorType = 'overlap' | 'invalid_time' | 'end_before_start' | 'duplicate_date';
35
+ interface AvailabilityError {
36
+ type: AvailabilityErrorType;
37
+ day?: number;
38
+ date?: CalendarDate;
39
+ /** Position in that day's list, when the error belongs to one slot. */
40
+ slotIndex?: number;
41
+ message: string;
42
+ severity: 'error' | 'warning';
43
+ }
44
+ /** Editing keeps the slots of a day that was switched off, so switching it back restores them. */
45
+ interface DaySchedule {
46
+ isWorking: boolean;
47
+ slots: WeeklySlot[];
48
+ }
49
+ type WeekSchedule = Record<number, DaySchedule>;
50
+ interface AvailabilityTemplate {
51
+ id: string;
52
+ name: string;
53
+ description: string;
54
+ weeklySchedule: WeeklySlot[];
55
+ }
56
+
57
+ export type { AvailabilityTemplate as A, CalendarDate as C, DoctorAvailability as D, SchedulingRules as S, TimeOfDay as T, WeeklySlot as W, AvailabilityError as a, WeekSchedule as b, DateOverride as c, AvailabilityErrorType as d, DaySchedule as e };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@free-intelligence/core",
3
- "version": "1.12.1",
3
+ "version": "1.13.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/BernardUriza/free-intelligence",
@@ -20,6 +20,10 @@
20
20
  "./availability": {
21
21
  "types": "./dist/availability/index.d.ts",
22
22
  "import": "./dist/availability/index.js"
23
+ },
24
+ "./membership": {
25
+ "types": "./dist/membership/index.d.ts",
26
+ "import": "./dist/membership/index.js"
23
27
  }
24
28
  },
25
29
  "files": [
@@ -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,48 @@
1
+ import { isValidDate } from '../availability/time';
2
+ import type { CalendarDate } from '../availability/types';
3
+ import type { MembershipRecord, MembershipStatus, MembershipTerm } from './types';
4
+
5
+ const MS_PER_DAY = 24 * 60 * 60 * 1000;
6
+
7
+ function toUtc(date: CalendarDate): number {
8
+ if (!isValidDate(date)) throw new RangeError(`Invalid calendar date: ${date}`);
9
+ const [year, month, day] = date.split('-').map(Number);
10
+ return Date.UTC(year, month - 1, day);
11
+ }
12
+
13
+ const fromUtc = (time: number): CalendarDate => new Date(time).toISOString().slice(0, 10);
14
+
15
+ const addDays = (date: CalendarDate, days: number): CalendarDate => fromUtc(toUtc(date) + days * MS_PER_DAY);
16
+
17
+ /** Same day of the month, clamped to the last day when the target month is shorter. */
18
+ export function addMonths(date: CalendarDate, months: number): CalendarDate {
19
+ const from = new Date(toUtc(date));
20
+ const total = from.getUTCFullYear() * 12 + from.getUTCMonth() + months;
21
+ const year = Math.floor(total / 12);
22
+ const month = total - year * 12;
23
+ const lastDay = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
24
+ return fromUtc(Date.UTC(year, month, Math.min(from.getUTCDate(), lastDay)));
25
+ }
26
+
27
+ /** Renewing before the current term ends chains the new one to the next day, so no paid day is lost. */
28
+ export function membershipTerm(months: number, today: CalendarDate, currentEnd?: CalendarDate | null): MembershipTerm {
29
+ const start = currentEnd && currentEnd >= today ? addDays(currentEnd, 1) : today;
30
+ return { start, end: addDays(addMonths(start, months), -1) };
31
+ }
32
+
33
+ /** Negative once `end` has passed. */
34
+ export function daysRemaining(end: CalendarDate, today: CalendarDate): number {
35
+ return Math.round((toUtc(end) - toUtc(today)) / MS_PER_DAY);
36
+ }
37
+
38
+ export function membershipStatus(membership: MembershipRecord, today: CalendarDate): MembershipStatus {
39
+ if (membership.refunded) return 'refunded';
40
+ if (membership.end < today) return 'expired';
41
+ if (membership.cancelled) return 'cancelled';
42
+ return membership.start > today ? 'upcoming' : 'active';
43
+ }
44
+
45
+ export function isRenewalNoticeDue(end: CalendarDate, today: CalendarDate, noticeDays: number): boolean {
46
+ const days = daysRemaining(end, today);
47
+ return days >= 0 && days <= noticeDays;
48
+ }
@@ -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';