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/CHANGELOG.md b/CHANGELOG.md index 4f6feb4..5c2dfb3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,34 @@ # Changelog +## 0.11.0 + +FormLedger gets dashboards with charts, document templates, a short sidebar with a command palette and a full menubar, and encryption at rest. + +### New +- **Dashboards:** four tiles (revenue, expenses, profit, cash) with a sparkline and the change on the period before, and six charts: revenue and expenses by month, profit, cash, receivables and payables, top customers and top items. Each chart has a data table for screen readers, and pointing at a month shows its exact figures. `docs/ledger/dashboards.md` says where every number comes from. +- **Templates:** a Templates screen with built-in starting points and your own. A document form can be saved as a template and filled from one. +- **Print** on the document form. +- **A short sidebar, as in form.md:** Search, Home and Dashboards, the selling and buying documents, and a foot with Reports, Setup and Templates. Reports and Setup are pages of cards, one per screen. +- **A command palette** (Ctrl or Cmd+Shift+P, or Search in the sidebar) that opens every screen and starts every new document from the keyboard. +- **A full menubar for the desktop app,** ported from form.md: File (new documents, Export CSV, Print), Edit, View, Go (every screen), Window and Help. It has not been compiled or run. +- **Encryption at rest,** as form.md does it: `formledger keygen` makes a key, `FORMLEDGER_KEY_FILE` names it, and `formledger encrypt` converts an existing ledger. `docs/ENCRYPTION.md` has the steps. Without a key the ledger is stored plain and the server says so at start. +- **Cash on Home** can be chosen in the window, above the chart of accounts. +- **PDFs through FormTxt:** the server asks a running FormTxt to draw a printout first and falls back to the built-in pages. `./formledger cli print` takes `--plain` and says which one answered. +- Routes `GET /api/reports/series` and `GET /api/reports/top` behind the dashboards. + +### Changed +- Buttons and empty lists look as they do in form.md. +- Spelling is American English on screen and in the docs: "Canceled", "aging". Stored values and route names are unchanged. +- The README follows the family's layout. + +### Known issues +- Nothing creates a key for you, on the desktop or elsewhere, so encryption is off until you make one. form.md works the same way. +- `formledger encrypt` keeps no plain copy of the old database; copy the data folder first. +- The FormTxt printout has not been seen working: FormTxt refuses outside requests unless its window is open and a person allows them, and it holds its own templates. Every print here came from the built-in pages. +- FormCel's engine read a snapshot with one SELECT and pivoted it; FormCel's window was not used. +- Write Snapshot in the menubar and palette only tells you the command to run. +- The desktop shell has not been compiled. + ## 0.10.0 FormLedger now looks and behaves like a member of the Form family: its shell, sign-in, page heads and fields were brought over from form.md and checked against form.md running beside it. @@ -24,7 +53,7 @@ FormLedger now looks and behaves like a member of the Form family: its shell, si ### Fixed - In narrower windows the document form's buttons, and the payment, goods receipt and delivery note forms' buttons, could fall outside the window. -- A grey band behind the payment form's buttons in the light theme. +- A gray band behind the payment form's buttons in the light theme. ### Known issues - Buttons still differ a little from form.md's (hover, the danger style, height); the list is in the pull request. @@ -47,7 +76,7 @@ The window has had its first design pass, and two ways to take your figures out ### Changed - Every list and ledger screen fills the window, with its filters in one bar, and its main button on the title row. -- A status is a coloured badge everywhere. Codes and document numbers use the fixed-width face; amounts line up on the right. +- A status is a colored badge everywhere. Codes and document numbers use the fixed-width face; amounts line up on the right. - The document form reads like the paper: one heading with the number and status, a tidy header block, the lines, totals under the amount column, then the buttons with the main one last. A posted document shows as read-only. - Profit and loss and the balance sheet are laid out as statements, with the result as the one large number at the foot. - The setup screens show the list beside a form panel that scrolls, with its buttons always in view. The chart of accounts is indented by level. @@ -59,7 +88,7 @@ The window has had its first design pass, and two ways to take your figures out - A document line with a quantity or price but no item is now pointed out when you save, where it used to be dropped without a word. ### Known issues -- The design pass followed rules written for this app on form.md's colours and type; it has not been compared with form.md's own screens side by side. +- The design pass followed rules written for this app on form.md's colors and type; it has not been compared with form.md's own screens side by side. - The light theme, windows narrower than 1400 px and the purchase form were not looked at in this pass. - Totals on a draft document show 0.00 until it is saved. - An exported delivery note list stops at 500 notes. @@ -265,7 +294,7 @@ The first scaffold. The server starts and serves the web client; there are no le - `./build_app --server-only` compiles `bin/formledger`, one program with the web client inside. - The web client opens on a Home view with a line that says whether the server answers. - The server listens on this computer only, at `127.0.0.1:8340`, and answers a health check at `/api/health`. -- `docs/BEHAVIOURS.md` lists the 64 behaviours the app commits to, with the sources for each. +- `docs/BEHAVIOURS.md` lists the 64 behaviors the app commits to, with the sources for each. ### Known issues - The desktop app in `src-tauri/` has not been compiled and cannot be bundled until the app has its icon set. @@ -274,4 +303,4 @@ The first scaffold. The server starts and serves the web client; there are no le ## 0.1.0 -- The repository's first commit: the licence, the notice and a short README. +- The repository's first commit: the license, the notice and a short README. 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 diff --git a/Makefile b/Makefile index e72e439..839de2e 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -VERSION := v0.10.0 +VERSION := v0.11.0 GO_BUILD := CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" .PHONY: build web server check clean diff --git a/NOTICE.md b/NOTICE.md index e15a6c8..415b1ef 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -4,26 +4,26 @@ FormLedger. Copyright 2026 NodeAgentc, Inc. Licensed under the Apache License 2. ## Ported code -A file brought over from another Form repository gets a row here with its source, that source's licence and version, and what came over. The source belongs to the same owner. +A file brought over from another Form repository gets a row here with its source, that source's license and version, and what came over. The source belongs to the same owner. -| Source | Licence | What came over | +| Source | License | What came over | | --- | --- | --- | -| form.md v0.61.1 (`nodemode-dev/form.md`) | Apache-2.0 | `cmd/formledger/main.go`, `embed.go` and `internal/` (`app`, `config`, `httpx`, `i18n`, `ids`, `netguard`, `nowindow`, `secrets`, `settings`, `store` with its migration runner and the instance and settings tables, `server`, `static`, `startup`), reduced to a skeleton and renamed, with the encryption hooks cut for now. Since 0.3.0 also `internal/auth` (password hashing nearly verbatim; the desktop entry, sessions, tokens and invitations cut down to one company and one role per person), `internal/policy` (the roles and actions are FormLedger's own), `internal/audit` and `internal/auditapi` (the workspace, page and agent parts, the purge and the export removed), `internal/crypt` and `internal/cryptvfs` (nearly verbatim, not switched on yet), and the users, sessions, tokens and invitations tables cut from form.md's accounts migration. `web/`: the engine store and commands, `ui/dom`, `ui/icons`, `ui/toast`, the theme tokens and shell styles, the Vite and TypeScript configuration, `oc_install` and `boot_frontend`. `src-tauri/`: the whole shell, renamed, with the menus reduced. The root launcher, installer, `build_app` and `Makefile`. `CODE_OF_CONDUCT.md`, `CONTRIBUTING.md`, `SECURITY.md`, `BRANCHING.md`, `.github/` and `.claude/settings.json`, rewritten for this repository. Since 0.10.0 also, from form.md at its `main` of 2026-11-27: the system-theme start in `web/index.html`; the sidebar head, user chip and menu, the top bar's back, forward and crumb, the sign-in card and the Home head (`web/src/styles/shell.css`, `auth.css`, `home.css`, `panels.css`, `pages.css`, `controls.css`, `web/src/ui/auth.ts`, `web/src/ui/icons.ts`, the tokens); the field, select and checkbox styles (`forms.css`, `settings.css`); the page head (`home.css`); the PDF page setup and page counter (`internal/transfer/pdf.go`); and the splash page's layout, which FormLedger shows with its own icon | +| form.md v0.61.1 (`nodemode-dev/form.md`) | Apache-2.0 | `cmd/formledger/main.go`, `embed.go` and `internal/` (`app`, `config`, `httpx`, `i18n`, `ids`, `netguard`, `nowindow`, `secrets`, `settings`, `store` with its migration runner and the instance and settings tables, `server`, `static`, `startup`), reduced to a skeleton and renamed, with the encryption hooks cut for now. Since 0.3.0 also `internal/auth` (password hashing nearly verbatim; the desktop entry, sessions, tokens and invitations cut down to one company and one role per person), `internal/policy` (the roles and actions are FormLedger's own), `internal/audit` and `internal/auditapi` (the workspace, page and agent parts, the purge and the export removed), `internal/crypt` and `internal/cryptvfs` (nearly verbatim, not switched on yet), and the users, sessions, tokens and invitations tables cut from form.md's accounts migration. `web/`: the engine store and commands, `ui/dom`, `ui/icons`, `ui/toast`, the theme tokens and shell styles, the Vite and TypeScript configuration, `oc_install` and `boot_frontend`. `src-tauri/`: the whole shell, renamed, with the menus reduced. The root launcher, installer, `build_app` and `Makefile`. `CODE_OF_CONDUCT.md`, `CONTRIBUTING.md`, `SECURITY.md`, `BRANCHING.md`, `.github/` and `.claude/settings.json`, rewritten for this repository. Since 0.10.0 also, from form.md at its `main` of 2026-11-27: the system-theme start in `web/index.html`; the sidebar head, user chip and menu, the top bar's back, forward and crumb, the sign-in card and the Home head (`web/src/styles/shell.css`, `auth.css`, `home.css`, `panels.css`, `pages.css`, `controls.css`, `web/src/ui/auth.ts`, `web/src/ui/icons.ts`, the tokens); the field, select and checkbox styles (`forms.css`, `settings.css`); the page head (`home.css`); the PDF page setup and page counter (`internal/transfer/pdf.go`); and the splash page's layout, which FormLedger shows with its own icon. Since 0.11.0 also, from the same `main`: the native menubar and its wiring (`src-tauri/src/menu.rs`, `main.rs`); the command palette (`web/src/ui/command-palette.ts`, the `.cpal`, scrim and dialog rules); the buttons (`forms.css`); the bar chart and the chart and dashboard card rules (`web/src/ui/bar-chart.ts`, `charts.css`); and encryption at rest, now switched on when a key is given (`internal/crypt/key.go`, `internal/cryptvfs/vfs.go`, `internal/store/store.go`, `internal/ops/encrypt.go`, the key options in `internal/config/config.go` and the `keygen` and `encrypt` commands) | ## Third-party software -Each component gets a row here with its licence and its use before it is added. +Each component gets a row here with its license and its use before it is added. -| Component | Licence | Use | +| Component | License | Use | | --- | --- | --- | | modernc.org/sqlite v1.60.1 and modernc.org/libc v1.77.1 | BSD-3-Clause | server | | golang.org/x/crypto v0.58.0 | BSD-3-Clause | server | | github.com/go-pdf/fpdf v0.9.0, the version form.md ships | MIT, read from the module's LICENSE: Copyright (c) 2021 The Go-PDF authors, (c) 2020 David Barnes, (c) 2017 Kurt Jung and contributors | server, the built-in PDF printouts | -| The indirect Go modules in `go.sum` (go-humanize, google/uuid, go-isatty, go-strftime, bigfft, x/net, x/sys, x/text, mathutil, memory) | the same modules form.md uses; their licences have not been read for this repository yet | server | +| The indirect Go modules in `go.sum` (go-humanize, google/uuid, go-isatty, go-strftime, bigfft, x/net, x/sys, x/text, mathutil, memory) | the same modules form.md uses; their licenses have not been read for this repository yet | server | | Inter, the variable latin and latin-ext files from @fontsource-variable/inter 5.3.0, by way of form.md | SIL Open Font License 1.1, text in `web/src/fonts/Inter-OFL.txt` | interface font | | typescript 7.0.2 | Apache-2.0 | building the web client; not shipped | | vite 8.4.0 and what it pulls in (rolldown, postcss and others: MIT; lightningcss: MPL-2.0; picocolors: ISC; source-map-js: BSD-3-Clause), and @types/node | MIT | building the web client; not shipped | | Tauri 2 with the shell, dialog, opener and single-instance plugins | MIT OR Apache-2.0, per form.md's notices | desktop shell, which has not been compiled yet | -| windows-sys, objc2, objc2-app-kit | the same crates form.md's shell uses; their licences have not been read for this repository yet | desktop shell | +| windows-sys, objc2, objc2-app-kit | the same crates form.md's shell uses; their licenses have not been read for this repository yet | desktop shell | The web client has no runtime dependency. diff --git a/README.md b/README.md index 92b59d5..139f78f 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,111 @@ -# FormLedger +

