Skip to content
Draft
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
31 changes: 31 additions & 0 deletions backend/src/bookkeepingAllocations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown>,
): Record<string, unknown>[] {
return readTransactionAllocations(transaction).map((allocation) => {
const child: Record<string, unknown> = {
...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;
});
}
12 changes: 11 additions & 1 deletion backend/src/db/bookkeeping.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -35,12 +36,21 @@ export type BookkeepingItem = Record<string, unknown> & {
// 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<Record<string, unknown>>) {
function isReportExemptClassification(item: Readonly<Record<string, unknown>>) {
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<Record<string, unknown>>) {
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 {
Expand Down
31 changes: 12 additions & 19 deletions backend/src/finance/accountantReport.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { isReportExemptTransaction } from "../db/bookkeeping";
import { readTransactionAllocations } from "../bookkeepingAllocations";
import { projectTransactionAllocations, readTransactionAllocations } from "../bookkeepingAllocations";

export type AccountantReportEntry = Record<string, unknown>;

Expand All @@ -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);
});
}

Expand All @@ -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();
}
Expand Down
132 changes: 83 additions & 49 deletions backend/src/routes/bookkeepingReports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import {
addDocumentReportReference,
deleteBookkeepingItem,
getBookkeepingItem,
isReportExemptTransaction,
listBookkeepingItems,
markGenerationCleanupRequired,
markReportGenerated,
Expand All @@ -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,
Expand Down Expand Up @@ -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, unknown>) => 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)
Expand All @@ -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;
Expand All @@ -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,
Expand Down Expand Up @@ -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,
},
});
Expand Down Expand Up @@ -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<string, unknown>[];
const transactions = includedAccountantReportRows(payments);
if (!cachedArchive) {
const parentOf = (t: Record<string, unknown>) => 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<string, unknown>[];
const columns = [
"transactionDate",
"paidDate",
Expand Down
41 changes: 41 additions & 0 deletions backend/tests/api-bookkeeping.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading