/** * 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(); }); });