Files
cross-financial-management/tests/integration/posting.balance.spec.ts
T
Joshua OosthuizenandClaude Sonnet 5 4acbc03b35 Initial commit: multi-company financial management system
Root company app (src/, client/) — GL foundation, AR, and AP:
- Segmented Chart of Accounts (Sage 300-style), double-entry PostingService with
  three-layer balance enforcement (app validation, CHECK constraints, deferred
  DB trigger), gap-free document numbering, RBAC with branch restrictions.
- Accounts Receivable: Customers, Invoices, Credit Notes, Receipts with
  allocation, all posting through PostingService.
- Accounts Payable: Suppliers, Supplier Invoices, Debit Notes, Payments with
  allocation, mirroring AR's posting pattern.
- Tax Codes shared between AR and AP.
- Company-app login is a token handoff from the Account Manager (RS256,
  single-use, company-scoped) rather than a local password.
- Frontend reskinned to the approved mockup: navy sidebar, dashboard, tree-view
  Chart of Accounts, Customer/Supplier 360 pages.

Account Manager (manager/, manager/client/) — central login gateway:
- Password + TOTP 2FA + Google/Microsoft OAuth, company picker, and the RS256
  handoff token issuance that the company app verifies.

Covered by unit + integration tests against a real Postgres database (GL
balance invariants, AR/AP posting correctness and allocation limits, the full
handoff exchange including replay/cross-company/expiry/forgery rejection).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Tq2DbEvzHzs13jDFhLaX44
2026-09-03 13:27:19 +02:00

127 lines
4.9 KiB
TypeScript

/**
* Requires a real, migrated, seeded Postgres database (see SETUP.md) reachable via DATABASE_URL.
* Run with: npm run test:integration
*/
import { PrismaClient } from '@prisma/client';
import { PostingService } from '../../src/modules/gl/posting.service';
import { UnbalancedEntryError } from '../../src/modules/gl/posting.types';
const prisma = new PrismaClient();
async function getAccount(accountCode: string) {
return prisma.gLAccount.findUniqueOrThrow({ where: { accountCode } });
}
describe('PostingService — double-entry balance invariant (real DB)', () => {
let adminId: number;
let bankHQ: { id: number };
let salesHQ: { id: number };
beforeAll(async () => {
const admin = await prisma.user.findUniqueOrThrow({ where: { email: 'joosth2002@icloud.com' } });
adminId = admin.id;
bankHQ = await getAccount('1000-000-000-HQ');
salesHQ = await getAccount('4000-000-000-HQ');
});
afterAll(async () => {
await prisma.$disconnect();
});
it('posts a balanced entry and persists matching totals', async () => {
const entry = await PostingService.postEntry({
journalCode: 'GJ',
entryDate: new Date(),
description: 'Integration test — balanced entry',
sourceModule: 'GL',
sourceType: 'IntegrationTest',
createdById: adminId,
lines: [
{ glAccountId: bankHQ.id, debit: 250, credit: 0 },
{ glAccountId: salesHQ.id, debit: 0, credit: 250 },
],
});
expect(entry.totalDebits.toString()).toBe('250');
expect(entry.totalCredits.toString()).toBe('250');
const lines = await prisma.journalEntryLine.findMany({ where: { journalEntryId: entry.id } });
const totalDebits = lines.reduce((sum, line) => sum + Number(line.debit), 0);
const totalCredits = lines.reduce((sum, line) => sum + Number(line.credit), 0);
expect(totalDebits).toBe(totalCredits);
});
it('rejects an unbalanced entry via the application layer and writes nothing', async () => {
const before = await prisma.journalEntry.count();
await expect(
PostingService.postEntry({
journalCode: 'GJ',
entryDate: new Date(),
description: 'Integration test — unbalanced entry',
sourceModule: 'GL',
sourceType: 'IntegrationTest',
createdById: adminId,
lines: [
{ glAccountId: bankHQ.id, debit: 100, credit: 0 },
{ glAccountId: salesHQ.id, debit: 0, credit: 40 },
],
}),
).rejects.toBeInstanceOf(UnbalancedEntryError);
const after = await prisma.journalEntry.count();
expect(after).toBe(before);
});
it('rejects an unbalanced write at the database layer even bypassing PostingService', async () => {
// Prove Layer 3 (the deferred trigger) is the real backstop: attempt to insert an
// unbalanced JournalEntryLine set directly via raw SQL, bypassing the service entirely.
//
// Note: with Prisma's interactive transactions, a commit failure caused by a DEFERRED
// constraint trigger is not always surfaced as a rejected promise (observed with
// @prisma/client 5.22 — the engine logs "transaction failed to commit" and correctly
// rolls back at the database level, but the JS promise can still resolve). So the
// authoritative assertion here is "nothing persisted", checked directly against the
// database after the attempt — not whether the promise rejected.
const marker = `TRIGGER-TEST-${Date.now()}`;
try {
await prisma.$transaction(async (tx) => {
const entry = await tx.journalEntry.create({
data: {
entryNumber: marker,
journalId: (await tx.journal.findUniqueOrThrow({ where: { code: 'GJ' } })).id,
fiscalPeriodId: (
await tx.fiscalPeriod.findFirstOrThrow({ where: { status: 'OPEN' } })
).id,
entryDate: new Date(),
description: 'Trigger bypass attempt — must be rejected at commit',
sourceModule: 'GL',
status: 'POSTED',
totalDebits: 100,
totalCredits: 100,
createdById: adminId,
},
});
await tx.$executeRawUnsafe(
`INSERT INTO "JournalEntryLine" ("journalEntryId", "lineNumber", "glAccountId", debit, credit, "currencyCode", "exchangeRateToBase")
VALUES ($1, 1, $2, 100, 0, 'BASE', 1)`,
entry.id,
bankHQ.id,
);
await tx.$executeRawUnsafe(
`INSERT INTO "JournalEntryLine" ("journalEntryId", "lineNumber", "glAccountId", debit, credit, "currencyCode", "exchangeRateToBase")
VALUES ($1, 2, $2, 0, 40, 'BASE', 1)`,
entry.id,
salesHQ.id,
);
});
} catch {
// Expected outcome on Prisma versions that do propagate the commit failure — fine either way.
}
const persisted = await prisma.journalEntry.findUnique({ where: { entryNumber: marker } });
expect(persisted).toBeNull();
});
});