A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(billing): compute withdrawal period ends around holidays
Hampus28420278b35a
diff --git a/fluxer_api/src/api/billing/WithdrawalPeriod.ts b/fluxer_api/src/api/billing/WithdrawalPeriod.tsnew file mode 100644index 000000000..91b719c2d--- /dev/null+++ b/fluxer_api/src/api/billing/WithdrawalPeriod.ts@@ -0,0 +1,68 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {ms} from 'itty-time';++const WITHDRAWAL_PERIOD_DAYS = 14;++const EASTERNMOST_BUYER_UTC_OFFSET_MS = ms('4 hours');++const WESTERNMOST_BUYER_UTC_OFFSET_MS = -ms('4 hours');++const FIXED_DATE_HOLIDAYS = new Set(['01-01', '01-06', '05-01', '06-06', '12-24', '12-25', '12-26', '12-31']);++const EASTER_HOLIDAY_OFFSETS_DAYS = [-2, 1, 39];++function calendarDay(year: number, monthIndex: number, date: number): Date {+ return new Date(Date.UTC(year, monthIndex, date));+}++function addDays(day: Date, days: number): Date {+ return calendarDay(day.getUTCFullYear(), day.getUTCMonth(), day.getUTCDate() + days);+}++function getEasterSunday(year: number): Date {+ const a = year % 19;+ const b = Math.floor(year / 100);+ const c = year % 100;+ const d = Math.floor(b / 4);+ const e = b % 4;+ const f = Math.floor((b + 8) / 25);+ const g = Math.floor((b - f + 1) / 3);+ const h = (19 * a + b - d - g + 15) % 30;+ const i = Math.floor(c / 4);+ const k = c % 4;+ const l = (32 + 2 * e + 2 * i - h - k) % 7;+ const m = Math.floor((a + 11 * h + 22 * l) / 451);+ const month = Math.floor((h + l - 7 * m + 114) / 31);+ const date = ((h + l - 7 * m + 114) % 31) + 1;+ return calendarDay(year, month - 1, date);+}++function isMidsummerEve(day: Date): boolean {+ return day.getUTCDay() === 5 && day.getUTCMonth() === 5 && day.getUTCDate() >= 19 && day.getUTCDate() <= 25;+}++export function isWithdrawalPeriodWorkingDay(day: Date): boolean {+ const weekday = day.getUTCDay();+ if (weekday === 0 || weekday === 6 || isMidsummerEve(day)) {+ return false;+ }+ const monthDay = `${String(day.getUTCMonth() + 1).padStart(2, '0')}-${String(day.getUTCDate()).padStart(2, '0')}`;+ if (FIXED_DATE_HOLIDAYS.has(monthDay)) {+ return false;+ }+ const easter = getEasterSunday(day.getUTCFullYear());+ return !EASTER_HOLIDAY_OFFSETS_DAYS.some((offset) => addDays(easter, offset).getTime() === day.getTime());+}++export function getWithdrawalPeriodEndsAt(purchasedAt: Date): Date {+ const latestPurchaseDay = new Date(purchasedAt.getTime() + EASTERNMOST_BUYER_UTC_OFFSET_MS);+ let lastDay = addDays(+ calendarDay(latestPurchaseDay.getUTCFullYear(), latestPurchaseDay.getUTCMonth(), latestPurchaseDay.getUTCDate()),+ WITHDRAWAL_PERIOD_DAYS,+ );+ while (!isWithdrawalPeriodWorkingDay(lastDay)) {+ lastDay = addDays(lastDay, 1);+ }+ return new Date(addDays(lastDay, 1).getTime() - WESTERNMOST_BUYER_UTC_OFFSET_MS);+}diff --git a/fluxer_api/src/api/billing/tests/WithdrawalPeriod.test.ts b/fluxer_api/src/api/billing/tests/WithdrawalPeriod.test.tsnew file mode 100644index 000000000..1c3d9f1aa--- /dev/null+++ b/fluxer_api/src/api/billing/tests/WithdrawalPeriod.test.ts@@ -0,0 +1,172 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {getWithdrawalPeriodEndsAt, isWithdrawalPeriodWorkingDay} from '@app/api/billing/WithdrawalPeriod';+import {describe, expect, test} from 'vitest';++const BUYER_TIME_ZONES = [+ 'America/Guadeloupe',+ 'America/Martinique',+ 'America/Cayenne',+ 'Atlantic/Azores',+ 'Atlantic/Reykjavik',+ 'Atlantic/Canary',+ 'Atlantic/Madeira',+ 'Europe/London',+ 'Europe/Dublin',+ 'Europe/Lisbon',+ 'Europe/Stockholm',+ 'Europe/Berlin',+ 'Europe/Helsinki',+ 'Europe/Athens',+ 'Asia/Nicosia',+ 'Indian/Mayotte',+ 'Indian/Reunion',+];++const wallClockFormats = new Map<string, Intl.DateTimeFormat>();++function wallClock(instant: Date, timeZone: string): {year: number; month: number; day: number; utcMs: number} {+ let format = wallClockFormats.get(timeZone);+ if (!format) {+ format = new Intl.DateTimeFormat('en-US', {+ timeZone,+ hourCycle: 'h23',+ year: 'numeric',+ month: 'numeric',+ day: 'numeric',+ hour: 'numeric',+ minute: 'numeric',+ second: 'numeric',+ });+ wallClockFormats.set(timeZone, format);+ }+ const parts = Object.fromEntries(format.formatToParts(instant).map((part) => [part.type, Number(part.value)]));+ return {+ year: parts.year!,+ month: parts.month!,+ day: parts.day!,+ utcMs: Date.UTC(parts.year!, parts.month! - 1, parts.day!, parts.hour!, parts.minute!, parts.second!),+ };+}++function startOfLocalDay(year: number, month: number, day: number, timeZone: string): Date {+ const wall = Date.UTC(year, month - 1, day);+ let guess = wall;+ for (let round = 0; round < 3; round++) {+ guess = wall - (wallClock(new Date(guess), timeZone).utcMs - guess);+ }+ return new Date(guess);+}++function localDeadline(purchasedAt: Date, timeZone: string): Date {+ const purchaseDay = wallClock(purchasedAt, timeZone);+ let lastDay = new Date(Date.UTC(purchaseDay.year, purchaseDay.month - 1, purchaseDay.day + 14));+ while (!isWithdrawalPeriodWorkingDay(lastDay)) {+ lastDay = new Date(lastDay.getTime() + 24 * 60 * 60 * 1000);+ }+ return startOfLocalDay(lastDay.getUTCFullYear(), lastDay.getUTCMonth() + 1, lastDay.getUTCDate() + 1, timeZone);+}++function day(isoDate: string): Date {+ return new Date(`${isoDate}T00:00:00Z`);+}++describe('withdrawal period', () => {+ test('a Friday 20 November 13:00 CET purchase ends after Friday 4 December in every buyer zone', () => {+ const endsAt = getWithdrawalPeriodEndsAt(new Date('2026-11-20T12:00:00Z'));+ expect(endsAt.toISOString()).toBe('2026-12-05T04:00:00.000Z');+ expect(localDeadline(new Date('2026-11-20T12:00:00Z'), 'Europe/Stockholm').toISOString()).toBe(+ '2026-12-04T23:00:00.000Z',+ );+ });++ test('a last day on a Saturday moves the end to the end of Monday', () => {+ const endsAt = getWithdrawalPeriodEndsAt(new Date('2026-11-21T09:00:00Z'));+ expect(endsAt.toISOString()).toBe('2026-12-08T04:00:00.000Z');+ expect(localDeadline(new Date('2026-11-21T09:00:00Z'), 'Europe/Stockholm').toISOString()).toBe(+ '2026-12-07T23:00:00.000Z',+ );+ });++ test('Christmas and New Year move the end to the next working day', () => {+ expect(getWithdrawalPeriodEndsAt(new Date('2026-12-10T11:00:00Z')).toISOString()).toBe('2026-12-29T04:00:00.000Z');+ expect(getWithdrawalPeriodEndsAt(new Date('2026-12-17T11:00:00Z')).toISOString()).toBe('2027-01-05T04:00:00.000Z');+ expect(getWithdrawalPeriodEndsAt(new Date('2026-12-23T11:00:00Z')).toISOString()).toBe('2027-01-08T04:00:00.000Z');+ });++ test('Easter and Ascension move the end to the next working day', () => {+ expect(getWithdrawalPeriodEndsAt(new Date('2027-03-12T11:00:00Z')).toISOString()).toBe('2027-03-31T04:00:00.000Z');+ expect(getWithdrawalPeriodEndsAt(new Date('2027-04-22T10:00:00Z')).toISOString()).toBe('2027-05-08T04:00:00.000Z');+ });++ test('the holiday set covers weekends, the fixed days, Midsummer Eve and the Easter days', () => {+ const closed = [+ '2026-11-21',+ '2026-11-22',+ '2026-12-24',+ '2026-12-25',+ '2026-12-31',+ '2027-01-01',+ '2027-01-06',+ '2027-03-26',+ '2027-03-29',+ '2027-05-06',+ '2027-06-25',+ '2028-04-14',+ '2028-04-17',+ '2028-05-01',+ '2028-05-25',+ '2028-06-06',+ '2028-06-23',+ ];+ const open = ['2026-11-20', '2026-12-28', '2027-01-04', '2027-03-30', '2027-06-24', '2028-06-22', '2028-06-26'];+ expect(closed.filter((date) => isWithdrawalPeriodWorkingDay(day(date)))).toEqual([]);+ expect(open.filter((date) => !isWithdrawalPeriodWorkingDay(day(date)))).toEqual([]);+ });++ test('a period across the end of summer time is never short in local time', () => {+ const purchasedAt = new Date('2026-10-11T10:00:00Z');+ expect(getWithdrawalPeriodEndsAt(purchasedAt).toISOString()).toBe('2026-10-27T04:00:00.000Z');+ expect(localDeadline(purchasedAt, 'Europe/Stockholm').toISOString()).toBe('2026-10-26T23:00:00.000Z');+ expect(localDeadline(purchasedAt, 'Europe/London').toISOString()).toBe('2026-10-27T00:00:00.000Z');+ });++ test('a period across the start of summer time is never short in local time', () => {+ const purchasedAt = new Date('2028-03-14T11:00:00Z');+ expect(getWithdrawalPeriodEndsAt(purchasedAt).toISOString()).toBe('2028-03-29T04:00:00.000Z');+ expect(localDeadline(purchasedAt, 'Europe/Stockholm').toISOString()).toBe('2028-03-28T22:00:00.000Z');+ expect(localDeadline(purchasedAt, 'Atlantic/Azores').toISOString()).toBe('2028-03-29T00:00:00.000Z');+ });++ test('a purchase just after local midnight counts from that local day', () => {+ const purchasedAt = new Date('2026-11-20T23:05:00Z');+ expect(localDeadline(purchasedAt, 'Europe/Stockholm').toISOString()).toBe('2026-12-07T23:00:00.000Z');+ expect(getWithdrawalPeriodEndsAt(purchasedAt).toISOString()).toBe('2026-12-08T04:00:00.000Z');+ const reunion = new Date('2026-11-20T20:05:00Z');+ expect(localDeadline(reunion, 'Indian/Reunion').toISOString()).toBe('2026-12-07T20:00:00.000Z');+ expect(getWithdrawalPeriodEndsAt(reunion).toISOString()).toBe('2026-12-08T04:00:00.000Z');+ });++ test('without knowing the buyer zone, the end is never before the local end in any EU, EEA or UK zone', () => {+ const step = 97 * 60 * 1000;+ const from = Date.parse('2026-09-01T00:00:00Z');+ const to = Date.parse('2028-12-31T00:00:00Z');+ const short: Array<string> = [];+ let maxOvershootMs = 0;+ for (let at = from; at < to; at += step) {+ const purchasedAt = new Date(at);+ const endsAt = getWithdrawalPeriodEndsAt(purchasedAt).getTime();+ for (const timeZone of BUYER_TIME_ZONES) {+ const local = localDeadline(purchasedAt, timeZone).getTime();+ if (endsAt < local) {+ short.push(`${purchasedAt.toISOString()} ${timeZone}`);+ }+ if (timeZone === 'Europe/Stockholm') {+ maxOvershootMs = Math.max(maxOvershootMs, endsAt - local);+ }+ }+ }+ expect(short).toEqual([]);+ expect(maxOvershootMs).toBeLessThanOrEqual(6 * 24 * 60 * 60 * 1000);+ });+});