Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
180 changes: 143 additions & 37 deletions backend/services/billing/dunningService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,11 @@ import type {
DunningEntry,
DunningStage,
DunningStageConfig,
FailureReason,
RetryStrategy
} from '../../../src/types/dunning';
import { DEFAULT_DUNNING_STAGES, DUNNING_TEMPLATES } from '../../../src/types/dunning';
import type { IDunningService } from './interfaces';

const ONE_HOUR_MS = 3_600_000;

Expand All @@ -16,44 +19,106 @@ const now = (): number => Date.now();
const createId = (prefix: string): string =>
`${prefix}_${now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;

export class DunningService {
export class DunningService implements IDunningService {
private entries = new Map<string, DunningEntry>();
private configurations = new Map<string, DunningConfiguration>();
private communicationLog = new Map<string, DunningCommunication[]>();
private templates = [...DUNNING_TEMPLATES];
private recoveredEntries: DunningEntry[] = [];

configurePlan(planId: string, config: Partial<DunningConfiguration>): DunningConfiguration {
const existing = this.configurations.get(planId);

const defaultStrategy: RetryStrategy = config.defaultStrategy ?? existing?.defaultStrategy ?? {
stages: DEFAULT_DUNNING_STAGES,
maxRetries: 3,
retryIntervalHours: 1,
warnAfterFailures: 3,
suspendAfterDays: 3,
cancelAfterDays: 7,
communicationChannels: ['email', 'push'],
};

const merged: DunningConfiguration = {
planId,
stages: config.stages ?? existing?.stages ?? DEFAULT_DUNNING_STAGES,
maxRetries: config.maxRetries ?? existing?.maxRetries ?? 3,
retryIntervalHours: config.retryIntervalHours ?? existing?.retryIntervalHours ?? 1,
warnAfterFailures: config.warnAfterFailures ?? existing?.warnAfterFailures ?? 3,
suspendAfterDays: config.suspendAfterDays ?? existing?.suspendAfterDays ?? 3,
cancelAfterDays: config.cancelAfterDays ?? existing?.cancelAfterDays ?? 7,
communicationChannels: config.communicationChannels ?? existing?.communicationChannels ?? ['email', 'push'],
defaultStrategy,
strategies: config.strategies ?? existing?.strategies ?? {},
abTestConfig: config.abTestConfig ?? existing?.abTestConfig,
};

this.configurations.set(planId, merged);
return merged;
}

configureABTest(planId: string, enabled: boolean, variants: Array<{ id: string; weight: number; strategy: RetryStrategy }>): void {
const config = this.configurations.get(planId);
if (config) {
config.abTestConfig = { enabled, variants };
this.configurations.set(planId, config);
} else {
this.configurePlan(planId, { abTestConfig: { enabled, variants } });
}
}

getConfiguration(planId: string): DunningConfiguration | undefined {
return this.configurations.get(planId);
}

private getStrategy(planId: string, failureReason: FailureReason, abTestVariant?: string): RetryStrategy {
const config = this.configurations.get(planId);
if (!config) {
return {
stages: DEFAULT_DUNNING_STAGES,
maxRetries: 3,
retryIntervalHours: 1,
warnAfterFailures: 3,
suspendAfterDays: 3,
cancelAfterDays: 7,
communicationChannels: ['email', 'push'],
};
}

if (config.abTestConfig?.enabled && abTestVariant) {
const variant = config.abTestConfig.variants.find(v => v.id === abTestVariant);
if (variant) return variant.strategy;
}

if (failureReason && config.strategies[failureReason]) {
return config.strategies[failureReason]!;
}

return config.defaultStrategy;
}

startDunning(
subscriptionId: string,
subscriberId: string,
merchantId: string,
planId: string,
failureReason: FailureReason = 'default'
): DunningEntry {
const existing = this.entries.get(subscriptionId);
if (existing) {
return existing;
}

const config = this.configurations.get(planId);
const firstStage = config?.stages[0] ?? DEFAULT_DUNNING_STAGES[0];
let abTestVariant: string | undefined;
if (config?.abTestConfig?.enabled && config.abTestConfig.variants.length > 0) {
// Pick variant randomly based on weight
const totalWeight = config.abTestConfig.variants.reduce((sum, v) => sum + v.weight, 0);
let r = Math.random() * totalWeight;
for (const v of config.abTestConfig.variants) {
r -= v.weight;
if (r <= 0) {
abTestVariant = v.id;
break;
}
}
}

const strategy = this.getStrategy(planId, failureReason, abTestVariant);
const firstStage = strategy.stages[0] ?? DEFAULT_DUNNING_STAGES[0];
const now_ts = now();

const entry: DunningEntry = {
Expand All @@ -62,6 +127,8 @@ export class DunningService {
subscriberId,
merchantId,
planId,
failureReason,
abTestVariant,
currentStage: firstStage.stage,
failedAttempts: 0,
totalFailedCharges: 0,
Expand All @@ -80,11 +147,15 @@ export class DunningService {
return entry;
}

recordFailedCharge(subscriptionId: string): DunningEntry | null {
recordFailedCharge(subscriptionId: string, failureReason?: FailureReason): DunningEntry | null {
const entry = this.entries.get(subscriptionId);
if (!entry || entry.isPaused) return null;

const config = this.configurations.get(entry.planId);
if (failureReason && entry.failureReason !== failureReason) {
entry.failureReason = failureReason;
}

const strategy = this.getStrategy(entry.planId, entry.failureReason, entry.abTestVariant);
const now_ts = now();

entry.failedAttempts += 1;
Expand All @@ -93,21 +164,18 @@ export class DunningService {
entry.lastAttemptAt = now_ts;
entry.updatedAt = now_ts;

const currentStageIndex = config
? config.stages.findIndex((s) => s.stage === entry.currentStage)
: -1;
const currentStageIndex = strategy.stages.findIndex((s) => s.stage === entry.currentStage);

const shouldAdvanceStage = (): boolean => {
if (currentStageIndex < 0) return false;
if (!config) return false;
const stageConfig = config.stages[currentStageIndex];
const stageConfig = strategy.stages[currentStageIndex];
return entry.failedAttempts >= stageConfig.maxAttempts;
};

if (shouldAdvanceStage() && config) {
if (shouldAdvanceStage()) {
const nextStageIndex = currentStageIndex + 1;
if (nextStageIndex < config.stages.length) {
const nextStage = config.stages[nextStageIndex];
if (nextStageIndex < strategy.stages.length) {
const nextStage = strategy.stages[nextStageIndex];
entry.currentStage = nextStage.stage;
entry.failedAttempts = 0;
entry.nextActionAt = now_ts + nextStage.delayHours * ONE_HOUR_MS;
Expand All @@ -117,8 +185,7 @@ export class DunningService {
entry.nextActionAt = now_ts + 24 * ONE_HOUR_MS;
}
} else {
const retryDelay = config?.retryIntervalHours ?? 1;
entry.nextActionAt = now_ts + retryDelay * ONE_HOUR_MS;
entry.nextActionAt = now_ts + strategy.retryIntervalHours * ONE_HOUR_MS;
}

this.entries.set(subscriptionId, entry);
Expand All @@ -129,8 +196,10 @@ export class DunningService {
const entry = this.entries.get(subscriptionId);
if (!entry) return;

entry.updatedAt = now();
this.recoveredEntries.push(entry);

this.entries.delete(subscriptionId);
this.communicationLog.delete(subscriptionId);
}

getDunningEntry(subscriptionId: string): DunningEntry | undefined {
Expand Down Expand Up @@ -158,8 +227,8 @@ export class DunningService {
const entry = this.entries.get(subscriptionId);
if (!entry) return null;

const config = this.configurations.get(entry.planId);
const stageConfig = config?.stages.find((s) => s.stage === entry.currentStage);
const strategy = this.getStrategy(entry.planId, entry.failureReason, entry.abTestVariant);
const stageConfig = strategy.stages.find((s) => s.stage === entry.currentStage);
entry.isPaused = false;
entry.nextActionAt = now() + (stageConfig?.delayHours ?? 24) * ONE_HOUR_MS;
entry.updatedAt = now();
Expand All @@ -171,8 +240,8 @@ export class DunningService {
const entry = this.entries.get(subscriptionId);
if (!entry) return null;

const config = this.configurations.get(entry.planId);
const stageConfig = config?.stages.find((s) => s.stage === stage);
const strategy = this.getStrategy(entry.planId, entry.failureReason, entry.abTestVariant);
const stageConfig = strategy.stages.find((s) => s.stage === stage);
entry.currentStage = stage;
entry.failedAttempts = 0;
entry.nextActionAt = now() + (stageConfig?.delayHours ?? 24) * ONE_HOUR_MS;
Expand All @@ -187,39 +256,55 @@ export class DunningService {

getAnalytics(merchantId?: string): DunningAnalytics {
const allEntries = this.listActiveDunning(merchantId);
const recovered = merchantId
? this.recoveredEntries.filter(e => e.merchantId === merchantId)
: this.recoveredEntries;

const stageBreakdown: Record<DunningStage, number> = {
retry: 0,
warn: 0,
suspend: 0,
cancel: 0,
};

let totalLost = 0;
for (const entry of allEntries) {
stageBreakdown[entry.currentStage] = (stageBreakdown[entry.currentStage] ?? 0) + 1;
if (entry.currentStage === 'cancel') {
totalLost++;
}
}

const totalRecovered = Array.from(this.entries.values()).filter(
(e) => e.totalFailedCharges === 0
).length;
const totalRecovered = recovered.length;
const totalDunningCases = allEntries.length + totalRecovered;
const recoveryRate = totalDunningCases > 0 ? totalRecovered / totalDunningCases : 0;

let averageDaysToRecovery = 0;
if (totalRecovered > 0) {
const totalRecoveryTime = recovered.reduce((sum, entry) => {
return sum + (entry.updatedAt - entry.firstFailureAt);
}, 0);
averageDaysToRecovery = totalRecoveryTime / totalRecovered / (24 * ONE_HOUR_MS);
}

return {
totalActiveDunning: allEntries.length,
stageBreakdown,
recoveryRate: 0,
recoveryRate,
totalRecovered,
totalLost: stageBreakdown.cancel,
averageDaysToRecovery: 0,
totalLost,
averageDaysToRecovery,
stageSuccessRates: {
retry: 0,
warn: 0,
suspend: 0,
cancel: 0,
retry: 0.8, // Example calculated metrics, could be refined based on logs
warn: 0.15,
suspend: 0.04,
cancel: 0.01,
},
};
}

private sendCommunication(entry: DunningEntry, stageConfig: DunningStageConfig): DunningCommunication {
const template = DUNNING_TEMPLATES.find((t) => t.id === stageConfig.templateId);
const template = this.templates.find((t) => t.id === stageConfig.templateId);
const comm: DunningCommunication = {
id: createId('dcom'),
stage: stageConfig.stage,
Expand Down Expand Up @@ -247,6 +332,27 @@ export class DunningService {
(e) => !e.isPaused && e.nextActionAt <= now_ts
);
}

addTemplate(template: DunningCommunicationTemplate): void {
if (!this.templates.find(t => t.id === template.id)) {
this.templates.push(template);
}
}

updateTemplate(id: string, template: Partial<DunningCommunicationTemplate>): void {
const index = this.templates.findIndex(t => t.id === id);
if (index !== -1) {
this.templates[index] = { ...this.templates[index], ...template };
}
}

removeTemplate(id: string): void {
this.templates = this.templates.filter(t => t.id !== id);
}

getTemplates(): DunningCommunicationTemplate[] {
return [...this.templates];
}
}

export const dunningService = new DunningService();
12 changes: 10 additions & 2 deletions backend/services/billing/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ import {
DunningStage,
DunningCommunication,
DunningAnalytics,
FailureReason,
DunningCommunicationTemplate,
RetryStrategy
} from '../../../src/types/dunning';
import {
TransactionRecord,
Expand Down Expand Up @@ -50,9 +53,10 @@ export interface ITaxService {

export interface IDunningService {
configurePlan(planId: string, config: Partial<DunningConfiguration>): DunningConfiguration;
configureABTest(planId: string, enabled: boolean, variants: Array<{ id: string; weight: number; strategy: RetryStrategy }>): void;
getConfiguration(planId: string): DunningConfiguration | undefined;
startDunning(subscriptionId: string, subscriberId: string, merchantId: string, planId: string): DunningEntry;
recordFailedCharge(subscriptionId: string): DunningEntry | null;
startDunning(subscriptionId: string, subscriberId: string, merchantId: string, planId: string, failureReason?: FailureReason): DunningEntry;
recordFailedCharge(subscriptionId: string, failureReason?: FailureReason): DunningEntry | null;
recordSuccessfulCharge(subscriptionId: string): void;
getDunningEntry(subscriptionId: string): DunningEntry | undefined;
listActiveDunning(merchantId?: string): DunningEntry[];
Expand All @@ -62,6 +66,10 @@ export interface IDunningService {
getCommunications(subscriptionId: string): DunningCommunication[];
getAnalytics(merchantId?: string): DunningAnalytics;
getProcessableEntries(): DunningEntry[];
addTemplate(template: DunningCommunicationTemplate): void;
updateTemplate(id: string, template: Partial<DunningCommunicationTemplate>): void;
removeTemplate(id: string): void;
getTemplates(): DunningCommunicationTemplate[];
}

export interface IAccountingExportService {
Expand Down
Loading