diff --git a/backend/src/bookkeepingAllocations.ts b/backend/src/bookkeepingAllocations.ts index 1929790c..ec137eff 100644 --- a/backend/src/bookkeepingAllocations.ts +++ b/backend/src/bookkeepingAllocations.ts @@ -473,3 +473,34 @@ export function readTransactionAllocations( } return result; } + +/** + * Accountant-facing child rows for a payment with invoice allocations. Parent-only + * classification markers are dropped so each child is classified on its own + * category/text; the parent `id` is kept so omit/month-gate lookups still match. + */ +export function projectTransactionAllocations( + transaction: Record, +): Record[] { + return readTransactionAllocations(transaction).map((allocation) => { + const child: Record = { + ...transaction, + sourceTransactionId: String(transaction.id || ""), + allocationDocumentId: allocation.documentId, + invoiceId: allocation.invoiceId, + invoiceNumber: allocation.invoiceNumber, + counterparty: allocation.counterparty, + description: allocation.description, + amount: allocation.amount, + currency: allocation.currency, + amountEur: allocation.amountEur, + vatAmount: allocation.vatAmount, + vatCurrency: allocation.vatCurrency, + category: allocation.category || transaction.category, + subtype: allocation.subtype || transaction.subtype, + }; + for (const key of ["mandatoryKind", "ownerPayType", "kind", "taxType", "reference", "allocations"]) + delete child[key]; + return child; + }); +} diff --git a/backend/src/db/bookkeeping.ts b/backend/src/db/bookkeeping.ts index 2f77abe2..a0a3ecca 100644 --- a/backend/src/db/bookkeeping.ts +++ b/backend/src/db/bookkeeping.ts @@ -14,6 +14,7 @@ import { cleanItem } from "./cleanItem"; import { TABLE_BOOKKEEPING } from "./tableNames"; import { classifyMandatoryPayment } from "../finance/mandatoryPayments"; import { isOwnerWithdrawalReportExempt } from "../finance/ownerPay"; +import { projectTransactionAllocations } from "../bookkeepingAllocations"; import { deriveInventoryItems, dismissedInventorySeedId, inventoryItemId, inventoryItemSeed } from "../finance/inventory"; import { BOOKKEEPING_AUDIT_PARTITION_PREFIX, @@ -35,12 +36,21 @@ export type BookkeepingItem = Record & { // Payment categories tracked in the ledger but kept out of the accountant's // monthly package: they are settled from private money and reported separately. export const REPORT_EXEMPT_CATEGORIES = new Set(["Taxes", "Health Insurance"]); -export function isReportExemptTransaction(item: Readonly>) { +function isReportExemptClassification(item: Readonly>) { return REPORT_EXEMPT_CATEGORIES.has(String(item.category || "")) || classifyMandatoryPayment(item) !== null || isOwnerWithdrawalReportExempt(item); } +// A payment with invoice allocations is exempt only when every reportable child is; +// each child is classified on its own, not on the parent's markers. +export function isReportExemptTransaction(item: Readonly>) { + const children = projectTransactionAllocations(item); + return children.length + ? children.every(isReportExemptClassification) + : isReportExemptClassification(item); +} + // Raised when a conditional mutation loses its optimistic-concurrency race or // the item is claimed by sponsor finance, as opposed to an unexpected failure. export class BookkeepingItemLockedError extends Error { diff --git a/backend/src/finance/accountantReport.ts b/backend/src/finance/accountantReport.ts index c36336d1..b45fb114 100644 --- a/backend/src/finance/accountantReport.ts +++ b/backend/src/finance/accountantReport.ts @@ -1,5 +1,5 @@ import { isReportExemptTransaction } from "../db/bookkeeping"; -import { readTransactionAllocations } from "../bookkeepingAllocations"; +import { projectTransactionAllocations, readTransactionAllocations } from "../bookkeepingAllocations"; export type AccountantReportEntry = Record; @@ -15,24 +15,7 @@ export function accountantReportRows(transactions: AccountantReportEntry[]) { return transactions.flatMap((entry) => { const allocations = readTransactionAllocations(entry); if (!allocations.length) return [entry]; - return allocations.map((allocation) => ({ - ...entry, - transactionDate: entry.transactionDate, - paidDate: entry.paidDate, - counterparty: allocation.counterparty, - description: allocation.description, - amount: allocation.amount, - currency: allocation.currency, - ...(allocation.amountEur !== undefined ? { amountEur: allocation.amountEur } : { amountEur: undefined }), - ...(allocation.vatAmount !== undefined ? { vatAmount: allocation.vatAmount } : { vatAmount: undefined }), - ...(allocation.vatCurrency !== undefined ? { vatCurrency: allocation.vatCurrency } : { vatCurrency: undefined }), - category: allocation.category || entry.category, - subtype: allocation.subtype || entry.subtype, - invoiceNumber: allocation.invoiceNumber, - allocationDocumentId: allocation.documentId, - invoiceId: allocation.invoiceId, - allocations: undefined, - })); + return projectTransactionAllocations(entry); }); } @@ -50,6 +33,16 @@ export function selectAccountantReportRows(transactions: AccountantReportEntry[] return accountantReportRowsForPeriod(transactions, period).filter(isAccountantReportRowIncluded); } +/** + * The rows already-selected payments contribute to the accountant package: a + * payment with invoice allocations as its reportable children in saved order, + * any other payment as itself. The portal snapshot counts its payments this + * way and its archive lists them this way, so both show the same rows. + */ +export function includedAccountantReportRows(transactions: AccountantReportEntry[]) { + return accountantReportRows(transactions).filter(isAccountantReportRowIncluded); +} + function accountantCurrency(entry: AccountantReportEntry) { return String(entry.currency || "EUR").trim().toUpperCase(); } diff --git a/backend/src/routes/bookkeepingReports.ts b/backend/src/routes/bookkeepingReports.ts index f8d6326c..485d88b2 100644 --- a/backend/src/routes/bookkeepingReports.ts +++ b/backend/src/routes/bookkeepingReports.ts @@ -8,7 +8,6 @@ import { addDocumentReportReference, deleteBookkeepingItem, getBookkeepingItem, - isReportExemptTransaction, listBookkeepingItems, markGenerationCleanupRequired, markReportGenerated, @@ -19,7 +18,14 @@ import { } from "../db/bookkeeping"; import { preflightOrganizations } from '../vies/service'; import { assertAccountantPaymentReady, MonthGateError } from "../reconcile/monthService"; -import { accountantCashDate } from "../finance/accountantReport"; +import { + accountantCashDate, + accountantReportRows, + includedAccountantReportRows, + isAccountantReportRowIncluded, + unconvertedAccountantReportRows, +} from "../finance/accountantReport"; +import { readTransactionAllocations } from "../bookkeepingAllocations"; import { businessAccountRequiresStatement } from "../finance/businessAccounts"; import { headDocumentObject, @@ -106,34 +112,42 @@ export async function handleBookkeepingReportRoutes( }); const monthTransactions = ledger .filter((t) => accountantCashDate(t).startsWith(month) && !omitted.has(String(t.id))); - const excludedTransactions = monthTransactions.filter( - isReportExemptTransaction, - ); - const transactions = monthTransactions.filter( - (t) => !isReportExemptTransaction(t), - ); - const unconverted = transactions.filter( - (t) => - String(t.currency || "EUR").toUpperCase() !== "EUR" && - !String(t.amountEur ?? "").trim(), - ); + // Each reportable child of an allocated payment is classified on its own. + const projected = accountantReportRows(monthTransactions); + const excludedTransactions = projected.filter((t) => !isAccountantReportRowIncluded(t)); + const transactions = projected.filter(isAccountantReportRowIncluded); + const unconverted = unconvertedAccountantReportRows(transactions); if (unconverted.length) return json(409, { error: `${unconverted.length} transaction(s) have no EUR value; convert them before preparing the package`, unconvertedTransactionIds: unconverted.map((t) => String(t.id)), }); const links = await listBookkeepingItems(client, "link"); + const parentOf = (t: Record) => String(t.sourceTransactionId || t.id); + const allocatedParentIds = new Set( + monthTransactions.filter((t) => readTransactionAllocations(t).length).map((t) => String(t.id)), + ); + const includedParentIds = new Set(transactions.map(parentOf)); + // Evidence of an allocated payment comes from its reportable children only; + // parent-level links are not attributable to a child. const linkedIds = new Set( links - .filter((l) => transactions.some((t) => t.id === l.transactionId)) + .filter((l) => includedParentIds.has(String(l.transactionId)) && !allocatedParentIds.has(String(l.transactionId))) .map((l) => String(l.documentId)), ); - const excludedTransactionIds = new Set(excludedTransactions.map((transaction) => String(transaction.id))); + for (const t of transactions) if (t.allocationDocumentId) linkedIds.add(String(t.allocationDocumentId)); + const excludedTransactionIds = new Set(excludedTransactions.map(parentOf)); const excludedLinkedIds = new Set( links - .filter((link) => excludedTransactionIds.has(String(link.transactionId))) + .filter((link) => excludedTransactionIds.has(String(link.transactionId)) && !includedParentIds.has(String(link.transactionId))) .map((link) => String(link.documentId)), ); + for (const link of links) + if (allocatedParentIds.has(String(link.transactionId)) && !linkedIds.has(String(link.documentId))) + excludedLinkedIds.add(String(link.documentId)); + for (const t of excludedTransactions) + if (t.allocationDocumentId && !linkedIds.has(String(t.allocationDocumentId))) + excludedLinkedIds.add(String(t.allocationDocumentId)); const selectedPrivate = new Set( Array.isArray(body?.privateDocumentIds) ? body!.privateDocumentIds.map(String) @@ -147,6 +161,7 @@ export async function handleBookkeepingReportRoutes( linkedIds.has(d.id) || (selectedPrivate.has(d.id) && !excludedLinkedIds.has(String(d.id))), ); + const includedDocIds = new Set(includedDocs.map((d) => String(d.id))); const reportId = createHash("sha256").update(`report#${month}`).digest("hex"); const guarded: string[] = []; let report: BookkeepingItem; @@ -163,7 +178,7 @@ export async function handleBookkeepingReportRoutes( id: reportId, month, status: "ready", - transactionIds: transactions.map((t) => t.id), + transactionIds: [...includedParentIds], documentIds: includedDocs.map((d) => d.id), reconciliation: { transactionCount: transactions.length, @@ -191,11 +206,14 @@ export async function handleBookkeepingReportRoutes( report, vatPreflight: await vatPreflightSummary(client), warnings: { + // An allocated child is evidenced by its own allocation document; a + // parent-level link is not attributable to it. missingEvidence: transactions.filter( - (t) => - !links.some( - (l) => l.transactionId === t.id && l.coverageType === "evidence", - ), + (t) => t.allocationDocumentId + ? !includedDocIds.has(String(t.allocationDocumentId)) + : !links.some( + (l) => l.transactionId === t.id && l.coverageType === "evidence", + ), ).length, }, }); @@ -256,46 +274,62 @@ export async function handleBookkeepingReportRoutes( if (error instanceof MonthGateError) return json(409, { reportPeriod: month, error: error.message, blockers: error.blockers }); throw error; } - // Generating the pack is the monthly bookkeeping landmark: catch the - // inventory up on every physical purchase seen since the last run. - const inventorySweep = await sweepInventory(client); - if (report.archiveDocumentId) { - const doc = await getBookkeepingItem( - client, - "document", - String(report.archiveDocumentId), - ); - if (doc) { - const url = await signUrl( - s3, - new GetObjectCommand({ - Bucket: bookkeepingDocumentsBucket(), - Key: String(doc.s3Key), - }), - { expiresIn: 300 }, - ); - return json(200, { reportPeriod: month, downloadUrl: url, expiresIn: 300, duplicate: true, inventoryItemsAdded: inventorySweep.created.length, vatPreflight: await vatPreflightSummary(client) }); - } - } const transactionIds = Array.isArray(report.transactionIds) ? report.transactionIds.map(String) : [], documentIds = Array.isArray(report.documentIds) ? report.documentIds.map(String) : []; + // An archived report is a historical record and is served as stored. One + // still to be generated lists the payments its snapshot selected as the + // rows the snapshot counted: an allocated payment as its reportable + // children, never as the parent total. + const cachedArchive = report.archiveDocumentId + ? await getBookkeepingItem(client, "document", String(report.archiveDocumentId)) + : undefined; + const payments = cachedArchive ? [] : (await Promise.all( + transactionIds.map((id) => getBookkeepingItem(client, "bookkeeping", id)), + )).filter(Boolean) as Record[]; + const transactions = includedAccountantReportRows(payments); + if (!cachedArchive) { + const parentOf = (t: Record) => String(t.sourceTransactionId || t.id); + const staleTransactionIds = payments + .filter((payment) => !transactions.some((row) => parentOf(row) === String(payment.id))) + .map((payment) => String(payment.id)); + if (staleTransactionIds.length) + return json(409, { + reportPeriod: month, + error: `${staleTransactionIds.length} payment(s) in this package no longer have a reportable invoice allocation; delete the package and prepare the month again`, + staleTransactionIds, + }); + const unconverted = unconvertedAccountantReportRows(transactions); + if (unconverted.length) + return json(409, { + reportPeriod: month, + error: `${unconverted.length} transaction(s) have no EUR value; convert them before preparing the package`, + unconvertedTransactionIds: [...new Set(unconverted.map(parentOf))], + }); + } + // Generating the pack is the monthly bookkeeping landmark: catch the + // inventory up on every physical purchase seen since the last run. + const inventorySweep = await sweepInventory(client); + if (cachedArchive) { + const url = await signUrl( + s3, + new GetObjectCommand({ + Bucket: bookkeepingDocumentsBucket(), + Key: String(cachedArchive.s3Key), + }), + { expiresIn: 300 }, + ); + return json(200, { reportPeriod: month, downloadUrl: url, expiresIn: 300, duplicate: true, inventoryItemsAdded: inventorySweep.created.length, vatPreflight: await vatPreflightSummary(client) }); + } const maxFiles = Number(process.env.BOOKKEEPING_ARCHIVE_MAX_FILES || 500), maxBytes = Number( process.env.BOOKKEEPING_ARCHIVE_MAX_BYTES || 50 * 1024 * 1024, ); if (documentIds.length + 1 > maxFiles) return json(413, { error: "Archive file limit exceeded" }); - const transactions = ( - await Promise.all( - transactionIds.map((id) => - getBookkeepingItem(client, "bookkeeping", id), - ), - ) - ).filter(Boolean) as Record[]; const columns = [ "transactionDate", "paidDate", diff --git a/backend/tests/api-bookkeeping.test.ts b/backend/tests/api-bookkeeping.test.ts index 34427ef6..59186c95 100644 --- a/backend/tests/api-bookkeeping.test.ts +++ b/backend/tests/api-bookkeeping.test.ts @@ -146,6 +146,47 @@ describe('bookkeeping API',()=>{ assert.equal(report.reconciliation.businessStatementCount,2); assert.ok(statementIds.every((id)=>report.documentIds.includes(id))); }); + it('snapshots mixed allocations by reportable child and selects only child evidence',async()=>{ + const month='2026-11'; + for(const [id,name] of [['synthetic-mixed-account-a','Synthetic Business Account A'],['synthetic-mixed-account-b','Synthetic Business Account B']]) + await putBookkeepingItem(client,'account',{id,displayName:name,kind:'business',active:true,statementRequiredFromMonth:month},`business-account#${id}`); + const activeAccounts=JSON.parse((await invoke('GET','/api/bookkeeping/accounts')).body).items + .filter((account:any)=>account.kind==='business'&&account.active!==false); + for(const account of activeAccounts) await putBookkeepingItem(client,'document',{ + documentType:'bank-statement',status:'active',accountId:account.id,statementMonth:month, + originalFilename:`${account.id}-november.pdf`,contentType:'application/pdf',byteSize:9, + sha256:createHash('sha256').update(`synthetic-mixed-statement-${account.id}`).digest('hex'), + s3Key:`documents/synthetic-mixed-${account.id}`, + },`synthetic-mixed-statement#${account.id}`); + const makeDoc=async(id:string)=> (await putBookkeepingItem(client,'document',{documentType:'invoice',status:'active',originalFilename:`${id}.pdf`,contentType:'application/pdf',byteSize:9,sha256:createHash('sha256').update(id).digest('hex'),s3Key:`documents/${id}`},`synthetic-mixed-doc#${id}`)).item; + const [ordinaryA,exemptA,ordinaryB,exemptB,parentEvidenceA]=await Promise.all(['ordinary-a','exempt-a','ordinary-b','exempt-b','parent-evidence-a'].map(makeDoc)); + const parentA=(await putBookkeepingItem(client,'bookkeeping',{ + transactionDate:`${month}-02`,paidDate:`${month}-03`,counterparty:'Synthetic combined payee A',description:'Synthetic tax settlement', + amount:'30.00',amountEur:'30.00',currency:'EUR',entryType:'expense',category:'Taxes',mandatoryKind:'tax_debit', + allocations:[ + {id:'ordinary-a',documentId:ordinaryA.id,counterparty:'Synthetic service A',description:'Service A',amount:'10.00',amountEur:'10.00',currency:'EUR',category:'Software'}, + {id:'exempt-a',documentId:exemptA.id,counterparty:'Synthetic tax A',description:'Tax A',amount:'20.00',amountEur:'20.00',currency:'EUR',category:'Taxes'}, + ], + },'synthetic-mixed-parent#a')).item; + await putBookkeepingItem(client,'bookkeeping',{ + transactionDate:`${month}-04`,paidDate:`${month}-04`,counterparty:'Synthetic combined payee B',description:'Synthetic owner draw', + amount:'70.00',amountEur:'70.00',currency:'EUR',entryType:'expense',category:'Owner pay',ownerPayType:'draw', + allocations:[ + {id:'exempt-b',documentId:exemptB.id,counterparty:'Synthetic tax B',description:'Tax B',amount:'30.00',amountEur:'30.00',currency:'EUR',category:'Taxes'}, + {id:'ordinary-b',documentId:ordinaryB.id,counterparty:'Synthetic service B',description:'Service B',amount:'40.00',amountEur:'40.00',currency:'EUR',category:'Software'}, + ], + },'synthetic-mixed-parent#b'); + await putBookkeepingItem(client,'link',{transactionId:parentA.id,documentId:parentEvidenceA.id,coverageType:'evidence'},`synthetic-mixed-link#${parentA.id}`); + const snapshot=await invoke('POST','/api/bookkeeping/reports/snapshot',{month,privateDocumentIds:[exemptA.id,exemptB.id,parentEvidenceA.id]}); + assert.equal(snapshot.statusCode,201,snapshot.body); + const report=JSON.parse(snapshot.body).report; + assert.equal(report.snapshotVersion,2); + assert.equal(report.reconciliation.transactionCount,2); + assert.equal(report.reconciliation.excludedTransactionCount,2); + assert.equal(report.transactionIds.length,2); + assert.ok(report.documentIds.includes(ordinaryA.id)&&report.documentIds.includes(ordinaryB.id)); + assert.ok(![exemptA.id,exemptB.id,parentEvidenceA.id].some((id:string)=>report.documentIds.includes(id))); + }); it('records VAT amounts and keeps tax and health-insurance entries out of monthly snapshots',async()=>{ const bad=await invoke('POST','/api/bookkeeping/transactions',{...valid,description:'bad vat',vatAmount:'-1',vatCurrency:'eur'});assert.equal(bad.statusCode,400);assert.deepEqual(JSON.parse(bad.body).fields.sort(),['vatAmount','vatCurrency']); const income=JSON.parse((await invoke('POST','/api/bookkeeping/transactions',{...valid,transactionDate:'2026-09-05',description:'VAT income',entryType:'income',vatAmount:'19.00',vatCurrency:'EUR'})).body); diff --git a/backend/tests/bookkeeping-accountant-report.test.ts b/backend/tests/bookkeeping-accountant-report.test.ts index 06c6b26f..20f4163f 100644 --- a/backend/tests/bookkeeping-accountant-report.test.ts +++ b/backend/tests/bookkeeping-accountant-report.test.ts @@ -220,6 +220,26 @@ describe("native accountant report API", () => { assert.equal(selectAccountantReportRows([ { id: "moved", transactionDate: "2026-10-31", paidDate: "2026-11-02", amount: "30.00", currency: "EUR", entryType: "income" }, ], "2026-10").length, 0); + const parentRefRows = selectAccountantReportRows([ + { + id: "mixed-ref", paidDate: "2026-11-08", amount: "50.00", currency: "EUR", entryType: "expense", + category: "Taxes", reference: "Finanzamt monthly statement", statementRef: "Synthetic Bank", + allocations: [ + { documentId: "doc-host", counterparty: "Synthetic Host", description: "Hosting", amount: "20.00", currency: "EUR", category: "Software" }, + { documentId: "doc-tax", counterparty: "Finanzamt Example", description: "Tax portion", amount: "30.00", currency: "EUR", category: "Taxes" }, + ], + }, + { + id: "ordinary-ref", paidDate: "2026-11-08", amount: "15.00", currency: "EUR", entryType: "expense", + category: "Other", reference: "Finanzamt monthly statement", statementRef: "Synthetic Bank", + }, + ], "2026-11"); + assert.equal(parentRefRows.length, 1); + assert.deepEqual( + [parentRefRows[0].counterparty, parentRefRows[0].description, parentRefRows[0].amount, parentRefRows[0].category, parentRefRows[0].statementRef], + ["Synthetic Host", "Hosting", "20.00", "Software", "Synthetic Bank"], + ); + assert.equal("reference" in parentRefRows[0], false); assert.equal(formatAccountantCsv([ { paidDate: "2026-11-07", transactionDate: "2026-10-30", counterparty: "Synthetic USD Vendor", description: "Converted service", amount: "10.00", amountEur: "9.25", currency: "USD", entryType: "expense" }, ]), '"Date","Company","What","Amount, EUR"\r\n"2026-11-07","Synthetic USD Vendor","Converted service","-9.25"\r\n'); diff --git a/backend/tests/bookkeeping-report-archive.test.ts b/backend/tests/bookkeeping-report-archive.test.ts new file mode 100644 index 00000000..f7af458d --- /dev/null +++ b/backend/tests/bookkeeping-report-archive.test.ts @@ -0,0 +1,360 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { Readable } from "node:stream"; +import { after, before, describe, it } from "node:test"; +import type { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; +import { fromBuffer } from "yauzl"; +import { getClient } from "../src/db/client"; +import { createDocumentLink, getBookkeepingItem, listBookkeepingItems, putBookkeepingItem } from "../src/db/bookkeeping"; +import { createTables, startLocal, stopLocal } from "../scripts/local-dynamodb"; +import { attachProof } from "../src/reconcile/monthService"; +import { handleBookkeepingReportRoutes } from "../src/routes/bookkeepingReports"; +import * as storage from "../src/routes/bookkeepingShared"; + +const COLUMNS = ["transactionDate", "paidDate", "counterparty", "description", "amount", "currency", "amountEur", + "vatAmount", "vatCurrency", "category", "entryType", "statementRef"]; +const QUOTED_ROW = /^(?:"(?:[^"]|"")*")(?:,"(?:[^"]|"")*")*$/; + +// Minimal RFC 4180 reader: quoted cells may hold commas, doubled quotes and line breaks. +function parseCsv(text: string): string[][] { + const rows: string[][] = []; + let row: string[] = [], cell = "", quoted = false; + for (let index = 0; index < text.length; index++) { + const character = text[index]; + if (quoted) { + if (character === '"' && text[index + 1] === '"') { cell += '"'; index++; } + else if (character === '"') quoted = false; + else cell += character; + } else if (character === '"') quoted = true; + else if (character === ",") { row.push(cell); cell = ""; } + else if (character === "\n") { row.push(cell); rows.push(row); row = []; cell = ""; } + else if (character !== "\r") cell += character; + } + if (cell !== "" || row.length) { row.push(cell); rows.push(row); } + return rows; +} + +function unzip(bytes: Buffer): Promise> { + return new Promise((resolve, reject) => fromBuffer(bytes, { lazyEntries: true }, (error, zip) => { + if (error || !zip) return reject(error); + const files: Record = {}; + zip.on("error", reject); + zip.on("end", () => resolve(files)); + zip.on("entry", (entry) => zip.openReadStream(entry, (streamError, stream) => { + if (streamError || !stream) return reject(streamError); + const chunks: Buffer[] = []; + stream.on("error", reject); + stream.on("data", (chunk: Buffer) => chunks.push(chunk)); + stream.on("end", () => { + files[entry.fileName] = Buffer.concat(chunks); + zip.readEntry(); + }); + })); + zip.readEntry(); + })); +} + +describe("portal monthly archive", () => { + let client: DynamoDBDocumentClient; + let writes = 0, signs = 0, uploads = 0, objectReads = 0; + const objects = new Map(); + let archiveBytes: Buffer | undefined; + const originalStorage = { s3: storage.s3, signUrl: storage.signUrl, uploadStream: storage.uploadStream }; + const originalBucket = process.env.BOOKKEEPING_DOCUMENTS_BUCKET; + before(async () => { + process.env.BOOKKEEPING_DOCUMENTS_BUCKET = "synthetic-bookkeeping-documents"; + const underlying = await getClient(await startLocal()); + await createTables(underlying); + client = { send: async (command: any) => { + if (["PutCommand", "UpdateCommand", "DeleteCommand", "TransactWriteCommand"].includes(command.constructor.name)) writes++; + return underlying.send(command); + } } as unknown as DynamoDBDocumentClient; + storage.setBookkeepingStorageForTests({ send: async (command: any) => { + if (command.constructor.name !== "GetObjectCommand") return {}; + objectReads++; + const bytes = objects.get(String(command.input.Key)); + if (!bytes) throw new Error(`synthetic object missing: ${command.input.Key}`); + return { Body: Readable.from([bytes]), VersionId: "synthetic-version" }; + } } as never, async () => { signs++; return "https://invented.example.test/archive"; }); + storage.setBookkeepingArchiveUploaderForTests(async (params: any) => { + uploads++; + const chunks: Buffer[] = []; + for await (const chunk of params.Body) chunks.push(Buffer.from(chunk)); + archiveBytes = Buffer.concat(chunks); + return { VersionId: "synthetic-version" }; + }); + }); + after(async () => { + storage.setBookkeepingStorageForTests(originalStorage.s3, originalStorage.signUrl); + storage.setBookkeepingArchiveUploaderForTests(originalStorage.uploadStream); + if (originalBucket === undefined) delete process.env.BOOKKEEPING_DOCUMENTS_BUCKET; + else process.env.BOOKKEEPING_DOCUMENTS_BUCKET = originalBucket; + await stopLocal(); + }); + const invoke = (path: string, body: unknown = {}) => handleBookkeepingReportRoutes(path, "POST", { + httpMethod: "POST", path, body: JSON.stringify(body), headers: {}, + }, client); + const document = async (id: string, fields: Record = {}) => { + const bytes = Buffer.from(`%PDF-synthetic-${id}`); + objects.set(`documents/${id}`, bytes); + await putBookkeepingItem(client, "document", { + id, documentType: "invoice", status: "active", originalFilename: `${id}.pdf`, contentType: "application/pdf", + byteSize: bytes.length, sha256: createHash("sha256").update(bytes).digest("hex"), s3Key: `documents/${id}`, ...fields, + }); + return { id, bytes }; + }; + const payment = (id: string, row: Record) => + putBookkeepingItem(client, "bookkeeping", { id, currency: "EUR", entryType: "expense", ...row }); + // The readiness gate only exports payments whose source is verified. + const verify = async (transactionId: string, month: string) => { + const proof = await document(`arch-proof-${transactionId}`, { documentType: "receipt" }); + await createDocumentLink(client, { documentId: proof.id, transactionId, coverageType: "evidence" }); + await attachProof(client, month, "invented-operator", transactionId, proof.id); + return proof; + }; + const statements = async (month: string) => { + const ids: string[] = []; + for (const [index, id] of ["invented-archive-business-one", "invented-archive-business-two"].entries()) { + if (!await getBookkeepingItem(client, "account", id)) await putBookkeepingItem(client, "account", { id, kind: "business", active: true }); + ids.push((await document(`arch-statement-${index}-${month}`, { documentType: "bank-statement", accountId: id, statementMonth: month })).id); + } + return ids; + }; + const reset = () => { writes = signs = uploads = objectReads = 0; archiveBytes = undefined; }; + const counters = () => ({ writes, signs, uploads, objectReads }); + const untouched = { writes: 0, signs: 0, uploads: 0, objectReads: 0 }; + // The ledger and its evidence documents are the financial records an archive must never change. + const financialRecords = async () => ({ + ledger: await listBookkeepingItems(client, "bookkeeping"), + documents: (await listBookkeepingItems(client, "document")).filter((item) => item.documentType !== "monthly-report"), + }); + async function archive(reportId: string, month: string) { + reset(); + const response = await invoke(`/api/bookkeeping/reports/${reportId}/archive`); + const files = archiveBytes ? await unzip(archiveBytes) : {}; + return { response, body: JSON.parse(response!.body), files, csv: files[`datatalksclub-${month}.csv`]?.toString("utf8") || "" }; + } + const byCounterparty = (left: string[], right: string[]) => left[2].localeCompare(right[2]); + + it("archives reportable allocation children with their totals, labels and evidence instead of the parent payment", async () => { + const month = "2037-03"; + const statementIds = await statements(month); + const [a1, taxA, a3, taxB, b, plainReceipt] = await Promise.all([ + document("arch-a1"), document("arch-tax-a"), document("arch-a3"), document("arch-tax-b"), document("arch-b"), + document("arch-plain-receipt", { documentType: "receipt" }), + ]); + const parentA = (await payment("invented-archive-parent-a", { + transactionDate: `${month}-02`, paidDate: `${month}-03`, counterparty: "Synthetic combined payee A", description: "Synthetic tax settlement", + amount: "60.00", amountEur: "60.00", category: "Taxes", mandatoryKind: "tax_debit", statementRef: "BANK-A 0001", + allocations: [ + { id: "a1", documentId: a1.id, counterparty: "Synthetic service A1", description: "Service A1", amount: "10.00", amountEur: "10.00", currency: "EUR", category: "Software" }, + { id: "tax-a", documentId: taxA.id, counterparty: "Synthetic tax A", description: "Tax A", amount: "21.00", amountEur: "21.00", currency: "EUR", category: "Taxes" }, + { id: "a3", documentId: a3.id, counterparty: "Synthetic service A3", description: "Service A3", amount: "29.00", amountEur: "29.00", currency: "EUR", category: "Consulting" }, + ], + })).item; + const parentB = (await payment("invented-archive-parent-b", { + transactionDate: `${month}-04`, paidDate: `${month}-04`, counterparty: "Synthetic combined payee B", description: "Synthetic owner draw", + amount: "70.00", amountEur: "70.00", category: "Owner pay", ownerPayType: "draw", statementRef: "BANK-A 0002", + allocations: [ + { id: "tax-b", documentId: taxB.id, counterparty: "Synthetic tax B", description: "Tax B", amount: "31.00", amountEur: "31.00", currency: "EUR", category: "Taxes" }, + { id: "b", documentId: b.id, counterparty: "Synthetic service B", description: "Service B", amount: "39.00", amountEur: "39.00", currency: "EUR", category: "Software" }, + ], + })).item; + const plain = (await payment("invented-archive-plain", { + transactionDate: `${month}-05`, paidDate: `${month}-05`, counterparty: "Synthetic plain vendor", description: "Plain service", + amount: "5.00", category: "Software", statementRef: "BANK-A 0003", + })).item; + // Parent-level evidence is the payment's verification; it belongs to no child. + const parentProofA = await verify(parentA.id, month); + // A payment booked from its bank statement is verified by the bank row alone + // and has no parent-level evidence link at all. + await putBookkeepingItem(client, "statement", { + recordType: "reconcile-statement", accountId: "finom", period: month, filename: "synthetic-statement.csv", + from: `${month}-01`, to: `${month}-31`, + rows: [{ date: `${month}-04`, amount: "-70.00", currency: "EUR", counterparty: "Synthetic combined payee B", reference: "BANK-A 0002" }], + }); + await createDocumentLink(client, { documentId: plainReceipt.id, transactionId: plain.id, coverageType: "evidence" }); + await attachProof(client, month, "invented-operator", plain.id, plainReceipt.id); + + const snapshot = await invoke("/api/bookkeeping/reports/snapshot", { + month, privateDocumentIds: [taxA.id, taxB.id, parentProofA.id], + }); + assert.equal(snapshot.statusCode, 201, snapshot.body); + const report = JSON.parse(snapshot.body).report; + assert.equal(report.snapshotVersion, 2, "the snapshot stays an ID list; nothing is migrated"); + assert.deepEqual([...report.transactionIds].sort(), [parentA.id, parentB.id, plain.id].sort(), "transaction references stay the three ledger payments"); + assert.deepEqual([...report.documentIds].sort(), [a1.id, a3.id, b.id, plainReceipt.id, ...statementIds].sort(), + "document references are the reportable children's own documents, the plain receipt and the statements"); + assert.equal(report.reconciliation.transactionCount, 4, "the snapshot counts the rows the archive lists"); + assert.equal(report.reconciliation.excludedTransactionCount, 2); + assert.equal(JSON.parse(snapshot.body).warnings.missingEvidence, 0, "each reportable child is evidenced by its own allocation document"); + + const before = await financialRecords(); + const result = await archive(report.id, month); + assert.equal(result.response.statusCode, 201, result.response.body); + assert.equal(uploads, 1); + assert.deepEqual(Object.keys(result.files).sort(), [ + `datatalksclub-${month}.csv`, + ...[a1, a3, b, plainReceipt, ...statementIds.map((id) => ({ id }))].map(({ id }) => `documents/${id}.pdf`), + ].sort(), "evidence is the reportable children's own documents, the plain receipt and the statements"); + for (const { id, bytes } of [a1, a3, b, plainReceipt]) + assert.equal(result.files[`documents/${id}.pdf`]?.toString(), bytes.toString(), `${id} keeps its own bytes`); + + const rows = parseCsv(result.csv); + assert.deepEqual(rows[0], COLUMNS, "the archive keeps the twelve-column ledger format and its header line"); + assert.ok(result.csv.split("\n").filter(Boolean).slice(1).every((line) => QUOTED_ROW.test(line)), "every data cell stays quoted"); + const listed = rows.slice(1); + assert.equal(listed.length, 4); + assert.equal(listed.reduce((sum, row) => sum + Math.round(Number(row[4]) * 100), 0) / 100, 83, + "10 + 29 + 39 + 5: the parent totals never reach the accountant"); + assert.deepEqual([...listed].sort(byCounterparty), [ + [`${month}-05`, `${month}-05`, "Synthetic plain vendor", "Plain service", "5.00", "EUR", "", "", "", "Software", "expense", "BANK-A 0003"], + [`${month}-02`, `${month}-03`, "Synthetic service A1", "Service A1", "10.00", "EUR", "10.00", "", "", "Software", "expense", "BANK-A 0001"], + [`${month}-02`, `${month}-03`, "Synthetic service A3", "Service A3", "29.00", "EUR", "29.00", "", "", "Consulting", "expense", "BANK-A 0001"], + [`${month}-04`, `${month}-04`, "Synthetic service B", "Service B", "39.00", "EUR", "39.00", "", "", "Software", "expense", "BANK-A 0002"], + ].sort(byCounterparty), "child rows carry the payment's dates, direction and bank reference with each child's own label, amount and category"); + assert.ok(listed.findIndex((row) => row[2] === "Synthetic service A1") < listed.findIndex((row) => row[2] === "Synthetic service A3"), + "children of one payment keep their saved allocation order"); + for (const withheld of ["Synthetic combined payee", "Synthetic tax settlement", "Synthetic owner draw", "Synthetic tax A", "Synthetic tax B", + "60.00", "70.00", "21.00", "31.00", '"Taxes"', '"Owner pay"']) + assert.equal(result.csv.includes(withheld), false, `the archive leaves out ${withheld}`); + assert.deepEqual(await financialRecords(), before, "generating the archive changes no ledger row and no evidence document"); + + const stored = await getBookkeepingItem(client, "report", report.id); + assert.equal(stored?.status, "generated"); + assert.equal(stored?.snapshotVersion, 2); + assert.deepEqual(stored?.transactionIds, report.transactionIds, "the report keeps its transaction references"); + assert.deepEqual(stored?.documentIds, report.documentIds, "the report keeps its document references"); + assert.equal((await getBookkeepingItem(client, "document", String(stored?.archiveDocumentId)))?.documentType, "monthly-report"); + + const cached = await archive(report.id, month); + assert.equal(cached.response.statusCode, 200); + assert.equal(cached.body.duplicate, true); + assert.deepEqual(counters(), { ...untouched, signs: 1 }, "an archived report is served as stored and never rebuilt"); + }); + + it("keeps payment direction, cash dates and cell format on children of a converted foreign-currency payment", async () => { + const month = "2037-05"; + await statements(month); + // The third child's invoice upload never completed, so it is not an active document. + const [first, second, pending] = await Promise.all([ + document("arch-usd-first"), document("arch-usd-second"), document("arch-usd-pending", { status: "pending" }), + ]); + const parent = (await payment("invented-archive-usd", { + transactionDate: `${month}-10`, paidDate: `${month}-11`, counterparty: "Synthetic card settlement", description: "Combined synthetic income", + entryType: "income", amount: "100.00", amountEur: "90.00", currency: "USD", vatAmount: "19.00", vatCurrency: "USD", statementRef: "CARD 77", + allocations: [ + { id: "first", documentId: first.id, counterparty: 'Synthetic client "one"', description: 'Talk "Q1",\nretainer', amount: "60.00", currency: "USD", amountEur: "54.00", + vatAmount: "11.40", vatCurrency: "USD", category: "Work-related", transactionDate: "2037-04-20", paidDate: "2037-04-28" }, + { id: "second", documentId: second.id, counterparty: "Synthetic client two", description: "Workshop two", amount: "25.00", currency: "USD", amountEur: "22.50", category: "Work-related" }, + { id: "third", documentId: pending.id, counterparty: "Synthetic client three", description: "Workshop three", amount: "15.00", currency: "USD", amountEur: "13.50", category: "Work-related" }, + ], + })).item; + await verify(parent.id, month); + const snapshot = await invoke("/api/bookkeeping/reports/snapshot", { month }); + assert.equal(snapshot.statusCode, 201, snapshot.body); + assert.equal(JSON.parse(snapshot.body).warnings.missingEvidence, 1, "a child whose allocation document is unavailable is the one missing evidence"); + const result = await archive(JSON.parse(snapshot.body).report.id, month); + assert.equal(result.response.statusCode, 201, result.response.body); + assert.deepEqual(Object.keys(result.files).sort(), [ + `datatalksclub-${month}.csv`, `documents/${first.id}.pdf`, `documents/${second.id}.pdf`, + ...[0, 1].map((index) => `documents/arch-statement-${index}-${month}.pdf`), + ].sort(), "only active allocation documents ship"); + assert.deepEqual(parseCsv(result.csv).slice(1), [ + [`${month}-10`, `${month}-11`, 'Synthetic client "one"', 'Talk "Q1",\nretainer', "60.00", "USD", "54.00", "11.40", "USD", "Work-related", "income", "CARD 77"], + [`${month}-10`, `${month}-11`, "Synthetic client two", "Workshop two", "25.00", "USD", "22.50", "", "", "Work-related", "income", "CARD 77"], + [`${month}-10`, `${month}-11`, "Synthetic client three", "Workshop three", "15.00", "USD", "13.50", "", "", "Work-related", "income", "CARD 77"], + ], "children use the payment's cash dates, unsigned amounts with the payment's entry type, their own EUR value and VAT, and the payment's bank reference"); + assert.equal(result.csv.includes("2037-04"), false, "invoice-level allocation dates never replace the payment date"); + assert.equal(result.csv.includes("19.00"), false, "the parent's VAT total is not copied onto a child"); + assert.equal(result.csv.includes("100.00") || result.csv.includes("90.00"), false, "the parent total is not listed beside its children"); + assert.match(result.csv, /"Synthetic client ""one""","Talk ""Q1"",\nretainer","60.00"/, "cells stay quoted with doubled quotes and kept line breaks"); + assert.ok(result.csv.endsWith("\n") && !result.csv.includes("\r"), "line endings stay as contracted"); + }); + + it("renders an older ID-list report by child without rewriting the snapshot or the ledger", async () => { + const month = "2037-06"; + await statements(month); + const [reportable, exempt] = await Promise.all([document("arch-old-reportable"), document("arch-old-exempt")]); + // A snapshot prepared while classification ran on the parent: the payment was + // selected and counted as one ordinary transaction. + await payment("invented-archive-old-parent", { + transactionDate: `${month}-07`, paidDate: `${month}-07`, counterparty: "Synthetic old payee", description: "Old combined payment", + amount: "50.00", category: "Software", statementRef: "BANK-A 0007", + allocations: [ + { id: "old-reportable", documentId: reportable.id, counterparty: "Synthetic old service", description: "Old service", amount: "18.00", amountEur: "18.00", currency: "EUR", category: "Software" }, + { id: "old-exempt", documentId: exempt.id, counterparty: "Synthetic old tax", description: "Old tax", amount: "32.00", amountEur: "32.00", currency: "EUR", category: "Taxes" }, + ], + }); + await verify("invented-archive-old-parent", month); + const storedBefore = (await putBookkeepingItem(client, "report", { + id: "invented-archive-old-report", month, status: "ready", snapshotVersion: 2, + transactionIds: ["invented-archive-old-parent"], documentIds: [reportable.id, exempt.id], + reconciliation: { transactionCount: 1, excludedTransactionCount: 0, documentCount: 2, businessStatementCount: 2 }, + })).item; + const before = await financialRecords(); + const result = await archive(storedBefore.id, month); + assert.equal(result.response.statusCode, 201, result.response.body); + assert.deepEqual(parseCsv(result.csv).slice(1), [ + [`${month}-07`, `${month}-07`, "Synthetic old service", "Old service", "18.00", "EUR", "18.00", "", "", "Software", "expense", "BANK-A 0007"], + ], "the exempt child's share is no longer shipped inside a parent total"); + assert.ok(Object.keys(result.files).includes(`documents/${exempt.id}.pdf`), "the documents a stored snapshot selected are served as stored"); + assert.deepEqual(await financialRecords(), before); + const stored = await getBookkeepingItem(client, "report", storedBefore.id); + assert.equal(stored?.status, "generated"); + assert.equal(stored?.snapshotVersion, 2, "the stored snapshot is not migrated or re-versioned"); + assert.deepEqual(stored?.transactionIds, storedBefore.transactionIds); + assert.deepEqual(stored?.documentIds, storedBefore.documentIds); + assert.deepEqual(stored?.reconciliation, storedBefore.reconciliation, "the recorded counts stay the historical record"); + }); + + it("refuses to archive a snapshot whose payment has no reportable child left, before any write", async () => { + const month = "2037-07"; + await statements(month); + const exempt = await document("arch-stale-exempt"); + await payment("invented-archive-stale-parent", { + transactionDate: `${month}-08`, paidDate: `${month}-08`, counterparty: "Synthetic stale payee", description: "Stale combined payment", + amount: "12.00", category: "Software", + allocations: [{ id: "stale-exempt", documentId: exempt.id, counterparty: "Synthetic stale tax", description: "Stale tax", amount: "12.00", amountEur: "12.00", currency: "EUR", category: "Taxes" }], + }); + await verify("invented-archive-stale-parent", month); + const stored = (await putBookkeepingItem(client, "report", { + id: "invented-archive-stale-report", month, status: "ready", snapshotVersion: 2, + transactionIds: ["invented-archive-stale-parent"], documentIds: [exempt.id], + reconciliation: { transactionCount: 1, excludedTransactionCount: 0, documentCount: 1, businessStatementCount: 2 }, + })).item; + const before = await financialRecords(); + const result = await archive(stored.id, month); + assert.equal(result.response.statusCode, 409, result.response.body); + assert.equal(result.body.reportPeriod, month); + assert.deepEqual(result.body.staleTransactionIds, ["invented-archive-stale-parent"]); + assert.match(result.body.error, /reportable invoice allocation/i); + assert.deepEqual(counters(), untouched); + assert.deepEqual(await getBookkeepingItem(client, "report", stored.id), stored); + assert.deepEqual(await financialRecords(), before); + }); + + it("refuses to archive a snapshot with a foreign-currency child that has no EUR value, before any write", async () => { + const month = "2037-08"; + await statements(month); + const child = await document("arch-unconverted-child"); + await payment("invented-archive-unconverted-parent", { + transactionDate: `${month}-09`, paidDate: `${month}-09`, counterparty: "Synthetic unconverted payee", description: "Unconverted combined payment", + amount: "20.00", amountEur: "18.00", currency: "USD", + allocations: [{ id: "unconverted-child", documentId: child.id, counterparty: "Synthetic unconverted service", description: "Unconverted service", amount: "20.00", currency: "USD", category: "Software" }], + }); + await verify("invented-archive-unconverted-parent", month); + const stored = (await putBookkeepingItem(client, "report", { + id: "invented-archive-unconverted-report", month, status: "ready", snapshotVersion: 2, + transactionIds: ["invented-archive-unconverted-parent"], documentIds: [child.id], + reconciliation: { transactionCount: 1, excludedTransactionCount: 0, documentCount: 1, businessStatementCount: 2 }, + })).item; + const result = await archive(stored.id, month); + assert.equal(result.response.statusCode, 409, result.response.body); + assert.equal(result.body.reportPeriod, month); + assert.deepEqual(result.body.unconvertedTransactionIds, ["invented-archive-unconverted-parent"]); + assert.match(result.body.error, /no EUR value; convert them before preparing the package/); + assert.deepEqual(counters(), untouched); + assert.equal((await getBookkeepingItem(client, "report", stored.id))?.status, "ready"); + }); +}); diff --git a/backend/tests/bookkeeping-reporting.test.ts b/backend/tests/bookkeeping-reporting.test.ts new file mode 100644 index 00000000..bef4a6fa --- /dev/null +++ b/backend/tests/bookkeeping-reporting.test.ts @@ -0,0 +1,36 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { isReportExemptTransaction } from "../src/db/bookkeeping"; +import { accountantReportRows, formatAccountantCsv } from "../src/routes/bookkeepingAccountantReport"; + +const alloc = (id: string, documentId: string, counterparty: string, description: string, amount: string, category: string) => + ({ id, documentId, counterparty, description, amount, amountEur: amount, currency: "EUR", category }); + +test("mixed allocations are classified per child regardless of parent markers", () => { + const payments = [ + { id: "synthetic-parent-tax", transactionDate: "2026-11-02", paidDate: "2026-11-03", counterparty: "Synthetic combined payee A", + description: "Synthetic tax settlement", amount: "30.00", amountEur: "30.00", currency: "EUR", entryType: "expense", + category: "Taxes", mandatoryKind: "tax_debit", kind: "tax_debit", + allocations: [alloc("a1", "doc-a", "Synthetic software", "Service A", "10.00", "Software"), + alloc("a2", "doc-x-a", "Synthetic tax office", "Tax A", "20.00", "Taxes")] }, + { id: "synthetic-parent-owner", transactionDate: "2026-11-04", paidDate: "2026-11-04", counterparty: "Synthetic combined payee B", + description: "Synthetic owner draw", amount: "70.00", amountEur: "70.00", currency: "EUR", entryType: "expense", + category: "Owner pay", ownerPayType: "draw", + allocations: [alloc("b1", "doc-x-b", "Synthetic tax office", "Tax B", "30.00", "Taxes"), + alloc("b2", "doc-b", "Synthetic hosting", "Service B", "40.00", "Software")] }, + { id: "synthetic-all-exempt", transactionDate: "2026-11-05", counterparty: "Synthetic payee C", description: "Tax C", + amount: "5.00", amountEur: "5.00", currency: "EUR", entryType: "expense", category: "Software", + allocations: [alloc("c1", "doc-c", "Synthetic tax office", "Tax C", "5.00", "Taxes")] }, + ]; + assert.equal(isReportExemptTransaction(payments[0]), false); + assert.equal(isReportExemptTransaction(payments[1]), false); + assert.equal(isReportExemptTransaction(payments[2]), true); + const rows = accountantReportRows(payments); + assert.ok(rows.every((row) => row.id === (row.sourceTransactionId as string)), "child keeps parent id for omit lookups"); + const included = rows.filter((row) => !isReportExemptTransaction(row)); + assert.deepEqual(included.map((r) => [r.counterparty, r.amount, r.category, r.allocationDocumentId]), [ + ["Synthetic software", "10.00", "Software", "doc-a"], ["Synthetic hosting", "40.00", "Software", "doc-b"]]); + const csv = formatAccountantCsv(included); + assert.ok(csv.includes("Synthetic software") && csv.includes("Synthetic hosting")); + assert.ok(!csv.includes("Synthetic tax office") && !csv.includes("20.00") && !csv.includes("30.00")); +}); diff --git a/frontend/src/surfaces/finance/bookkeeping-format.js b/frontend/src/surfaces/finance/bookkeeping-format.js index 1e0fc566..a732bb1c 100644 --- a/frontend/src/surfaces/finance/bookkeeping-format.js +++ b/frontend/src/surfaces/finance/bookkeeping-format.js @@ -164,31 +164,90 @@ export function isReportExempt(entry) { || isOwnerWithdrawalReportExempt(entry); } +// Keys of the payment itself: its classification markers, free-text reference, +// and saved allocations. A child is classified on its own category and text, +// never on what the payment carried; bank statementRef stays on the child. +const PAYMENT_ONLY_KEYS = ["mandatoryKind", "ownerPayType", "kind", "taxType", "reference", "allocations"]; + +// Mirror of the backend mandatory-payment text. A child inherits no mandatory +// markers or parent reference, so its own counterparty and description decide. +const MANDATORY_TEXT = [ + /techniker\s*krankenkasse|krankenkasse|\btk\b/i, + /finanzamt|bundeskasse|steuerverwaltung/i, +]; + +/** Saved invoice allocations complete enough to become report rows. */ +function reportAllocations(entry) { + if (!Array.isArray(entry?.allocations)) return []; + return entry.allocations.filter( + (allocation) => + allocation && + typeof allocation === "object" && + ["documentId", "counterparty", "description", "amount"].every( + (field) => String(allocation[field] || "").trim(), + ), + ); +} + /** Expand persisted allocations for package counts and previews. The parent remains the only ledger transaction. */ export function expandReportEntries(entries) { return (Array.isArray(entries) ? entries : []).flatMap((entry) => { - const allocations = Array.isArray(entry.allocations) ? entry.allocations : []; + const allocations = reportAllocations(entry); if (!allocations.length) return [entry]; - return allocations.map((allocation) => ({ - ...entry, - ...allocation, - sourceTransactionId: entry.id, - transactionDate: allocation.transactionDate || entry.transactionDate, - paidDate: allocation.paidDate || entry.paidDate, - counterparty: allocation.counterparty || entry.counterparty, - description: allocation.description || entry.description, - amount: allocation.amount, - currency: allocation.currency || entry.currency, - amountEur: allocation.amountEur, - category: allocation.category || entry.category, - subtype: allocation.subtype || entry.subtype, - invoiceNumber: allocation.invoiceNumber, - allocationDocumentId: allocation.documentId, - allocations: undefined, - })); + return allocations.map((allocation) => { + const child = { + ...entry, + sourceTransactionId: entry.id, + transactionDate: allocation.transactionDate || entry.transactionDate, + paidDate: allocation.paidDate || entry.paidDate, + counterparty: allocation.counterparty, + description: allocation.description, + amount: allocation.amount, + currency: allocation.currency || entry.currency, + amountEur: allocation.amountEur, + vatAmount: allocation.vatAmount, + vatCurrency: allocation.vatCurrency, + category: allocation.category || entry.category, + subtype: allocation.subtype || entry.subtype, + invoiceId: allocation.invoiceId, + invoiceNumber: allocation.invoiceNumber, + allocationDocumentId: allocation.documentId, + }; + for (const key of PAYMENT_ONLY_KEYS) delete child[key]; + return child; + }); }); } +/** Whether a child row is kept out of the package on its own category and text. */ +function isReportExemptChild(row) { + const category = String(row?.category || "").trim().toLowerCase(); + if (["taxes", "health insurance", "vat"].includes(category)) return true; + const text = [row?.counterparty, row?.description, row?.reference] + .map((value) => (value == null ? "" : String(value))) + .join(" "); + return MANDATORY_TEXT.some((pattern) => pattern.test(text)); +} + +/** + * The rows the monthly package lists, mirroring the backend snapshot: a + * payment with saved invoice allocations as its children, each listed or kept + * out on its own; any other entry as itself under the caller's rule. + */ +export function selectReportEntries(entries, isExemptEntry) { + const included = []; + const excluded = []; + for (const entry of Array.isArray(entries) ? entries : []) { + const children = reportAllocations(entry).length ? expandReportEntries([entry]) : []; + if (!children.length) { + (isExemptEntry(entry) ? excluded : included).push(entry); + continue; + } + for (const child of children) (isReportExemptChild(child) ? excluded : included).push(child); + } + return { included, excluded }; +} + // Format full raw ledger entries matching the backend snapshot format. export function formatFullCsv(entries) { const columns = [ diff --git a/frontend/src/surfaces/finance/bookkeeping-reporting.js b/frontend/src/surfaces/finance/bookkeeping-reporting.js index 1be7bf48..dd939048 100644 --- a/frontend/src/surfaces/finance/bookkeeping-reporting.js +++ b/frontend/src/surfaces/finance/bookkeeping-reporting.js @@ -1,5 +1,5 @@ // Package and VAT views for the bookkeeping surface. -import { formatAmount, monthLabel } from "./bookkeeping-format.js"; +import { formatAmount, monthLabel, selectReportEntries } from "./bookkeeping-format.js"; import { eurValue } from "./bookkeeping-ledger.js"; import { packageReviewMarkup } from "./bookkeeping-views.js"; import { html } from "./shared.js"; @@ -43,17 +43,32 @@ export function createBookkeepingReports({ (!account.statementRequiredThroughMonth || lens <= account.statementRequiredThroughMonth), ); - const monthEntries = lensEntries().filter((entry) => !isReportExemptEntry(entry)); + // The package lists reportable allocation children, never payment totals. + const { included: monthEntries, excluded: excludedEntries } = + selectReportEntries(lensEntries(), isReportExemptEntry); const unconverted = monthEntries.filter((entry) => eurValue(entry) === null); surface.querySelector("[data-report]").disabled = !isMonth || unconverted.length > 0; - const excludedCount = lensEntries().filter(isReportExemptEntry).length; + const excludedCount = excludedEntries.length; + // An ordinary entry is evidenced by its own links. Evidence of an + // allocated payment comes from its reportable children's allocation + // documents; parent-level links are not attributable to a child. const linkedDocIds = new Set( links - .filter((link) => monthEntries.some((entry) => entry.id === link.transactionId)) + .filter((link) => + monthEntries.some((entry) => !entry.sourceTransactionId && entry.id === link.transactionId), + ) .map((link) => String(link.documentId)), ); + const allocationDocIds = new Set( + monthEntries + .filter((entry) => entry.sourceTransactionId) + .map((entry) => String(entry.allocationDocumentId)), + ); const evidenceDocs = documents.filter( - (document) => document.documentType !== "bank-statement" && linkedDocIds.has(document.id), + (document) => + document.documentType !== "bank-statement" && + (linkedDocIds.has(document.id) || + (document.status === "active" && allocationDocIds.has(String(document.id)))), ); const statementStates = businessAccounts.map((account) => ({ account, diff --git a/frontend/test/bookkeeping-reporting.test.mjs b/frontend/test/bookkeeping-reporting.test.mjs index 50c4e43b..e887c547 100644 --- a/frontend/test/bookkeeping-reporting.test.mjs +++ b/frontend/test/bookkeeping-reporting.test.mjs @@ -2,7 +2,11 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { escapeHtml } from "../src/core/html.js"; -import { expandReportEntries, isReportExempt } from "../src/surfaces/finance/bookkeeping-format.js"; +import { + expandReportEntries, + isReportExempt, + selectReportEntries, +} from "../src/surfaces/finance/bookkeeping-format.js"; import { createBookkeepingReports } from "../src/surfaces/finance/bookkeeping-reporting.js"; test("current package preflight omits legacy accounts after their statement period", () => { @@ -87,7 +91,7 @@ test("the package button stays disabled while a row has no EUR value", () => { assert.match(nodes.get("[data-package-review]").innerHTML, /without a EUR value/); }); -test("package preview expands one payment into invoice rows while keeping exempt owner and tax rows out", () => { +test("report rows expand one payment into invoice rows while keeping exempt owner and tax rows out", () => { const entries = [ { id: "synthetic-payment-123", @@ -189,6 +193,206 @@ test("package preview expands one payment into invoice rows while keeping exempt assert.equal(reportRows[3].amount, "238.00"); }); +test("report children are classified on their own category and text, never on the payment's markers or reference", () => { + const payment = { + id: "synthetic-mixed-payment", transactionDate: "2026-10-18", paidDate: "2026-10-18", + counterparty: "Synthetic Card Settlement", description: "Combined settlement", + amount: "240.00", currency: "EUR", entryType: "expense", category: "Health Insurance", + subtype: "Insurance", mandatoryKind: "tk_debit", taxType: "health-insurance", ownerPayType: "unknown", + reference: "Finanzamt monthly statement", statementRef: "Synthetic Bank", vatAmount: "40.00", vatCurrency: "EUR", + allocations: [ + { id: "alloc-software", documentId: "synthetic-document-1", invoiceNumber: "INV-1", counterparty: "Synthetic Software GmbH", description: "Hosting", amount: "200.00", currency: "EUR", category: "Software" }, + { id: "alloc-tax", documentId: "synthetic-document-2", counterparty: "Finanzamt Example", description: "USt prepayment", amount: "40.00", currency: "EUR", vatAmount: "6.40", vatCurrency: "EUR" }, + { id: "alloc-incomplete", documentId: "synthetic-document-3" }, + ], + }; + const { included, excluded } = selectReportEntries([payment], isReportExempt); + + assert.deepEqual(included.map((r) => [r.counterparty, r.amount, r.category, r.sourceTransactionId]), [ + ["Synthetic Software GmbH", "200.00", "Software", "synthetic-mixed-payment"], + ]); + assert.deepEqual(excluded.map((r) => [r.counterparty, r.category, r.vatAmount]), [ + ["Finanzamt Example", "Health Insurance", "6.40"], + ]); + const [child] = included; + assert.equal(child.id, "synthetic-mixed-payment"); + for (const marker of ["mandatoryKind", "taxType", "ownerPayType", "kind", "reference", "allocations"]) + assert.equal(marker in child, false, marker); + assert.equal(child.statementRef, "Synthetic Bank"); + assert.equal(child.vatAmount, undefined); + assert.equal(child.subtype, "Insurance"); + assert.equal(child.allocationDocumentId, "synthetic-document-1"); + + // Parent reference "Finanzamt monthly statement" must not drop a Software/Hosting child, + // while an ordinary row with that reference stays exempt when the caller checks reference. + const refPayment = { + id: "mixed-ref", transactionDate: "2026-10-18", counterparty: "Card", description: "Combined", + amount: "50.00", currency: "EUR", entryType: "expense", category: "Taxes", + reference: "Finanzamt monthly statement", statementRef: "Synthetic Bank", + allocations: [ + { id: "a1", documentId: "d1", counterparty: "Synthetic Host", description: "Hosting", amount: "20.00", currency: "EUR", category: "Software" }, + { id: "a2", documentId: "d2", counterparty: "Finanzamt Example", description: "Tax portion", amount: "30.00", currency: "EUR", category: "Taxes" }, + ], + }; + const ordinaryWithRef = { + id: "ordinary-ref", transactionDate: "2026-10-18", counterparty: "Other", description: "Fee", + amount: "15.00", currency: "EUR", entryType: "expense", category: "Other", reference: "Finanzamt monthly statement", + }; + const isExemptWithRef = (e) => isReportExempt(e) || /finanzamt/i.test(String(e?.reference || "")); + const refResult = selectReportEntries([refPayment, ordinaryWithRef], isExemptWithRef); + assert.deepEqual(refResult.included.map((r) => [r.counterparty, r.amount, r.statementRef]), [ + ["Synthetic Host", "20.00", "Synthetic Bank"], + ]); + assert.equal(refResult.excluded.length, 2); + + // A payment whose saved allocations are all incomplete stays one ordinary row. + const incomplete = { ...payment, allocations: [{ id: "alloc-incomplete", documentId: "synthetic-document-3" }] }; + assert.deepEqual(selectReportEntries([incomplete], () => false), { included: [incomplete], excluded: [] }); + assert.deepEqual(selectReportEntries([incomplete], () => true), { included: [], excluded: [incomplete] }); +}); + +// ---- package preview -------------------------------------------------------- + +const statementDocuments = ["revolut", "finom"].map((accountId) => ({ + id: `${accountId}-statement`, documentType: "bank-statement", accountId, statementMonth: "2026-10", status: "active", +})); +const doc = (id, overrides = {}) => ({ id, documentType: "invoice", status: "active", ...overrides }); +const alloc = (id, documentId, counterparty, description, amount, extra = {}) => ({ + id, documentId, counterparty, description, amount, currency: "EUR", ...extra, +}); +const tx = (id, counterparty, description, amount, category, extra = {}) => ({ + id, transactionDate: "2026-10-18", paidDate: "2026-10-18", counterparty, description, + amount, currency: "EUR", entryType: "expense", category, ...extra, +}); + +function renderPreview({ entries, links = [], documents = [], reports = [] }) { + const nodes = new Map([ + ["[data-package-review]", { innerHTML: "" }], + ["[data-report-month]", { value: "" }], + ["[data-report]", { disabled: true }], + ]); + createBookkeepingReports({ + api: async () => ({}), + escapeHtml, + getAccounts: () => ["revolut", "finom"].map((id) => ({ id, displayName: id, kind: "business", active: true })), + getDocuments: () => [...statementDocuments, ...documents], + getLens: () => "2026-10", + getLinks: () => links, + getReports: () => reports, + isReportExemptEntry: (entry) => isReportExempt(entry) || entry.id === "tx-summary-tax", + lensEntries: () => entries, + safeAction: async (action) => action(), + surface: { querySelector: (selector) => nodes.get(selector) }, + }).renderPackageReview(); + return { markup: nodes.get("[data-package-review]").innerHTML, button: nodes.get("[data-report]") }; +} + +function previewCounts(markup) { + const preview = markup.match(/

([\s\S]*?)<\/p>/)?.[1] || ""; + return [...preview.matchAll(/(\d+)<\/span>/g)].map((m) => Number(m[1])); +} + +const mixedPayment = tx("synthetic-card-settlement", "Synthetic Card Settlement", "Combined settlement", "600.00", "Tools", { + allocations: [ + alloc("alloc-compute", "doc-compute", "Synthetic Compute GmbH", "Dedicated cluster October", "500.00", { category: "Infrastructure" }), + alloc("alloc-mail", "doc-mail", "Synthetic Mail B.V.", "Transactional email usage", "40.00", { category: "Tools" }), + alloc("alloc-health", "doc-health", "Synthetic Health Insurance", "October premium", "60.00", { category: "Health Insurance" }), + ], +}); +const ordinaryEntries = [ + tx("tx-consulting", "Synthetic Tax Advisory GmbH", "Monthly compliance consulting fee", "238.00", "Compliance & Taxes"), + tx("tx-owner", "Owner Person", "Owner withdrawal", "1200.00", "Owner pay", { ownerPayType: "draw" }), + tx("tx-summary-tax", "Synthetic Bank", "Sweep transfer", "1500.00", "Bank"), +]; + +test("package preview lists reportable children, active allocation docs, and ignores parent links", () => { + const { markup, button } = renderPreview({ + entries: [mixedPayment, ...ordinaryEntries], + links: [ + { transactionId: "tx-consulting", documentId: "doc-consulting", coverageType: "evidence" }, + { transactionId: "synthetic-card-settlement", documentId: "doc-payment-proof", coverageType: "evidence" }, + ], + documents: ["doc-compute", "doc-mail", "doc-health", "doc-consulting", "doc-payment-proof"].map((id) => doc(id)), + }); + assert.deepEqual(previewCounts(markup), [3, 3, 3]); + assert.doesNotMatch(markup, /without a EUR value/); + assert.equal(button.disabled, false); + + // Counts only active allocation documents (voided excluded) and no parent-level links. + const voidedCheck = renderPreview({ + entries: [tx("synthetic-evidence-payment", "Card", "Settlement", "120.00", "Tools", { + allocations: [ + alloc("a-void", "doc-voided", "Voided GmbH", "Voided", "100.00"), + alloc("a-live", "doc-live", "Live GmbH", "Live", "20.00"), + ], + })], + links: [ + { transactionId: "synthetic-evidence-payment", documentId: "doc-parent-link", coverageType: "evidence" }, + { transactionId: "synthetic-evidence-payment", documentId: "doc-live", coverageType: "evidence" }, + ], + documents: [doc("doc-voided", { status: "voided" }), doc("doc-live"), doc("doc-parent-link")], + }); + assert.deepEqual(previewCounts(voidedCheck.markup), [2, 1, 0]); + assert.equal(voidedCheck.button.disabled, false); +}); + +test("package preview handles exempt parent markers/reference, all-exempt children, and ready fallback", () => { + const exemptParent = renderPreview({ + entries: [tx("p-exempt", "Card", "Split", "160.00", "Health Insurance", { + mandatoryKind: "tk_debit", reference: "Finanzamt monthly statement", + allocations: [ + alloc("a-h", "doc-health", "Health", "Premium", "60.00", { category: "Health Insurance" }), + alloc("a-s", "doc-software", "Software GmbH", "Hosting", "100.00", { category: "Software" }), + ], + })], + documents: [doc("doc-health"), doc("doc-software")], + }); + assert.deepEqual(previewCounts(exemptParent.markup), [1, 1, 1]); + assert.equal(exemptParent.button.disabled, false); + + const allExempt = renderPreview({ + entries: [tx("p-all-exempt", "Card", "Tax settlement", "90.00", "Bank", { + allocations: [ + alloc("a-v", "doc-vat", "Card", "USt prepayment", "50.00", { category: "VAT" }), + alloc("a-tk", "doc-tk", "Techniker Krankenkasse Example", "October premium", "40.00"), + ], + })], + documents: [doc("doc-vat"), doc("doc-tk")], + }); + assert.deepEqual(previewCounts(allExempt.markup), [0, 0, 2]); + assert.equal(allExempt.button.disabled, false); + + const readyFallback = renderPreview({ + entries: [mixedPayment, ...ordinaryEntries], + documents: ["doc-compute", "doc-mail", "doc-health"].map((id) => doc(id)), + reports: [{ id: "report-1", month: "2026-10", status: "ready", transactionIds: ["synthetic-card-settlement"] }], + }); + assert.match(readyFallback.markup, /Package ready\./); + assert.match(readyFallback.markup, /3<\/span> transactions/); +}); + +test("package preview checks EUR values on reportable children, not on the payment", () => { + const usdPayment = tx("synthetic-usd-payment", "Card", "USD settlement", "300.00", "Tools", { + currency: "USD", amountEur: "250.00", + allocations: [ + alloc("a-conv", "doc-converted", "Compute GmbH", "Cluster", "150.00", { currency: "USD", amountEur: "125.00" }), + alloc("a-unconv", "doc-unconverted", "Mail B.V.", "Email", "150.00", { currency: "USD" }), + ], + }); + const blocked = renderPreview({ entries: [usdPayment], documents: [doc("doc-converted"), doc("doc-unconverted")] }); + assert.equal(blocked.button.disabled, true); + assert.match(blocked.markup, /1 transaction without a EUR value/); + assert.deepEqual(previewCounts(blocked.markup), [2, 2, 0]); + + const allowed = renderPreview({ + entries: [{ ...usdPayment, allocations: [usdPayment.allocations[0], { ...usdPayment.allocations[1], category: "Taxes" }] }], + documents: [doc("doc-converted"), doc("doc-unconverted")], + }); + assert.equal(allowed.button.disabled, false); + assert.doesNotMatch(allowed.markup, /without a EUR value/); + assert.deepEqual(previewCounts(allowed.markup), [1, 1, 1]); +}); + test("switching from a month to a year disables package creation", () => { let lens = "2026-10";