Skip to content
Merged
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
8 changes: 7 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,10 @@ npm-debug.log*
# Keys
*.pem

.claude
.claude
# additional ignores
*.snap
**/*.snap
__snapshots__/
**/__snapshots__/

8 changes: 8 additions & 0 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ import { funnelTrackingRouter } from './routes/funnel-tracking.js';
import { mlForecastRouter } from './routes/ml-forecast.js';
import { abTestingRouter } from './routes/ab-testing.js';
import { customerHealthRouter } from './routes/customer-health.js';
import { pnlRouter } from './routes/pnl.js';
import { clvRouter } from './routes/clv.js';
import { paymentMethodAnalyticsRouter } from './routes/payment-method-analytics.js';
import { cashFlowRouter } from './routes/cash-flow.js';
import { kybRouter } from './routes/kyb.js';
import { kycRouter } from './routes/kyc.js';
import { batchRouter } from './routes/batch.js';
Expand Down Expand Up @@ -356,6 +360,10 @@ apiV1Router.use('/funnels', funnelTrackingRouter);
apiV1Router.use('/forecast/ml', mlForecastRouter);
apiV1Router.use('/ab-tests', abTestingRouter);
apiV1Router.use('/customer-health', customerHealthRouter);
apiV1Router.use('/reports/pnl', pnlRouter);
apiV1Router.use('/clv', clvRouter);
apiV1Router.use('/payment-methods/analytics', paymentMethodAnalyticsRouter);
apiV1Router.use('/cash-flow', cashFlowRouter);
apiV1Router.use('/nfc', nfcRouter);
apiV1Router.use('/cache', cacheRouter);
apiV1Router.use('/circuit-breaker', circuitBreakerRouter);
Expand Down
42 changes: 42 additions & 0 deletions backend/src/routes/cash-flow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// Cash flow forecasting routes — Issue #944
// Mount at /api/v1/cash-flow
import { Router, Request, Response } from 'express';
import { cashFlowService } from '../services/cash-flow.js';
import { AppError, asyncHandler } from '../middleware/errorHandler.js';

export const cashFlowRouter = Router();
function parseMoney(value: unknown, field: string): number {
const n = Number(value); if (!Number.isFinite(n) || n < 0) throw new AppError(400, `${field} must be a non-negative number`, 'VALIDATION_ERROR');
return n;
}
function parseDate(value: unknown): Date | undefined {
if (value === undefined || value === null || value === '') return undefined;
const d = new Date(String(value)); if (isNaN(d.getTime())) throw new AppError(400, 'Invalid date', 'VALIDATION_ERROR');
return d;
}
cashFlowRouter.post('/inflow', asyncHandler(async (req: Request, res: Response) => {
const { amount, currency, reference, metadata, timestamp } = req.body as Record<string, unknown>;
const flow = cashFlowService.recordInflow(parseMoney(amount, 'amount'), {
currency: typeof currency === 'string' ? currency : 'USD', reference: typeof reference === 'string' ? reference : undefined,
metadata: metadata as Record<string, unknown> | undefined, timestamp: timestamp ? parseDate(timestamp) : undefined });
res.status(201).json({ ok: true, flow });
}));
cashFlowRouter.post('/outflow', asyncHandler(async (req: Request, res: Response) => {
const { amount, currency, reference, metadata, timestamp } = req.body as Record<string, unknown>;
const flow = cashFlowService.recordOutflow(parseMoney(amount, 'amount'), {
currency: typeof currency === 'string' ? currency : 'USD', reference: typeof reference === 'string' ? reference : undefined,
metadata: metadata as Record<string, unknown> | undefined, timestamp: timestamp ? parseDate(timestamp) : undefined });
res.status(201).json({ ok: true, flow });
}));
cashFlowRouter.get('/summary', asyncHandler(async (req: Request, res: Response) => {
res.json(cashFlowService.summary({ since: parseDate(req.query.since), until: parseDate(req.query.until),
currency: typeof req.query.currency === 'string' ? req.query.currency : undefined }));
}));
cashFlowRouter.get('/forecast', asyncHandler(async (req: Request, res: Response) => {
const horizon = req.query.horizon ? Number(req.query.horizon) : undefined;
if (horizon !== undefined && (!Number.isFinite(horizon) || horizon < 1 || horizon > 60)) throw new AppError(400, 'horizon must be between 1 and 60', 'VALIDATION_ERROR');
res.json(cashFlowService.forecast({ horizon, asOf: parseDate(req.query.asOf), currency: typeof req.query.currency === 'string' ? req.query.currency : undefined }));
}));
cashFlowRouter.get('/flows', asyncHandler(async (_req: Request, res: Response) => {
const flows = cashFlowService.list(); res.json({ flows, count: flows.length });
}));
41 changes: 41 additions & 0 deletions backend/src/routes/clv.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Customer Lifetime Value dashboard routes — Issue #943
// Mount at /api/v1/clv
import { Router, Request, Response } from 'express';
import { clvService } from '../services/clv.js';
import { AppError, asyncHandler } from '../middleware/errorHandler.js';

