diff --git a/demo/seed.sql b/demo/seed.sql
new file mode 100644
index 0000000..7f8ce58
--- /dev/null
+++ b/demo/seed.sql
@@ -0,0 +1,59 @@
+-- Fictional bookkeeping sample for an isolated demo. No real companies, people or accounts.
+INSERT INTO company (id,name,vat_number,chamber_number,country,address_line1,postal_code,city,email,default_currency,default_due_days) VALUES
+(1,'Northlight Studio B.V.','NL000000000B00','00000000','NL','Voorbeeldstraat 1','1000 AA','Amsterdam','billing@northlight.example.test','EUR',30);
+
+-- The RGS starter chart, as "Load starter" would insert it.
+INSERT INTO accounts (rgs_code,reknr,parent_code,nivo,omskort,omslang,dc,bw,sortimentcode,is_leaf) VALUES
+('B',NULL,NULL,1,'Balans','Balansrekeningen',NULL,'B',NULL,0),
+('BIva',NULL,'B',2,'Imm. vaste activa','Immateriële vaste activa','D','B',NULL,0),
+('BMva',NULL,'B',2,'Mat. vaste activa','Materiële vaste activa','D','B',NULL,0),
+('BFva',NULL,'B',2,'Fin. vaste activa','Financiële vaste activa','D','B',NULL,0),
+('BVrd',NULL,'B',2,'Voorraden','Voorraden','D','B',NULL,0),
+('BPro',NULL,'B',2,'Onderh. projecten','Onderhanden projecten in opdracht van derden','D','B',NULL,0),
+('BVor',NULL,'B',2,'Vorderingen','Vorderingen','D','B',NULL,0),
+('BEff',NULL,'B',2,'Effecten','Effecten','D','B',NULL,0),
+('BLim',NULL,'B',2,'Liquide middelen','Liquide middelen','D','B',NULL,0),
+('BEiv',NULL,'B',2,'Eigen vermogen','Eigen vermogen','C','B',NULL,0),
+('BVrz',NULL,'B',2,'Voorzieningen','Voorzieningen','C','B',NULL,0),
+('BLas',NULL,'B',2,'Langlop. schulden','Langlopende schulden','C','B',NULL,0),
+('BKas',NULL,'B',2,'Kortlop. schulden','Kortlopende schulden','C','B',NULL,0),
+('W',NULL,NULL,1,'Winst & verlies','Winst- en verliesrekening',NULL,'W',NULL,0),
+('WOmz',NULL,'W',2,'Netto-omzet','Netto-omzet','C','W',NULL,0),
+('WWiv',NULL,'W',2,'Wijz. voorraden','Wijziging in voorraden gereed product en onderhanden werk','C','W',NULL,0),
+('WGec',NULL,'W',2,'Geac. productie','Geactiveerde productie eigen bedrijf','C','W',NULL,0),
+('WOvb',NULL,'W',2,'Ov. bedr.opbrengst','Overige bedrijfsopbrengsten','C','W',NULL,0),
+('WKpr',NULL,'W',2,'Kostprijs omzet','Kostprijs van de omzet','D','W',NULL,0),
+('WPer',NULL,'W',2,'Personeelskosten','Personeelskosten','D','W',NULL,0),
+('WAfs',NULL,'W',2,'Afschrijvingen','Afschrijvingen op vaste activa','D','W',NULL,0),
+('WBwv',NULL,'W',2,'Bijz. waardeverm.','Bijzondere waardeverminderingen','D','W',NULL,0),
+('WOvk',NULL,'W',2,'Ov. bedr.kosten','Overige bedrijfskosten','D','W',NULL,0),
+('WFbl',NULL,'W',2,'Fin. baten/lasten','Financiële baten en lasten','D','W',NULL,0),
+('WBel',NULL,'W',2,'Belastingen','Belastingen over de winst','D','W',NULL,0);
+
+INSERT INTO parties (id,kind,name,contact_name,email,vat_number,country,address_line1,postal_code,city,currency) VALUES
+(1,'customer','Harbour Coffee Roasters','Sam Jansen','accounts@harbour-coffee.example.test',NULL,'NL','Kade 12','3511 AB','Utrecht','EUR'),
+(2,'customer','Atelier Verde','Lina Peeters','finance@atelier-verde.example.test','BE0000000000','BE','Groenstraat 4','2000','Antwerpen','EUR'),
+(3,'customer','Kestrel Logistics','Noor de Wit','ap@kestrel.example.test',NULL,'NL','Havenweg 88','3089 JH','Rotterdam','EUR'),
+(4,'supplier','Pixel Print Works','Ties Bakker','invoices@pixelprint.example.test',NULL,'NL','Drukkerijlaan 3','5611 AA','Eindhoven','EUR');
+
+INSERT INTO products (id,kind,sku,name,description,price_cents,vat_rate,unit,income_account) VALUES
+(1,'service','WS-01','Brand workshop','One-day brand strategy workshop',95000,21,'day','WOmz'),
+(2,'service','MT-01','Website maintenance','Monthly updates and monitoring',45000,21,'month','WOmz'),
+(3,'service','PH-01','Photography session','Half-day product shoot',60000,21,'session','WOmz');
+
+-- Totals follow recomputeTotals: Atelier Verde is an EU business with a VAT id, so its line is reverse charged.
+INSERT INTO invoices (id,type,party_id,issue_date,due_date,subtotal_cents,vat_cents,total_cents,reverse_charge,reference,notes) VALUES
+(1,'invoice',1,date('now','-40 days'),date('now','-10 days'),185000,38850,223850,0,'PO-4471','Thank you for your business.'),
+(2,'invoice',2,date('now','-12 days'),date('now','+18 days'),60000,0,60000,1,NULL,'Reverse charge: VAT to be accounted for by the recipient.'),
+(3,'invoice',3,NULL,NULL,45000,9450,54450,0,NULL,NULL);
+
+INSERT INTO invoice_lines (invoice_id,position,product_id,description,quantity,unit,unit_price_cents,vat_rate,account_code,subtotal_cents,vat_cents,total_cents) VALUES
+(1,1,1,'Brand workshop',1,'day',95000,21,'WOmz',95000,19950,114950),
+(1,2,2,'Website maintenance',2,'month',45000,21,'WOmz',90000,18900,108900),
+(2,1,3,'Photography session',1,'session',60000,21,'WOmz',60000,0,60000),
+(3,1,2,'Website maintenance',1,'month',45000,21,'WOmz',45000,9450,54450);
+
+-- Issuing through the ledger triggers numbers the invoices and posts their balanced journal entries.
+UPDATE invoices SET status = 'issued', mutation_actor = 'Sample data', mutation_actor_kind = 'system' WHERE id IN (1, 2);
+UPDATE invoices SET status = 'paid' WHERE id = 1;
+UPDATE invoices SET status = 'sent' WHERE id = 2;
diff --git a/package.json b/package.json
index c00da73..7cff52c 100644
--- a/package.json
+++ b/package.json
@@ -10,8 +10,9 @@
},
"dependencies": {
"@clawnify/app": "^0.2.1",
- "@clawnify/db": "^0.4.1",
+ "@clawnify/db": "^0.4.2",
"@hono/zod-openapi": "^0.18.0",
+ "@phosphor-icons/react": "^2.1.10",
"hono": "^4.13.7",
"react": "^19.0.0",
"react-dom": "^19.0.0"
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6562ea6..596ae66 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -10,13 +10,16 @@ importers:
dependencies:
'@clawnify/app':
specifier: ^0.2.1
- version: 0.2.1(@cloudflare/workers-types@4.20260503.1)(@hono/zod-openapi@0.18.4(hono@4.13.7)(zod@3.25.76))(hono@4.13.7)(react@19.2.5)
+ version: 0.2.1(@cloudflare/workers-types@4.20260503.1)(@hono/zod-openapi@0.18.4(hono@4.13.7)(zod@3.25.76))(@phosphor-icons/react@2.1.10(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(hono@4.13.7)(react@19.2.5)
'@clawnify/db':
- specifier: ^0.4.1
- version: 0.4.1(@cloudflare/workers-types@4.20260503.1)
+ specifier: ^0.4.2
+ version: 0.4.2(@cloudflare/workers-types@4.20260503.1)
'@hono/zod-openapi':
specifier: ^0.18.0
version: 0.18.4(hono@4.13.7)(zod@3.25.76)
+ '@phosphor-icons/react':
+ specifier: ^2.1.10
+ version: 2.1.10(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
hono:
specifier: ^4.13.7
version: 4.13.7
@@ -161,8 +164,8 @@ packages:
react:
optional: true
- '@clawnify/db@0.4.1':
- resolution: {integrity: sha512-Ck9RGqEElt6P/3S9quxvr2MIg8mZk1n9wFftH3PpGPFnpA6hbk0td67oaioeMRuDCn7vePcJCeyYEkbvNVYy/g==}
+ '@clawnify/db@0.4.2':
+ resolution: {integrity: sha512-s+G/5bDVFx7Na8WVETfl8EhyPcbmgs5LIE1TsM0vGUOAtPihQGlVX1xpfmg5lsMv8+OChKaHsZIMnzpXY8pyAw==}
'@clawnify/routes@0.2.2':
resolution: {integrity: sha512-+s7gjRyH8bmIUHQDHmmwGyUeEcV5m+IoWEYr2tLiWdVW7WKlFlgeKIuJ61vW9mc9k4TizL+B+Tg8qJ72zAbvOA==}
@@ -892,6 +895,13 @@ packages:
'@cfworker/json-schema':
optional: true
+ '@phosphor-icons/react@2.1.10':
+ resolution: {integrity: sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA==}
+ engines: {node: '>=10'}
+ peerDependencies:
+ react: '>= 16.8'
+ react-dom: '>= 16.8'
+
'@poppinss/colors@4.1.6':
resolution: {integrity: sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==}
@@ -2152,13 +2162,14 @@ snapshots:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.28.5
- '@clawnify/app@0.2.1(@cloudflare/workers-types@4.20260503.1)(@hono/zod-openapi@0.18.4(hono@4.13.7)(zod@3.25.76))(hono@4.13.7)(react@19.2.5)':
+ '@clawnify/app@0.2.1(@cloudflare/workers-types@4.20260503.1)(@hono/zod-openapi@0.18.4(hono@4.13.7)(zod@3.25.76))(@phosphor-icons/react@2.1.10(react-dom@19.2.5(react@19.2.5))(react@19.2.5))(hono@4.13.7)(react@19.2.5)':
dependencies:
- '@clawnify/db': 0.4.1(@cloudflare/workers-types@4.20260503.1)
+ '@clawnify/db': 0.4.2(@cloudflare/workers-types@4.20260503.1)
'@clawnify/routes': 0.2.2(@hono/zod-openapi@0.18.4(hono@4.13.7)(zod@3.25.76))(hono@4.13.7)
'@hono/zod-openapi': 0.18.4(hono@4.13.7)(zod@3.25.76)
hono: 4.13.7
optionalDependencies:
+ '@phosphor-icons/react': 2.1.10(react-dom@19.2.5(react@19.2.5))(react@19.2.5)
react: 19.2.5
transitivePeerDependencies:
- '@aws-sdk/client-rds-data'
@@ -2191,7 +2202,7 @@ snapshots:
- sql.js
- sqlite3
- '@clawnify/db@0.4.1(@cloudflare/workers-types@4.20260503.1)':
+ '@clawnify/db@0.4.2(@cloudflare/workers-types@4.20260503.1)':
dependencies:
drizzle-orm: 0.45.2(@cloudflare/workers-types@4.20260503.1)
transitivePeerDependencies:
@@ -2656,6 +2667,11 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ '@phosphor-icons/react@2.1.10(react-dom@19.2.5(react@19.2.5))(react@19.2.5)':
+ dependencies:
+ react: 19.2.5
+ react-dom: 19.2.5(react@19.2.5)
+
'@poppinss/colors@4.1.6':
dependencies:
kleur: 4.1.5
diff --git a/src/client/app.tsx b/src/client/app.tsx
index 20a6009..3af4a13 100644
--- a/src/client/app.tsx
+++ b/src/client/app.tsx
@@ -1,3 +1,6 @@
+import { useEffect } from "react";
+import { AppNav, embedded, reportLocation } from "@clawnify/app/client";
+import { Notice } from "./notice";
import { AccountsPage } from "./pages/accounts";
import { HomePage } from "./pages/home";
import { InvoiceEditorPage } from "./pages/invoice-editor";
@@ -7,7 +10,7 @@ import { PartiesPage } from "./pages/parties";
import { ProductsPage } from "./pages/products";
import { ReportsPage } from "./pages/reports";
import { SettingsPage } from "./pages/settings";
-import { Link, usePath } from "./router";
+import { Link, navigate, usePath } from "./router";
const NAV: { to: string; label: string }[] = [
{ to: "/invoices", label: "Invoices" },
@@ -19,11 +22,44 @@ const NAV: { to: string; label: string }[] = [
{ to: "/accounts", label: "Accounts" },
];
+// Embedded in the Clawnify workspace, the dashboard sidebar draws these and the
+// in-page header is hidden. Standalone keeps the header below.
+const HOST_NAV = [
+ { items: [
+ { id: "home", label: "Home", icon: "home", href: "/", home: true },
+ { id: "invoices", label: "Invoices", icon: "file-text", href: "/invoices", color: "blue" as const },
+ { id: "customers", label: "Customers", icon: "users", href: "/customers", color: "green" as const },
+ { id: "suppliers", label: "Suppliers", icon: "truck", href: "/suppliers", color: "orange" as const },
+ { id: "products", label: "Products", icon: "package", href: "/products", color: "violet" as const },
+ { id: "journals", label: "Journal", icon: "book-open", href: "/journals", color: "sky" as const },
+ { id: "reports", label: "Reports", icon: "bar-chart-3", href: "/reports", color: "red" as const },
+ { id: "accounts", label: "Accounts", icon: "list", href: "/accounts", color: "amber" as const },
+ ] },
+ { label: "Admin", items: [
+ { id: "settings", label: "Settings", icon: "settings", href: "/settings", color: "pink" as const },
+ ] },
+];
+
+function activeNavId(path: string): string {
+ const section = path.split("/")[1] ?? "";
+ return section === "" ? "home" : section;
+}
+
export function App() {
const path = usePath();
+ useEffect(() => {
+ reportLocation(path + window.location.search);
+ }, [path]);
+
return (
+ {embedded ? (
+
+
item.href && navigate(item.href)} />
+
+ ) : (
open-books
@@ -39,6 +75,8 @@ export function App() {
Settings
+ )}
+
{renderRoute(path)}
);
diff --git a/src/client/notice.tsx b/src/client/notice.tsx
new file mode 100644
index 0000000..066d559
--- /dev/null
+++ b/src/client/notice.tsx
@@ -0,0 +1,65 @@
+import { useEffect, useState } from "react";
+
+/**
+ * In-page messages.
+ *
+ * Native alert() and confirm() are blocked when the app runs inside the
+ * Clawnify workspace iframe, so a message shown that way silently never
+ * appears. `notify` shows it in the page instead.
+ */
+const EVENT = "clw:notice";
+
+export function notify(message: string) {
+ window.dispatchEvent(new CustomEvent(EVENT, { detail: message }));
+}
+
+export function Notice() {
+ const [message, setMessage] = useState(null);
+ useEffect(() => {
+ const onNotice = (e: Event) => setMessage((e as CustomEvent).detail);
+ window.addEventListener(EVENT, onNotice);
+ return () => window.removeEventListener(EVENT, onNotice);
+ }, []);
+ if (!message) return null;
+ return (
+
+
{message}
+
+
+ );
+}
+
+/** A destructive button that asks for confirmation inline before acting. */
+export function ConfirmButton({
+ prompt,
+ confirmLabel = "Delete",
+ onConfirm,
+ className,
+ title,
+ disabled,
+ children,
+}: {
+ prompt: string;
+ confirmLabel?: string;
+ onConfirm: () => void;
+ className?: string;
+ title?: string;
+ disabled?: boolean;
+ children: React.ReactNode;
+}) {
+ const [asking, setAsking] = useState(false);
+ if (asking) {
+ return (
+
+ {prompt}
+
+
+
+ );
+ }
+ return (
+
+ );
+}
diff --git a/src/client/pages/accounts.tsx b/src/client/pages/accounts.tsx
index 25198d9..8b0b746 100644
--- a/src/client/pages/accounts.tsx
+++ b/src/client/pages/accounts.tsx
@@ -1,4 +1,6 @@
import { useEffect, useState } from "react";
+import { ConfirmButton } from "../notice";
+import { refused } from "../refusal";
interface AccountNode {
rgs_code: string;
@@ -35,9 +37,8 @@ export function AccountsPage() {
}
async function clearAll() {
- if (!confirm("Clear all accounts?")) return;
setLoading(true);
- await fetch("/api/accounts", { method: "DELETE" });
+ await refused(await fetch("/api/accounts", { method: "DELETE" }));
await load();
setLoading(false);
}
@@ -56,13 +57,15 @@ export function AccountsPage() {
{count === 0 ? "Load starter chart" : "Reload starter chart"}
{count !== null && count > 0 && (
-
+
)}
{count !== null && (
{count} accounts
diff --git a/src/client/pages/invoice-editor.tsx b/src/client/pages/invoice-editor.tsx
index 89afc6d..fe502bf 100644
--- a/src/client/pages/invoice-editor.tsx
+++ b/src/client/pages/invoice-editor.tsx
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
+import { ConfirmButton, notify } from "../notice";
import { refused } from "../refusal";
import { Link, navigate } from "../router";
@@ -168,7 +169,7 @@ export function InvoiceEditorPage({ id }: { id: number }) {
async function issue() {
if (invoice!.lines.length === 0) {
- alert("Add at least one line before issuing.");
+ notify("Add at least one line before issuing.");
return;
}
const res = await fetch(`/api/invoices/${id}/issue`, { method: "POST" });
@@ -187,7 +188,6 @@ export function InvoiceEditorPage({ id }: { id: number }) {
}
async function remove() {
- if (!confirm("Delete this draft?")) return;
const res = await fetch(`/api/invoices/${id}`, { method: "DELETE" });
if (await refused(res)) return;
navigate("/invoices");
@@ -380,7 +380,7 @@ export function InvoiceEditorPage({ id }: { id: number }) {
)}
{invoice.status === "draft" && (
-
+ Delete
)}
diff --git a/src/client/pages/invoices.tsx b/src/client/pages/invoices.tsx
index c496b42..79a9030 100644
--- a/src/client/pages/invoices.tsx
+++ b/src/client/pages/invoices.tsx
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
+import { ConfirmButton } from "../notice";
import { refused } from "../refusal";
import { Link, navigate } from "../router";
@@ -74,7 +75,6 @@ export function InvoicesPage() {
}
async function remove(id: number) {
- if (!confirm("Delete this draft (and all lines)?")) return;
const res = await fetch(`/api/invoices/${id}`, { method: "DELETE" });
if (await refused(res)) return;
load();
@@ -170,7 +170,7 @@ export function InvoicesPage() {
)}
{inv.status === "draft" && (
-
+ remove(inv.id)} className="text-gray-300 hover:text-red-600 text-lg leading-none px-1" title="Delete draft">×
)}
diff --git a/src/client/pages/journals.tsx b/src/client/pages/journals.tsx
index 9d22d5c..8d8602f 100644
--- a/src/client/pages/journals.tsx
+++ b/src/client/pages/journals.tsx
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
+import { notify } from "../notice";
interface JournalLine {
id: number;
@@ -54,7 +55,7 @@ export function JournalsPage() {
const data: { created: number } = await res.json();
setBackfilling(false);
if (data.created > 0) await load();
- alert(`Backfilled ${data.created} journal ${data.created === 1 ? "entry" : "entries"}.`);
+ notify(`Backfilled ${data.created} journal ${data.created === 1 ? "entry" : "entries"}.`);
}
const totalDebit = trial.reduce((s, r) => s + r.debit_cents, 0);
diff --git a/src/client/pages/parties.tsx b/src/client/pages/parties.tsx
index d59691b..e837944 100644
--- a/src/client/pages/parties.tsx
+++ b/src/client/pages/parties.tsx
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
+import { ConfirmButton } from "../notice";
type PartyKind = "customer" | "supplier" | "both";
@@ -38,7 +39,6 @@ export function PartiesPage({ kind }: { kind: "customer" | "supplier" }) {
useEffect(() => { load(); }, [kind, q]);
async function remove(id: number) {
- if (!confirm("Delete this party?")) return;
await fetch(`/api/parties/${id}`, { method: "DELETE" });
load();
}
@@ -109,12 +109,14 @@ export function PartiesPage({ kind }: { kind: "customer" | "supplier" }) {
>
Edit
-
+
))}
diff --git a/src/client/pages/products.tsx b/src/client/pages/products.tsx
index 116a6d7..d03a03f 100644
--- a/src/client/pages/products.tsx
+++ b/src/client/pages/products.tsx
@@ -1,4 +1,5 @@
import { useEffect, useState } from "react";
+import { ConfirmButton } from "../notice";
type ProductKind = "good" | "service";
@@ -49,7 +50,6 @@ export function ProductsPage() {
useEffect(() => { load(); }, [q]);
async function remove(id: number) {
- if (!confirm("Delete this product?")) return;
await fetch(`/api/products/${id}`, { method: "DELETE" });
load();
}
@@ -114,12 +114,14 @@ export function ProductsPage() {
>
Edit
-
+
))}
diff --git a/src/client/refusal.ts b/src/client/refusal.ts
index 75739d7..65c39d7 100644
--- a/src/client/refusal.ts
+++ b/src/client/refusal.ts
@@ -1,3 +1,5 @@
+import { notify } from "./notice";
+
/**
* Surface a refused write.
*
@@ -11,6 +13,6 @@
export async function refused(res: Response): Promise {
if (res.ok) return false;
const data = (await res.json().catch(() => ({}))) as { error?: string };
- alert(data.error || "That change was refused.");
+ notify(data.error || "That change was refused.");
return true;
}
diff --git a/src/server/domain/rgs.ts b/src/server/domain/rgs.ts
index 705f014..6480a3d 100644
--- a/src/server/domain/rgs.ts
+++ b/src/server/domain/rgs.ts
@@ -1,4 +1,5 @@
import { get, query, run } from "../db";
+import { LedgerError } from "./errors";
import starter from "./rgs-starter.json";
export interface Account {
@@ -88,5 +89,10 @@ 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/tests/demo-seed.test.ts b/tests/demo-seed.test.ts
new file mode 100644
index 0000000..d80ec66
--- /dev/null
+++ b/tests/demo-seed.test.ts
@@ -0,0 +1,78 @@
+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";
+
+// demo/seed.sql is loaded after schema.sql for the public demo workspace. It
+// issues its invoices through the ledger triggers, so it must stay consistent
+// with them and with the totals the app computes.
+let db: DatabaseSync;
+let env: unknown;
+
+beforeEach(() => {
+ db = new DatabaseSync(":memory:");
+ db.exec(readFileSync(new URL("../src/server/schema.sql", import.meta.url), "utf8"));
+ db.exec(readFileSync(new URL("../demo/seed.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);
+
+test("seed satisfies foreign keys and posts balanced entries for issued invoices", async () => {
+ assert.deepEqual(db.prepare("PRAGMA foreign_key_check").all(), []);
+ const year = new Date().getUTCFullYear();
+ assert.deepEqual(
+ db.prepare("SELECT number, status FROM invoices ORDER BY id").all().map((r) => ({ ...r })),
+ [
+ { number: `INV-${year}-0001`, status: "paid" },
+ { number: `INV-${year}-0002`, status: "sent" },
+ { number: null, status: "draft" },
+ ],
+ );
+ const trial = await (await call("/api/reports/trial-balance")).json() as { debit_cents: number; credit_cents: number }[];
+ assert.equal(trial.reduce((s, r) => s + r.debit_cents, 0), trial.reduce((s, r) => s + r.credit_cents, 0));
+ assert.ok(trial.length > 0);
+});
+
+test("seeded totals match what the app computes", async () => {
+ const before = db.prepare("SELECT subtotal_cents, vat_cents, total_cents, reverse_charge FROM invoices WHERE id = 3").get();
+ // Any edit to the draft recomputes its totals from its lines.
+ assert.equal((await call("/api/invoices/3", { method: "PATCH", body: JSON.stringify({ notes: "Recomputed" }) })).status, 200);
+ assert.deepEqual(
+ { ...db.prepare("SELECT subtotal_cents, vat_cents, total_cents, reverse_charge FROM invoices WHERE id = 3").get() },
+ { ...before },
+ );
+ // The issued invoices are frozen, so check them against the same rule directly.
+ for (const [id, party, reverseCharge] of [[1, 1, 0], [2, 2, 1]] as const) {
+ const vat = await (await call(`/api/vat/compute?seller=NL&buyer=${party === 2 ? "BE" : "NL"}&buyer_vat=${party === 2 ? 1 : 0}&rate=21`)).json() as { effectiveRate: number };
+ const lines = db.prepare("SELECT subtotal_cents, vat_cents FROM invoice_lines WHERE invoice_id = ?").all(id) as { subtotal_cents: number; vat_cents: number }[];
+ for (const line of lines) assert.equal(line.vat_cents, Math.round((line.subtotal_cents * vat.effectiveRate) / 100));
+ assert.equal(db.prepare("SELECT reverse_charge FROM invoices WHERE id = ?").get(id)!.reverse_charge, reverseCharge);
+ }
+});
+
+test("the primary workflows work on the seeded books", async () => {
+ const year = new Date().getUTCFullYear();
+ const issued = await (await call("/api/invoices/3/issue", { method: "POST" })).json() as { number: string };
+ assert.equal(issued.number, `INV-${year}-0003`);
+
+ assert.equal((await call("/api/invoices/2/status", { method: "POST", body: JSON.stringify({ status: "cancelled" }) })).status, 200);
+ assert.equal(db.prepare("SELECT COUNT(*) AS n FROM journal_entries WHERE reverses_entry_id IS NOT NULL").get()!.n, 1);
+
+ const draft = await (await call("/api/invoices", { method: "POST", body: JSON.stringify({ party_id: 1 }) })).json() as { id: number };
+ assert.equal((await call(`/api/invoices/${draft.id}`, { method: "DELETE" })).status, 200);
+
+ const cleared = await call("/api/accounts", { method: "DELETE" });
+ assert.equal(cleared.status, 409);
+ assert.match(((await cleared.json()) as { error: string }).error, /posted journal entries/);
+ assert.equal(db.prepare("SELECT COUNT(*) AS n FROM accounts").get()!.n, 25);
+});