+ FormLedger icon +

-The FormLedger icon +

FormLedger

-A local-first business app from the FormAI family of apps: every sale, purchase, payment and stock movement is a numbered document that posts to shared ledgers for money and stock. +

+ Books for a small company; sales, purchases, payments and stock in one ledger.
+ Every sale, purchase, payment and stock movement is a numbered document
+ that posts to shared ledgers for money and stock. Local-first, on your own machine. +

-**Status:** early. People can sign in with a role, the owner can invite others, and an audit trail records who did what ([`docs/ROLES.md`](docs/ROLES.md)). The ledger core works from the command line and over the server's routes: a chart of accounts, fiscal periods, journal entries that post and cancel, and a trial balance ([`docs/ledger/`](docs/ledger/)). So does the selling chain: customers, items and tax rates, then a quote, an order, an invoice that posts to the ledger, payments with part payment, and receivables ageing ([`docs/selling/`](docs/selling/README.md)). And the buying chain and stock: suppliers, purchase orders, goods receipts into a warehouse, purchase invoices, payments made, payables ageing, a stock ledger valued at moving average cost, and delivery notes that take stock out and post its cost ([`docs/buying/`](docs/buying/documents.md), [`docs/stock/`](docs/stock/README.md)). The web client now has screens for this: a list for every document type, one form for sales and purchase documents with a line grid, payments with allocation, the setup lists, and trial balance, general ledger, profit and loss, balance sheet, ageing and stock ([`docs/window/`](docs/window/README.md)). They are new and only partly checked in a browser; the desktop app in `src-tauri/` has not been compiled. [`docs/BEHAVIOURS.md`](docs/BEHAVIOURS.md) lists what the app commits to do. +

+ version v0.11.0 + Go 1.26+ + TypeScript and Vite + License: Apache-2.0 + Status: early +

+ +

+ Download · + Run it from source +

+ +

+ Features · In the box · Agents · Under the hood · + Download · Run from source +

+ + + + + + + + +

One ledger

Documents post to a general ledger and a stock ledger, and a trial balance and the stock check say whether the books agree.

Whole chains

Quote, order, invoice and payment on the selling side; order, receipt, bill and payment on the buying side.

Roles and audit

Six roles, invitations by the owner, and an audit trail the database will not let anyone edit.

Scriptable

A command line and an HTTP API drive the same books as the window.
+ +## Features + + + + + + + + + + +
+

The ledger core

A chart of accounts, fiscal years and period locks, and journal entries that post and cancel by reversal. A trial balance, general ledger, profit and loss and balance sheet read from it. See docs/ledger/. +
+

Selling

Customers, items and tax rates, then a quote, an order, an invoice that posts to the ledger, payments with part payment, and receivables aging. Document templates, built-in and your own, start a quote, order or invoice from the Templates screen. See docs/selling/. +
+

Buying and stock

Suppliers, purchase orders, goods receipts into a warehouse, purchase invoices, payments made and payables aging. A stock ledger valued at moving average cost, and delivery notes that take stock out and post its cost. See docs/buying/ and docs/stock/. +
+

People and audit

Every user has one role, the owner invites the others, and an audit trail records who did what. See docs/ROLES.md. +
+ +## Everything in the box + + + + + + + +

Window

A list for every document type · one form with a line grid for sales and purchase documents · payments with allocation · setup lists · a dashboard of revenue, expenses, profit, cash and top customers by month · a command palette that reaches every screen · light, dark or system theme. See docs/window/

