From dc0f3026614e3fa3b50ac2218739fa0fd1d5e513 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:29:48 -0500 Subject: [PATCH 01/51] refactor(buttons): port form.md button states and layout The button now lays out icon and label itself and takes the edge, hover wash, danger variant and disabled opacity from form.md. Export button loses its inline style. --- web/src/styles/account.css | 42 +++++++++++++++++++++++++++++++---- web/src/styles/parts.css | 4 ++++ web/src/ui/parts/exportbtn.ts | 1 - 3 files changed, 42 insertions(+), 5 deletions(-) diff --git a/web/src/styles/account.css b/web/src/styles/account.css index e8ed22c..ad3c790 100644 --- a/web/src/styles/account.css +++ b/web/src/styles/account.css @@ -158,6 +158,11 @@ } .btn { + display: inline-grid; + grid-auto-flow: column; + align-items: center; + justify-content: center; + column-gap: var(--space-2); block-size: var(--control); padding: 0 var(--space-3); font: inherit; @@ -167,14 +172,42 @@ color: var(--text); cursor: pointer; background: var(--surface-2); - border: 1px solid var(--border-strong); + border: 1px solid var(--border); border-radius: var(--radius-sm); + transition: background-color var(--dur-fast) var(--ease), border-color var(--dur-fast) var(--ease), opacity var(--dur-fast) var(--ease); +} + +.btn:hover { + background: var(--active); +} + +.btn:focus-visible { + outline-offset: 2px; +} + +.btn .icon { + inline-size: 14px; + block-size: 14px; } .btn--primary { color: var(--on-accent); background: var(--accent); - border-color: var(--accent); + border-color: transparent; +} + +.btn--primary:hover { + background: color-mix(in srgb, var(--accent) 86%, var(--text)); +} + +.btn--danger { + color: var(--danger); + background: color-mix(in srgb, var(--danger) 10%, transparent); + border-color: color-mix(in srgb, var(--danger) 30%, transparent); +} + +.btn--danger:hover { + background: color-mix(in srgb, var(--danger) 18%, transparent); } .btn--quiet { @@ -186,9 +219,10 @@ background: var(--hover); } -.btn:disabled { +.btn:disabled, +.btn[aria-busy="true"] { cursor: default; - opacity: 0.55; + opacity: 0.6; } .menu__hint[data-ref="who-role"] { diff --git a/web/src/styles/parts.css b/web/src/styles/parts.css index be56a36..aac0975 100644 --- a/web/src/styles/parts.css +++ b/web/src/styles/parts.css @@ -368,6 +368,10 @@ color: var(--danger); } +.exportbtn { + flex: none; +} + .tbl__empty, .tbl__error { position: absolute; diff --git a/web/src/ui/parts/exportbtn.ts b/web/src/ui/parts/exportbtn.ts index 9f72d18..b5ee4cd 100644 --- a/web/src/ui/parts/exportbtn.ts +++ b/web/src/ui/parts/exportbtn.ts @@ -30,7 +30,6 @@ export function exportUrl(name: string, params: Record = {}): st export function mountExport(actions: HTMLElement, spec: ExportSpec): HTMLButtonElement { const btn = h("button", { class: "btn btn--quiet exportbtn", attrs: { type: "button", title: "Download what this screen shows as a CSV file", "data-export": spec.name } }, iconNode("trayIn"), h("span", { text: "Export CSV" })); - btn.style.cssText = "display:inline-flex;align-items:center;gap:var(--space-1);white-space:nowrap;flex:none"; if (spec.can && !spec.can()) btn.hidden = true; let busy = false; btn.addEventListener("click", async () => { From 8cdddc1f19b286caf36ea9214cfc1b44f40b9a61 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:30:17 -0500 Subject: [PATCH 02/51] feat(table): empty state with icon, title and line The shared table empty state is now a centered block with an icon, a title and one line, set through a setEmpty method. The general ledger and payment allocation screens use it instead of writing into the element. --- web/src/styles/parts.css | 30 ++++++++++++++++++++++++- web/src/ui/parts/table.ts | 36 +++++++++++++++++++++++++++--- web/src/ui/views/ledger-screens.ts | 5 ++--- web/src/ui/views/payments.ts | 8 +++---- 4 files changed, 68 insertions(+), 11 deletions(-) diff --git a/web/src/styles/parts.css b/web/src/styles/parts.css index aac0975..3d37f57 100644 --- a/web/src/styles/parts.css +++ b/web/src/styles/parts.css @@ -387,11 +387,39 @@ .tbl__empty { inset-block: var(--row) 0; display: grid; - place-items: center; + place-content: center; + justify-items: center; + row-gap: var(--space-1); padding: var(--space-6); visibility: hidden; } +.tbl__empty-icon { + display: grid; + place-items: center; + margin-block-end: var(--space-2); + color: var(--text-muted); +} + +.tbl__empty-icon .icon { + inline-size: 28px; + block-size: 28px; + opacity: 0.7; +} + +.tbl__empty-title, +.tbl__empty-line { + margin: 0; + max-inline-size: 44ch; + overflow-wrap: anywhere; +} + +.tbl__empty-title { + font-size: var(--text-md); + font-weight: var(--weight-medium); + color: var(--text); +} + .tbl--grow { overflow: auto; min-block-size: calc(var(--row) * 6); diff --git a/web/src/ui/parts/table.ts b/web/src/ui/parts/table.ts index 9df2bf6..ee30b41 100644 --- a/web/src/ui/parts/table.ts +++ b/web/src/ui/parts/table.ts @@ -1,4 +1,30 @@ import { delayedIndicator, h, setAttr, setText } from "../dom"; +import { iconNode } from "../icons"; + +export interface EmptyText { + title: string; + line: string; +} + +export interface EmptyBlock { + el: HTMLElement; + set(title: string, line: string): void; +} + +const EMPTY_TITLE = "Nothing here yet"; + +export function emptyBlock(text: EmptyText, extraClass = ""): EmptyBlock { + const title = h("p", { class: "tbl__empty-title", text: text.title }); + const line = h("p", { class: "tbl__empty-line", text: text.line }); + const el = h("div", { class: extraClass ? `tbl__empty ${extraClass}` : "tbl__empty" }, h("span", { class: "tbl__empty-icon", attrs: { "aria-hidden": "true" } }, iconNode("document")), title, line); + return { + el, + set(t, l) { + setText(title, t); + setText(line, l); + }, + }; +} export interface Column { key: string; @@ -14,7 +40,7 @@ export interface TableOptions { label: string; columns: Column[]; rowKey(row: T): string; - empty: string; + empty: string | EmptyText; foot?: boolean; grow?: boolean; onOpen?(row: T): void; @@ -71,13 +97,14 @@ export interface TableHandle { setFoot(cells: Record): void; setBusy(busy: boolean): void; setError(message: string): void; + setEmpty(title: string, line: string): void; } export function mountTable(host: HTMLElement, o: TableOptions): TableHandle { const align = (c: Column) => ({ "data-align": c.align ?? "start" }); const body = h("tbody"); const footCells = new Map(); - const empty = h("p", { class: "tbl__empty", text: o.empty }); + const empty = emptyBlock(typeof o.empty === "string" ? { title: EMPTY_TITLE, line: o.empty } : o.empty); const error = h("p", { class: "tbl__error", attrs: { role: "alert" } }); const table = h( "table", @@ -96,7 +123,7 @@ export function mountTable(host: HTMLElement, o: TableOptions): TableHandl const fill = h("td", { attrs: { colspan: String(o.columns.length), "aria-hidden": "true" } }); table.append(h("tbody", { class: "tbl__fill" }, h("tr", {}, fill)), h("tfoot", {}, row)); } - const root = h("div", { class: o.grow ? "tbl tbl--grow" : "tbl", attrs: o.foot ? { "data-empty": "true", "data-foot": "true" } : { "data-empty": "true" } }, table, empty, error); + const root = h("div", { class: o.grow ? "tbl tbl--grow" : "tbl", attrs: o.foot ? { "data-empty": "true", "data-foot": "true" } : { "data-empty": "true" } }, table, empty.el, error); host.append(o.grow && o.foot ? h("div", { class: "tbl-wrap" }, root) : root); const rows = new Map(); @@ -198,5 +225,8 @@ export function mountTable(host: HTMLElement, o: TableOptions): TableHandl setError(message) { setText(error, message); }, + setEmpty(title, line) { + empty.set(title, line); + }, }; } diff --git a/web/src/ui/views/ledger-screens.ts b/web/src/ui/views/ledger-screens.ts index eaa230a..807e79d 100644 --- a/web/src/ui/views/ledger-screens.ts +++ b/web/src/ui/views/ledger-screens.ts @@ -145,14 +145,13 @@ function ledgerScreen(): ViewDef { num("credit", "Credit", (r) => r.credit, "120px", true), num("balance", "Balance", (r) => r.balance, "130px"), ]; - const table = mountTable(tableHost, { label: "General ledger", columns: cols, rowKey: (r) => `${r.entryId}:${r.lineNo}`, empty: PICK, foot: true }); - const hint = table.root.querySelector(".tbl__empty"); + const table = mountTable(tableHost, { label: "General ledger", columns: cols, rowKey: (r) => `${r.entryId}:${r.lineNo}`, empty: { title: "No account chosen", line: PICK }, foot: true }); const run = guard(table as TableHandle, status); reload = () => { if (!account.read()) return; void run(async () => { const l = await loadLedger(ctx.api, account.read(), from.read(), to.read()); - if (hint) setText(hint, "No lines in this range."); + table.setEmpty("No lines in this range", "Pick another date range or account to see its ledger lines."); const first: LedgerLine = { date: from.read(), number: "", entryId: OPENING, lineNo: 0, memo: "Opening balance", debit: 0, credit: 0, balance: l.opening }; table.setRows([first, ...l.lines]); const sum = (pick: (r: LedgerLine) => number) => l.lines.reduce((s, r) => s + pick(r), 0); diff --git a/web/src/ui/views/payments.ts b/web/src/ui/views/payments.ts index 15735b3..e094a22 100644 --- a/web/src/ui/views/payments.ts +++ b/web/src/ui/views/payments.ts @@ -29,7 +29,7 @@ import { import { delayedIndicator, h, setAttr, setText } from "../dom"; import { mountExport } from "../parts/exportbtn"; import { mountPicker } from "../parts/picker"; -import { mountTable, statusTone } from "../parts/table"; +import { emptyBlock, mountTable, statusTone } from "../parts/table"; import type { ViewContext, ViewDef } from "../views"; const STATUSES = ["", "draft", "posted", "cancelled"]; @@ -177,11 +177,11 @@ function mountForm(dir: PayDir, host: HTMLElement, ctx: ViewContext): (params: U ), body, ); - const allocEmpty = h("p", { class: "tbl__empty pay__empty" }); + const allocEmpty = emptyBlock({ title: "Nothing to allocate", line: "Choose a party to see open invoices." }, "pay__empty"); const remainLabel = h("span", { class: "pay__remain-label", text: "Unallocated" }); const remainValue = h("span", { class: "pay__remain-value" }); const remain = h("div", { class: "pay__remain", attrs: { "aria-live": "polite" } }, remainLabel, remainValue); - const allocBox = h("div", { class: "tbl pay__alloc-box" }, table, allocEmpty, remain); + const allocBox = h("div", { class: "tbl pay__alloc-box" }, table, allocEmpty.el, remain); const save = h("button", { class: "btn", attrs: { type: "button" }, text: "Save draft" }); const post = h("button", { class: "btn btn--primary", attrs: { type: "button" }, text: "Post" }); const allocate = h("button", { class: "btn", attrs: { type: "button" }, text: "Allocate" }); @@ -289,7 +289,7 @@ function mountForm(dir: PayDir, host: HTMLElement, ctx: ViewContext): (params: U r.el.remove(); rows.delete(id); } - setText(allocEmpty, list.length ? "" : partyCode() ? "No open invoices for this party." : "Choose a party to see open invoices."); + if (!list.length) allocEmpty.set(partyCode() ? "No open invoices" : "Nothing to allocate", partyCode() ? "This party has no open invoices to allocate against." : "Choose a party to see open invoices."); setAttr(allocBox, "data-empty", list.length ? null : "true"); writeRemainder(); }; From 5aa70db106234607a7fc43a91b0429fbf7fd545a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:30:49 -0500 Subject: [PATCH 03/51] feat(menu): native menubar with file view go and help menus Ports form.md's menubar so each item with a cmd: id runs that window command, and adds Go submenus that list every screen. Not compiled here, there is no GTK in this sandbox. --- src-tauri/src/main.rs | 2 + src-tauri/src/menu.rs | 153 +++++++++++++++++++++++++++++++++++++++++- 2 files changed, 152 insertions(+), 3 deletions(-) diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index b75f982..0b3b498 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -352,6 +352,8 @@ fn main() { stopped: Arc::new(AtomicBool::new(false)), quitting: AtomicBool::new(false), }) + .manage(menu::Zoom(Mutex::new(1.0))) + .on_menu_event(menu::handle) .invoke_handler(tauri::generate_handler![reveal::app_ready]) .setup(|app| { reveal::round_splash(app.handle()); diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index 6071b35..c743ba3 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -1,10 +1,66 @@ -use tauri::menu::{Menu, MenuBuilder, SubmenuBuilder}; -use tauri::{AppHandle, Runtime}; +use std::sync::Mutex; + +use tauri::menu::{Menu, MenuBuilder, MenuEvent, MenuItemBuilder, Submenu, SubmenuBuilder}; +use tauri::{AppHandle, Manager, Runtime}; + +pub struct Zoom(pub Mutex); + +const ZOOM_STEPS: [f64; 9] = [0.67, 0.75, 0.8, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75]; + +const SELLING: [(&str, &str); 5] = [ + ("quotes", "Quotes"), + ("sales-orders", "Sales Orders"), + ("sales-invoices", "Sales Invoices"), + ("payments-in", "Payments Received"), + ("receivables-ageing", "Receivables Ageing"), +]; +const BUYING: [(&str, &str); 5] = [ + ("purchase-orders", "Purchase Orders"), + ("goods-receipts", "Goods Receipts"), + ("purchase-invoices", "Purchase Invoices"), + ("payments-out", "Payments Made"), + ("payables-ageing", "Payables Ageing"), +]; +const STOCK: [(&str, &str); 2] = [("delivery-notes", "Delivery Notes"), ("stock-balance", "Stock Balance")]; +const LEDGER: [(&str, &str); 5] = [ + ("reports", "All Reports"), + ("trial-balance", "Trial Balance"), + ("general-ledger", "General Ledger"), + ("profit-and-loss", "Profit and Loss"), + ("balance-sheet", "Balance Sheet"), +]; +const SETUP: [(&str, &str); 7] = [ + ("setup", "All Setup"), + ("customers", "Customers"), + ("suppliers", "Suppliers"), + ("items", "Items"), + ("tax-rates", "Tax Rates"), + ("warehouses", "Warehouses"), + ("accounts", "Chart of Accounts"), +]; + +fn item(app: &AppHandle, id: &str, label: &str, keys: Option<&str>) -> tauri::Result> { + let mut b = MenuItemBuilder::with_id(id, label); + if let Some(k) = keys { + b = b.accelerator(k); + } + b.build(app) +} + +fn screens(app: &AppHandle, title: &str, list: &[(&str, &str)]) -> tauri::Result> { + let mut b = SubmenuBuilder::new(app, title); + for (view, label) in list { + b = b.item(&item(app, &format!("cmd:go.{view}"), label, None)?); + } + b.build() +} pub fn build(app: &AppHandle) -> tauri::Result> { let app_menu = SubmenuBuilder::new(app, "FormLedger") .about(None) .separator() + .item(&item(app, "cmd:nav.account", "Settings...", Some("CmdOrCtrl+,"))?) + .separator() .services() .separator() .hide() @@ -13,6 +69,23 @@ pub fn build(app: &AppHandle) -> tauri::Result> { .separator() .quit() .build()?; + let file = SubmenuBuilder::new(app, "File") + .item(&item(app, "cmd:new.salesInvoice", "New Invoice", Some("CmdOrCtrl+N"))?) + .item(&item(app, "cmd:new.quote", "New Quote", None)?) + .item(&item(app, "cmd:new.salesOrder", "New Sales Order", None)?) + .item(&item(app, "cmd:new.purchaseOrder", "New Purchase Order", None)?) + .item(&item(app, "cmd:new.purchaseInvoice", "New Purchase Invoice", None)?) + .item(&item(app, "cmd:new.paymentIn", "Receive Payment", None)?) + .item(&item(app, "cmd:new.paymentOut", "Make Payment", None)?) + .separator() + .item(&item(app, "cmd:file.exportCsv", "Export CSV...", None)?) + .item(&item(app, "cmd:file.print", "Print...", Some("CmdOrCtrl+P"))?) + .item(&item(app, "cmd:file.snapshot", "Write Snapshot...", None)?) + .separator() + .item(&item(app, "cmd:palette.open", "Find a Command...", None)?) + .separator() + .close_window() + .build()?; let edit = SubmenuBuilder::new(app, "Edit") .undo() .redo() @@ -22,11 +95,85 @@ pub fn build(app: &AppHandle) -> tauri::Result> { .paste() .select_all() .build()?; + let view = SubmenuBuilder::new(app, "View") + .item(&item(app, "cmd:shell.toggleSidebar", "Toggle Sidebar", Some("CmdOrCtrl+\\"))?) + .item(&item(app, "cmd:shell.theme.toggle", "Toggle Dark Mode", Some("CmdOrCtrl+Shift+L"))?) + .separator() + .item(&item(app, "cmd:nav.back", "Back", Some("CmdOrCtrl+["))?) + .item(&item(app, "cmd:nav.forward", "Forward", Some("CmdOrCtrl+]"))?) + .item(&item(app, "cmd:nav.home", "Home", None)?) + .item(&item(app, "cmd:go.dashboards", "Dashboards", None)?) + .separator() + .item(&item(app, "zoom:in", "Zoom In", Some("CmdOrCtrl+="))?) + .item(&item(app, "zoom:out", "Zoom Out", Some("CmdOrCtrl+-"))?) + .item(&item(app, "zoom:reset", "Actual Size", Some("CmdOrCtrl+0"))?) + .separator() + .item(&item(app, "app:reload", "Reload", Some("CmdOrCtrl+R"))?) + .fullscreen() + .build()?; + let go = SubmenuBuilder::new(app, "Go") + .item(&item(app, "cmd:nav.home", "Home", None)?) + .item(&item(app, "cmd:go.dashboards", "Dashboards", None)?) + .item(&item(app, "cmd:go.templates", "Templates", None)?) + .separator() + .item(&screens(app, "Selling", &SELLING)?) + .item(&screens(app, "Buying", &BUYING)?) + .item(&screens(app, "Stock", &STOCK)?) + .item(&screens(app, "Ledger", &LEDGER)?) + .item(&screens(app, "Setup", &SETUP)?) + .build()?; let window = SubmenuBuilder::new(app, "Window") .minimize() .maximize() .separator() .bring_all_to_front() .build()?; - MenuBuilder::new(app).items(&[&app_menu, &edit, &window]).build() + let help = SubmenuBuilder::new(app, "Help") + .item(&item(app, "cmd:palette.open", "Find a Command...", Some("CmdOrCtrl+Shift+P"))?) + .item(&item(app, "cmd:shell.showShortcuts", "Keyboard Shortcuts", None)?) + .separator() + .item(&item(app, "app:notices", "Third-Party Notices", None)?) + .build()?; + MenuBuilder::new(app) + .items(&[&app_menu, &file, &edit, &view, &go, &window, &help]) + .build() +} + +fn step(current: f64, up: bool) -> f64 { + if up { + ZOOM_STEPS.iter().copied().find(|z| *z > current + 0.001).unwrap_or(current) + } else { + ZOOM_STEPS.iter().rev().copied().find(|z| *z < current - 0.001).unwrap_or(current) + } +} + +pub fn handle(app: &AppHandle, event: MenuEvent) { + let Some(window) = app.get_webview_window("main") else { + return; + }; + let id = event.id().as_ref(); + if let Some(command) = id.strip_prefix("cmd:") { + let js = format!("window.__formledgerRun && window.__formledgerRun({command:?})"); + let _ = window.eval(js); + return; + } + match id { + "zoom:in" | "zoom:out" | "zoom:reset" => { + let zoom = app.state::(); + let mut z = zoom.0.lock().unwrap(); + *z = match id { + "zoom:in" => step(*z, true), + "zoom:out" => step(*z, false), + _ => 1.0, + }; + let _ = window.set_zoom(*z); + } + "app:reload" => { + let _ = window.eval("location.reload()"); + } + "app:notices" => { + let _ = window.eval("window.open(location.origin + '/notices')"); + } + _ => {} + } } From e32393f2e86e3209fe025689681ae11c85ffec65 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:30:51 -0500 Subject: [PATCH 04/51] feat(reports): add monthly series and top rows routes Adds GET /api/reports/series and GET /api/reports/top, computed from posted ledger lines and posted invoices, guarded by reports.read. --- internal/reports/reports.go | 1 + internal/reports/series.go | 255 ++++++++++++++++++++++++++++++ internal/reports/series_routes.go | 80 ++++++++++ 3 files changed, 336 insertions(+) create mode 100644 internal/reports/series.go create mode 100644 internal/reports/series_routes.go diff --git a/internal/reports/reports.go b/internal/reports/reports.go index 3038567..6ee5263 100644 --- a/internal/reports/reports.go +++ b/internal/reports/reports.go @@ -50,6 +50,7 @@ func (m module) Mount(rt *httpx.Router, d *app.Deps) error { m.route(rt, db, "GET /api/reports/period-activity", activity) m.route(rt, db, "GET /api/reports/verify", verify) m.mountStatements(rt, db) + m.mountSeries(rt, db) return nil } diff --git a/internal/reports/series.go b/internal/reports/series.go new file mode 100644 index 0000000..de00838 --- /dev/null +++ b/internal/reports/series.go @@ -0,0 +1,255 @@ +package reports + +import ( + "context" + "database/sql" + "time" +) + +type seriesPoint struct { + Period string `json:"period"` + Value int64 `json:"value"` +} + +type seriesSpan struct { + From string `json:"from"` + To string `json:"to"` + Total int64 `json:"total"` +} + +type series struct { + Metric string `json:"metric"` + Currency string `json:"currency"` + By string `json:"by"` + From string `json:"from"` + To string `json:"to"` + Points []seriesPoint `json:"points"` + Total int64 `json:"total"` + Previous seriesSpan `json:"previous"` +} + +type month struct { + period string + from string + to string +} + +var seriesMetrics = []string{"revenue", "expenses", "profit", "cash", "receivables", "payables"} + +func flowMetric(metric string) bool { + return metric == "revenue" || metric == "expenses" || metric == "profit" +} + +func months(from, to string) []month { + f, _ := time.Parse(dateLayout, from) + t, _ := time.Parse(dateLayout, to) + out := []month{} + for c := time.Date(f.Year(), f.Month(), 1, 0, 0, 0, 0, time.UTC); !c.After(t); c = c.AddDate(0, 1, 0) { + m := month{period: c.Format("2006-01"), from: c.Format(dateLayout), to: c.AddDate(0, 1, -1).Format(dateLayout)} + if m.from < from { + m.from = from + } + if m.to > to { + m.to = to + } + out = append(out, m) + } + return out +} + +func previousSpan(from, to string) (string, string) { + f, _ := time.Parse(dateLayout, from) + t, _ := time.Parse(dateLayout, to) + days := int(t.Sub(f).Hours()/24) + 1 + pt := f.AddDate(0, 0, -1) + return pt.AddDate(0, 0, 1-days).Format(dateLayout), pt.Format(dateLayout) +} + +const flowSQL = ` +SELECT a.type, SUM(l.debit) - SUM(l.credit) +FROM journal_lines l +JOIN journal_entries e ON e.id = l.entry_id +JOIN accounts a ON a.id = l.account_id +WHERE ` + counted + ` AND e.entry_date >= ? AND e.entry_date <= ? AND a.type IN ('income', 'expense') +GROUP BY a.type` + +func flowValue(ctx context.Context, db *sql.DB, metric, from, to string) (int64, error) { + rows, err := db.QueryContext(ctx, flowSQL, from, to) + if err != nil { + return 0, err + } + defer rows.Close() + var income, expense int64 + for rows.Next() { + var kind string + var net int64 + if err := rows.Scan(&kind, &net); err != nil { + return 0, err + } + if kind == "income" { + income = -net + } else { + expense = net + } + } + if err := rows.Err(); err != nil { + return 0, err + } + switch metric { + case "revenue": + return income, nil + case "expenses": + return expense, nil + } + return income - expense, nil +} + +const controlSQL = ` +SELECT receivable_account_id, 'receivables' FROM customers +UNION SELECT payable_account_id, 'payables' FROM suppliers` + +func controlAccounts(ctx context.Context, db *sql.DB, metric string) (map[string]bool, error) { + rows, err := db.QueryContext(ctx, controlSQL) + if err != nil { + return nil, err + } + defer rows.Close() + out := map[string]bool{} + for rows.Next() { + var id, kind string + if err := rows.Scan(&id, &kind); err != nil { + return nil, err + } + if kind == metric { + out[id] = true + } + } + return out, rows.Err() +} + +func balanceRows(ctx context.Context, db *sql.DB, asOf string) ([]balanceRow, error) { + rows, err := db.QueryContext(ctx, balancesSQL, asOf) + if err != nil { + return nil, err + } + defer rows.Close() + out := []balanceRow{} + for rows.Next() { + var b balanceRow + if err := rows.Scan(&b.AccountID, &b.Code, &b.Name, &b.Type, &b.Currency, &b.IsGroup, &b.IsCash, &b.Active, &b.Debit, &b.Credit, &b.Balance); err != nil { + return nil, err + } + out = append(out, b) + } + return out, rows.Err() +} + +func stockValue(ctx context.Context, db *sql.DB, metric, asOf, pref string, control map[string]bool) (int64, error) { + rows, err := balanceRows(ctx, db, asOf) + if err != nil { + return 0, err + } + if metric == "cash" { + return cashOf(pref, rows).Total, nil + } + var sum int64 + for _, b := range rows { + if control[b.AccountID] { + sum += b.Balance + } + } + if metric == "payables" { + return -sum, nil + } + return sum, nil +} + +func baseCurrency(ctx context.Context, db *sql.DB) string { + var c string + if err := db.QueryRowContext(ctx, `SELECT currency FROM accounts WHERE is_group = 0 GROUP BY currency ORDER BY COUNT(*) DESC, currency LIMIT 1`).Scan(&c); err != nil { + return "" + } + return c +} + +func buildSeries(ctx context.Context, db *sql.DB, metric, from, to string) (*series, error) { + s := &series{Metric: metric, Currency: baseCurrency(ctx, db), By: "month", From: from, To: to, Points: []seriesPoint{}} + pf, pt := previousSpan(from, to) + s.Previous = seriesSpan{From: pf, To: pt} + if flowMetric(metric) { + for _, m := range months(from, to) { + v, err := flowValue(ctx, db, metric, m.from, m.to) + if err != nil { + return nil, err + } + s.Points = append(s.Points, seriesPoint{m.period, v}) + s.Total += v + } + v, err := flowValue(ctx, db, metric, pf, pt) + if err != nil { + return nil, err + } + s.Previous.Total = v + return s, nil + } + pref, err := cashPreference(ctx, db) + if err != nil { + return nil, err + } + control, err := controlAccounts(ctx, db, metric) + if err != nil { + return nil, err + } + for _, m := range months(from, to) { + v, err := stockValue(ctx, db, metric, m.to, pref, control) + if err != nil { + return nil, err + } + s.Points = append(s.Points, seriesPoint{m.period, v}) + s.Total = v + } + v, err := stockValue(ctx, db, metric, pt, pref, control) + if err != nil { + return nil, err + } + s.Previous.Total = v + return s, nil +} + +type topRow struct { + Code string `json:"code"` + Name string `json:"name"` + Value int64 `json:"value"` +} + +var topSQL = map[string]string{ + "customers": ` +SELECT c.code, c.name, SUM(d.subtotal) FROM sales_docs d JOIN customers c ON c.id = d.customer_id +WHERE d.kind = 'invoice' AND d.status = 'posted' AND d.doc_date >= ? AND d.doc_date <= ? +GROUP BY c.id ORDER BY 3 DESC, c.code LIMIT ?`, + "items": ` +SELECT i.code, i.name, SUM(l.line_subtotal) FROM sales_lines l JOIN sales_docs d ON d.id = l.doc_id JOIN items i ON i.id = l.item_id +WHERE d.kind = 'invoice' AND d.status = 'posted' AND d.doc_date >= ? AND d.doc_date <= ? +GROUP BY i.id ORDER BY 3 DESC, i.code LIMIT ?`, + "suppliers": ` +SELECT s.code, s.name, SUM(d.subtotal) FROM purchase_docs d JOIN suppliers s ON s.id = d.supplier_id +WHERE d.kind = 'invoice' AND d.status = 'posted' AND d.doc_date >= ? AND d.doc_date <= ? +GROUP BY s.id ORDER BY 3 DESC, s.code LIMIT ?`, +} + +func buildTop(ctx context.Context, db *sql.DB, what, from, to string, limit int) ([]topRow, error) { + rows, err := db.QueryContext(ctx, topSQL[what], from, to, limit) + if err != nil { + return nil, err + } + defer rows.Close() + out := []topRow{} + for rows.Next() { + var t topRow + if err := rows.Scan(&t.Code, &t.Name, &t.Value); err != nil { + return nil, err + } + out = append(out, t) + } + return out, rows.Err() +} diff --git a/internal/reports/series_routes.go b/internal/reports/series_routes.go new file mode 100644 index 0000000..d9e66b4 --- /dev/null +++ b/internal/reports/series_routes.go @@ -0,0 +1,80 @@ +package reports + +import ( + "context" + "database/sql" + "net/http" + "strconv" + "time" + + "github.com/nodemode-ai/formledger/internal/httpx" +) + +func (m module) mountSeries(rt *httpx.Router, db *sql.DB) { + m.route(rt, db, "GET /api/reports/series", seriesRoute) + m.route(rt, db, "GET /api/reports/top", topRoute) +} + +func span(r *http.Request) (string, string, error) { + to, err := date(r, "to", today()) + if err != nil { + return "", "", err + } + t, _ := time.Parse(dateLayout, to) + from, err := date(r, "from", time.Date(t.Year(), t.Month()-11, 1, 0, 0, 0, 0, time.UTC).Format(dateLayout)) + if err != nil { + return "", "", err + } + if from > to { + return "", "", httpx.Fail(http.StatusBadRequest, "bad_range", "from must not be later than to") + } + if len(months(from, to)) > 120 { + return "", "", httpx.Fail(http.StatusBadRequest, "bad_range", "a series covers at most 120 months") + } + return from, to, nil +} + +func seriesRoute(ctx context.Context, db *sql.DB, r *http.Request) (any, error) { + q := r.URL.Query() + metric := q.Get("metric") + ok := false + for _, x := range seriesMetrics { + ok = ok || x == metric + } + if !ok { + return nil, httpx.Fail(http.StatusBadRequest, "bad_metric", "metric must be one of revenue, expenses, profit, cash, receivables, payables") + } + if by := q.Get("by"); by != "" && by != "month" { + return nil, httpx.Fail(http.StatusBadRequest, "bad_by", "by must be month") + } + from, to, err := span(r) + if err != nil { + return nil, err + } + return buildSeries(ctx, db, metric, from, to) +} + +func topRoute(ctx context.Context, db *sql.DB, r *http.Request) (any, error) { + q := r.URL.Query() + what := q.Get("what") + if _, ok := topSQL[what]; !ok { + return nil, httpx.Fail(http.StatusBadRequest, "bad_what", "what must be one of customers, items, suppliers") + } + limit := 5 + if v := q.Get("limit"); v != "" { + n, err := strconv.Atoi(v) + if err != nil || n < 1 || n > 50 { + return nil, httpx.Fail(http.StatusBadRequest, "bad_limit", "limit must be a whole number from 1 to 50") + } + limit = n + } + from, to, err := span(r) + if err != nil { + return nil, err + } + rows, err := buildTop(ctx, db, what, from, to, limit) + if err != nil { + return nil, err + } + return map[string]any{"what": what, "from": from, "to": to, "rows": rows}, nil +} From 94a4a5a7534fc75c2f1b8ee70dd4fa145a8060d8 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:31:29 -0500 Subject: [PATCH 05/51] docs(behaviors): american spelling in the behaviors page Behavior, recognized and organizations, with the file name left as it is. --- docs/BEHAVIOURS.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/BEHAVIOURS.md b/docs/BEHAVIOURS.md index f16f504..357ba95 100644 --- a/docs/BEHAVIOURS.md +++ b/docs/BEHAVIOURS.md @@ -1,18 +1,18 @@ -# FormLedger behaviours +# FormLedger behaviors -This file lists the behaviours FormLedger commits to. Each one is an outcome that a person using the app, or a command run against its data, can check. None of them says how the app is built. +This file lists the behaviors FormLedger commits to. Each one is an outcome that a person using the app, or a command run against its data, can check. None of them says how the app is built. FormLedger is a local-first business app and the system of record for a small company. Every sale, purchase, payment and stock movement is a numbered document that posts to shared ledgers for money and stock. Version 1 covers accounts, selling, buying and stock. How to read an entry: -- The id is stable. A behaviour that is dropped keeps its id retired; ids are never reused. -- "v1: matched" means version 1 commits to the behaviour. "v1: not matched" means it is out of scope. +- The id is stable. A behavior that is dropped keeps its id retired; ids are never reused. +- "v1: matched" means version 1 commits to the behavior. "v1: not matched" means it is out of scope. - The phase is the DEV_PLAN phase that delivers it. -- Sources follow the verified-sourcing rule: each key claim names at least two independent approved sources, or carries an explicit single-source note. Source short names are expanded in Sources Used at the end. Where a behaviour states a FormLedger design choice (a default, a limit) rather than a general accounting fact, the entry says so; the sources then back the underlying practice, not the choice. +- Sources follow the verified-sourcing rule: each key claim names at least two independent approved sources, or carries an explicit single-source note. Source short names are expanded in Sources Used at the end. Where a behavior states a FormLedger design choice (a default, a limit) rather than a general accounting fact, the entry says so; the sources then back the underlying practice, not the choice. - Worked numbers in this file are FormLedger's own arithmetic on a sourced method. -There are 64 matched behaviours and 9 not-matched items. Of the 64, 56 rest fully on two or more independent sources, 7 are flagged as single-source, and 1 (B-AUDIT-01) has a two-source main claim with a single-source part. +There are 64 matched behaviors and 9 not-matched items. Of the 64, 56 rest fully on two or more independent sources, 7 are flagged as single-source, and 1 (B-AUDIT-01) has a two-source main claim with a single-source part. ## 1. Double entry (ledger core) @@ -432,7 +432,7 @@ A posting that would take an item's on-hand quantity in a warehouse below zero i v1: matched · Phase 6 [Source: Business Central help (Dynamics NAV 2013 R2), Prevent Negative Inventory field ("Specifies if you can post transactions that will bring inventory levels below zero"); corroborated by Frappe ERPNext, Stock Settings (Allow Negative Stock can be set globally or per item)] -The sources show that both refusing and allowing are recognised settings. Refusing by default is a FormLedger design choice. +The sources show that both refusing and allowing are recognized settings. Refusing by default is a FormLedger design choice. ### B-STOCK-08 · Cancelling a stock document reverses stock @@ -578,7 +578,7 @@ These are out of scope for version 1. FormLedger makes no claim about them, and These items are scope decisions, not factual claims, and carry no sources. -## Single-source behaviours +## Single-source behaviors B-LEDGER-04, B-DOC-08, B-DOC-10, B-PERIOD-03, B-SELL-10, B-AUDIT-01 (the cannot-edit part only), B-REPORT-03, B-REPORT-04. Further, these entries rest on two sources for the practice but on a FormLedger design choice for one detail: B-MONEY-02 (integer storage), B-STOCK-05 (rounding rule), B-STOCK-07 (refuse by default), B-DOC-10 (concurrency), B-AUDIT-01 (immutability). @@ -637,4 +637,4 @@ Official user documentation, Microsoft Dynamics 365 Business Central help (learn - Set up invoice rounding: https://learn.microsoft.com/en-us/dynamics365/business-central/finance-set-up-invoice-rounding - Prevent Negative Inventory field (Dynamics NAV 2013 R2): https://learn.microsoft.com/en-us/previous-versions/dynamics-nav-2013-r2/dn414711(v=nav.71) -Independence: OpenStax, the IRS, ISO, Frappe and Microsoft are separate organisations. Two pages from the same organisation are counted as one source. +Independence: OpenStax, the IRS, ISO, Frappe and Microsoft are separate organizations. Two pages from the same organization are counted as one source. From a9f912cb9d82a0c6907527829b33dd49344bcc13 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:31:32 -0500 Subject: [PATCH 06/51] feat(templates): add document templates with built-in starters Adds the templates table, a templates package with list, get, create, update, delete and use routes, and seven built-in starter templates. --- internal/server/server.go | 2 + internal/store/migrations/0019_templates.sql | 16 ++ internal/templates/module.go | 133 +++++++++ internal/templates/template.go | 282 +++++++++++++++++++ 4 files changed, 433 insertions(+) create mode 100644 internal/store/migrations/0019_templates.sql create mode 100644 internal/templates/module.go create mode 100644 internal/templates/template.go diff --git a/internal/server/server.go b/internal/server/server.go index c3f88db..be4ce9f 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -34,6 +34,7 @@ import ( "github.com/nodemode-ai/formledger/internal/store" "github.com/nodemode-ai/formledger/internal/suppliers" "github.com/nodemode-ai/formledger/internal/taxrates" + "github.com/nodemode-ai/formledger/internal/templates" ) type Server struct { @@ -76,6 +77,7 @@ func Build(ctx context.Context, cfg config.Config, log *slog.Logger, st *store.S stock.Module(st, accounts), suppliers.Module(st, accounts), taxrates.Module(accounts), + templates.Module(accounts), static.Module(nil), } return s, nil diff --git a/internal/store/migrations/0019_templates.sql b/internal/store/migrations/0019_templates.sql new file mode 100644 index 0000000..39f9b4d --- /dev/null +++ b/internal/store/migrations/0019_templates.sql @@ -0,0 +1,16 @@ +CREATE TABLE doc_templates ( + id TEXT PRIMARY KEY, + kind TEXT NOT NULL CHECK (kind IN ('quote', 'sales-order', 'sales-invoice', 'purchase-order', 'purchase-invoice')), + name TEXT NOT NULL, + description TEXT NOT NULL DEFAULT '', + category TEXT NOT NULL DEFAULT '', + party_id TEXT NOT NULL DEFAULT '', + currency TEXT NOT NULL DEFAULT '', + terms_days INTEGER NOT NULL DEFAULT 0 CHECK (terms_days >= 0), + notes TEXT NOT NULL DEFAULT '', + lines_json TEXT NOT NULL DEFAULT '[]', + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL +) STRICT; + +CREATE INDEX doc_templates_kind ON doc_templates (kind); diff --git a/internal/templates/module.go b/internal/templates/module.go new file mode 100644 index 0000000..ddf00af --- /dev/null +++ b/internal/templates/module.go @@ -0,0 +1,133 @@ +package templates + +import ( + "database/sql" + "net/http" + "time" + + "github.com/nodemode-ai/formledger/internal/app" + "github.com/nodemode-ai/formledger/internal/audit" + "github.com/nodemode-ai/formledger/internal/auth" + "github.com/nodemode-ai/formledger/internal/httpx" + "github.com/nodemode-ai/formledger/internal/policy" +) + +type module struct { + auth *auth.Service +} + +func Module(a *auth.Service) app.Module { return module{auth: a} } + +func (module) ID() string { return "templates" } + +func canWrite(p *policy.Principal, kind string) error { + info, ok := kinds[kind] + if !ok { + return invalid("bad_kind", "kind must be quote, sales-order, sales-invoice, purchase-order or purchase-invoice") + } + if !policy.Can(p, info.draft) { + return fail(http.StatusForbidden, "forbidden", "you cannot create "+kind+" documents") + } + return nil +} + +func (m module) Mount(r *httpx.Router, d *app.Deps) error { + svc := New(d.Store) + read := func(h auth.PrincipalHandler) http.HandlerFunc { return m.auth.Require(policy.ReportsRead, h) } + r.HandleFunc("GET /api/templates", read(func(w http.ResponseWriter, r *http.Request, _ *policy.Principal) error { + q := r.URL.Query() + list, err := svc.List(r.Context(), q.Get("kind"), q.Get("q")) + if err != nil { + return err + } + w.Header().Set("Cache-Control", "no-store") + httpx.JSON(w, http.StatusOK, map[string]any{"templates": list}) + return nil + })) + r.HandleFunc("GET /api/templates/{id}", read(func(w http.ResponseWriter, r *http.Request, _ *policy.Principal) error { + t, err := svc.Get(r.Context(), r.PathValue("id")) + if err != nil { + return err + } + w.Header().Set("Cache-Control", "no-store") + httpx.JSON(w, http.StatusOK, t) + return nil + })) + write := func(action string, status int, fn func(tx *sql.Tx, r *http.Request, p *policy.Principal) (Template, error)) http.HandlerFunc { + return read(func(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + var out Template + err := d.Store.Tx(r.Context(), func(tx *sql.Tx) error { + t, err := fn(tx, r, p) + if err != nil { + return err + } + out = t + return m.auth.Record(r, tx, m.auth.Actor(r, p), action, "template", t.ID, audit.OK, + map[string]any{"kind": t.Kind, "name": t.Name, "lines": len(t.Lines)}) + }) + if err != nil { + return err + } + if status == http.StatusNoContent { + w.WriteHeader(status) + return nil + } + httpx.JSON(w, status, out) + return nil + }) + } + r.HandleFunc("POST /api/templates", write("template.create", http.StatusCreated, func(tx *sql.Tx, r *http.Request, p *policy.Principal) (Template, error) { + var in Template + if err := httpx.Decode(r, &in); err != nil { + return in, err + } + if err := canWrite(p, in.Kind); err != nil { + return in, err + } + return svc.Create(r.Context(), tx, in) + })) + r.HandleFunc("PUT /api/templates/{id}", write("template.update", http.StatusOK, func(tx *sql.Tx, r *http.Request, p *policy.Principal) (Template, error) { + var in Template + if err := httpx.Decode(r, &in); err != nil { + return in, err + } + if err := canWrite(p, in.Kind); err != nil { + return in, err + } + if before, err := svc.Get(r.Context(), r.PathValue("id")); err == nil && !before.BuiltIn { + if err := canWrite(p, before.Kind); err != nil { + return in, err + } + } + return svc.Update(r.Context(), tx, r.PathValue("id"), in) + })) + r.HandleFunc("DELETE /api/templates/{id}", write("template.delete", http.StatusNoContent, func(tx *sql.Tx, r *http.Request, p *policy.Principal) (Template, error) { + before, err := svc.Get(r.Context(), r.PathValue("id")) + if err != nil { + return before, err + } + if !before.BuiltIn { + if err := canWrite(p, before.Kind); err != nil { + return before, err + } + } + return svc.Delete(r.Context(), tx, r.PathValue("id")) + })) + r.HandleFunc("POST /api/templates/{id}/use", read(func(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + t, err := svc.Get(r.Context(), r.PathValue("id")) + if err != nil { + return err + } + if err := canWrite(p, t.Kind); err != nil { + return err + } + body, err := svc.Use(r.Context(), t, time.Now()) + if err != nil { + return err + } + w.Header().Set("Cache-Control", "no-store") + httpx.JSON(w, http.StatusOK, body) + return nil + })) + return nil +} diff --git a/internal/templates/template.go b/internal/templates/template.go new file mode 100644 index 0000000..99643a5 --- /dev/null +++ b/internal/templates/template.go @@ -0,0 +1,282 @@ +package templates + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "net/http" + "sort" + "strings" + "time" + + "github.com/nodemode-ai/formledger/internal/httpx" + "github.com/nodemode-ai/formledger/internal/ids" + "github.com/nodemode-ai/formledger/internal/items" + "github.com/nodemode-ai/formledger/internal/policy" + "github.com/nodemode-ai/formledger/internal/store" +) + +type Line struct { + Item string `json:"item,omitempty"` + Description string `json:"description"` + QuantityMilli int64 `json:"quantityMilli"` + UnitPrice int64 `json:"unitPrice"` + CurrentPrice bool `json:"currentPrice"` + TaxRate string `json:"taxRate,omitempty"` +} + +type Template struct { + ID string `json:"id"` + Kind string `json:"kind"` + Name string `json:"name"` + Description string `json:"description"` + Category string `json:"category"` + Party string `json:"party"` + Currency string `json:"currency"` + TermsDays int `json:"termsDays"` + Notes string `json:"notes"` + Lines []Line `json:"lines"` + BuiltIn bool `json:"builtIn"` + CreatedAt int64 `json:"createdAt"` + UpdatedAt int64 `json:"updatedAt"` +} + +type kindInfo struct { + family, docKind, partyField string + draft policy.Action +} + +var kinds = map[string]kindInfo{ + "quote": {"sales", "quote", "customer", policy.SalesDraft}, + "sales-order": {"sales", "order", "customer", policy.SalesDraft}, + "sales-invoice": {"sales", "invoice", "customer", policy.SalesDraft}, + "purchase-order": {"purchase", "order", "supplier", policy.PurchaseDraft}, + "purchase-invoice": {"purchase", "invoice", "supplier", policy.PurchaseDraft}, +} + +func fail(status int, code, msg string) *httpx.APIError { return httpx.Fail(status, code, msg) } + +func invalid(code, msg string) *httpx.APIError { + return fail(http.StatusUnprocessableEntity, code, msg) +} + +func free(desc string, qty, price int64, tax string) Line { + return Line{Description: desc, QuantityMilli: qty, UnitPrice: price, TaxRate: tax} +} + +var builtins = []Template{ + {ID: "builtin-service-hours", Kind: "sales-invoice", Name: "Service invoice (hours)", Category: "Services", TermsDays: 30, + Description: "Hours worked at an hourly rate, with a line for expenses.", Notes: "Thank you for your business.", + Lines: []Line{free("Consulting hours", 10000, 12000, ""), free("Project management hours", 2000, 9000, ""), free("Expenses at cost", 1000, 0, "")}}, + {ID: "builtin-product", Kind: "sales-invoice", Name: "Product invoice", Category: "Products", TermsDays: 30, + Description: "Goods sold, with shipping on its own line.", + Lines: []Line{free("Product", 1000, 5000, ""), free("Shipping and handling", 1000, 1500, "")}}, + {ID: "builtin-retainer", Kind: "sales-invoice", Name: "Retainer invoice (monthly)", Category: "Services", TermsDays: 14, + Description: "A fixed monthly fee for ongoing work.", Notes: "Monthly retainer, billed in advance.", + Lines: []Line{free("Monthly retainer", 1000, 250000, "")}}, + {ID: "builtin-quote-options", Kind: "quote", Name: "Quote with options", Category: "Quotes", TermsDays: 30, + Description: "A base offer with optional extras the customer can choose.", Notes: "This quote is valid for 30 days.", + Lines: []Line{free("Base package", 1000, 150000, ""), free("Option A: extended support", 1000, 40000, ""), free("Option B: training session", 1000, 60000, "")}}, + {ID: "builtin-deposit", Kind: "sales-invoice", Name: "Deposit invoice (50 percent)", Category: "Deposits", TermsDays: 7, + Description: "Half of the agreed price, due before work starts.", Notes: "Deposit of 50 percent; the balance is invoiced on completion.", + Lines: []Line{free("Deposit, 50 percent of the agreed price", 1000, 100000, "")}}, + {ID: "builtin-po-stock", Kind: "purchase-order", Name: "Purchase order (stock)", Category: "Purchasing", TermsDays: 30, + Description: "Restocking goods from a supplier.", + Lines: []Line{free("Stock item", 10000, 1200, ""), free("Freight", 1000, 3500, "")}}, + {ID: "builtin-pi-services", Kind: "purchase-invoice", Name: "Purchase invoice (services)", Category: "Purchasing", TermsDays: 30, + Description: "A bill for services received from a supplier.", + Lines: []Line{free("Professional services", 1000, 80000, "")}}, +} + +func builtin(id string) (Template, bool) { + for _, t := range builtins { + if t.ID == id { + t.BuiltIn = true + return t, true + } + } + return Template{}, false +} + +type Service struct { + st *store.Store + items *items.Service +} + +func New(st *store.Store) *Service { return &Service{st: st, items: items.New(st)} } + +func clean(t *Template) error { + if _, ok := kinds[t.Kind]; !ok { + return invalid("bad_kind", "kind must be quote, sales-order, sales-invoice, purchase-order or purchase-invoice") + } + t.Name = strings.TrimSpace(t.Name) + if t.Name == "" || len([]rune(t.Name)) > 120 { + return invalid("bad_name", "name must be 1 to 120 characters") + } + t.Description, t.Category, t.Notes = strings.TrimSpace(t.Description), strings.TrimSpace(t.Category), strings.TrimSpace(t.Notes) + if len(t.Description) > 500 || len(t.Category) > 60 || len(t.Notes) > 500 { + return invalid("too_long", "description and notes allow 500 characters, category 60") + } + if t.TermsDays < 0 || t.TermsDays > 3650 { + return invalid("bad_terms", "termsDays must be 0 to 3650") + } + if len(t.Lines) > 200 { + return invalid("too_many_lines", "a template holds at most 200 lines") + } + if t.Lines == nil { + t.Lines = []Line{} + } + for i := range t.Lines { + l := &t.Lines[i] + l.Item, l.Description = strings.TrimSpace(l.Item), strings.TrimSpace(l.Description) + if l.Item == "" && l.Description == "" { + return invalid("bad_line", "each line needs an item or a description") + } + if l.QuantityMilli < 0 || l.UnitPrice < 0 { + return invalid("bad_line", "quantity and price cannot be negative") + } + if l.Item == "" { + l.CurrentPrice = false + } + } + return nil +} + +func scan(row interface{ Scan(...any) error }) (Template, error) { + var t Template + var lines string + err := row.Scan(&t.ID, &t.Kind, &t.Name, &t.Description, &t.Category, &t.Party, &t.Currency, &t.TermsDays, &t.Notes, &lines, &t.CreatedAt, &t.UpdatedAt) + if err == nil { + err = json.Unmarshal([]byte(lines), &t.Lines) + } + return t, err +} + +const cols = `id, kind, name, description, category, party_id, currency, terms_days, notes, lines_json, created_at, updated_at` + +func (s *Service) Get(ctx context.Context, id string) (Template, error) { + if t, ok := builtin(id); ok { + return t, nil + } + t, err := scan(s.st.R.QueryRowContext(ctx, `SELECT `+cols+` FROM doc_templates WHERE id = ?`, id)) + if errors.Is(err, sql.ErrNoRows) { + return t, fail(http.StatusNotFound, "template_not_found", "no template with id "+id) + } + return t, err +} + +func matches(t Template, kind, q string) bool { + if kind != "" && t.Kind != kind { + return false + } + if q == "" { + return true + } + hay := strings.ToLower(t.Name + " " + t.Description + " " + t.Category + " " + t.Kind) + return strings.Contains(hay, q) +} + +func (s *Service) List(ctx context.Context, kind, q string) ([]Template, error) { + q = strings.ToLower(strings.TrimSpace(q)) + out := []Template{} + for _, t := range builtins { + t.BuiltIn = true + if matches(t, kind, q) { + out = append(out, t) + } + } + rows, err := s.st.R.QueryContext(ctx, `SELECT `+cols+` FROM doc_templates ORDER BY name COLLATE NOCASE`) + if err != nil { + return nil, err + } + defer rows.Close() + var own []Template + for rows.Next() { + t, err := scan(rows) + if err != nil { + return nil, err + } + if matches(t, kind, q) { + own = append(own, t) + } + } + sort.SliceStable(own, func(i, j int) bool { return strings.ToLower(own[i].Name) < strings.ToLower(own[j].Name) }) + return append(out, own...), rows.Err() +} + +func (s *Service) Create(ctx context.Context, q store.Querier, t Template) (Template, error) { + if err := clean(&t); err != nil { + return t, err + } + lines, _ := json.Marshal(t.Lines) + t.ID, t.CreatedAt = ids.New(), store.NowMS() + t.UpdatedAt, t.BuiltIn = t.CreatedAt, false + _, err := q.ExecContext(ctx, `INSERT INTO doc_templates (`+cols+`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + t.ID, t.Kind, t.Name, t.Description, t.Category, t.Party, t.Currency, t.TermsDays, t.Notes, string(lines), t.CreatedAt, t.UpdatedAt) + return t, err +} + +func (s *Service) Update(ctx context.Context, q store.Querier, id string, t Template) (Template, error) { + if _, ok := builtin(id); ok { + return t, fail(http.StatusConflict, "builtin_template", "built-in templates are read-only; duplicate it to change it") + } + before, err := s.Get(ctx, id) + if err != nil { + return t, err + } + if err := clean(&t); err != nil { + return t, err + } + lines, _ := json.Marshal(t.Lines) + t.ID, t.CreatedAt, t.UpdatedAt = id, before.CreatedAt, store.NowMS() + _, err = q.ExecContext(ctx, `UPDATE doc_templates SET kind = ?, name = ?, description = ?, category = ?, party_id = ?, currency = ?, + terms_days = ?, notes = ?, lines_json = ?, updated_at = ? WHERE id = ?`, + t.Kind, t.Name, t.Description, t.Category, t.Party, t.Currency, t.TermsDays, t.Notes, string(lines), t.UpdatedAt, id) + return t, err +} + +func (s *Service) Delete(ctx context.Context, q store.Querier, id string) (Template, error) { + if _, ok := builtin(id); ok { + return Template{}, fail(http.StatusConflict, "builtin_template", "built-in templates cannot be deleted") + } + t, err := s.Get(ctx, id) + if err != nil { + return t, err + } + _, err = q.ExecContext(ctx, `DELETE FROM doc_templates WHERE id = ?`, id) + return t, err +} + +func (s *Service) Use(ctx context.Context, t Template, today time.Time) (map[string]any, error) { + info := kinds[t.Kind] + lines := make([]map[string]any, 0, len(t.Lines)) + for _, l := range t.Lines { + out := map[string]any{"description": l.Description, "quantityMilli": l.QuantityMilli, "unitPrice": l.UnitPrice, "taxRate": l.TaxRate} + if l.Item != "" { + it, err := s.items.Get(ctx, nil, l.Item) + if err != nil { + it, err = s.items.ByCode(ctx, nil, l.Item) + } + if err != nil { + return nil, invalid("unknown_item", "template line names item "+l.Item+", which no longer exists") + } + out["item"], out["itemCode"] = it.ID, it.Code + if l.CurrentPrice { + out["unitPrice"] = it.SalePrice + } + if l.TaxRate == "" { + out["taxRate"] = it.TaxRateID + } + } + lines = append(lines, out) + } + body := map[string]any{ + "family": info.family, "kind": info.docKind, "date": today.Format("2006-01-02"), + info.partyField: t.Party, "currency": t.Currency, "memo": t.Notes, "lines": lines, "template": t.ID, + } + if t.TermsDays > 0 { + body["dueDate"] = today.AddDate(0, 0, t.TermsDays).Format("2006-01-02") + } + return body, nil +} From 022105cf44e0c1dca84138662042e5038d01e523 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:31:32 -0500 Subject: [PATCH 07/51] docs(spelling): american spelling in contributing and conduct Organization, license and artifacts. --- BRANCHING.md | 2 +- CODE_OF_CONDUCT.md | 2 +- CONTRIBUTING.md | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/BRANCHING.md b/BRANCHING.md index 4ee5fa7..1c75f71 100644 --- a/BRANCHING.md +++ b/BRANCHING.md @@ -40,7 +40,7 @@ Examples: `feature/server-data-dir`, `fix/web-dev-proxy-origin`, `docs/readme-qu ## Releases and tagging -This repository has no release workflow and builds no release artefacts: packaging and releases are done by FormCompiler (`nodemode-dev/formcompiler`). A release starts with one version bump commit on `main`. +This repository has no release workflow and builds no release artifacts: packaging and releases are done by FormCompiler (`nodemode-dev/formcompiler`). A release starts with one version bump commit on `main`. 1. On a `chore/release-vX.Y.Z` branch, bump the version everywhere it is written: - `VERSION := vX.Y.Z` in `Makefile` diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index ddc0889..e2e5af0 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -26,7 +26,7 @@ for the project elsewhere. Report anything that breaks this code by opening an [issue](https://github.com/nodemode-dev/formledger/issues), or by reaching the maintainers on GitHub: the [nodemode-dev](https://github.com/nodemode-dev) -organisation, [@nodemode-ai](https://github.com/nodemode-ai) and +organization, [@nodemode-ai](https://github.com/nodemode-ai) and [@gbarnai](https://github.com/gbarnai). ## What happens next diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b065a47..3cead65 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -51,7 +51,7 @@ There are no automated tests yet. FormLedger is maintained by: -- the [nodemode-dev](https://github.com/nodemode-dev) organisation on GitHub +- the [nodemode-dev](https://github.com/nodemode-dev) organization on GitHub - [@nodemode-ai](https://github.com/nodemode-ai) - [@gbarnai](https://github.com/gbarnai) @@ -72,14 +72,14 @@ release. See [BRANCHING.md](BRANCHING.md). FormLedger is licensed under the Apache License 2.0 ([LICENSE](LICENSE), SPDX `Apache-2.0`). By contributing, you agree that your contribution is licensed under the same terms. Only add code you have the right to contribute, and name any third-party -code and its licence in the pull request. +code and its license in the pull request. ### Rules for every contribution - Patents: do not add a feature, or a dependency that provides one, that reproduces a method you know to be patented. If you are unsure, open an issue that describes what the feature does, not which patent it resembles. Patent numbers stay out of code, commits, comments, logs and changelogs. - Trademarks: other vendors' product and feature names appear only to name a file format or compatibility ("opens files", "for use with"). No command, menu, panel or tool takes another product's feature name, and no text says "like X" or "the way X does it". Describe what the feature does. - Copyright: never copy another product's help, tooltip, dialog or documentation text (link to it instead); never trace or import vendor icons; never bundle vendor templates, themes, sample files, stock media or fonts. -- Licences: every new dependency, binary or data file gets a row in `NOTICE.md` before it is used. GPL stays outside the distributed bundle, AGPL nowhere, LGPL dynamically linked and replaceable, MPL files unedited. CC BY credited, CC BY-SA only unmodified, CC NC and ND never. +- Licenses: every new dependency, binary or data file gets a row in `NOTICE.md` before it is used. GPL stays outside the distributed bundle, AGPL nowhere, LGPL dynamically linked and replaceable, MPL files unedited. CC BY credited, CC BY-SA only unmodified, CC NC and ND never. ## Conduct From 3b03b179d2b2f3f297e7c26b3992d792c290c817 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:31:32 -0500 Subject: [PATCH 08/51] docs(spelling): american spelling in roles, payments and window Behavior, neighbor and grayed. --- docs/ROLES.md | 4 ++-- docs/buying/payments.md | 2 +- docs/ledger/money.md | 2 +- docs/window/README.md | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/ROLES.md b/docs/ROLES.md index 8b76367..7ac1d76 100644 --- a/docs/ROLES.md +++ b/docs/ROLES.md @@ -1,6 +1,6 @@ # Roles -FormLedger gives every user one role. What a role may do is set in one place, `internal/policy/policy.go`, and every server route asks that table through `policy.Can`. This page is the same table in plain words. Each row names the behaviour in `docs/BEHAVIOURS.md` it serves. +FormLedger gives every user one role. What a role may do is set in one place, `internal/policy/policy.go`, and every server route asks that table through `policy.Can`. This page is the same table in plain words. Each row names the behavior in `docs/BEHAVIOURS.md` it serves. ## The roles @@ -13,7 +13,7 @@ FormLedger gives every user one role. What a role may do is set in one place, `i ## Role by action -| Action | What it allows | owner | accountant | sales | purchasing | stock | viewer | Behaviour | +| Action | What it allows | owner | accountant | sales | purchasing | stock | viewer | Behavior | |---|---|---|---|---|---|---|---|---| | `users.manage` | invite users, list and withdraw invitations | yes | no | no | no | no | no | B-ROLE-03 | | `settings.manage` | change settings of this copy, turn the app lock on or off | yes | no | no | no | no | no | B-ROLE-03 | diff --git a/docs/buying/payments.md b/docs/buying/payments.md index 3ac1e67..0cafc9f 100644 --- a/docs/buying/payments.md +++ b/docs/buying/payments.md @@ -1,6 +1,6 @@ # Payments made -A payment made records money paid out to a supplier. It posts one journal entry and can be allocated to one or more of that supplier's posted purchase invoices, in full or in part. What is not allocated stays on account. This is behaviour B-BUY-06, the mirror of payments received (`docs/selling/payments.md`): every rule there holds here unless this page says otherwise. +A payment made records money paid out to a supplier. It posts one journal entry and can be allocated to one or more of that supplier's posted purchase invoices, in full or in part. What is not allocated stays on account. This is behavior B-BUY-06, the mirror of payments received (`docs/selling/payments.md`): every rule there holds here unless this page says otherwise. Code: `internal/paymentsmade` (copied from `internal/payments`, then edited by hand), migration `internal/store/migrations/0016_payments_made.sql`, command-line verbs in `internal/cli/paymentsmade.go`. diff --git a/docs/ledger/money.md b/docs/ledger/money.md index b4a5a8a..fe397ab 100644 --- a/docs/ledger/money.md +++ b/docs/ledger/money.md @@ -56,7 +56,7 @@ The parts always add up to the total exactly. Each part first gets its share rou Multiplies by the fraction numerator/denominator and rounds once to a whole minor unit. A rate of 8.25 percent is `825, 10000`. The denominator must be positive. - `HalfUp`: a half rounds away from zero. 2.50 becomes 3, -2.50 becomes -3. -- `HalfEven`: a half rounds to the even neighbour. 2.50 becomes 2, 3.50 becomes 4. +- `HalfEven`: a half rounds to the even neighbor. 2.50 becomes 2, 3.50 becomes 4. - 8.25 percent of 1000 is 82.5: `HalfEven` gives `82`, `HalfUp` gives `83`. Which mode a document uses is decided by the tax and rounding work in a later phase. diff --git a/docs/window/README.md b/docs/window/README.md index 0309ba2..391b49f 100644 --- a/docs/window/README.md +++ b/docs/window/README.md @@ -18,7 +18,7 @@ The grid of lines has a fixed height of eight lines and scrolls after that; the The server works out every amount. Line totals and the document total appear after a save, in space that was already there for them. -The buttons along the bottom are always the same ones; a button that does not apply right now is greyed, not removed. From there a document is saved as a draft, confirmed or posted, cancelled or amended, and the next document in the chain is made: an order from a quote, an invoice from an order, a delivery note or a goods receipt. +The buttons along the bottom are always the same ones; a button that does not apply right now is grayed, not removed. From there a document is saved as a draft, confirmed or posted, cancelled or amended, and the next document in the chain is made: an order from a quote, an invoice from an order, a delivery note or a goods receipt. When the server refuses something, for example a locked period, its own sentence is shown under the grid. From 2d47bc91a90be9feb07301fdf85c879f0e99e510 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:32:17 -0500 Subject: [PATCH 09/51] feat(printout): put a formtxt renderer in front of the plain one The statement comes under the renderer interface, a FormTxt renderer calls the engine's report route and gives way to plain on any failure, and the print route names the renderer that answered. --- internal/printout/document.go | 23 +++++-- internal/printout/formtxt.go | 109 +++++++++++++++++++++++++++++++++ internal/printout/module.go | 7 ++- internal/printout/plain.go | 2 + internal/printout/statement.go | 2 +- 5 files changed, 135 insertions(+), 8 deletions(-) create mode 100644 internal/printout/formtxt.go diff --git a/internal/printout/document.go b/internal/printout/document.go index c9518d7..8ff3411 100644 --- a/internal/printout/document.go +++ b/internal/printout/document.go @@ -8,20 +8,33 @@ import ( var ErrUnavailable = errors.New("renderer not available") type Renderer interface { + Name() string Render(d *Document) ([]byte, error) + Statement(s *Statement) ([]byte, error) } -var renderers = []Renderer{plain{}} +var renderers = []Renderer{formtxt{}, plain{}} -func Render(d *Document) ([]byte, error) { +func pick(plainOnly bool, draw func(Renderer) ([]byte, error)) ([]byte, string, error) { for _, r := range renderers { - b, err := r.Render(d) + if plainOnly && r.Name() != "plain" { + continue + } + b, err := draw(r) if errors.Is(err, ErrUnavailable) { continue } - return b, err + return b, r.Name(), err } - return nil, ErrUnavailable + return nil, "", ErrUnavailable +} + +func Render(d *Document, plainOnly bool) ([]byte, string, error) { + return pick(plainOnly, func(r Renderer) ([]byte, error) { return r.Render(d) }) +} + +func RenderStatement(s *Statement, plainOnly bool) ([]byte, string, error) { + return pick(plainOnly, func(r Renderer) ([]byte, error) { return r.Statement(s) }) } type Line struct { diff --git a/internal/printout/formtxt.go b/internal/printout/formtxt.go new file mode 100644 index 0000000..b0abab3 --- /dev/null +++ b/internal/printout/formtxt.go @@ -0,0 +1,109 @@ +package printout + +import ( + "bytes" + "encoding/json" + "net/http" + "os" + "path/filepath" + "strings" + "time" +) + +type formtxt struct{} + +func (formtxt) Name() string { return "formtxt" } + +func formtxtBase() string { + if strings.EqualFold(strings.TrimSpace(os.Getenv("FORMLEDGER_PRINT")), "plain") { + return "" + } + port := strings.TrimSpace(os.Getenv("FORMTXT_ENGINE_PORT")) + if port == "" { + port = "8210" + } + return "http://127.0.0.1:" + port +} + +func formtxtTemplate(kind string) string { + return strings.TrimSpace(os.Getenv("FORMLEDGER_FORMTXT_TEMPLATE_" + strings.ToUpper(strings.ReplaceAll(kind, "-", "_")))) +} + +func (f formtxt) Render(d *Document) ([]byte, error) { + kind := d.Kind + if d.Side == "purchase" { + kind = "purchase-" + d.Kind + } + head := map[string]any{ + "company": d.Company, "title": d.Title(), "number": d.Number, "date": d.Date, "dueDate": d.DueDate, + "customer": d.Customer, "customerName": d.CustomerName, "supplier": d.Supplier, "supplierName": d.SupplierName, + "currency": d.Currency, "status": d.Status, "memo": d.Memo, + "subtotal": amount(d.Subtotal, d.Currency), "taxTotal": amount(d.TaxTotal, d.Currency), "total": amount(d.Total, d.Currency), + } + var rows []map[string]any + for _, l := range d.Lines { + r := map[string]any{"item": l.Item, "description": l.Description, "quantity": quantity(l.QuantityMilli), + "unitPrice": amount(l.UnitPrice, d.Currency), "taxRate": l.TaxRate, "lineSubtotal": amount(l.LineSubtotal, d.Currency)} + for k, v := range head { + r[k] = v + } + rows = append(rows, r) + } + if len(rows) == 0 { + rows = append(rows, head) + } + return f.run(kind, d.Title()+" "+d.Number, rows) +} + +func (f formtxt) Statement(s *Statement) ([]byte, error) { + head := map[string]any{ + "company": s.Company, "customer": s.Customer.Code, "customerName": s.Customer.Name, "currency": s.Currency, + "from": s.From, "to": s.To, "opening": amount(s.Opening, s.Currency), "closing": amount(s.Closing, s.Currency), + } + var rows []map[string]any + for _, l := range s.Lines { + r := map[string]any{"lineDate": l.Date, "event": eventWords[l.Kind], "reference": l.Number, + "debit": amount(l.Debit, s.Currency), "credit": amount(l.Credit, s.Currency), "balance": amount(l.Balance, s.Currency)} + for k, v := range head { + r[k] = v + } + rows = append(rows, r) + } + if len(rows) == 0 { + rows = append(rows, head) + } + return f.run("statement", "Statement "+s.Customer.Code, rows) +} + +func (formtxt) run(kind, title string, rows []map[string]any) ([]byte, error) { + base, template := formtxtBase(), formtxtTemplate(kind) + if base == "" || template == "" { + return nil, ErrUnavailable + } + dir, err := os.MkdirTemp("", "formledger-print-") + if err != nil { + return nil, ErrUnavailable + } + defer os.RemoveAll(dir) + out := filepath.Join(dir, "print.pdf") + body, err := json.Marshal(map[string]any{ + "template": template, "data": map[string]any{"records": rows}, + "mode": "list", "format": "pdf", "out": out, "title": title, + }) + if err != nil { + return nil, ErrUnavailable + } + resp, err := (&http.Client{Timeout: 45 * time.Second}).Post(base+"/api/reports/run", "application/json", bytes.NewReader(body)) + if err != nil { + return nil, ErrUnavailable + } + resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, ErrUnavailable + } + pdf, err := os.ReadFile(out) + if err != nil || !bytes.HasPrefix(pdf, []byte("%PDF")) { + return nil, ErrUnavailable + } + return pdf, nil +} diff --git a/internal/printout/module.go b/internal/printout/module.go index 040796e..b6637b1 100644 --- a/internal/printout/module.go +++ b/internal/printout/module.go @@ -51,13 +51,15 @@ func (module) Mount(rt *httpx.Router, d *app.Deps) error { } st, err := DecodeStatement(raw, company) var body []byte + var by string if err == nil { - body, err = RenderStatement(st) + body, by, err = RenderStatement(st, r.URL.Query().Get("renderer") == "plain") } if err != nil { httpx.Error(w, http.StatusInternalServerError, "internal", "the PDF could not be drawn") return } + w.Header().Set("X-FormLedger-Renderer", by) w.Header().Set("Content-Type", "application/pdf") w.Header().Set("Content-Disposition", `attachment; filename="statement-`+safeName(st.Customer.Code)+`-`+safeName(st.To)+`.pdf"`) _, _ = w.Write(body) @@ -93,11 +95,12 @@ func (module) Mount(rt *httpx.Router, d *app.Deps) error { httpx.Error(w, http.StatusNotFound, "not_found", "no "+r.PathValue("kind")+" with that id or number") return } - body, err := Render(doc) + body, by, err := Render(doc, r.URL.Query().Get("renderer") == "plain") if err != nil { httpx.Error(w, http.StatusInternalServerError, "internal", "the PDF could not be drawn") return } + w.Header().Set("X-FormLedger-Renderer", by) name := doc.Number if name == "" { name = doc.Kind + "-draft" diff --git a/internal/printout/plain.go b/internal/printout/plain.go index f5d4aaa..ab834a1 100644 --- a/internal/printout/plain.go +++ b/internal/printout/plain.go @@ -34,6 +34,8 @@ func quantity(milli int64) string { return s } +func (plain) Name() string { return "plain" } + func (plain) Render(d *Document) ([]byte, error) { pdf := fpdf.New("P", "mm", PageSize(d.Currency), "") tr := pdf.UnicodeTranslatorFromDescriptor("cp1252") diff --git a/internal/printout/statement.go b/internal/printout/statement.go index e9ba21d..db01c1a 100644 --- a/internal/printout/statement.go +++ b/internal/printout/statement.go @@ -43,7 +43,7 @@ func DecodeStatement(raw []byte, company string) (*Statement, error) { var eventWords = map[string]string{"invoice": "Invoice", "payment": "Payment", "invoice_cancelled": "Invoice cancelled", "payment_cancelled": "Payment cancelled"} -func RenderStatement(s *Statement) ([]byte, error) { +func (plain) Statement(s *Statement) ([]byte, error) { pdf := fpdf.New("P", "mm", PageSize(s.Currency), "") tr := pdf.UnicodeTranslatorFromDescriptor("cp1252") t := func(v string) string { return tr(printable(v)) } From d7970c2534a988db4100efeda3b70338bce52169 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:32:17 -0500 Subject: [PATCH 10/51] feat(printout): add a plain flag and name the renderer on stderr The print command takes --plain to force the fallback and says on standard error which renderer drew the file. --- internal/printout/command.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/internal/printout/command.go b/internal/printout/command.go index d56daf6..926ac39 100644 --- a/internal/printout/command.go +++ b/internal/printout/command.go @@ -12,7 +12,7 @@ import ( "time" ) -const Usage = "print KIND NUMBER [--out FILE] [--token-file FILE], or print statement CUSTOMER [--from DATE] [--to DATE]" +const Usage = "print KIND NUMBER [--out FILE] [--token-file FILE] [--plain], or print statement CUSTOMER [--from DATE] [--to DATE] [--plain]" func Command(args []string, out io.Writer) error { var pos []string @@ -25,6 +25,10 @@ func Command(args []string, out io.Writer) error { continue } k, v, has := strings.Cut(strings.TrimLeft(a, "-"), "=") + if k == "plain" && !has { + q.Set("renderer", "plain") + continue + } if !has { if i+1 >= len(args) { return fmt.Errorf("--%s needs a value", k) @@ -86,6 +90,7 @@ func Command(args []string, out io.Writer) error { if resp.StatusCode != http.StatusOK { return fmt.Errorf("print %s %s answered %d: %s", pos[0], pos[1], resp.StatusCode, strings.TrimSpace(string(body))) } + fmt.Fprintf(os.Stderr, "printed by the %s renderer\n", resp.Header.Get("X-FormLedger-Renderer")) if file == "" { _, err = out.Write(body) return err From f4607a6c175e3079dadc12bdd1fcb2c3aa3cce54 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:32:20 -0500 Subject: [PATCH 11/51] feat(config): add the formledger key file setting FORMLEDGER_KEY_FILE names the at-rest encryption key, as FORMMD_KEY_FILE does in form.md. --- internal/config/config.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/internal/config/config.go b/internal/config/config.go index f22ebb4..9064eea 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -19,6 +19,8 @@ type Config struct { TLSCert string TLSKey string + KeyFile string + ACMEDomains []string ACMEEmail string ACMEDirectory string @@ -38,6 +40,7 @@ var Vars = []Var{ {"DATA", "./data", "data directory holding the database"}, {"TLS_CERT", "", "path to a TLS certificate; set together with FORMLEDGER_TLS_KEY"}, {"TLS_KEY", "", "path to the TLS private key; set together with FORMLEDGER_TLS_CERT"}, + {"KEY_FILE", "", "path to the at-rest encryption key (formledger keygen makes one); keep it outside the data directory. A systemd credential named formledger.key is used when this is unset"}, {"ACME_DOMAINS", "", "comma-separated host names to get certificates for automatically (Let's Encrypt by default); needs ports 443 and 80 reachable"}, {"ACME_EMAIL", "", "contact address given to the certificate authority"}, {"ACME_DIRECTORY", "https://acme-v02.api.letsencrypt.org/directory", "ACME directory URL; point it at a staging or private CA to test"}, @@ -51,6 +54,7 @@ func Load() (Config, error) { DataDir: get("DATA"), TLSCert: get("TLS_CERT"), TLSKey: get("TLS_KEY"), + KeyFile: get("KEY_FILE"), ACMEEmail: get("ACME_EMAIL"), ACMEDirectory: get("ACME_DIRECTORY"), From 16108846f1e34359c5d69e49f9bb564ef22fe819 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:32:20 -0500 Subject: [PATCH 12/51] feat(store): open the ledger through the encrypting vfs when a key is set Ports the form.md store open path: the formledger-crypt VFS with keys derived from the master key, and a 4096-byte page check. --- internal/store/store.go | 42 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/internal/store/store.go b/internal/store/store.go index fe93d17..1f8370a 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -9,8 +9,11 @@ import ( "os" "path/filepath" "runtime" + "sync" "time" + "github.com/nodemode-ai/formledger/internal/crypt" + "github.com/nodemode-ai/formledger/internal/cryptvfs" _ "modernc.org/sqlite" ) @@ -20,6 +23,20 @@ type Store struct { W *sql.DB R *sql.DB Path string + Key *crypt.Key + vfs string +} + +const VFSName = "formledger-crypt" + +var registered sync.Once + +func Register(key *crypt.Key) error { + var err error + registered.Do(func() { + err = cryptvfs.Register(VFSName, cryptvfs.Keys{DB: key.Sub("db", 64), WAL: key.Sub("wal", 64), Journal: key.Sub("journal", 64)}) + }) + return err } func HasData(dataDir string) bool { @@ -27,7 +44,7 @@ func HasData(dataDir string) bool { return err == nil && st.Size() > 0 } -func Open(ctx context.Context, dataDir string) (*Store, error) { +func Open(ctx context.Context, dataDir string, key *crypt.Key) (*Store, error) { if err := os.MkdirAll(dataDir, 0o700); err != nil { return nil, fmt.Errorf("data directory: %w", err) } @@ -41,7 +58,13 @@ func Open(ctx context.Context, dataDir string) (*Store, error) { _ = os.Chmod(path+suffix, 0o600) } } - s := &Store{Path: path} + s := &Store{Path: path, Key: key} + if key != nil { + if err := Register(key); err != nil { + return nil, err + } + s.vfs = VFSName + } w, err := sql.Open("sqlite", s.dsn(true)) if err != nil { @@ -56,6 +79,13 @@ func Open(ctx context.Context, dataDir string) (*Store, error) { } s.W = w + if s.vfs != "" { + var size int + if err := w.QueryRowContext(ctx, "PRAGMA page_size").Scan(&size); err != nil || size != cryptvfs.PageSize { + w.Close() + return nil, fmt.Errorf("an encrypted database must use %d-byte pages (found %d): %v", cryptvfs.PageSize, size, err) + } + } if err := s.migrate(ctx); err != nil { w.Close() return nil, err @@ -80,6 +110,10 @@ func Open(ctx context.Context, dataDir string) (*Store, error) { func (s *Store) dsn(writer bool) string { q := url.Values{} + if s.vfs != "" { + q.Set("vfs", s.vfs) + q.Add("_pragma", "temp_store(MEMORY)") + } q.Add("_pragma", "busy_timeout(5000)") q.Add("_pragma", "foreign_keys(1)") q.Add("_pragma", "synchronous(NORMAL)") @@ -92,6 +126,10 @@ func (s *Store) dsn(writer bool) string { return s.Path + "?" + q.Encode() } +func (s *Store) VFS() string { + return s.vfs +} + func (s *Store) Ping(ctx context.Context) error { var one int return s.R.QueryRowContext(ctx, "SELECT 1").Scan(&one) From b1d42040859a6b712577231d61f4be0f04867f57 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:32:20 -0500 Subject: [PATCH 13/51] feat(startup): load the key before the store opens The server and the snapshot command check the key against encryption.json and refuse a locked or wrong-keyed data directory before opening it. --- cmd/formledger/main.go | 40 +++++++++++++++++- internal/crypt/key.go | 2 +- internal/snapshot/command.go | 8 +++- internal/store/encrypt.go | 78 ++++++++++++++++++++++++++++++++++++ 4 files changed, 125 insertions(+), 3 deletions(-) create mode 100644 internal/store/encrypt.go diff --git a/cmd/formledger/main.go b/cmd/formledger/main.go index 615b67a..0178a88 100644 --- a/cmd/formledger/main.go +++ b/cmd/formledger/main.go @@ -16,6 +16,7 @@ import ( "github.com/nodemode-ai/formledger/internal/auth" "github.com/nodemode-ai/formledger/internal/cli" "github.com/nodemode-ai/formledger/internal/config" + "github.com/nodemode-ai/formledger/internal/crypt" "github.com/nodemode-ai/formledger/internal/nowindow" "github.com/nodemode-ai/formledger/internal/server" "github.com/nodemode-ai/formledger/internal/snapshot" @@ -39,6 +40,11 @@ func run(args []string) int { return cli.Run(args[1:], os.Stdout, os.Stderr) case "report": return snapshot.Main(args[1:], os.Stdout, os.Stderr) + case "keygen": + fmt.Println(crypt.Generate()) + return 0 + case "encrypt": + return encrypt() case "version", "--version", "-v": fmt.Println(app.Version) return 0 @@ -52,6 +58,26 @@ func run(args []string) int { } } +func encrypt() int { + cfg, err := config.Load() + if err != nil { + fmt.Fprintln(os.Stderr, "formledger:", err) + return 2 + } + release, _, err := startup.Claim(cfg.DataDir, 0) + if err != nil { + fmt.Fprintln(os.Stderr, "formledger encrypt:", err) + return 2 + } + defer release() + if err := store.Encrypt(context.Background(), cfg.DataDir, cfg.KeyFile); err != nil { + fmt.Fprintln(os.Stderr, "formledger encrypt:", err) + return 1 + } + fmt.Println("encrypted the database; start FormLedger with the same FORMLEDGER_KEY_FILE") + return 0 +} + func serve() int { nowindow.OpenConsole() log := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelInfo})) @@ -92,11 +118,21 @@ func serve() int { if replaced > 0 { log.Info("an engine left running by an earlier start was stopped", "pid", replaced) } - st, err := store.Open(ctx, cfg.DataDir) + key, err := crypt.Load(cfg.DataDir, crypt.KeyPath(cfg.KeyFile), store.HasData(cfg.DataDir)) + if err != nil { + log.Error("encryption", "err", err) + return 2 + } + st, err := store.Open(ctx, cfg.DataDir, key) if err != nil { log.Error("storage", "err", err) return 1 } + if key != nil { + log.Info("at-rest encryption on", "database", "xts-aes-256") + } else { + log.Info("at-rest encryption off: set FORMLEDGER_KEY_FILE to a key from formledger keygen (an existing ledger needs formledger encrypt first)") + } defer func() { if err := st.Close(); err != nil { log.Error("storage close", "err", err) @@ -139,6 +175,8 @@ func usage(w io.Writer) { fmt.Fprintln(w, " serve run the server (default)") fmt.Fprintln(w, " cli ledger commands against the running server (formledger cli --help)") fmt.Fprintln(w, " report snapshot write a plain read-only SQLite snapshot (--out FILE, --force; server stopped)") + fmt.Fprintln(w, " keygen print a new at-rest encryption key") + fmt.Fprintln(w, " encrypt encrypt an existing plain ledger with FORMLEDGER_KEY_FILE (server stopped)") fmt.Fprintln(w, " version print the version") fmt.Fprintln(w, " help show this help") fmt.Fprintln(w, "\nEnvironment:") diff --git a/internal/crypt/key.go b/internal/crypt/key.go index 29d3a93..e236a52 100644 --- a/internal/crypt/key.go +++ b/internal/crypt/key.go @@ -111,7 +111,7 @@ func Load(dataDir, keyFile string, hasData bool) (*Key, error) { return k, nil } if hasData { - return nil, errors.New("a key is set but this FormLedger data directory is not encrypted: start with an empty data directory or unset FORMLEDGER_KEY_FILE") + return nil, errors.New("a key is set but this FormLedger data directory is not encrypted: stop FormLedger and run formledger encrypt first") } if err := os.MkdirAll(dataDir, 0o700); err != nil { return nil, err diff --git a/internal/snapshot/command.go b/internal/snapshot/command.go index 7bf8f89..f21dd87 100644 --- a/internal/snapshot/command.go +++ b/internal/snapshot/command.go @@ -10,6 +10,7 @@ import ( "time" "github.com/nodemode-ai/formledger/internal/config" + "github.com/nodemode-ai/formledger/internal/crypt" "github.com/nodemode-ai/formledger/internal/startup" "github.com/nodemode-ai/formledger/internal/store" ) @@ -53,7 +54,12 @@ func Main(args []string, stdout, stderr io.Writer) int { } defer release() ctx := context.Background() - st, err := store.Open(ctx, cfg.DataDir) + key, err := crypt.Load(cfg.DataDir, crypt.KeyPath(cfg.KeyFile), true) + if err != nil { + fmt.Fprintln(stderr, "formledger: encryption:", err) + return 2 + } + st, err := store.Open(ctx, cfg.DataDir, key) if err != nil { fmt.Fprintln(stderr, "formledger: storage:", err) return 1 diff --git a/internal/store/encrypt.go b/internal/store/encrypt.go new file mode 100644 index 0000000..2f8cb0a --- /dev/null +++ b/internal/store/encrypt.go @@ -0,0 +1,78 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/nodemode-ai/formledger/internal/crypt" +) + +func Encrypt(ctx context.Context, dataDir, keyFile string) error { + path := crypt.KeyPath(keyFile) + if path == "" { + return errors.New("set FORMLEDGER_KEY_FILE to the key (formledger keygen makes one, keep it outside the data directory)") + } + key, err := crypt.ReadKey(path) + if err != nil { + return err + } + if crypt.Encrypted(dataDir) { + _, err := crypt.Load(dataDir, path, true) + return err + } + if !HasData(dataDir) { + return errors.New("there is no ledger to encrypt; start FormLedger with FORMLEDGER_KEY_FILE set and it is encrypted from the first write") + } + + dbPath := filepath.Join(dataDir, FileName) + encPath := dbPath + ".encrypting" + os.Remove(encPath) + plain, err := sql.Open("sqlite", dbPath+"?_pragma=busy_timeout(5000)") + if err != nil { + return err + } + if _, err := plain.ExecContext(ctx, "PRAGMA wal_checkpoint(TRUNCATE)"); err != nil { + plain.Close() + return err + } + if err := Register(key); err != nil { + plain.Close() + return err + } + _, err = plain.ExecContext(ctx, "VACUUM INTO "+sqlString("file:"+encPath+"?vfs="+VFSName)) + plain.Close() + if err != nil { + os.Remove(encPath) + return fmt.Errorf("encrypting the database: %w", err) + } + enc, err := sql.Open("sqlite", "file:"+encPath+"?vfs="+VFSName) + if err != nil { + return err + } + var check string + err = enc.QueryRowContext(ctx, "PRAGMA integrity_check").Scan(&check) + enc.Close() + if err != nil || check != "ok" { + os.Remove(encPath) + return fmt.Errorf("the encrypted copy failed its check: %v %s", err, check) + } + if err := os.Chmod(encPath, 0o600); err != nil { + return err + } + if err := os.Rename(encPath, dbPath); err != nil { + return err + } + for _, suffix := range []string{"-wal", "-shm"} { + os.Remove(dbPath + suffix) + } + return key.WriteMeta(dataDir) +} + +func sqlString(s string) string { + return "'" + strings.ReplaceAll(s, "'", "''") + "'" +} From 4d118f09f9547f9244ffc536446e8b29437c473b Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:32:39 -0500 Subject: [PATCH 14/51] feat(masters): cash preference control on the chart of accounts A fixed-size select above the list sets how Cash on Home is counted, saves at the change, puts the old choice back with a toast on refusal, and a muted line names the accounts it counts. --- web/src/engine/masters.ts | 25 ++++++++++++++ web/src/styles/views/masters.css | 42 +++++++++++++++++++++++ web/src/ui/views/masters.ts | 57 ++++++++++++++++++++++++++++++-- 3 files changed, 121 insertions(+), 3 deletions(-) diff --git a/web/src/engine/masters.ts b/web/src/engine/masters.ts index 318cacd..6d6094d 100644 --- a/web/src/engine/masters.ts +++ b/web/src/engine/masters.ts @@ -282,6 +282,31 @@ export async function listAll(api: Api, m: Master): Promise { return out; } +export type CashPreference = "auto" | "flagged" | "named"; + +export const CASH_CHOICES: { value: CashPreference; label: string }[] = [ + { value: "auto", label: "Automatic" }, + { value: "flagged", label: "Accounts marked cash or bank" }, + { value: "named", label: "Accounts named cash or bank" }, +]; + +export async function loadCashPreference(api: Api): Promise { + const res = await api.call<{ preference: CashPreference }>("GET", "/api/reports/cash-rule"); + return res.preference; +} + +export async function saveCashPreference(api: Api, preference: CashPreference): Promise { + const res = await api.call<{ preference: CashPreference }>("PUT", "/api/reports/cash-rule", { preference }); + return res.preference; +} + +export async function cashSummary(api: Api): Promise { + const res = await api.call<{ cash?: { accounts?: { code: string }[] } }>("GET", "/api/reports/balances"); + const list = res.cash?.accounts ?? []; + if (!list.length) return "No accounts count as cash right now."; + return `${list.length} ${list.length === 1 ? "account" : "accounts"}: ${list.map((a) => a.code).join(", ")}`; +} + export function create(api: Api, m: Master, body: Row): Promise { return api.call("POST", m.path, body); } diff --git a/web/src/styles/views/masters.css b/web/src/styles/views/masters.css index a5bce69..01b40f2 100644 --- a/web/src/styles/views/masters.css +++ b/web/src/styles/views/masters.css @@ -24,6 +24,48 @@ block-size: 100%; } +.masters--tree .masters__list { + grid-template-rows: auto minmax(0, 1fr); + row-gap: var(--space-2); +} + +.cashrule { + display: flex; + align-items: center; + column-gap: var(--space-3); + block-size: var(--control); + min-inline-size: 0; + font-size: var(--text-sm); +} + +.cashrule__control { + display: flex; + flex: none; + align-items: center; + column-gap: var(--space-2); +} + +.cashrule__control[data-hidden] { + visibility: hidden; +} + +.cashrule__label { + color: var(--text-muted); + white-space: nowrap; +} + +.cashrule__select { + inline-size: calc(var(--space-14) * 5); +} + +.cashrule__line { + min-inline-size: 0; + overflow: hidden; + color: var(--text-muted); + text-overflow: ellipsis; + white-space: nowrap; +} + .masters__form { grid-template-rows: auto minmax(0, 1fr) auto; row-gap: 0; diff --git a/web/src/ui/views/masters.ts b/web/src/ui/views/masters.ts index 8444695..3d3e07f 100644 --- a/web/src/ui/views/masters.ts +++ b/web/src/ui/views/masters.ts @@ -1,9 +1,10 @@ -import { boolValue, buildBody, cashAllowed, cell, create, depthOf, fieldText, listAll, MASTERS, title, update, type Field, type Master, type Raw, type Row } from "../../engine/masters"; +import { boolValue, buildBody, CASH_CHOICES, cashAllowed, cashSummary, cell, create, depthOf, fieldText, listAll, loadCashPreference, MASTERS, saveCashPreference, title, update, type CashPreference, type Field, type Master, type Raw, type Row } from "../../engine/masters"; import { ApiError } from "../../engine/session"; import { h, setAttr, setText } from "../dom"; import type { IconName } from "../icons"; import { mountExport } from "../parts/exportbtn"; import { mountTable, type TableHandle } from "../parts/table"; +import { toast } from "../toast"; import type { ViewContext, ViewDef } from "../views"; const ICONS: Record = { customers: "user", suppliers: "user" }; @@ -13,6 +14,53 @@ function mountMaster(m: Master, host: HTMLElement, ctx: ViewContext): { show(): const root = h("div", { class: m.id === "accounts" ? "masters masters--tree" : "masters" }); const listHost = h("div", { class: "masters__list" }); root.append(listHost); + + const cashSelect = h("select", { class: "input cashrule__select", attrs: { id: "cashrule-select", "aria-describedby": "cashrule-line" } }); + for (const c of CASH_CHOICES) cashSelect.append(h("option", { text: c.label, attrs: { value: c.value } })); + const cashLine = h("span", { class: "cashrule__line", attrs: { id: "cashrule-line", "aria-live": "polite" } }); + const cashControl = h("span", { class: "cashrule__control" }, h("label", { class: "cashrule__label", text: "Cash on Home counts:", attrs: { for: "cashrule-select" } }), cashSelect); + const cashBar = h("div", { class: "cashrule" }, cashControl, cashLine); + if (m.id === "accounts") listHost.append(cashBar); + let cashReady = false; + let cashShown: CashPreference = "auto"; + const refreshCash = () => { + void cashSummary(ctx.api).then( + (text) => setText(cashLine, text), + () => setText(cashLine, ""), + ); + }; + cashSelect.addEventListener("change", () => { + const next = cashSelect.value as CashPreference; + if (!cashReady) { + cashSelect.value = cashShown; + return; + } + cashReady = false; + saveCashPreference(ctx.api, next).then( + (saved) => { + cashShown = saved; + refreshCash(); + }, + (e: unknown) => { + cashSelect.value = cashShown; + toast({ id: "cash-rule", tone: "danger", message: e instanceof ApiError && e.status === 403 ? "Your role cannot change how cash is counted." : e instanceof ApiError ? e.message : "The cash setting could not be saved." }); + }, + ).finally(() => { + cashReady = true; + }); + }); + const loadCash = () => { + setAttr(cashControl, "data-hidden", ctx.can("settings.manage") ? null : "true"); + void loadCashPreference(ctx.api).then( + (p) => { + cashShown = p; + cashSelect.value = p; + cashReady = true; + }, + () => undefined, + ); + refreshCash(); + }; host.append(root); let depth = new Map(); @@ -29,7 +77,7 @@ function mountMaster(m: Master, host: HTMLElement, ctx: ViewContext): { show(): tone: (r: Row) => (!c.badge ? "" : c.key === "active" ? (r.active ? "ok" : "inactive") : cell(r, c.key) ? "inactive" : ""), })), rowKey: (r) => String(r.id), - empty: `No ${m.title.toLowerCase()} yet. Fill in the form at the right and press Save to add the first one.`, + empty: { title: `No ${m.title.toLowerCase()} yet`, line: "Fill in the form at the right and press Save to add the first one." }, grow: true, onOpen: (r) => fill(r), }); @@ -161,6 +209,7 @@ function mountMaster(m: Master, host: HTMLElement, ctx: ViewContext): { show(): decorate(rowEl(String(row.id))); if (isNew) place(row); fill(row); + if (tree) refreshCash(); } catch (e) { setText(error, e instanceof ApiError ? e.message : "The change could not be saved."); } finally { @@ -196,7 +245,9 @@ function mountMaster(m: Master, host: HTMLElement, ctx: ViewContext): { show(): return { show() { gate(); - if (!loaded) void load(); + if (loaded) return; + void load(); + if (tree) loadCash(); }, }; } From c0b7fe51cae47cf958c1443cf371c86f36c2a4b4 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Fri, 27 Nov 2026 16:32:58 -0500 Subject: [PATCH 15/51] feat(docform): save as template, fill from a template and print The document form gains a quiet Save as template button that asks for a name in place, fills a new draft from a template address, and downloads its PDF with Print. --- web/src/engine/templates.ts | 126 +++++++++++++++++++++++++++++++ web/src/styles/views/docform.css | 30 ++++++++ web/src/ui/views/docform.ts | 115 +++++++++++++++++++++++++++- 3 files changed, 270 insertions(+), 1 deletion(-) create mode 100644 web/src/engine/templates.ts diff --git a/web/src/engine/templates.ts b/web/src/engine/templates.ts new file mode 100644 index 0000000..2bae9ca --- /dev/null +++ b/web/src/engine/templates.ts @@ -0,0 +1,126 @@ +import type { Api } from "./index"; +import type { Family } from "./docform"; + +export type TemplateKind = "quote" | "sales-order" | "sales-invoice" | "purchase-order" | "purchase-invoice"; + +export interface TemplateLine { + item?: string | undefined; + description: string; + quantityMilli: number; + unitPrice: number; + currentPrice: boolean; + taxRate?: string | undefined; +} + +export interface Template { + id: string; + kind: TemplateKind; + name: string; + description: string; + category: string; + party: string; + currency: string; + termsDays: number; + notes: string; + lines: TemplateLine[]; + builtIn: boolean; +} + +export interface UsedLine { + item?: string; + itemCode?: string; + description: string; + quantityMilli: number; + unitPrice: number; + taxRate: string; +} + +export interface UsedDraft { + family: Family; + kind: string; + date: string; + dueDate?: string; + customer?: string; + supplier?: string; + memo: string; + lines: UsedLine[]; +} + +export const KIND_LABELS: Record = { + quote: "Quote", + "sales-order": "Sales order", + "sales-invoice": "Sales invoice", + "purchase-order": "Purchase order", + "purchase-invoice": "Purchase invoice", +}; + +export function templateKind(family: Family, docKind: string): TemplateKind { + if (family === "sales") return docKind === "quote" ? "quote" : docKind === "order" ? "sales-order" : "sales-invoice"; + return docKind === "order" ? "purchase-order" : "purchase-invoice"; +} + +export function familyOf(kind: TemplateKind): Family { + return kind.startsWith("purchase") ? "purchase" : "sales"; +} + +export function categoryOf(t: Template): string { + return t.category || KIND_LABELS[t.kind]; +} + +export function categoryCounts(list: Template[]): [string, number][] { + const counts = new Map(); + for (const t of list) counts.set(categoryOf(t), (counts.get(categoryOf(t)) ?? 0) + 1); + return [...counts.entries()].sort((a, b) => a[0].localeCompare(b[0])); +} + +export function matchesQuery(t: Template, q: string): boolean { + const s = q.trim().toLowerCase(); + if (!s) return true; + return `${t.name} ${t.description} ${t.category} ${KIND_LABELS[t.kind]}`.toLowerCase().includes(s); +} + +export function lineTotal(l: { quantityMilli: number; unitPrice: number }): number { + return Math.round((l.quantityMilli * l.unitPrice) / 1000); +} + +const enc = encodeURIComponent; + +export async function listTemplates(api: Api): Promise { + const out = await api.call<{ templates: Template[] }>("GET", "/api/templates"); + return out.templates ?? []; +} + +export async function useTemplate(api: Api, id: string): Promise { + return api.call("POST", `/api/templates/${enc(id)}/use`, {}); +} + +export async function createTemplate(api: Api, t: Omit): Promise