diff --git a/src/domain/returns.js b/src/domain/returns.js index 5b2e27e3..a684afb7 100644 --- a/src/domain/returns.js +++ b/src/domain/returns.js @@ -1,5 +1,6 @@ 'use strict'; +const { todayAsIso } = require('../utils/clock'); const { toMinorUnits, formatAmount, mulBps } = require('../lib/money'); const MINOR_SCALE = 7; @@ -30,6 +31,16 @@ function daysBetween(asOf, maturity) { return Math.round((end - start) / 86400000); } +/** + * Calculates days to maturity from today (UTC). + * + * @param {string} maturity maturity date in YYYY-MM-DD format + * @returns {number} days until maturity (negative if matured) + */ +function daysToMaturity(maturity) { + return daysBetween(todayAsIso(), maturity); +} + function annualisedBps(yieldBps, daysToMaturity) { const simple = Math.floor((yieldBps * 365 + daysToMaturity / 2) / daysToMaturity); // Effective annualisation is a comparison metric only; never use this float for money. @@ -37,4 +48,4 @@ function annualisedBps(yieldBps, daysToMaturity) { return { simpleAnnualisedBps: simple, effectiveAnnualisedBps: effective }; } -module.exports = { MINOR_SCALE, toMinor, fromMinor, couponMinor, daysBetween, annualisedBps }; +module.exports = { MINOR_SCALE, toMinor, fromMinor, couponMinor, daysBetween, daysToMaturity, annualisedBps }; diff --git a/src/routes/invoices.js b/src/routes/invoices.js index fa4eedd5..b5cd5f08 100644 --- a/src/routes/invoices.js +++ b/src/routes/invoices.js @@ -7,7 +7,7 @@ const { StrKey } = require('@stellar/stellar-sdk'); const store = require('../data/store'); const { auditContext } = require('../audit/middleware'); const contributions = require('../data/contributions'); -const { toMinor, fromMinor, couponMinor, daysBetween, annualisedBps } = require('../domain/returns'); +const { toMinor, fromMinor, couponMinor, daysBetween, daysToMaturity, annualisedBps } = require('../domain/returns'); const { ApiError, badRequest, notFound, conflict, unprocessable, sendProblem } = require('../errors'); const { parseInvoiceQuery, queryInvoices, InvoiceQueryError } = require('../services/invoice-query'); const { requireAdminToken } = require('../middleware/require-admin-token'); @@ -349,6 +349,10 @@ router.post('/:id/fund', requireRole('investor', 'admin'), idempotency, validate metadata: requested, }); } + const currentDaysToMaturity = daysToMaturity(invoice.dueDate); + if (currentDaysToMaturity <= 0) { + return reject(409, 'INVOICE_MATURED', { before, metadata: requested }); + } // Contributions are accepted in full or rejected; allowPartial explicitly caps at remaining capacity. const remainingMinor = store.remaining(invoice); diff --git a/src/utils/clock.js b/src/utils/clock.js new file mode 100644 index 00000000..b3ed6a05 --- /dev/null +++ b/src/utils/clock.js @@ -0,0 +1,40 @@ +'use strict'; + +/** + * Clock helper for injectable "now" in tests. + * + * Default implementation returns current UTC date as YYYY-MM-DD string. + * Tests can override this by calling setTestClock with a fixed date. + */ + +let testClock = null; + +/** + * Returns current UTC date as YYYY-MM-DD string. + * + * @returns {string} date in YYYY-MM-DD format + */ +function todayAsIso() { + if (testClock !== null) { + return testClock; + } + return new Date().toISOString().slice(0, 10); +} + +/** + * Sets a fixed date for testing (e.g., '2026-11-24'). + * + * @param {string|null} date ISO date string (YYYY-MM-DD) or null to reset + */ +function setTestClock(date) { + testClock = date; +} + +/** + * Resets the test clock to use real time. + */ +function resetTestClock() { + testClock = null; +} + +module.exports = { todayAsIso, setTestClock, resetTestClock }; diff --git a/tests/api.test.js b/tests/api.test.js index 523aac75..e248214a 100644 --- a/tests/api.test.js +++ b/tests/api.test.js @@ -10,6 +10,7 @@ const app = require('../src/app'); const { buildSpec } = require('../src/openapi'); const store = require('../src/data/store'); const { defaultDocumentStore } = require('../src/data/documentStore'); +const { setTestClock, resetTestClock } = require('../src/utils/clock'); const FIXTURE_PATH = path.join(__dirname, 'fixtures', 'sample.pdf'); const FIXTURE_BYTES = fs.readFileSync(FIXTURE_PATH); @@ -21,6 +22,7 @@ beforeEach(() => { store.reset(); defaultDocumentStore.clear(); idempotency.resetStore(); + resetTestClock(); }); describe('system', () => { @@ -423,6 +425,119 @@ describe('invoices', () => { expect((await request(app).post('/api/invoices/missing/settle').set(authHeader())).status).toBe(404); expect((await request(app).post('/api/invoices/missing/cancel').set(authHeader())).status).toBe(404); }); + + describe('maturity guard', () => { + const INVESTOR = 'GBTUJNOF2WAAUPKCJHBB76ID5HGN6KMTUG43F3Z344T7QRTP7B7TVPVC'; + + test('funding a matured invoice (due date is today) returns 409 INVOICE_MATURED', async () => { + setTestClock('2026-11-24'); + const created = await request(app).post('/api/invoices').set(authHeader()).send({ + sme: 'Test SME', + debtor: 'Buyer', + amount: 500, + dueDate: '2026-11-24', + }); + expect(created.status).toBe(201); + const res = await request(app) + .post(`/api/invoices/${created.body.data.id}/fund`) + .set(authHeader()) + .send({ amount: 100, investor: INVESTOR }); + expect(res.status).toBe(409); + expect(res.body.code).toBe('INVOICE_MATURED'); + resetTestClock(); + }); + + test('funding a matured invoice (due date was yesterday) returns 409 INVOICE_MATURED', async () => { + setTestClock('2026-11-24'); + const created = await request(app).post('/api/invoices').set(authHeader()).send({ + sme: 'Test SME', + debtor: 'Buyer', + amount: 500, + dueDate: '2026-11-23', + }); + expect(created.status).toBe(201); + const res = await request(app) + .post(`/api/invoices/${created.body.data.id}/fund`) + .set(authHeader()) + .send({ amount: 100, investor: INVESTOR }); + expect(res.status).toBe(409); + expect(res.body.code).toBe('INVOICE_MATURED'); + resetTestClock(); + }); + + test('funding the day before maturity succeeds', async () => { + setTestClock('2026-11-23'); + const created = await request(app).post('/api/invoices').set(authHeader()).send({ + sme: 'Test SME', + debtor: 'Buyer', + amount: 500, + dueDate: '2026-11-24', + }); + expect(created.status).toBe(201); + const res = await request(app) + .post(`/api/invoices/${created.body.data.id}/fund`) + .set(authHeader()) + .send({ amount: 100, investor: INVESTOR }); + expect(res.status).toBe(200); + expect(res.body.data.status).toBe('open'); + expect(res.body.data.fundedAmount).toBe('100'); + resetTestClock(); + }); + + test('quote and fund use the same date logic', async () => { + setTestClock('2026-11-24'); + const created = await request(app).post('/api/invoices').set(authHeader()).send({ + sme: 'Test SME', + debtor: 'Buyer', + amount: 500, + dueDate: '2026-11-24', + }); + expect(created.status).toBe(201); + + const quote = await request(app) + .get(`/api/invoices/${created.body.data.id}/quote?amount=100`); + expect(quote.status).toBe(409); + expect(quote.body.code).toBe('INVOICE_MATURED'); + + const fund = await request(app) + .post(`/api/invoices/${created.body.data.id}/fund`) + .set(authHeader()) + .send({ amount: 100, investor: INVESTOR }); + expect(fund.status).toBe(409); + expect(fund.body.code).toBe('INVOICE_MATURED'); + resetTestClock(); + }); + + test('maturity rejection is audited with before state', async () => { + const auditLog = require('../src/audit/audit-log').auditLog; + auditLog.resetForTests(); + setTestClock('2026-11-24'); + const created = await request(app).post('/api/invoices').set(authHeader()).send({ + sme: 'Test SME', + debtor: 'Buyer', + amount: 500, + dueDate: '2026-11-24', + }); + expect(created.status).toBe(201); + + const fund = await request(app) + .post(`/api/invoices/${created.body.data.id}/fund`) + .set(authHeader()) + .send({ amount: 100, investor: INVESTOR }); + expect(fund.status).toBe(409); + expect(fund.body.code).toBe('INVOICE_MATURED'); + + const entries = auditLog.entries(); + const fundEntry = entries.find((e) => e.action === 'invoice.fund'); + expect(fundEntry).toBeDefined(); + expect(fundEntry.outcome).toBe('rejected'); + expect(fundEntry.statusCode).toBe(409); + expect(fundEntry.metadata.error).toBe('INVOICE_MATURED'); + expect(fundEntry.before).toEqual({ fundedAmount: '0', status: 'open' }); + resetTestClock(); + auditLog.resetForTests(); + }); + }); }); describe('escrow', () => {