export const clvRouter = Router();
type PaymentStatus = 'completed' | 'pending' | 'failed' | 'refunded';
function parseMoney(value: unknown, field: string): number {
const n = Number(value); if (!Number.isFinite(n) || n < 0) throw new AppError(400, `${field} must be a non-negative number`, 'VALIDATION_ERROR');
return n;
}
function parseDate(value: unknown): Date | undefined {
if (value === undefined || value === null || value === '') return undefined;
const d = new Date(String(value)); if (isNaN(d.getTime())) throw new AppError(400, 'Invalid date', 'VALIDATION_ERROR');
return d;
}
function parseStatus(value: unknown): PaymentStatus {
if (typeof value !== 'string' || !['completed', 'pending', 'failed', 'refunded'].includes(value)) return 'completed';
return value as PaymentStatus;
}
clvRouter.post('/payments', asyncHandler(async (req: Request, res: Response) => {
const { customerId, amount, currency, status, timestamp, metadata } = req.body as Record<string, unknown>;
if (typeof customerId !== 'string' || customerId.length === 0) throw new AppError(400, 'customerId is required', 'VALIDATION_ERROR');
const entry = clvService.recordPayment({
customerId, amount: parseMoney(amount, 'amount'), currency: typeof currency === 'string' ? currency : 'USD',
status: parseStatus(status), timestamp: timestamp ? parseDate(timestamp) : undefined,
metadata: metadata as Record<string, unknown> | undefined });
res.status(201).json({ ok: true, payment: entry });
}));
clvRouter.get('/dashboard', asyncHandler(async (req: Request, res: Response) => {
const asOf = parseDate(req.query.asOf); const limit = req.query.limit ? Number(req.query.limit) : undefined;
if (limit !== undefined && (!Number.isFinite(limit) || limit < 1)) throw new AppError(400, 'limit must be a positive integer', 'VALIDATION_ERROR');
res.json(clvService.dashboard({ asOf, limit }));
}));
clvRouter.get('/:customerId', asyncHandler(async (req: Request, res: Response) => {
res.json(clvService.getCLV(req.params.customerId, parseDate(req.query.asOf)));
}));
clvRouter.get('/payments', asyncHandler(async (_req: Request, res: Response) => {
const payments = clvService.list(); res.json({ payments, count: payments.length });
}));
31 changes: 31 additions & 0 deletions backend/src/routes/payment-method-analytics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Payment method usage analytics routes — Issue #942
// Mount at /api/v1/payment-methods/analytics
import { Router, Request, Response } from 'express';
import { paymentMethodAnalyticsService } from '../services/payment-method-analytics.js';
import { AppError, asyncHandler } from '../middleware/errorHandler.js';

export const paymentMethodAnalyticsRouter = Router();
function parseDate(value: unknown): Date | undefined {
if (value === undefined || value === null || value === '') return undefined;
const d = new Date(String(value)); if (isNaN(d.getTime())) throw new AppError(400, 'Invalid date', 'VALIDATION_ERROR');
return d;
}
paymentMethodAnalyticsRouter.post('/usage', asyncHandler(async (req: Request, res: Response) => {
const { method, amount, currency, status, timestamp, metadata } = req.body as Record<string, unknown>;
if (typeof method !== 'string' || method.length === 0) throw new AppError(400, 'method is required', 'VALIDATION_ERROR');
const n = Number(amount); if (!Number.isFinite(n) || n < 0) throw new AppError(400, 'amount must be a non-negative number', 'VALIDATION_ERROR');
const validStatus = ['success', 'failure', 'pending'].includes(String(status ?? '')) ? (status as 'success' | 'failure' | 'pending') : 'success';
const entry = paymentMethodAnalyticsService.recordUsage({
method, amount: n, currency: typeof currency === 'string' ? currency : 'USD', status: validStatus,
timestamp: timestamp ? parseDate(timestamp) : undefined, metadata: metadata as Record<string, unknown> | undefined });
res.status(201).json({ ok: true, event: entry });
}));
paymentMethodAnalyticsRouter.get('/analytics', asyncHandler(async (req: Request, res: Response) => {
res.json(paymentMethodAnalyticsService.getAnalytics({ since: parseDate(req.query.since) }));
}));
paymentMethodAnalyticsRouter.get('/:method/stats', asyncHandler(async (req: Request, res: Response) => {
res.json(paymentMethodAnalyticsService.getMethodStats(req.params.method));
}));
paymentMethodAnalyticsRouter.get('/usage', asyncHandler(async (_req: Request, res: Response) => {
const events = paymentMethodAnalyticsService.list(); res.json({ events, count: events.length });
}));
46 changes: 46 additions & 0 deletions backend/src/routes/pnl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Multi-currency Profit & Loss routes — Issue #941
// Mount at /api/v1/reports/pnl
import { Router, Request, Response } from 'express';
import { pnlService } from '../services/pnl.js';
import { AppError, asyncHandler } from '../middleware/errorHandler.js';