Reports

Trial balance · general ledger · profit and loss · balance sheet · receivables and payables aging · stock balance and value

Taking figures out

CSV of every list and report · PDF of quotes, orders, invoices, purchase documents and customer statements · a read-only SQLite snapshot of the books. See docs/EXPORT.md, docs/PRINT.md and docs/SNAPSHOT.md
+ +## Built for agents + +The command line is a client of the running server; it never opens the database. It prints JSON, or a table with `--table`, and needs an app token in `FORMLEDGER_TOKEN`. + +```sh +./formledger cli --help # every command: accounts, journal, sales, invoice, payment, stock, report, export, print ... +./formledger cli token # how to make an app token +./formledger cli whoami # the user and role behind the token +``` + +[`docs/ledger/cli.md`](docs/ledger/cli.md) walks from an empty company to a trial balance. What the app commits to do is listed in [`docs/BEHAVIOURS.md`](docs/BEHAVIOURS.md), and [`AGENTS.md`](AGENTS.md) is the guide for coding agents working on the repo. + +## Under the hood + +- **Go server:** one process is the only writer to the database; amounts are whole numbers of a currency's minor unit, never floats. +- **Encryption at rest:** the database is encrypted when you give the server a key (`formledger keygen`, then `FORMLEDGER_KEY_FILE`); `formledger encrypt` converts an existing ledger. Without a key the ledger is stored plain, and the server says so when it starts. See [`docs/ENCRYPTION.md`](docs/ENCRYPTION.md). +- **Web client:** vanilla TypeScript and Vite, with no UI framework, embedded into the server binary by `./build_app --server-only`. +- **Desktop shell:** a Tauri shell in `src-tauri/` around the server binary, with a native menubar (File, Edit, View, Go, Window, Help). It has not been compiled yet, so the menubar has not been run. +- **Checks:** `./formledger check` runs gofmt, go vet and the web client's type check. + +## Download + +Not released yet. The desktop app has not been compiled and there is no release to download. To use FormLedger now, run it from source below. ## Run it from source **Requires:** Go 1.26 and Node 22, the versions the checks use. ```sh +git clone https://github.com/nodemode-dev/formledger.git +cd formledger ./formledger_oc_install # Go modules and the web client's packages ./formledger # server at http://127.0.0.1:8340, web client dev server at http://127.0.0.1:5340 ./build_app --server-only # compiles bin/formledger with the web client inside -./formledger cli --help # the ledger from the command line, through the running server +./formledger help # every launcher command ``` -The command line needs an app token in `FORMLEDGER_TOKEN`; [`docs/ledger/cli.md`](docs/ledger/cli.md) shows how to make one and walks from an empty company to a trial balance. +On Windows use `formledger_oc_install.bat` and `formledger.bat`. | Port | What listens | Change it with | | --- | --- | --- | @@ -25,6 +113,42 @@ The command line needs an app token in `FORMLEDGER_TOKEN`; [`docs/ledger/cli.md` | 5340 | the web client's dev server | | | 5341 | the web client's preview server | | -The data directory is `./data` (`FORMLEDGER_DATA`). Working on the code: see [`CONTRIBUTING.md`](CONTRIBUTING.md), [`BRANCHING.md`](BRANCHING.md) and [`AGENTS.md`](AGENTS.md). +| Variable | Purpose | +| --- | --- | +| `FORMLEDGER_ADDR` | Listen address of the server, default `127.0.0.1:8340` | +| `FORMLEDGER_DATA` | Data directory for the database, default `./data` | +| `FORMLEDGER_URL` | Server the command line talks to, default `http://127.0.0.1:8340` | +| `FORMLEDGER_TOKEN` | App token for the command line | +| `FORMLEDGER_KEY_FILE` | Key file that turns on encryption at rest; unset means the ledger is stored plain | + +> [!IMPORTANT] +> **Status:** early. The ledger, selling, buying and stock work from the command line and over the server's routes. The window's screens for them are new and only partly checked in a browser, and the desktop app in `src-tauri/` has not been compiled. + +**Contributing:** see [`CONTRIBUTING.md`](CONTRIBUTING.md), [`BRANCHING.md`](BRANCHING.md) and [`AGENTS.md`](AGENTS.md). Security reports: [`SECURITY.md`](SECURITY.md). + +## Repository + +| Path | What it is | +| --- | --- | +| `cmd/formledger/` | Entry point: the server and the `cli` subcommands | +| `internal/` | The Go server: ledger, selling, buying, stock, reports, printing, roles, audit | +| `web/` | The TypeScript and Vite client | +| `src-tauri/` | The desktop shell around the server binary | +| `docs/` | What each part does and the behaviors the app commits to | + +
+ +--- + +## Maintainers + +| Maintainer | Role | +| --- | --- | +| [@nodemode-ai](https://github.com/nodemode-ai) | Owner | +| [@gbarnai](https://github.com/gbarnai) | Co-owner | + +Code owners are set in [`.github/CODEOWNERS`](.github/CODEOWNERS). + +## License -**License:** Apache-2.0. Copyright 2026 NodeAgentc, Inc. See [`LICENSE`](LICENSE) and [`NOTICE.md`](NOTICE.md). +FormLedger is licensed under the Apache License 2.0 ([`LICENSE`](LICENSE), SPDX `Apache-2.0`). Copyright 2026 NodeAgentc, Inc. Third-party notices: [`NOTICE.md`](NOTICE.md). diff --git a/SECURITY.md b/SECURITY.md index 48521c0..97d8c0e 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -40,3 +40,16 @@ things that matter most are: Bugs that need someone to already control the computer, or to run a modified build of FormLedger, are ordinary bugs: please open an issue for those. + +## Data at rest + +With a key (`FORMLEDGER_KEY_FILE`, or a systemd credential named `formledger.key`), +the ledger database, its WAL and its journal are encrypted with XTS-AES-256 through the +`formledger-crypt` SQLite VFS, ported from form.md. Without a key the ledger is plain, +and the server says so at start. A missing or wrong key stops the server before any +database is opened. The key is never stored in the data directory; if it is lost, the +ledger cannot be recovered by anyone. `formledger report snapshot` writes a plain copy +by design and must be treated as sensitive. See [`docs/ENCRYPTION.md`](docs/ENCRYPTION.md). + +Reading the encrypted database without the key, or anything that leaves ledger data +in the clear inside an encrypted data directory, counts as a vulnerability. diff --git a/cmd/HASHOUT_LOG.md b/cmd/HASHOUT_LOG.md index 8a7e7ca..5295993 100644 --- a/cmd/HASHOUT_LOG.md +++ b/cmd/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the entry point, `embed.go`, `internal/server`, `internal/static` and `internal/startup`. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. Read it first, then edit code surgically. -Current build version: v0.10.0 +Current build version: v0.11.0 Last updated: 2026-11-26 (US Eastern) · skeleton port from form.md --- 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/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. diff --git a/docs/ENCRYPTION.md b/docs/ENCRYPTION.md new file mode 100644 index 0000000..9f69c21 --- /dev/null +++ b/docs/ENCRYPTION.md @@ -0,0 +1,83 @@ +# Encryption at rest + +FormLedger can encrypt its data directory at rest with a 256-bit key that you hold outside the data directory. The wiring is ported from form.md (`internal/crypt/key.go`, `internal/cryptvfs/vfs.go`, `internal/store/store.go`, `internal/ops/encrypt.go`, `cmd/form-md/main.go`, `cmd/form-md/tool.go` and `.docs/wiki/Encryption.md`), changing only names. As in form.md, encryption is on when FormLedger is given a key and off when it is not. + +**There is no recovery without the key.** If the key is lost, the ledger cannot be read by anyone, including you. Back the key up before you put data in. + +## What is encrypted, and with what + +| Data | How | +|---|---| +| `formledger.db` | Every page, in 4096-byte units, with XTS-AES-256 (`golang.org/x/crypto/xts`) tweaked by its file offset, through the `formledger-crypt` SQLite VFS (`internal/cryptvfs/vfs.go`, from form.md's `internal/cryptvfs/vfs.go`) | +| `formledger.db-wal` | The page inside every WAL frame, with its own XTS key | +| Rollback journal | Page records, with their own XTS key | +| SQLite temporary files | AES-CTR with a random key per open file; temporary storage is kept in memory | + +The database, WAL and journal keys and the key check are derived from the one master key with HKDF-SHA256 (`internal/crypt/key.go`, from form.md's `internal/crypt/key.go`). `encryption.json` in the data directory records the format and a key check value, never the key. It still names `aes-256-gcm in 64 KiB chunks` for files, as form.md writes it; FormLedger keeps no uploaded files today, so nothing uses that format yet. + +## What is not encrypted + +- `encryption.json`, the lock file, file sizes and timestamps. +- The WAL file header and each WAL frame header, and the `-shm` file. +- Tampering is not detected as such: XTS carries no authentication tag, so a page changed on disk decrypts to noise, which SQLite reports as a damaged database. +- Anything outside the data directory: memory, network traffic (use TLS), and any snapshot you write (below). +- Copies made before encryption was turned on. `formledger encrypt` converts only the data directory. + +## Where the key is + +FormLedger looks for the key in this order: + +1. `FORMLEDGER_KEY_FILE`, when set. +2. Otherwise a systemd credential named `formledger.key`, that is `$CREDENTIALS_DIRECTORY/formledger.key`, when that file exists. + +With neither, the ledger is stored plain and the server says so at start: `at-rest encryption off`. The key file holds 32 bytes written as 64 hex characters or as base64. + +**On a desktop**, as in form.md, nothing makes a key for you. Make one and keep it outside the data directory, readable only by you: + +``` +formledger keygen > ~/formledger.key && chmod 600 ~/formledger.key +FORMLEDGER_KEY_FILE=~/formledger.key formledger +``` + +**On a server**, keep the key readable by root only and hand it to the service as a systemd credential: + +``` +sudo sh -c 'umask 077; formledger keygen > /etc/formledger/formledger.key' +# in the unit: +LoadCredential=formledger.key:/etc/formledger/formledger.key +``` + +## Backing up the key + +Copy the key file to somewhere that is not the data directory and not the same disk: a password manager or an offline drive. A backup of the data directory without the key is useless; a key kept beside the data directory protects nothing. + +## Turning it on for an existing ledger + +A key given to a plain ledger is refused, so a plain ledger is never opened as if it were encrypted: + +``` +a key is set but this FormLedger data directory is not encrypted: stop FormLedger and run formledger encrypt first +``` + +Stop FormLedger, then run: + +``` +FORMLEDGER_KEY_FILE=~/formledger.key formledger encrypt +``` + +It copies the database with `VACUUM INTO` to `formledger.db.encrypting` through the encrypting VFS, opens the copy and runs `PRAGMA integrity_check`, and only when that says `ok` renames the copy over `formledger.db` and writes `encryption.json`. If anything fails, the copy is removed and the plain database is left as it was. As in form.md, the plain database is not kept after a successful swap: take a copy of the data directory first if you want one, and delete it once you have checked the encrypted ledger. + +## Missing or wrong key + +The server exits with status 2 and logs `encryption`; no database is opened or created. + +| Situation | Message | +|---|---| +| Directory is encrypted, no key given | `this FormLedger data directory is encrypted: set FORMLEDGER_KEY_FILE to the key file` | +| Key does not match the directory | `the key does not match this data directory` | +| Key file is not 32 bytes of hex or base64 | `the key file must hold 32 bytes as 64 hex characters or base64 (formledger keygen makes one)` | +| Key given to a plain directory | `a key is set but this FormLedger data directory is not encrypted: stop FormLedger and run formledger encrypt first` | + +## The snapshot is plain by design + +`formledger report snapshot` reads the ledger through the key and writes a **plain** SQLite file, so any SQLite tool can open it. With encryption on, it is the only plain route to the data. Treat every snapshot as sensitive: it holds every customer, amount and ledger line in the clear. Keep it where the ledger itself would be safe, and delete it when you are done with it. diff --git a/docs/PRINT.md b/docs/PRINT.md index 2a352e4..b099109 100644 --- a/docs/PRINT.md +++ b/docs/PRINT.md @@ -1,6 +1,6 @@ # Printing documents as PDF -FormLedger draws a plain PDF of a sales or purchase document itself, with no other program installed. +FormLedger draws a plain PDF of a sales or purchase document itself, with no other program installed. When FormTxt is running and set up for it, FormTxt draws the page instead (see FormTxt below). ## What can be printed @@ -19,7 +19,7 @@ A customer statement prints at `GET /api/print/statement/{customer code or id}.p `GET /api/print/{kind}/{number}.pdf` answers `application/pdf` as an attachment named after the document number. A draft has no number yet: ask for it by its id and the file is named `invoice-draft.pdf` (or the kind's name). The route reads the document through its own JSON route, so it needs exactly the permission that reading the document needs, and answers that route's refusal unchanged. -`./formledger cli print KIND NUMBER [--out FILE] [--token-file FILE]` fetches the same address with the app token (`FORMLEDGER_TOKEN` or `--token-file`, server at `FORMLEDGER_URL`) and writes the same bytes to standard output or `FILE`. +`./formledger cli print KIND NUMBER [--out FILE] [--token-file FILE] [--plain]` fetches the same address with the app token (`FORMLEDGER_TOKEN` or `--token-file`, server at `FORMLEDGER_URL`) and writes the same bytes to standard output or `FILE`. The same document gives the same bytes every time: the PDF's creation and change dates are the document's latest of created, posted and cancelled time. @@ -33,4 +33,13 @@ The page uses the PDF core font Helvetica in the Windows-1252 code page, so Lati ## FormTxt -Rendering goes through a list of renderers, each of which returns PDF bytes or "not available". The plain fallback is the only one today. A FormTxt renderer that goes in front of it is not built yet. +Rendering goes through a list of renderers, each of which draws a document and a statement, or answers "not available" so the next one is tried. The FormTxt renderer is first and the plain one is last. The response carries `X-FormLedger-Renderer: formtxt` or `plain`, and `./formledger cli print` prints `printed by the plain renderer` (or `formtxt`) on standard error. `--plain` on the command, or `?renderer=plain` on the address, skips FormTxt; `FORMLEDGER_PRINT=plain` in the server's environment skips it for every print. + +**Status: unverified.** The FormTxt renderer is built against FormTxt's documented `report run` route and has never produced a PDF here. What it does: + +- It finds FormTxt the way FormTxt's own tools do (`setup/report.py`, `setup/catalogue.py`): the engine at `http://127.0.0.1:$FORMTXT_ENGINE_PORT`, port `8210` when unset. There is no discovery file. +- It posts to `/api/reports/run` with the data as `records` (one record per line, the document's header fields repeated on each: `company`, `title`, `number`, `date`, `dueDate`, `customer`, `customerName`, `supplier`, `supplierName`, `currency`, `status`, `memo`, `subtotal`, `taxTotal`, `total`, then `item`, `description`, `quantity`, `unitPrice`, `taxRate`, `lineSubtotal`; a statement's are `customer`, `customerName`, `currency`, `from`, `to`, `opening`, `closing`, then `lineDate`, `event`, `reference`, `debit`, `credit`, `balance`), `mode` `list`, `format` `pdf`, and `out` a file in a fresh temporary folder that it reads back and removes. Amounts arrive formatted, as on the plain page. +- The template is a FormTxt document id, named per kind in the server's environment: `FORMLEDGER_FORMTXT_TEMPLATE_INVOICE`, `_QUOTE`, `_ORDER`, `_PURCHASE_ORDER`, `_PURCHASE_INVOICE`, `_GOODS_RECEIPT`, `_STATEMENT`. A kind with no template goes to the plain renderer. +- Any failure (no engine, a refusal, a timeout of 45 seconds, a file that is not a PDF) goes to the plain renderer. + +Why no templates ship and why it could not be shown: FormTxt's report route merges into a document that already lives in FormTxt's own store, and creating a document there is answered only by the FormTxt window (`POST /api/documents` answers `Only the FormTxt window can do this`). The route also asks the person **Allow outside agents?** in the open window before it writes a file (FormTxt `README.md`, Mail merge and list reports; `backend/app/routers/reports.py` `run`; `backend/app/routers/mcp.py` `consent`). With FormTxt's engine running and no window, it answers 403 `No FormTxt window is open`, and FormLedger prints with the plain renderer. A person who wants FormTxt pages makes a template in the FormTxt window from its built-in `business-invoice` template with merge fields named as above, allows outside agents once, and sets the environment variables. 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/SNAPSHOT.md b/docs/SNAPSHOT.md index eb691b2..7a2ed59 100644 --- a/docs/SNAPSHOT.md +++ b/docs/SNAPSHOT.md @@ -280,3 +280,18 @@ GROUP BY account_code HAVING net_minor <> 0 ORDER BY account_code; ``` `ROUND(..., 2)` suits two digit currencies; for an exact total sum the `_minor` column and divide by `currencies.scale`. + +## Opening it in FormCel + +FormCel reads a SQLite file as a data source with one SELECT (its `README.md`, "SQLite as a data source"). In the window, a query's Source list has "SQLite database (SELECT)": give the snapshot's full path, paste one of the SELECTs above, leave "Allow saving to this database" off, then pivot the result (a pivot step on `month` with values `amount`, or a PivotTable on the loaded table). The window path was not run here; the engine path below was. + +The same thing without the window, through FormCel's own query engine (`backend/app/services/pquery.py`: `sqlite_table`, `run`, and the `pivot` step), from a FormCel checkout's `backend` folder: + +```python +from app.services import pquery +sql = "SELECT month, account_type, account_code, account_name, ROUND(SUM(credit - debit), 2) AS amount FROM ledger_lines WHERE account_type IN ('income', 'expense') GROUP BY month, account_code ORDER BY month, account_code" +out = pquery.run({"source": {"kind": "sqlite", "path": "/path/formledger-snapshot-2026-11-27.sqlite", "sql": sql}, + "steps": [{"op": "pivot", "column": "month", "values": "amount", "agg": "sum"}]}, {}) +``` + +On a company with twelve months of invoices and rent, the profit and loss SELECT returned 24 rows, and the pivot returned one row per account (`4100 Sales`, `6100 Rent`) with a column per month `2026-01` to `2026-12`. FormCel read the snapshot as written: no pragma, type, journal mode or column name had to change. FormCel's `run` marks text that looks like a number with a leading `'` (so `4100` stays text in a cell); that is FormCel's cell convention, not part of the file. 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/dashboards.md b/docs/ledger/dashboards.md new file mode 100644 index 0000000..64726c8 --- /dev/null +++ b/docs/ledger/dashboards.md @@ -0,0 +1,42 @@ +# Dashboards + +The Dashboards screen (`#/dashboards`) shows the company's figures for a period: This month, This quarter, This year or Last 12 months (the default). Every period ends today; This month starts on the first of the month, This quarter on the first day of the calendar quarter, This year on January 1, and Last 12 months on the first day of the month eleven months back. Amounts are in the company's main currency, the currency most of its accounts are kept in. + +Every number comes from two read-only routes, both guarded by `reports.read`: + +- `GET /api/reports/series?metric=revenue|expenses|profit|cash|receivables|payables&from=YYYY-MM-DD&to=YYYY-MM-DD&by=month` answers `{metric, currency, by, from, to, points:[{period, value}], total, previous:{from, to, total}}`. Values are whole minor units. Every month in the range has a point, with value 0 when nothing was posted. +- `GET /api/reports/top?what=customers|items|suppliers&from=&to=&limit=5` answers `{what, from, to, rows:[{code, name, value}]}`. `limit` is 1 to 50. + +A bad metric, date, range or limit answers 400 in the house error shape (`bad_metric`, `bad_from`, `bad_to`, `bad_range`, `bad_by`, `bad_what`, `bad_limit`). A series covers at most 120 months. + +## Which ledger lines count + +The series read journal lines with the same filter as the trial balance and the statements: entries whose status is posted or cancelled. A cancelled entry and its reversal are both counted, so together they net to nothing in the month they share, and each counts in its own month when they differ, exactly as in the trial balance. Drafts never count. + +## The cards + +- **Revenue** tile: income accounts, credit less debit, for the period. The figure equals the profit and loss statement's total income for the same dates. Its sparkline is the monthly points. The badge compares the figure with the same number of days just before the period (`previous`); up is good. +- **Expenses** tile: expense accounts, debit less credit. Equals the statement's total expenses. Up is bad. +- **Profit** tile: revenue less expenses. Equals the statement's net profit. A loss shows in the danger tone. +- **Cash** tile: the balance of the cash accounts at the end of the period, chosen by the company's cash rule (`cash.accounts`: flagged, named or auto, see `cash-accounts.md`). Equals the cash total of `GET /api/reports/balances?asOf=` the period's last day. The badge compares it with the balance at the end of the previous span. +- **Revenue and expenses by month**: grouped bars of the monthly revenue and expense points. Its title opens the profit and loss screen. +- **Profit by month**: a line with an area over a zero line; a month with a loss dips under the line and is marked in the danger tone. Opens profit and loss. +- **Cash balance**: the cash balance at each month end (or at the period's last day for the last month). Opens the balance sheet. +- **Receivables and payables**: the balances at each month end of the control accounts named on customers (receivable accounts, debit less credit) and on suppliers (payable accounts, credit less debit). The last points equal those accounts' lines on the balance sheet for the same day. Opens the balance sheet. +- **Top customers** and **Top items**: posted sales invoices dated in the period, summed before tax, by customer and by item, largest first, five rows. Cancelled invoices are left out. Opens the sales invoices list. + +## How they tie + +For a period from F to T: + +- series revenue total = profit and loss `income.total` for F to T +- series expenses total = profit and loss `expenses.total` +- series profit total = profit and loss `netProfit` +- last cash point = balances route `cash.total` as of T +- last receivables point = the sum of the receivable control accounts' balances as of T, and last payables point the same for payable accounts, sign turned + +Checked on a company with 60 sales invoices, 30 purchase invoices, 15 journals and 6 payments over 14 months, for December 1, 2025 to November 27, 2026: revenue 3,074,572, expenses 2,596,268 and profit 478,304 matched the statement; cash 4,123,928, receivables 3,522,435 and payables 1,443,363 matched the balances route. + +## The window + +Each card is built once at its final size before any figure arrives; a period change redraws the marks inside the same boxes. Each chart is inline SVG in token colors with a title, an `aria-label`, a visually hidden data table, and a readout line under the chart that shows the exact value of the hovered or focused month or row in space kept for it. When a period has nothing posted, the chart says "No posted entries in this period" in the same box. 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/selling/templates.md b/docs/selling/templates.md new file mode 100644 index 0000000..1638065 --- /dev/null +++ b/docs/selling/templates.md @@ -0,0 +1,43 @@ +# Document templates + +A template is a named, reusable document body: its kind, a name, a description, a category, an optional customer or supplier, a currency, payment terms in days, notes, and its lines. Using a template makes a new draft; it never posts anything. + +## Kinds + +| Template kind | Makes | +| --- | --- | +| `quote` | a sales quote | +| `sales-order` | a sales order | +| `sales-invoice` | a sales invoice | +| `purchase-order` | a purchase order | +| `purchase-invoice` | a purchase invoice | + +## Built-in templates + +FormLedger ships seven starter templates, marked "Built in": Service invoice (hours), Product invoice, Retainer invoice (monthly), Quote with options, Deposit invoice (50 percent), Purchase order (stock) and Purchase invoice (services). They are read-only; Duplicate makes an editable copy. Their lines are free descriptions with an account from the starter chart (4100 Sales, 4900 Other income, 5100 Purchases and cost of sales, 5200 Freight in), so they work on a company with no items yet. On a company whose chart has no such account, the draft shows the account error when saved; change the line or duplicate the template. + +## In the window + +Open Templates (`#/templates`). The left rail has a search field and one entry per category with its count; each card shows a small preview of the document's header and first four lines with the total, the name, the kind and line count, and "Built in" or "Yours". + +- Use opens the sales or purchase document form on a new draft filled from the template (`#/sales-doc?template=ID` or `#/purchase-doc?template=ID`). The date is today and the due date is today plus the template's terms. +- Duplicate makes a copy named "(copy)" that is yours. +- Edit (yours only) renames the template in place: Enter saves, Escape cancels. +- Delete (yours only) asks once on the button itself; a second click deletes. + +On the document form, "Save as template..." in the page header asks for a name in place and saves the current header (customer or supplier, payment terms counted from the date to the due date, notes) and lines. Print, beside it, downloads the saved document's PDF from `GET /api/print/{kind}/{number or id}.pdf` (see `docs/PRINT.md`) and shows a message if the server refuses; it is hidden on a new draft. + +## Routes + +| Route | Does | +| --- | --- | +| `GET /api/templates?kind=&q=` | lists built-in templates first, then yours by name | +| `GET /api/templates/{id}` | one template | +| `POST /api/templates` | creates one of yours | +| `PUT /api/templates/{id}` | replaces one of yours | +| `DELETE /api/templates/{id}` | deletes one of yours | +| `POST /api/templates/{id}/use` | returns a new draft body; saves nothing | + +A line is `{item, description, quantityMilli, unitPrice, currentPrice, taxRate, account}`. When `currentPrice` is true and the line names an item, `use` takes the item's current sale price; otherwise the template's own price. `use` answers `{family, kind, date, dueDate, customer or supplier, currency, memo, lines, template}`. + +Reading templates needs what reading documents needs. Creating, changing, deleting or using a template needs the right to draft that kind of document (`sales.draft` or `purchase.draft`). Built-in templates answer 409 to a change or delete. Templates live in the `doc_templates` table (migration 0019) and every change is recorded in the audit log as `template.create`, `template.update` or `template.delete`. diff --git a/docs/window/DESIGN.md b/docs/window/DESIGN.md index 59c211f..c7628ec 100644 --- a/docs/window/DESIGN.md +++ b/docs/window/DESIGN.md @@ -24,7 +24,7 @@ FormLedger is the financial counterpart of form.md. It uses form.md's tokens, sh - A zero in a debit or credit column is blank, not "0.00". A negative amount has a leading minus sign and takes `--danger` only in a result (a loss, an overdue balance), never in ordinary rows. - A status is a `.badge` with a tone, never bold text: `muted` for a draft, `info` for confirmed or open, `ok` for posted or paid, `warn` for part paid or overdue, `bad` for cancelled. - A row that opens shows the pointer and the hover wash across the whole row; the document number is the row's first cell. -- An empty table says what the list is for and how to add the first row, centred in the box (`.tbl__empty`), in muted text. +- An empty table is form.md's empty state: a muted icon, a title (`.tbl__empty-title`, medium weight) and one muted line (`.tbl__empty-line`), centered in the box (`.tbl__empty`). The table option `empty` takes a string (it becomes the line under the default title "Nothing here yet") or `{ title, line }`; a view changes the text with `setEmpty(title, line)` on the table handle, never by writing into the element. The line says what the list is for and how to add the first row. The block is absolute inside the box, so its text never moves the rows. - Totals rows are semibold with a strong top border. Section subtotals in a statement are medium weight; the result line (net profit, total assets) is the only large number on the screen. ## Forms @@ -32,14 +32,16 @@ FormLedger is the financial counterpart of form.md. It uses form.md's tokens, sh - A field is `.field`: label above, control below, optional hint or error line under it with reserved height. Fields sit on a grid of equal columns; short values (code, date, currency, terms) get short fields, names and addresses get wide ones. - A form never clips: if it is taller than its box, the box scrolls and the actions stay pinned at its foot (`.form__actions`). - Actions are trailing aligned at the foot: quiet buttons first, the primary button last. A destructive action is quiet and takes `--danger` on hover; it is never the primary. +- Buttons are form.md's (`web/src/styles/forms.css` `.btn`), kept at `--control` height (28 px, form.md uses 32): an inline grid that lays an icon (14 px) and label out in a row with `--space-2` between, `--border` edge, `--surface-2` fill, `--active` on hover, 0.6 opacity when disabled or `aria-busy`, a 2 px focus offset. `.btn--primary` is the accent fill with a transparent edge and a hover tint (`--accent-hover` does not exist in the tokens, so the hover is `color-mix` of `--accent` with `--text`). `.btn--danger` is a `--danger` text on a 10 percent wash, for a confirmed destructive step. `.btn--quiet` is form.md's `.btn--ghost`: no fill, no edge, `--hover` wash. Rules live in `web/src/styles/account.css`. +- The chart of accounts screen carries one quiet control above the list, "Cash on Home counts:", a fixed-size select (Automatic, Accounts marked cash or bank, Accounts named cash or bank) beside one muted line naming the accounts counted. It saves at the change; a refusal puts the old choice back and shows a toast. It is hidden (space kept) for a role without `settings.manage`. - Text, date and select fields follow form.md `web/src/styles/forms.css` (`.input`, `.select`): surface fill, `--border` edge, `--radius-sm`, `--space-3` inline padding, `--text-md` text, a `--border-strong` edge on hover, an accent edge with a 3 px `--accent-wash` ring on focus, `--danger` edge when invalid, a muted fill when disabled, and the native select's drawn arrow; checkboxes take `accent-color: var(--accent)` as in form.md `settings.css`. Rules live in `web/src/styles/base.css`. - Required fields are marked in the label. An error names the field and says what to do. - A document form reads top to bottom as the paper would: who and when in a header block, the lines, then totals trailing aligned under the amount column, then the actions. ## The shell -- The top bar shows where you are on the leading side and who you are on the trailing side (name, then role as a muted badge, then sign out). Nothing sits in its middle. -- The sidebar groups are the business areas. The current screen is marked with the accent wash and an accent icon. +- The top bar holds back and forward, then the breadcrumb (the sidebar group, a tile, the screen title), as in form.md. It carries no name, role or sign out. Who you are lives in the user chip at the foot of the sidebar (avatar, name, a "more" mark); it opens a menu with Account (the role as a muted hint), the theme choice (system, light, dark) and Sign out. +- The sidebar is short, as in form.md: Search, Home and Dashboards at the top, then the selling and buying documents, then a foot with Reports, Setup, Templates and the user chip. Reports and Setup are hub pages of cards, one per screen; every screen is also in the command palette (Ctrl or Cmd+Shift+P) and, in the desktop shell, in the Go menu of the menubar. The current screen is marked with the accent wash and an accent icon. - Home is a working page: what is owed to you, what you owe, cash, and the last documents, each a link to its screen. ## Where FormLedger differs from form.md, and why 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. diff --git a/internal/HASHOUT_LOG.md b/internal/HASHOUT_LOG.md index ada8f7c..fff747b 100644 --- a/internal/HASHOUT_LOG.md +++ b/internal/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of comment content, rationale and removed code for the core skeleton packages under `internal/`. Source files stay comment-free; what they would have said lives here, indexed. Read it first, then edit code surgically. Covers the packages ported in the core slice only; `internal/server`, `internal/static` and `internal/startup` are logged by their own slice. -Current build version: v0.10.0 +Current build version: v0.11.0 Last updated: 2026-11-27 (US Eastern) · profit and loss and the balance sheet --- @@ -1819,3 +1819,31 @@ Supersedes the note on `build` about `isMoney`, `moneyKeys` and the header taken - logged: v0.10.0 · 2026-11-27 Ported in approach from form.md internal/transfer/pdf.go (fpdf setup, margins, `AliasNbPages`, footer page counter). form.md embeds the Go fonts from golang.org/x/image as UTF-8 fonts; that module is not a FormLedger dependency, so this uses core Helvetica through fpdf's cp1252 translator and `printable` writes any rune outside cp1252 as `[U+XXXX]`. fpdf's `SplitText` reads the translated bytes as runes and index past the 256-entry width table (a panic on the first non-ASCII byte), so every wrapped text goes through `wrap`, which splits bytes and measures with `GetStringWidth`, and is drawn one `CellFormat` per line. Auto page break is off; the table breaks itself so the header repeats. The route finds the id by number with a direct query, then reads the document through its JSON route with `rt.Handler()` as internal/export does, so the permission and any refusal are that route's. Creation and modification dates are `Stamp` (latest of created, posted, cancelled, in milliseconds), which with `SetCatalogSort` makes reruns byte-identical. A FormTxt renderer goes first in `renderers` and returns `ErrUnavailable` when it cannot run. + +### internal/printout/formtxt.go · formtxt.run +- refers-to: internal/printout/formtxt.go :: formtxt, formtxtBase, formtxtTemplate, formtxt.run; internal/printout/document.go :: Renderer, pick, Render, RenderStatement; internal/printout/module.go :: Mount (X-FormLedger-Renderer, renderer=plain); internal/printout/command.go :: Command (--plain) +- kind: rationale +- logged: v0.10.0 · 2026-11-27 + +Nothing is ported from FormTxt; the renderer calls it. It follows FormTxt's `setup/report.py`: `POST http://127.0.0.1:$FORMTXT_ENGINE_PORT/api/reports/run` (8210 by default), but sends `data.records` instead of `path` and `sql`, which `backend/app/routers/reports.py` `_records` accepts, so FormLedger never writes a database for FormTxt to read. Record values are strings because FormTxt turns every value to text. `out` must be absolute and end in `.pdf` (`_target`), so the file goes to a new `os.MkdirTemp` folder that is removed after. FormTxt asks the person before it writes (`mcp.consent`, up to 180 seconds when a window is open); the 45 second client timeout ends that wait and the plain renderer answers. A template is a document in FormTxt's store, which only the FormTxt window can create, so templates are named by environment per kind rather than shipped. With the engine up and no window, FormTxt answered 403 to a well-formed body (its 422 validation passed), and the plain renderer drew the page. Statement now goes through the interface as a second method rather than a document union, because its fields share nothing with `Document`. + +### internal/store/encrypt.go · Encrypt +- refers-to: internal/store/store.go :: Register, VFSName, Open, dsn, VFS; internal/store/encrypt.go :: Encrypt, sqlString; internal/crypt/key.go :: Load, KeyPath; internal/config/config.go :: KeyFile; cmd/formledger/main.go :: serve, encrypt (keygen, encrypt cases); internal/snapshot/command.go :: Main +- kind: rationale +- logged: v0.10.0 · 2026-11-27 + +Ported from form.md internal/store/store.go (Register, the vfs DSN, the 4096-byte page check), internal/ops/encrypt.go (Encrypt without `sealAll` and `matchOwner`, since FormLedger keeps no uploaded files and no root-run service yet) and cmd/form-md/main.go, tool.go (the `crypt.Load` before the store opens, exit status 2, `keygen`). Encryption is on only when a key is found, as in form.md; nothing makes a desktop key. The snapshot command loads the key the same way and writes its destination with the default VFS, so the file it writes is plain. `secrets.Open` was not given form.md's sealer argument because nothing in FormLedger calls it. XTS is deterministic per page offset, so two databases under one key share the first 16 bytes of ciphertext (the same plain header); that is form.md's design and was ported as is. + +### internal/reports/series.go · buildSeries, buildTop +- refers-to: internal/reports/series.go :: buildSeries, flowValue, stockValue, controlAccounts, baseCurrency, previousSpan, months, buildTop, topSQL; internal/reports/series_routes.go :: mountSeries, seriesRoute, topRoute, span; internal/reports/reports.go :: Mount +- kind: rationale +- logged: v0.10.0 · 2026-11-27 + +Revenue, expenses and profit use the statements' filter (`counted`) per month, so their totals equal `buildProfitAndLoss` for the same range. Cash, receivables and payables are balances at each month end through `balancesSQL`, with cash chosen by `cashOf` and the company's preference; receivables and payables are the accounts customers and suppliers name as their control accounts. `previous` is the same number of days just before `from`; for a balance metric its total is the balance at its last day. There is no stored base currency yet, so the series names the currency most accounts are kept in. Top rows sum posted invoices before tax by `doc_date`; cancelled invoices are left out and amounts are not converted between currencies. Checked on a year of seeded data: revenue, expenses and profit equal the profit and loss route, and the last cash point equals the balances route. + +### templates/template.go, templates/module.go · Document templates +- refers-to: internal/templates/template.go :: builtins, Service.List, Service.Use, clean; internal/templates/module.go :: canWrite, Mount; internal/store/migrations/0019_templates.sql :: doc_templates +- kind: rationale +- logged: v0.10.0 · 2026-11-27 + +Built-in templates live in Go, not in the table, so an upgraded database gets them without a data migration and they can never be changed; their ids start with `builtin-` and change or delete answers 409. Every route is behind `reports.read`; writing and `use` then check `sales.draft` or `purchase.draft` for the template's kind (and, on change, for the stored kind too). Lines are a JSON column because a template is read and written whole. Built-in free lines name 4100, 4900, 5100 and 5200: the starter chart's 4000 and 6000 are groups and a line cannot post to a group. `use` never writes; `currentPrice` takes the item's sale price for purchase templates too, since items carry no purchase price. diff --git a/internal/app/version.go b/internal/app/version.go index 657a612..73bbaf5 100644 --- a/internal/app/version.go +++ b/internal/app/version.go @@ -1,5 +1,5 @@ package app -var Version = "v0.10.0" +var Version = "v0.11.0" const Product = "FormLedger" 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"), 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/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 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)) } 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 +} 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/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, "'", "''") + "'" +} 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/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) 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..a7bbad5 --- /dev/null +++ b/internal/templates/template.go @@ -0,0 +1,283 @@ +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"` + Account string `json:"account,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, account string) Line { + return Line{Description: desc, QuantityMilli: qty, UnitPrice: price, Account: account} +} + +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, "4100"), free("Project management hours", 2000, 9000, "4100"), free("Expenses at cost", 1000, 0, "4900")}}, + {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, "4100"), free("Shipping and handling", 1000, 1500, "4900")}}, + {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, "4100")}}, + {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, "4100"), free("Option A: extended support", 1000, 40000, "4100"), free("Option B: training session", 1000, 60000, "4100")}}, + {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, "4100")}}, + {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, "5100"), free("Freight", 1000, 3500, "5200")}}, + {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, "5100")}}, +} + +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, "account": l.Account} + 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 +} diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 6d95670..349790a 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1106,7 +1106,7 @@ dependencies = [ [[package]] name = "formledger-desktop" -version = "0.10.0" +version = "0.11.0" dependencies = [ "objc2", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 452e3db..3b189a2 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formledger-desktop" -version = "0.10.0" +version = "0.11.0" description = "FormLedger desktop app" authors = ["NodeAgentc, Inc."] license = "Apache-2.0" diff --git a/src-tauri/HASHOUT_LOG.md b/src-tauri/HASHOUT_LOG.md index fce7b1b..a9d2e38 100644 --- a/src-tauri/HASHOUT_LOG.md +++ b/src-tauri/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the Tauri 2 desktop shell (`src-tauri`). Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of the shell: read it first, then edit code surgically. -Current build version: v0.10.0 +Current build version: v0.11.0 Last updated: 2026-11-26 (US Eastern) · the shell ported from form.md's src-tauri and renamed for FormLedger --- @@ -317,3 +317,10 @@ Verbatim from form.md. On Windows the server is placed in a job object with kill - logged: v0.5.0 · 2026-11-26 The owner supplied the official artwork on 2026-11-26; the six originals (1024 px, with alpha) are in `assets/brand/`. This set is made from `assets/brand/formledger_icon_dark.png` by resizing with a Lanczos filter: 32, 128, 256 (`128x128@2x.png`) and 512 (`icon.png`) px PNGs, `icon.ico` holding 16, 24, 32, 48, 64, 128 and 256 px, and `icon.icns` holding 16 to 1024 px. Nothing was redrawn. The paths match `bundle.icon` in `tauri.conf.json`. `tauri build` has still not been run here, so the set is unproven in a bundle, and the splash page still shows the name in text where the donor showed its mark. When the artwork changes, remake every file from the new original rather than editing one. + +### src/menu.rs · the native menubar +- refers-to: src/menu.rs :: build, handle, screens, Zoom; src/main.rs :: main +- kind: rationale +- logged: v0.10.0 · 2026-11-27 + +Ported from form.md `src-tauri/src/menu.rs` and its wiring in `src-tauri/src/main.rs` (`manage(menu::Zoom)`, `on_menu_event(menu::handle)`). An item id `cmd:[command]` evaluates `window.__formledgerRun(command)` in the main window, which runs the window command of that id; `zoom:`, `app:reload` and `app:notices` are handled here. The Go menu lists every screen by `cmd:go.[view id]`; the window registers those commands in `web/src/ui/views.ts`. The menubar is still built on macOS only, as before. It has not been compiled: this sandbox has no GTK, so `cargo check` cannot run here. 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..2d092f2 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 Aging"), +]; +const BUYING: [(&str, &str); 5] = [ + ("purchase-orders", "Purchase Orders"), + ("goods-receipts", "Goods Receipts"), + ("purchase-invoices", "Purchase Invoices"), + ("payments-out", "Payments Made"), + ("payables-ageing", "Payables Aging"), +]; +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')"); + } + _ => {} + } } diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 8b7a7b9..01aa3fa 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "FormLedger", "mainBinaryName": "formledger-desktop", - "version": "0.10.0", + "version": "0.11.0", "identifier": "ai.nodemode.formledger", "build": { "frontendDist": "splash" }, "app": { diff --git a/web/HASHOUT_LOG.md b/web/HASHOUT_LOG.md index c1c33c9..f7db438 100644 --- a/web/HASHOUT_LOG.md +++ b/web/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the web client. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of the web side: read it first, then edit code surgically. -Current build version: v0.10.0 +Current build version: v0.11.0 Last updated: 2026-11-26 (US Eastern) · account screens, and the fixes from the throttled browser check --- @@ -684,3 +684,31 @@ Ported from form.md `web/index.html`, `web/src/styles/shell.css`, `auth.css`, `h - logged: v0.10.0 · 2026-11-27 Checked in light at 1100 by 800, 1400 by 700 and 1400 by 900. The document action row used to scroll sideways, so Post sat off screen at 1100; it now wraps and trails with the primary last. The goods receipt, delivery note and payment forms had no height, so their actions fell below 800; they now take the window height minus `--page-head`, the table gives way and the payment actions are sticky on `--sheet`. The document title row reuses the page head grid: number in the sans face at title size, status badge beside it. At CPU 4x, 400 ms and 50 kB/s, layout shift without input is 0 on payments received, goods receipt and a new purchase invoice and 0.00007 on the trial balance. + +### src/styles/account.css, src/ui/parts/table.ts · buttons and empty states from form.md +- refers-to: src/styles/account.css :: .btn, .btn--primary, .btn--danger, .btn--quiet; src/ui/parts/table.ts :: emptyBlock, setEmpty; src/styles/parts.css :: .tbl__empty; src/ui/views/masters.ts :: loadCash; src/engine/masters.ts :: saveCashPreference +- kind: rationale +- logged: v0.10.0 · 2026-11-27 + +Ported from form.md `web/src/styles/forms.css` (`.btn`, `.btn--primary`, `.btn--danger`, `.btn--ghost` as `.btn--quiet`) and its empty state, keeping the 28 px control height. `--accent-hover` is not a token, so the primary hover mixes `--accent` with `--text`. The table empty state is an icon, a title and a line; `emptyBlock` is shared with the payment allocation box so no view writes into the element. The cash control on the chart of accounts ignores a change while the first answer is pending and puts the old choice back when the server refuses. Checked under 4x CPU and the slowed network: layout shift 0 on five screens, rows 30 px, totals at the foot. + +### src/ui/views.ts, src/ui/hubs.ts, src/ui/command-palette.ts · lean sidebar, hubs and the command palette +- refers-to: src/ui/views.ts :: SIDEBAR, SIDEBAR_HIDDEN, EXTRA_SCREENS, mountViews; src/ui/hubs.ts :: HUB_VIEWS, HUB_OF, REPORT_SCREENS, SETUP_SCREENS; src/ui/command-palette.ts :: openPalette; src/ui/app.ts :: bindCommands; src/styles/palette.css :: .cpal; src/styles/shell.css :: .hub, .sb-foot-links, .app[data-sidebar="hidden"] +- kind: rationale +- logged: v0.10.0 · 2026-11-27 + +The owner asked for form.md's lean sidebar: Search, Home, Dashboards, then the daily selling and buying lists, then Reports, Setup and Templates in the foot. Every other screen lives in the native menubar's Go menu and in the palette as a `go.[view id]` command; the hubs are `#/reports` and `#/setup`, and the hub's foot link takes `aria-current="true"` while one of its screens is open (`HUB_OF`). The sidebar keeps hidden anchors for the trial balance, general ledger and profit and loss so `a.sb-item[href='#/...']` still finds them, but a hidden anchor cannot be clicked: reach those screens by hash, through the Reports hub card (`a.hub__card[data-hub-screen=...]`) or through the palette. The palette is form.md's `web/src/ui/command-palette.ts` and the `.cpal` rules of `web/src/styles/finder.css`, without its layer stack: it keeps its own scrim at `--z-scrim`, the box at `--z-overlay`, returns focus on Escape, and matches each typed word as a substring or, failing that, as letters in order. Write Snapshot has no HTTP route, so the command says to run `formledger snapshot`. `window.__formledgerRun` is what the native menubar calls. Checked under 4x CPU and the slowed network after a reload, dark and light: layout shift without input 0 on load, on opening the palette and on seven screen changes through the palette by keyboard; with input at most 0.0006. + +### src/ui/views/dashboards.ts, src/ui/parts/chart.ts · Dashboards view and inline SVG charts +- refers-to: src/ui/views/dashboards.ts :: dashboardsView, tile, card; src/ui/parts/chart.ts :: xyChart, hbarChart, sparkline, monthName; src/engine/dashboards.ts :: periodRange, series, top, change; src/styles/charts.css :: .chart, .chart__frame, .chart__readout, .chart__empty; src/styles/views/dashboards.css :: .dash__grid, .dash__card, .kpi +- kind: rationale +- logged: v0.10.0 · 2026-11-27 + +Ported from form.md `web/src/ui/bar-chart.ts` (the reuse-in-place `svg` and rect loop, fixed viewBox), `web/src/styles/charts.css` (`.chart`, `.chart__grid`, `.chart__base`, `.chart__tick`, `.chart__value`, `.chart__mark`, `.chart__line`, `.chart__area`, `.dash`, `.dash__grid`, `.dash__card` with its 32 px head and 240 px body, the kpi card, `.chart__kpi-change` as an ok or bad badge). form.md's palette tokens (`--c-blue` and so on) do not exist here, so a series takes a `data-tone` mapped to `--accent`, `--info`, `--success`, `--warning` or `--danger`. Each chart keeps one hit column per month (`.chart__hit`, focusable) that writes the exact values into a readout line under the chart, in reserved height, instead of a tooltip. The view is `nav: false` because the sidebar item belongs to the sidebar owner. The change badge has a fixed `10ch` width on the trailing side and caps at ">999%": with a centered or leading badge its text width moved the line by 0.00003 to 0.0003. Checked under 4x CPU and the slowed network after a hard reload at 1400 by 900 and 1100 by 800: layout shift 0 without input and 0 with input, on load and on changing the period. + +### src/ui/views/templates.ts, src/ui/views/docform.ts · Templates gallery, Save as template and Print +- refers-to: src/ui/views/templates.ts :: makeCard, writeCard, mount; src/engine/templates.ts :: categoryCounts, templateKind, printUrl, termsFrom; src/ui/views/docform.ts :: saveTpl, fromTemplate, accounts; src/styles/views/templates.css :: .tplgal, .tplcard, .tplmini +- kind: rationale +- logged: v0.10.0 · 2026-11-27 + +Ported from form.md `web/src/ui/templates-dialog.ts` (rail with search and category counts, card grid) and `web/src/styles/templates.css` (`.tplgal__*`, `.tplcard`, `.tplcard__flag`), as a page instead of a dialog and with token sizes. The gallery draws eight placeholder cards at final size before the list arrives and then writes into them; Edit and Delete keep their slot with `visibility` on built-in cards. Save as template and Print sit in the page head, not in `.df-actions`, so the action row cannot wrap and `.df-actions button` index 1 stays Post or Confirm; the name field lives in a fixed `30ch` box and Print is hidden with `visibility` on a new draft. A free line from a template keeps its account in a description-to-account map, because the line grid has no account column; the draft body sends it as `incomeAccount` or `expenseAccount`. diff --git a/web/index.html b/web/index.html index c9668ec..d612781 100644 --- a/web/index.html +++ b/web/index.html @@ -74,14 +74,31 @@

Join these books