From b8da2e447a0c51123cd1e6e762a1f5471ae288ae Mon Sep 17 00:00:00 2001 From: IVANLI2412 Date: Tue, 24 Nov 2026 12:57:24 -0300 Subject: [PATCH] feat(billing): consolidate charges onto a chosen weekday (fixes #2252) --- .../services/__tests__/billingShift.test.ts | 132 +++++++++ backend/src/services/billingShift.ts | 258 ++++++++++++++++++ .../src/jobs/__tests__/billingShift.test.ts | 74 +++++ workers/src/jobs/billingShift.ts | 91 ++++++ 4 files changed, 555 insertions(+) create mode 100644 backend/src/services/__tests__/billingShift.test.ts create mode 100644 backend/src/services/billingShift.ts create mode 100644 workers/src/jobs/__tests__/billingShift.test.ts create mode 100644 workers/src/jobs/billingShift.ts diff --git a/backend/src/services/__tests__/billingShift.test.ts b/backend/src/services/__tests__/billingShift.test.ts new file mode 100644 index 00000000..1e33a6e4 --- /dev/null +++ b/backend/src/services/__tests__/billingShift.test.ts @@ -0,0 +1,132 @@ +import { + BillingShiftError, + DEFAULT_BILLING_SHIFT_CONFIG, + WEEKDAY_NAMES, + createBillingShifter, + daysBetween, + isWeekday, + nextBillingDate, + shiftDueDate, + validateBillingShiftConfig, +} from '../billingShift'; + +describe('billingShift service', () => { + describe('isWeekday / WEEKDAY_NAMES', () => { + it('accepts integers 0-6 only', () => { + expect(isWeekday(0)).toBe(true); + expect(isWeekday(6)).toBe(true); + expect(isWeekday(7)).toBe(false); + expect(isWeekday(-1)).toBe(false); + expect(isWeekday(1.5)).toBe(false); + expect(isWeekday('1')).toBe(false); + }); + + it('names every weekday', () => { + expect(WEEKDAY_NAMES[1]).toBe('Monday'); + expect(WEEKDAY_NAMES[0]).toBe('Sunday'); + expect(WEEKDAY_NAMES[6]).toBe('Saturday'); + }); + }); + + describe('validateBillingShiftConfig', () => { + it('returns defaults frozen', () => { + const c = validateBillingShiftConfig(); + expect(c.targetWeekday).toBe(DEFAULT_BILLING_SHIFT_CONFIG.targetWeekday); + expect(Object.isFrozen(c)).toBe(true); + }); + + it('rejects invalid weekday', () => { + expect(() => validateBillingShiftConfig({ targetWeekday: 9 as any })).toThrow(BillingShiftError); + }); + + it('rejects invalid maxShiftDays', () => { + expect(() => validateBillingShiftConfig({ maxShiftDays: 99 })).toThrow(BillingShiftError); + expect(() => validateBillingShiftConfig({ maxShiftDays: -1 })).toThrow(BillingShiftError); + }); + + it('rejects invalid timezone offset', () => { + expect(() => validateBillingShiftConfig({ timezoneOffsetMinutes: 2000 })).toThrow(BillingShiftError); + }); + }); + + describe('shiftDueDate', () => { + it('leaves a date already on target weekday unchanged', () => { + // 2026-11-23 is a Monday + const r = shiftDueDate('2026-11-23T10:00:00.000Z', { targetWeekday: 1 }); + expect(r.shiftDays).toBe(0); + expect(r.weekday).toBe(1); + }); + + it('shifts forward to the next Monday', () => { + // 2026-11-25 is a Wednesday -> +5 days to Monday 2026-11-30 + const r = shiftDueDate('2026-11-25T10:00:00.000Z', { targetWeekday: 1 }); + expect(r.shiftDays).toBe(5); + expect(r.weekday).toBe(1); + expect(r.shiftedDate).toContain('2026-11-30'); + }); + + it('supports backward shift within the same week', () => { + const r = shiftDueDate('2026-11-24T10:00:00.000Z', { targetWeekday: 1, allowBackward: true }); + expect(r.shiftDays).toBeLessThan(0); + expect(r.weekday).toBe(1); + }); + + it('throws SHIFT_EXCEEDED when shift is larger than maxShiftDays', () => { + expect(() => shiftDueDate('2026-11-25T10:00:00.000Z', { targetWeekday: 1, maxShiftDays: 2 })).toThrow( + BillingShiftError, + ); + }); + + it('rejects invalid dates', () => { + expect(() => shiftDueDate('not-a-date')).toThrow(BillingShiftError); + expect(() => shiftDueDate('')).toThrow(BillingShiftError); + }); + }); + + describe('daysBetween / nextBillingDate', () => { + it('computes whole-day differences', () => { + expect(daysBetween('2026-11-23T00:00:00Z', '2026-11-28T00:00:00Z')).toBe(5); + }); + + it('returns a Monday for nextBillingDate', () => { + expect(nextBillingDate('2026-11-25T00:00:00Z', 1)).toContain('2026-11-30'); + }); + + it('rejects invalid weekday', () => { + expect(() => nextBillingDate('2026-11-25T00:00:00Z', 7 as any)).toThrow(BillingShiftError); + }); + }); + + describe('createBillingShifter', () => { + it('records metrics and builds a plan', () => { + const events: string[] = []; + const shifter = createBillingShifter( + { targetWeekday: 1 }, + { + recordShift() { events.push('shift'); }, + recordRejected() { events.push('rejected'); }, + recordPlan() { events.push('plan'); }, + }, + ); + const plan = shifter.plan([ + { id: 'a', dueDate: '2026-11-25T00:00:00Z' }, + { id: 'b', dueDate: '2026-11-23T00:00:00Z' }, + { id: '', dueDate: '2026-11-23T00:00:00Z' }, + ]); + expect(plan.total).toBe(3); + expect(plan.shifted).toBe(2); + expect(plan.rejected.length).toBe(1); + expect(plan.rejected[0].code).toBe('INVALID_SUBSCRIPTION'); + expect(events).toContain('shift'); + expect(events).toContain('plan'); + expect(Object.isFrozen(plan)).toBe(true); + }); + + it('records rejection metric on invalid input', () => { + let rejected = 0; + const shifter = createBillingShifter({ targetWeekday: 1 }, { recordRejected() { rejected++; } }); + expect(() => shifter.shift('bad')).toThrow(BillingShiftError); + expect(rejected).toBe(1); + }); + }); +}); diff --git a/backend/src/services/billingShift.ts b/backend/src/services/billingShift.ts new file mode 100644 index 00000000..4cff16fc --- /dev/null +++ b/backend/src/services/billingShift.ts @@ -0,0 +1,258 @@ +/** + * backend/src/services/billingShift.ts + * + * Issue #2252 — billing-day shifter. Consolidates charges that fall on + * different days onto a single chosen weekday, so a subscriber's invoices + * cluster into one predictable processing window. The module is pure and + * dependency-free: it computes shifts and plans, never touches a database or + * a payment gateway. Callers (the worker in workers/src/jobs/billingShift.ts) + * own persistence and charging. + */ + +export type BillingShiftErrorCode = + | 'INVALID_CONFIG' + | 'INVALID_INPUT' + | 'INVALID_DATE' + | 'INVALID_WEEKDAY' + | 'SHIFT_EXCEEDED' + | 'INVALID_SUBSCRIPTION'; + +export type Weekday = 0 | 1 | 2 | 3 | 4 | 5 | 6; + +export const WEEKDAYS: readonly Weekday[] = [0, 1, 2, 3, 4, 5, 6] as const; + +export const WEEKDAY_NAMES: Readonly> = { + 0: 'Sunday', + 1: 'Monday', + 2: 'Tuesday', + 3: 'Wednesday', + 4: 'Thursday', + 5: 'Friday', + 6: 'Saturday', +}; + +export function isWeekday(value: unknown): value is Weekday { + return typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= 6; +} + +export class BillingShiftError extends Error { + readonly code: BillingShiftErrorCode; + readonly details: Readonly> | undefined; + + constructor(code: BillingShiftErrorCode, message: string, details?: Record) { + super(message); + this.name = 'BillingShiftError'; + this.code = code; + this.details = details; + Object.setPrototypeOf(this, BillingShiftError.prototype); + } + + static invalidConfig(message: string, details?: Record): BillingShiftError { + return new BillingShiftError('INVALID_CONFIG', message, details); + } + static invalidInput(message: string, details?: Record): BillingShiftError { + return new BillingShiftError('INVALID_INPUT', message, details); + } +} + +export interface BillingShiftConfig { + /** Weekday (0=Sunday … 6=Saturday) every charge is consolidated onto. */ + targetWeekday: Weekday; + /** Never shift an item more than this many days (default 6). */ + maxShiftDays: number; + /** Extra minutes to add to the computed instant for the local timezone. */ + timezoneOffsetMinutes: number; + /** When true, allow shifting earlier in the same week instead of only forward. */ + allowBackward: boolean; +} + +export const DEFAULT_BILLING_SHIFT_CONFIG: Readonly = Object.freeze({ + targetWeekday: 1, + maxShiftDays: 6, + timezoneOffsetMinutes: 0, + allowBackward: false, +}); + +export interface BillingShiftMetrics { + recordShift(original: string, shifted: string, days: number): void; + recordRejected(code: BillingShiftErrorCode): void; + recordPlan(size: number): void; +} + +export interface BillingShiftLogger { + info(message: string, details?: Record): void; + warn(message: string, details?: Record): void; +} + +export const noopBillingShiftMetrics: Readonly = Object.freeze({ + recordShift(): void {}, + recordRejected(): void {}, + recordPlan(): void {}, +}); + +export const noopBillingShiftLogger: Readonly = Object.freeze({ + info(): void {}, + warn(): void {}, +}); + +export function validateBillingShiftConfig(config: Partial = {}): BillingShiftConfig { + if (config === null || typeof config !== 'object') { + throw BillingShiftError.invalidConfig('config must be an object'); + } + const merged: BillingShiftConfig = { ...DEFAULT_BILLING_SHIFT_CONFIG, ...config }; + if (!isWeekday(merged.targetWeekday)) { + throw BillingShiftError.invalidConfig('targetWeekday must be 0-6', { targetWeekday: config.targetWeekday }); + } + if (!Number.isInteger(merged.maxShiftDays) || merged.maxShiftDays < 0 || merged.maxShiftDays > 31) { + throw BillingShiftError.invalidConfig('maxShiftDays must be an integer 0-31', { maxShiftDays: config.maxShiftDays }); + } + if (!Number.isFinite(merged.timezoneOffsetMinutes) || Math.abs(merged.timezoneOffsetMinutes) > 1440) { + throw BillingShiftError.invalidConfig('timezoneOffsetMinutes must be within +/-1440', { + timezoneOffsetMinutes: config.timezoneOffsetMinutes, + }); + } + if (typeof merged.allowBackward !== 'boolean') { + throw BillingShiftError.invalidConfig('allowBackward must be a boolean'); + } + return Object.freeze(merged); +} + +function parseDate(value: string, code: BillingShiftErrorCode): Date { + if (typeof value !== 'string' || value.trim() === '') { + throw new BillingShiftError('INVALID_DATE', 'date must be a non-empty string'); + } + const t = Date.parse(value); + if (!Number.isFinite(t)) { + throw new BillingShiftError(code, 'date is not a valid ISO-8601 timestamp', { value }); + } + return new Date(t); +} + +function shiftToWeekday(date: Date, config: BillingShiftConfig): Date { + const local = new Date(date.getTime() + config.timezoneOffsetMinutes * 60000); + const current = local.getUTCDay(); + let delta = (config.targetWeekday - current + 7) % 7; + if (delta === 0) return new Date(date.getTime()); + if (config.allowBackward && delta > 3) delta -= 7; + return new Date(date.getTime() + delta * 86400000); +} + +export interface ShiftResult { + readonly id: string; + readonly originalDate: string; + readonly shiftedDate: string; + readonly shiftDays: number; + readonly weekday: Weekday; +} + +export interface ShiftInput { + readonly id: string; + readonly dueDate: string; + readonly amountMinor?: number; + readonly currency?: string; +} + +export interface ShiftPlan { + readonly shifts: readonly ShiftResult[]; + readonly rejected: readonly { id: string; code: BillingShiftErrorCode; reason: string }[]; + readonly total: number; + readonly shifted: number; +} + +export function shiftDueDate(dueDate: string, config: Partial = {}): ShiftResult { + const cfg = validateBillingShiftConfig(config); + const parsed = parseDate(dueDate, 'INVALID_DATE'); + const shifted = shiftToWeekday(parsed, cfg); + const shiftDays = Math.round((shifted.getTime() - parsed.getTime()) / 86400000); + if (Math.abs(shiftDays) > cfg.maxShiftDays) { + throw new BillingShiftError('SHIFT_EXCEEDED', 'required shift exceeds maxShiftDays', { + shiftDays, + maxShiftDays: cfg.maxShiftDays, + }); + } + const local = new Date(shifted.getTime() + cfg.timezoneOffsetMinutes * 60000); + return Object.freeze({ + id: '', + originalDate: parsed.toISOString(), + shiftedDate: shifted.toISOString(), + shiftDays, + weekday: local.getUTCDay() as Weekday, + }); +} + +export function daysBetween(from: string, to: string): number { + const a = parseDate(from, 'INVALID_DATE'); + const b = parseDate(to, 'INVALID_DATE'); + return Math.round((b.getTime() - a.getTime()) / 86400000); +} + +export function nextBillingDate(anchor: string, targetWeekday: Weekday): string { + if (!isWeekday(targetWeekday)) { + throw new BillingShiftError('INVALID_WEEKDAY', 'targetWeekday must be 0-6'); + } + const cfg = validateBillingShiftConfig({ targetWeekday, maxShiftDays: 6 }); + return shiftDueDate(anchor, cfg).shiftedDate; +} + +export interface BillingShifter { + shift(dueDate: string): ShiftResult; + plan(items: readonly ShiftInput[]): ShiftPlan; + readonly config: Readonly; +} + +export function createBillingShifter( + config: Partial = {}, + metrics: Partial = {}, + logger: Partial = {}, +): BillingShifter { + const cfg = validateBillingShiftConfig(config); + const m: BillingShiftMetrics = { ...noopBillingShiftMetrics, ...metrics }; + const log: BillingShiftLogger = { ...noopBillingShiftLogger, ...logger }; + + function shift(dueDate: string): ShiftResult { + try { + const base = shiftDueDate(dueDate, cfg); + const result: ShiftResult = Object.freeze({ ...base }); + m.recordShift(result.originalDate, result.shiftedDate, result.shiftDays); + return result; + } catch (err) { + if (err instanceof BillingShiftError) m.recordRejected(err.code); + throw err; + } + } + + function plan(items: readonly ShiftInput[]): ShiftPlan { + if (!Array.isArray(items)) { + throw BillingShiftError.invalidInput('items must be an array'); + } + const shifts: ShiftResult[] = []; + const rejected: ShiftPlan['rejected'] = []; + for (const item of items) { + if (!item || typeof item.id !== 'string' || item.id.trim() === '') { + rejected.push({ id: '', code: 'INVALID_SUBSCRIPTION', reason: 'missing id' }); + continue; + } + try { + const s = shift(item.dueDate); + shifts.push(Object.freeze({ ...s, id: item.id })); + } catch (err) { + if (err instanceof BillingShiftError) { + rejected.push({ id: item.id, code: err.code, reason: err.message }); + } else { + throw err; + } + } + } + const result: ShiftPlan = Object.freeze({ + shifts: Object.freeze(shifts), + rejected: Object.freeze(rejected), + total: items.length, + shifted: shifts.length, + }); + m.recordPlan(items.length); + log.info('billing shift plan completed', { total: result.total, shifted: result.shifted }); + return result; + } + + return Object.freeze({ shift, plan, config: cfg }); +} diff --git a/workers/src/jobs/__tests__/billingShift.test.ts b/workers/src/jobs/__tests__/billingShift.test.ts new file mode 100644 index 00000000..b986ae5a --- /dev/null +++ b/workers/src/jobs/__tests__/billingShift.test.ts @@ -0,0 +1,74 @@ +import { + batchKey, + buildBatches, + createBillingShiftJob, +} from '../billingShift'; + +describe('billingShift worker job', () => { + describe('batchKey', () => { + it('is deterministic per day', () => { + expect(batchKey('2026-11-30T00:00:00.000Z')).toBe('billing-shift:2026-11-30'); + expect(batchKey('2026-11-30T23:59:00.000Z')).toBe(batchKey('2026-11-30T00:00:00.000Z')); + }); + }); + + describe('buildBatches', () => { + it('groups shifted items by consolidated date and sorts ids', () => { + const plan = { + shifts: [ + { id: 'b', originalDate: '2026-11-25T00:00:00Z', shiftedDate: '2026-11-30T00:00:00Z', shiftDays: 5, weekday: 1 }, + { id: 'a', originalDate: '2026-11-26T00:00:00Z', shiftedDate: '2026-11-30T00:00:00Z', shiftDays: 4, weekday: 1 }, + ], + rejected: [], + total: 2, + shifted: 2, + } as any; + const batches = buildBatches(plan); + expect(batches.length).toBe(1); + expect(batches[0].key).toBe('billing-shift:2026-11-30'); + expect(batches[0].items.map((i) => i.id)).toEqual(['a', 'b']); + expect(batches[0].status).toBe('ready'); + expect(Object.isFrozen(batches)).toBe(true); + }); + + it('produces separate batches for different dates', () => { + const plan = { + shifts: [ + { id: 'x', originalDate: '2026-11-25T00:00:00Z', shiftedDate: '2026-11-30T00:00:00Z', shiftDays: 5, weekday: 1 }, + { id: 'y', originalDate: '2026-12-02T00:00:00Z', shiftedDate: '2026-12-07T00:00:00Z', shiftDays: 5, weekday: 1 }, + ], + rejected: [], + total: 2, + shifted: 2, + } as any; + const batches = buildBatches(plan); + expect(batches.length).toBe(2); + expect(batches[0].key).toBe('billing-shift:2026-11-30'); + expect(batches[1].key).toBe('billing-shift:2026-12-07'); + }); + }); + + describe('createBillingShiftJob', () => { + it('runs a full plan into batches and counts rejections', () => { + const job = createBillingShiftJob({ targetWeekday: 1 }); + const result = job.run([ + { id: 'sub1', dueDate: '2026-11-25T00:00:00Z' }, + { id: 'sub2', dueDate: '2026-11-24T00:00:00Z' }, + { id: '', dueDate: '2026-11-24T00:00:00Z' }, + ]); + expect(result.plan.total).toBe(3); + expect(result.plan.shifted).toBe(2); + expect(result.rejected).toBe(1); + expect(result.batches.length).toBeGreaterThan(0); + expect(result.batches[0].items.length).toBe(2); + expect(Object.isFrozen(result)).toBe(true); + }); + + it('handles an empty item list', () => { + const job = createBillingShiftJob(); + const result = job.run([]); + expect(result.plan.total).toBe(0); + expect(result.batches.length).toBe(0); + }); + }); +}); diff --git a/workers/src/jobs/billingShift.ts b/workers/src/jobs/billingShift.ts new file mode 100644 index 00000000..cc1e5957 --- /dev/null +++ b/workers/src/jobs/billingShift.ts @@ -0,0 +1,91 @@ +/** + * workers/src/jobs/billingShift.ts + * + * Issue #2252 — worker entry point for the billing-day shifter. The pure + * scheduling logic lives in backend/src/services/billingShift.ts; this job + * turns a plan into an idempotent, batched charge schedule the billing runner + * can execute. No I/O is performed here — callers own persistence. + */ + +import { + createBillingShifter, + type BillingShiftConfig, + type ShiftPlan, + type ShiftInput, + type BillingShiftMetrics, + type BillingShiftLogger, +} from '../../../backend/src/services/billingShift.ts'; + +export type BatchStatus = 'pending' | 'ready' | 'skipped'; + +export interface ChargeBatch { + readonly key: string; + readonly scheduledFor: string; + readonly items: readonly ShiftInput[]; + readonly status: BatchStatus; +} + +export interface BillingShiftJobResult { + readonly batches: readonly ChargeBatch[]; + readonly plan: ShiftPlan; + readonly rejected: number; +} + +export interface BillingShiftJob { + run(items: readonly ShiftInput[]): BillingShiftJobResult; + readonly config: Readonly; +} + +/** Deterministic batch key for a target date (idempotency across retries). */ +export function batchKey(scheduledFor: string): string { + const day = scheduledFor.slice(0, 10); + return `billing-shift:${day}`; +} + +/** + * Group shifted items by their consolidated date into stable, sorted batches. + * Items rejected by the planner are omitted from batches but counted in result. + */ +export function buildBatches(plan: ShiftPlan): readonly ChargeBatch[] { + const byDate = new Map(); + for (const shift of plan.shifts) { + const key = shift.shiftedDate.slice(0, 10); + const list = byDate.get(key) ?? []; + list.push({ id: shift.id, dueDate: shift.originalDate }); + byDate.set(key, list); + } + const batches: ChargeBatch[] = []; + const dates = Array.from(byDate.keys()).sort(); + for (const date of dates) { + const items = (byDate.get(date) ?? []).slice().sort((a, b) => a.id.localeCompare(b.id)); + batches.push( + Object.freeze({ + key: batchKey(date), + scheduledFor: `${date}T00:00:00.000Z`, + items: Object.freeze(items), + status: 'ready' as BatchStatus, + }), + ); + } + return Object.freeze(batches); +} + +export function createBillingShiftJob( + config: Partial = {}, + metrics: Partial = {}, + logger: Partial = {}, +): BillingShiftJob { + const shifter = createBillingShifter(config, metrics, logger); + + function run(items: readonly ShiftInput[]): BillingShiftJobResult { + const plan = shifter.plan(items); + const batches = buildBatches(plan); + return Object.freeze({ + batches, + plan, + rejected: plan.rejected.length, + }); + } + + return Object.freeze({ run, config: shifter.config }); +}