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
13 changes: 12 additions & 1 deletion src/domain/returns.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
'use strict';

const { todayAsIso } = require('../utils/clock');
const { toMinorUnits, formatAmount, mulBps } = require('../lib/money');

const MINOR_SCALE = 7;
Expand Down Expand Up @@ -30,11 +31,21 @@ 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.
const effective = Math.floor(((((1 + yieldBps / 10000) ** (365 / daysToMaturity)) - 1) * 10000) + 0.5);
return { simpleAnnualisedBps: simple, effectiveAnnualisedBps: effective };
}

module.exports = { MINOR_SCALE, toMinor, fromMinor, couponMinor, daysBetween, annualisedBps };
module.exports = { MINOR_SCALE, toMinor, fromMinor, couponMinor, daysBetween, daysToMaturity, annualisedBps };
6 changes: 5 additions & 1 deletion src/routes/invoices.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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);
Expand Down
40 changes: 40 additions & 0 deletions src/utils/clock.js
Original file line number Diff line number Diff line change
@@ -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 };
115 changes: 115 additions & 0 deletions tests/api.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -21,6 +22,7 @@ beforeEach(() => {
store.reset();
defaultDocumentStore.clear();
idempotency.resetStore();
resetTestClock();
});

describe('system', () => {
Expand Down Expand Up @@ -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', () => {
Expand Down
Loading