export const pnlRouter = Router();
function parseMoney(value: unknown, field: string): number {
const n = Number(value); if (!Number.isFinite(n) || n < 0) throw new AppError(400, `${field} must be a non-negative number`, 'VALIDATION_ERROR');
return n;
}
function parseDate(value: unknown): Date | undefined {
if (value === undefined || value === null || value === '') return undefined;
const d = new Date(String(value)); if (isNaN(d.getTime())) throw new AppError(400, 'Invalid date', 'VALIDATION_ERROR');
return d;
}
function resolveCurrency(value: unknown): string {
if (typeof value !== 'string' || value.length === 0) throw new AppError(400, 'currency is required', 'VALIDATION_ERROR');
return value.toUpperCase();
}
pnlRouter.post('/revenue', asyncHandler(async (req: Request, res: Response) => {
const { amount, currency, reference, metadata, timestamp } = req.body as Record<string, unknown>;
const entry = pnlService.recordRevenue(parseMoney(amount, 'amount'), resolveCurrency(currency), {
reference: typeof reference === 'string' ? reference : undefined,
metadata: metadata as Record<string, unknown> | undefined, timestamp: timestamp ? parseDate(timestamp) : undefined });
res.status(201).json({ ok: true, entry });
}));
pnlRouter.post('/cost', asyncHandler(async (req: Request, res: Response) => {
const { amount, currency, reference, metadata, timestamp } = req.body as Record<string, unknown>;
const entry = pnlService.recordCost(parseMoney(amount, 'amount'), resolveCurrency(currency), {
reference: typeof reference === 'string' ? reference : undefined,
metadata: metadata as Record<string, unknown> | undefined, timestamp: timestamp ? parseDate(timestamp) : undefined });
res.status(201).json({ ok: true, entry });
}));
pnlRouter.post('/fx', asyncHandler(async (req: Request, res: Response) => {
const { from, to, rate } = req.body as Record<string, unknown>;
if (typeof from !== 'string' || typeof to !== 'string') throw new AppError(400, 'from and to currencies are required', 'VALIDATION_ERROR');
const r = Number(rate); if (!Number.isFinite(r) || r <= 0) throw new AppError(400, 'rate must be a positive number', 'VALIDATION_ERROR');
pnlService.setFXRate(from, to, r); res.json({ ok: true, from: from.toUpperCase(), to: to.toUpperCase(), rate: r });
}));
pnlRouter.get('/report', asyncHandler(async (req: Request, res: Response) => {
res.json(pnlService.report({ since: parseDate(req.query.since), until: parseDate(req.query.until) }));
}));
pnlRouter.get('/ledger', asyncHandler(async (_req: Request, res: Response) => {
res.json({ entries: pnlService.list(), count: pnlService.count() });
}));
41 changes: 41 additions & 0 deletions backend/src/services/__tests__/cash-flow.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Cash flow forecasting service tests — Issue #944
import { describe, expect, it, beforeEach } from 'vitest';
import { CashFlowService } from '../cash-flow.js';
const base = new Date('2026-01-01T00:00:00Z');
function days(d: number): Date { return new Date(base.getTime() + d * 24 * 60 * 60 * 1000); }

describe('CashFlowService — Issue #944', () => {
let service: CashFlowService;
beforeEach(() => { service = new CashFlowService(); });
it('records inflow and outflow and computes summary', () => {
service.recordInflow(1000, { timestamp: base }); service.recordOutflow(300, { timestamp: days(1) }); service.recordOutflow(200, { timestamp: days(2) });
const summary = service.summary();
expect(summary.totalInflow).toBe(1000); expect(summary.totalOutflow).toBe(500); expect(summary.netFlow).toBe(500);
expect(summary.currentBalance).toBe(500); expect(summary.transactionCount).toBe(3);
});
it('forecasts balance using average net flow per period', () => {
for (let i = 0; i < 3; i++) { service.recordInflow(100, { timestamp: days(i) }); service.recordOutflow(40, { timestamp: days(i) }); }
const fc = service.forecast({ horizon: 3, asOf: days(10) });
expect(fc.startingBalance).toBe(180); expect(fc.avgNetFlowPerPeriod).toBeCloseTo(60, 1); expect(fc.horizon).toBe(3);
expect(fc.forecast).toHaveLength(3); expect(fc.riskOfShortfall).toBe(false);
expect(fc.forecast[2].projectedBalance).toBeCloseTo(360, 1);
});
it('detects shortfall risk when outflows exceed inflows', () => {
service.recordInflow(10, { timestamp: base }); service.recordOutflow(1000, { timestamp: base });
const fc = service.forecast({ horizon: 2, asOf: days(5) });
expect(fc.riskOfShortfall).toBe(true); expect(fc.minBalance).toBeLessThan(0);
});
it('returns zero forecast with no history', () => {
const fc = service.forecast({ horizon: 3, asOf: base });
expect(fc.startingBalance).toBe(0); expect(fc.avgNetFlowPerPeriod).toBe(0); expect(fc.riskOfShortfall).toBe(false);
});
it('filters summary by currency and time window', () => {
service.recordInflow(1000, { currency: 'USD', timestamp: base }); service.recordInflow(500, { currency: 'EUR', timestamp: days(1) }); service.recordOutflow(200, { currency: 'USD', timestamp: days(2) });
const usd = service.summary({ currency: 'USD' }); expect(usd.totalInflow).toBe(1000); expect(usd.totalOutflow).toBe(200);
const window = service.summary({ since: days(1), until: days(3) }); expect(window.transactionCount).toBe(2);
});
it('is read-only for forecast methods', () => {
service.recordInflow(100, { timestamp: base }); const before = service.list().length;
service.forecast({ horizon: 3, asOf: base }); expect(service.list().length).toBe(before);
});
});
48 changes: 48 additions & 0 deletions backend/src/services/__tests__/clv.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Customer Lifetime Value service tests — Issue #943
import { describe, expect, it, beforeEach } from 'vitest';
import { CLVService } from '../clv.js';
const base = new Date('2026-01-01T00:00:00Z');
function daysFromBase(days: number): Date { return new Date(base.getTime() + days * 24 * 60 * 60 * 1000); }

