259 lines
8.7 KiB
TypeScript
259 lines
8.7 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { identityApp, type IdentityApp } from './helpers/identity-app';
|
|
import {
|
|
seedPurchaseOrder,
|
|
receiveAccepted,
|
|
seedSupplierInvoice,
|
|
} from './helpers/procurement';
|
|
import { seedPartnerOrder } from './helpers/b2b-partner-order';
|
|
import { secondActor } from './helpers/commerce';
|
|
|
|
describe('provider-independent accounting source events', () => {
|
|
let ctx: IdentityApp;
|
|
beforeAll(async () => {
|
|
ctx = await identityApp();
|
|
});
|
|
afterAll(async () => {
|
|
await ctx.close();
|
|
});
|
|
beforeEach(async () => {
|
|
await ctx.clearLimits();
|
|
});
|
|
const window = { from: '2026-01-01T00:00:00Z', to: '2026-12-31T00:00:00Z' };
|
|
const auth = { type: 'bearer' as const };
|
|
const feed = (query: object = window, token = ctx.token) =>
|
|
ctx
|
|
.api()
|
|
.get('/api/v1/accounting/source-events')
|
|
.auth(token, auth)
|
|
.query(query);
|
|
async function evidence() {
|
|
const order = await seedPurchaseOrder(ctx);
|
|
await receiveAccepted(ctx, order, '1.000');
|
|
const invoice = await ctx
|
|
.api()
|
|
.post('/api/v1/purchase-orders/' + order.id + '/invoices')
|
|
.auth(ctx.token, auth)
|
|
.send({
|
|
invoiceNumber: randomUUID(),
|
|
invoiceDate: '2026-09-28',
|
|
taxAmount: '18.05',
|
|
shippingAmount: '1.20',
|
|
lines: [{ purchaseOrderLineId: order.lineId, quantity: '1.000' }],
|
|
})
|
|
.expect(201);
|
|
const payment = await ctx
|
|
.api()
|
|
.post('/api/v1/supplier-invoices/' + invoice.body.id + '/payments')
|
|
.auth(ctx.token, auth)
|
|
.send({
|
|
reference: randomUUID(),
|
|
method: 'BANK_TRANSFER',
|
|
amount: '50.01',
|
|
paidDate: '2026-09-28',
|
|
idempotencyKey: randomUUID(),
|
|
})
|
|
.expect(201);
|
|
await ctx
|
|
.api()
|
|
.post('/api/v1/supplier-payments/' + payment.body.id + '/reverse')
|
|
.auth(ctx.token, auth)
|
|
.send({ reason: 'Entered in error' })
|
|
.expect(201);
|
|
await ctx
|
|
.api()
|
|
.post('/api/v1/supplier-invoices/' + invoice.body.id + '/void')
|
|
.auth(ctx.token, auth)
|
|
.send({ reason: 'Invoice superseded' })
|
|
.expect(201);
|
|
const partner = await seedPartnerOrder(ctx);
|
|
const receipt = await ctx
|
|
.api()
|
|
.post('/api/v1/b2b/partner-orders/' + partner.order.id + '/payments')
|
|
.auth(ctx.token, auth)
|
|
.send({
|
|
reference: randomUUID(),
|
|
method: 'BANK_TRANSFER',
|
|
amount: '0.10',
|
|
receivedOn: '2026-10-03',
|
|
idempotencyKey: randomUUID(),
|
|
})
|
|
.expect(201);
|
|
await ctx
|
|
.api()
|
|
.post(
|
|
'/api/v1/b2b/partner-orders/' +
|
|
partner.order.id +
|
|
'/payments/' +
|
|
receipt.body.id +
|
|
'/reverse',
|
|
)
|
|
.auth(ctx.token, auth)
|
|
.send({ reason: 'Entered in error', idempotencyKey: randomUUID() })
|
|
.expect(201);
|
|
return {
|
|
invoice: invoice.body,
|
|
payment: payment.body,
|
|
receipt: receipt.body,
|
|
partner,
|
|
};
|
|
}
|
|
it('retains originals and correction events with exact amounts and source links', async () => {
|
|
const f = await evidence();
|
|
const result = await feed().expect(200);
|
|
expect(result.body.schemaVersion).toBe(1);
|
|
expect(result.body.events).toHaveLength(6);
|
|
const by = (type: string) =>
|
|
result.body.events.find((e: any) => e.eventType === type);
|
|
expect(by('SUPPLIER_INVOICE')).toMatchObject({
|
|
sourceId: f.invoice.id,
|
|
amount: '139.25',
|
|
merchandiseAmount: '120.00',
|
|
taxAmount: '18.05',
|
|
shippingAmount: '1.20',
|
|
businessDate: '2026-09-28',
|
|
operation: 'RECORD',
|
|
});
|
|
expect(by('SUPPLIER_INVOICE_VOID')).toMatchObject({
|
|
sourceId: f.invoice.id,
|
|
amount: '139.25',
|
|
operation: 'VOID',
|
|
reversesEventKey: 'SUPPLIER_INVOICE:' + f.invoice.id,
|
|
});
|
|
expect(by('SUPPLIER_PAYMENT')).toMatchObject({
|
|
sourceId: f.payment.id,
|
|
amount: '50.01',
|
|
relatedId: f.invoice.id,
|
|
operation: 'RECORD',
|
|
});
|
|
expect(by('SUPPLIER_PAYMENT_REVERSAL')).toMatchObject({
|
|
sourceId: f.payment.id,
|
|
amount: '50.01',
|
|
operation: 'REVERSE',
|
|
reversesEventKey: 'SUPPLIER_PAYMENT:' + f.payment.id,
|
|
});
|
|
expect(by('PARTNER_RECEIPT')).toMatchObject({
|
|
sourceId: f.receipt.id,
|
|
amount: '0.10',
|
|
counterpartyId: f.partner.accountId,
|
|
relatedId: f.partner.order.id,
|
|
});
|
|
expect(by('PARTNER_RECEIPT_REVERSAL')).toMatchObject({
|
|
sourceId: f.receipt.id,
|
|
amount: '0.10',
|
|
reversesEventKey: 'PARTNER_RECEIPT:' + f.receipt.id,
|
|
});
|
|
expect(new Set(result.body.events.map((e: any) => e.eventKey)).size).toBe(
|
|
6,
|
|
);
|
|
expect(JSON.stringify(result.body)).not.toMatch(
|
|
/contactEmail|contactPhone|reference|reason|requestHash|idempotencyKey|invoiceNumber|recordedById/,
|
|
);
|
|
expect(
|
|
(await feed({ ...window, currency: 'USD' }).expect(200)).body.events,
|
|
).toEqual([]);
|
|
});
|
|
it('pages without duplicate keys and rejects reuse with changed window or filters', async () => {
|
|
await evidence();
|
|
const initial = await feed({ ...window, limit: 1 }).expect(200);
|
|
expect(initial.body.nextCursor).toEqual(expect.any(String));
|
|
const keys = [initial.body.events[0].eventKey];
|
|
let cursor = initial.body.nextCursor;
|
|
for (let i = 0; cursor && i < 20; i++) {
|
|
const page = await feed({ ...window, limit: 1, cursor }).expect(200);
|
|
keys.push(...page.body.events.map((e: any) => e.eventKey));
|
|
cursor = page.body.nextCursor;
|
|
}
|
|
expect(cursor).toBeNull();
|
|
expect(new Set(keys).size).toBe(keys.length);
|
|
expect(keys.length).toBeGreaterThanOrEqual(6);
|
|
await feed({
|
|
...window,
|
|
cursor: initial.body.nextCursor,
|
|
currency: 'INR',
|
|
}).expect(400);
|
|
await feed({
|
|
...window,
|
|
cursor: initial.body.nextCursor,
|
|
to: '2026-12-30T00:00:00Z',
|
|
}).expect(400);
|
|
await feed({ ...window, cursor: 'not-json' }).expect(400);
|
|
});
|
|
it('bounds recorded timestamps independently of business dates and preserves scoped permissions', async () => {
|
|
const f = await evidence();
|
|
const event = await ctx.db.supplierInvoice.findUniqueOrThrow({
|
|
where: { id: f.invoice.id },
|
|
});
|
|
const from = event.createdAt.toISOString();
|
|
const to = new Date(event.createdAt.getTime() + 1).toISOString();
|
|
const result = await feed({ from, to, kind: 'SUPPLIER_INVOICE' }).expect(
|
|
200,
|
|
);
|
|
expect(result.body.events).toHaveLength(1);
|
|
expect(result.body.events[0].businessDate).toBe('2026-09-28');
|
|
const customer = await secondActor(ctx);
|
|
await feed(window, customer.token).expect(403);
|
|
const foreign = await secondActor(ctx, false, ['accounting.read']);
|
|
expect((await feed(window, foreign.token).expect(200)).body.events).toEqual(
|
|
[],
|
|
);
|
|
const accountant = await secondActor(ctx, true, ['accounting.read']);
|
|
await feed(window, accountant.token).expect(200);
|
|
await ctx
|
|
.api()
|
|
.get('/api/v1/accounting/source-events')
|
|
.query(window)
|
|
.expect(401);
|
|
for (const query of [
|
|
{ ...window, limit: 101 },
|
|
{ ...window, kind: 'PAID_RETAIL_SALE' },
|
|
{ ...window, organizationId: foreign.organizationId },
|
|
{ ...window, to: '2028-01-01T00:00:00Z' },
|
|
{ ...window, offset: 1 },
|
|
])
|
|
await feed(query).expect(400);
|
|
});
|
|
it('uses source IDs to traverse events sharing a recorded timestamp', async () => {
|
|
const { invoice } = await seedSupplierInvoice(ctx);
|
|
const recordedAt = new Date();
|
|
const payments = await ctx.db.$transaction(async (tx) => {
|
|
const rows = [];
|
|
for (const amount of ['25.01', '25.02'])
|
|
rows.push(
|
|
await tx.supplierPayment.create({
|
|
data: {
|
|
organizationId: ctx.owner.organizationId,
|
|
invoiceId: invoice.id,
|
|
createdById: ctx.owner.userId,
|
|
idempotencyKey: randomUUID(),
|
|
requestHash: 'a'.repeat(64),
|
|
reference: randomUUID().toUpperCase(),
|
|
method: 'BANK_TRANSFER',
|
|
currency: 'INR',
|
|
createdAt: recordedAt,
|
|
amount,
|
|
paidAt: new Date('2026-09-28T00:00:00Z'),
|
|
},
|
|
}),
|
|
);
|
|
return rows;
|
|
});
|
|
expect(payments[0].createdAt).toEqual(payments[1].createdAt);
|
|
const query = {
|
|
from: payments[0].createdAt.toISOString(),
|
|
to: new Date(payments[0].createdAt.getTime() + 1).toISOString(),
|
|
kind: 'SUPPLIER_PAYMENT',
|
|
limit: 1,
|
|
};
|
|
const first = await feed(query).expect(200);
|
|
const next = await feed({ ...query, cursor: first.body.nextCursor }).expect(
|
|
200,
|
|
);
|
|
expect([
|
|
first.body.events[0].sourceId,
|
|
next.body.events[0].sourceId,
|
|
]).toEqual(payments.map((p) => p.id).sort());
|
|
expect(next.body.nextCursor).toBeNull();
|
|
});
|
|
});
|