From 6f3361cefc8fdb6ca413af0b60e26d2438d69406 Mon Sep 17 00:00:00 2001 From: pallaoro Date: Mon, 21 Sep 2026 23:54:12 +0200 Subject: [PATCH] fix: refuse account clear while references exist --- src/server/domain/errors.ts | 1 + src/server/domain/rgs.ts | 6 ---- src/server/schema.sql | 15 ++++++++ tests/account-clear.test.ts | 69 +++++++++++++++++++++++++++++++++++++ 4 files changed, 85 insertions(+), 6 deletions(-) create mode 100644 tests/account-clear.test.ts diff --git a/src/server/domain/errors.ts b/src/server/domain/errors.ts index 3d65fdd..d801e7a 100644 --- a/src/server/domain/errors.ts +++ b/src/server/domain/errors.ts @@ -25,6 +25,7 @@ const SQL_REFUSALS: Record = { "invalid-transition": "That invoice status transition is not allowed. A cancelled invoice stays cancelled.", "issued-delete": "An issued invoice cannot be deleted. Cancel it instead to reverse its journal entry.", "frozen-invoice": "An issued invoice and its lines can no longer be edited. Cancel it or raise a credit note instead.", + "accounts-in-use": "The chart is used by products, invoice lines, or posted journal entries, so it cannot be cleared. Remove editable references first; posted entries keep their accounts permanently, so reload the starter chart to restore account names instead.", }; /** Only our explicit SQLite refusals are conflicts; storage faults remain 500s. */ diff --git a/src/server/domain/rgs.ts b/src/server/domain/rgs.ts index 6480a3d..705f014 100644 --- a/src/server/domain/rgs.ts +++ b/src/server/domain/rgs.ts @@ -1,5 +1,4 @@ import { get, query, run } from "../db"; -import { LedgerError } from "./errors"; import starter from "./rgs-starter.json"; export interface Account { @@ -89,10 +88,5 @@ export async function loadStarter(): Promise<{ inserted: number; total: number } } export async function clearAccounts(): Promise { - // Posted entries keep their accounts forever, so the chart cannot be cleared - // under them. Say so instead of failing on the foreign key. - if (await get("SELECT 1 FROM journal_lines LIMIT 1")) { - throw new LedgerError("The chart is used by posted journal entries, so it cannot be cleared. Reload the starter chart to restore account names instead."); - } await run("DELETE FROM accounts"); } diff --git a/src/server/schema.sql b/src/server/schema.sql index 28c64b7..1a5548a 100644 --- a/src/server/schema.sql +++ b/src/server/schema.sql @@ -181,6 +181,21 @@ CREATE INDEX IF NOT EXISTS idx_journal_lines_account ON journal_lines(account_co CREATE INDEX IF NOT EXISTS idx_journal_entries_reverses ON journal_entries(reverses_entry_id); CREATE INDEX IF NOT EXISTS idx_journal_entries_reversed_by ON journal_entries(reversed_by_entry_id); +-- Clearing the chart is one statement, so keep the refusal in SQLite: the +-- check and delete cannot race, and D1 plus preview storage return the same +-- named conflict instead of backend-specific foreign-key errors. +CREATE TRIGGER IF NOT EXISTS ledger_account_delete_guard_v1 +BEFORE DELETE ON accounts +BEGIN + SELECT RAISE(ABORT, 'ledger:accounts-in-use') WHERE + EXISTS ( + SELECT 1 FROM products + WHERE income_account = OLD.rgs_code OR expense_account = OLD.rgs_code + ) + OR EXISTS (SELECT 1 FROM invoice_lines WHERE account_code = OLD.rgs_code) + OR EXISTS (SELECT 1 FROM journal_lines WHERE account_code = OLD.rgs_code); +END; + -- A locked period is closed for good: nothing may be posted into it again. -- Locking is one-way on purpose -- an "unlock" would make every lock a -- suggestion, and the point of the lock is that it is not one. diff --git a/tests/account-clear.test.ts b/tests/account-clear.test.ts new file mode 100644 index 0000000..6c2b813 --- /dev/null +++ b/tests/account-clear.test.ts @@ -0,0 +1,69 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { DatabaseSync } from "node:sqlite"; +import { afterEach, beforeEach, test } from "node:test"; +import app from "../src/server/index"; + +let db: DatabaseSync; +let env: unknown; + +beforeEach(() => { + db = new DatabaseSync(":memory:"); + db.exec("PRAGMA foreign_keys = ON"); + db.exec(readFileSync(new URL("../src/server/schema.sql", import.meta.url), "utf8")); + env = { STORAGE: { query: async (sql: string, params: (string | number | null)[] = []) => { + const statement = db.prepare(sql); + if (statement.columns().length) return { rows: statement.all(...params), meta: {} }; + const result = statement.run(...params); + return { rows: [], meta: { changes: result.changes, last_row_id: Number(result.lastInsertRowid) } }; + } } }; +}); + +afterEach(() => db.close()); + +const call = (path: string, init?: RequestInit) => + app.request(path, { ...init, headers: { "Content-Type": "application/json", ...init?.headers } }, env as any); + +async function seedAccounts() { + assert.equal((await call("/api/accounts/seed", { method: "POST" })).status, 200); + assert.equal(db.prepare("SELECT COUNT(*) AS n FROM accounts").get()!.n, 25); +} + +async function assertClearRefused() { + const response = await call("/api/accounts", { method: "DELETE" }); + assert.equal(response.status, 409); + assert.match(((await response.json()) as { error: string }).error, /products, invoice lines, or posted journal entries/); + assert.equal(db.prepare("SELECT COUNT(*) AS n FROM accounts").get()!.n, 25); +} + +test("account clear succeeds when the chart is unused", async () => { + await seedAccounts(); + assert.equal((await call("/api/accounts", { method: "DELETE" })).status, 200); + assert.equal(db.prepare("SELECT COUNT(*) AS n FROM accounts").get()!.n, 0); +}); + +test("account clear returns 409 when a product uses the chart", async () => { + await seedAccounts(); + assert.equal((await call("/api/products", { + method: "POST", + body: JSON.stringify({ name: "Consulting", income_account: "WOmz" }), + })).status, 201); + await assertClearRefused(); +}); + +test("account clear returns 409 when a draft invoice line uses the chart", async () => { + await seedAccounts(); + const party = await (await call("/api/parties", { + method: "POST", + body: JSON.stringify({ name: "Example customer", kind: "customer" }), + })).json() as { id: number }; + const invoice = await (await call("/api/invoices", { + method: "POST", + body: JSON.stringify({ party_id: party.id }), + })).json() as { id: number }; + assert.equal((await call(`/api/invoices/${invoice.id}/lines`, { + method: "POST", + body: JSON.stringify({ description: "Consulting", account_code: "WOmz" }), + })).status, 201); + await assertClearRefused(); +});