Skip to content
Merged
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
1 change: 1 addition & 0 deletions src/server/domain/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const SQL_REFUSALS: Record<string, string> = {
"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. */
Expand Down
6 changes: 0 additions & 6 deletions src/server/domain/rgs.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { get, query, run } from "../db";
import { LedgerError } from "./errors";
import starter from "./rgs-starter.json";

export interface Account {
Expand Down Expand Up @@ -89,10 +88,5 @@ export async function loadStarter(): Promise<{ inserted: number; total: number }
}

export async function clearAccounts(): Promise<void> {
// 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");
}
15 changes: 15 additions & 0 deletions src/server/schema.sql
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
69 changes: 69 additions & 0 deletions tests/account-clear.test.ts
Original file line number Diff line number Diff line change
@@ -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();
});
Loading