describe('CLVService — Issue #943', () => {
let service: CLVService;
beforeEach(() => { service = new CLVService(); });
it('computes CLV for a customer with repeat purchases', () => {
const now = daysFromBase(60);
service.recordPayment({ customerId: 'c1', amount: 100, status: 'completed', timestamp: base });
service.recordPayment({ customerId: 'c1', amount: 200, status: 'completed', timestamp: daysFromBase(30) });
service.recordPayment({ customerId: 'c1', amount: 300, status: 'completed', timestamp: daysFromBase(60) });
const clv = service.getCLV('c1', now);
expect(clv.totalSpend).toBe(600); expect(clv.orderCount).toBe(3); expect(clv.averageOrderValue).toBe(200);
expect(clv.lifespanMonths).toBeCloseTo(2, 1); expect(clv.clv).toBeCloseTo(600, 1); expect(clv.tier).toBe('gold');
});
it('returns zero CLV for a customer with no completed payments', () => {
service.recordPayment({ customerId: 'c1', amount: 100, status: 'failed' });
const clv = service.getCLV('c1'); expect(clv.orderCount).toBe(0); expect(clv.clv).toBe(0); expect(clv.tier).toBe('bronze');
});
it('ranks customers by CLV in dashboard', () => {
const now = daysFromBase(30);
service.recordPayment({ customerId: 'low', amount: 10, status: 'completed', timestamp: base });
service.recordPayment({ customerId: 'high', amount: 5000, status: 'completed', timestamp: base });
const dash = service.dashboard({ asOf: now });
expect(dash.totalCustomers).toBe(2); expect(dash.topCustomers[0].customerId).toBe('high');
expect(dash.topCustomers[0].clv).toBeGreaterThan(dash.topCustomers[1].clv);
expect(dash.totalSpend).toBe(5010); expect(dash.averageCLV).toBeGreaterThan(0); expect(dash.medianCLV).toBeGreaterThan(0);
});
it('distributes customers into tiers', () => {
service.recordPayment({ customerId: 'p1', amount: 12000, status: 'completed', timestamp: base });
service.recordPayment({ customerId: 'p2', amount: 200, status: 'completed', timestamp: base });
const dash = service.dashboard(); expect(dash.distribution.platinum).toBe(1); expect(dash.distribution.bronze).toBe(1);
});
it('ignores refunded/failed payments in totals', () => {
service.recordPayment({ customerId: 'c1', amount: 1000, status: 'completed', timestamp: base });
service.recordPayment({ customerId: 'c1', amount: 500, status: 'refunded', timestamp: base });
service.recordPayment({ customerId: 'c1', amount: 300, status: 'failed', timestamp: base });
const clv = service.getCLV('c1'); expect(clv.totalSpend).toBe(1000); expect(clv.orderCount).toBe(1);
});
it('caps lifespan at the configured maximum', () => {
const now = daysFromBase(1000);
service.recordPayment({ customerId: 'c1', amount: 100, status: 'completed', timestamp: base });
const clv = service.getCLV('c1', now); expect(clv.lifespanMonths).toBeLessThanOrEqual(36);
});
});
Loading
Loading