diff --git a/CHANGELOG.md b/CHANGELOG.md index 531d543..4f6feb4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,40 @@ # Changelog +## 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. + +### New +- The splash shows FormLedger's app icon, as form.md's splash shows its own. +- The window follows your system's light or dark theme, with a choice of System, Light or Dark in the menu at the foot of the sidebar. +- Sign-in, first set-up, unlock and invitations are one card on the dotted ground, with a show-password control. +- The sidebar is headed by the app icon, name, a live dot and the version, and ends in a chip with your name that opens a menu for your account, the theme and signing out. +- The top bar has back and forward and shows where you are as group and screen. +- Every screen opens with its group, a large title and one line saying what it is for. +- "Export CSV" on every list, ledger screen and statement, with the filters you have on. +- PDFs: invoices, quotes, orders, purchase documents and customer statements, by `./formledger cli print KIND NUMBER` or from the server. `docs/PRINT.md` says how. +- A "Cash or bank account" tick on asset accounts, and a company choice of how Home counts cash: ticked accounts, accounts named cash or bank, or automatic (ticked ones if any are ticked). `docs/ledger/cash-accounts.md` explains it. +- Home greets you and offers "New invoice" and "Record payment". + +### Changed +- Fields, selects and tick boxes look and focus as they do in form.md. +- The delivery note list is read in pages like the other lists, so its export is no longer cut off at 500. +- An export of an empty list now has its real column header. +- The snapshot's accounts table has a new last column, `is_cash`. + +### 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. + +### Known issues +- Buttons still differ a little from form.md's (hover, the danger style, height); the list is in the pull request. +- The window has no place yet to change how Home counts cash; it can be set through the server only. +- PDFs print letters outside Western European alphabets as codes such as `[U+0141]`, not as the letters. +- PDFs through FormTxt are not built. The window has no print button yet. +- The sidebar and Home show "FormLedger" where your company's name should be. +- Tables' empty messages do not yet have form.md's icon and title. +- The desktop app has not been built yet, so the splash has been checked as a page, not in the running app. + ## 0.9.0 The window has had its first design pass, and two ways to take your figures out have arrived. diff --git a/Makefile b/Makefile index 8320c28..e72e439 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -VERSION := v0.9.0 +VERSION := v0.10.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 bebf7a1..e15a6c8 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -8,7 +8,7 @@ A file brought over from another Form repository gets a row here with its source | Source | Licence | 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 | +| 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 | ## Third-party software @@ -18,6 +18,7 @@ Each component gets a row here with its licence and its use before it is added. | --- | --- | --- | | 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 | | 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 | diff --git a/cmd/HASHOUT_LOG.md b/cmd/HASHOUT_LOG.md index 07aa9c1..8a7e7ca 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.9.0 +Current build version: v0.10.0 Last updated: 2026-11-26 (US Eastern) · skeleton port from form.md --- diff --git a/docs/EXPORT.md b/docs/EXPORT.md index 1d0349b..5c77b60 100644 --- a/docs/EXPORT.md +++ b/docs/EXPORT.md @@ -9,22 +9,23 @@ The command line fetches the same route with the app token (`FORMLEDGER_TOKEN` o ## How it works -The export route runs the list or report's own JSON route inside the server, with the caller's own session or token. So each export takes exactly the query parameters of its JSON route and is guarded by exactly the same permission; a refusal or a bad parameter answers that route's own status and JSON error body. An unknown name answers `404` with `{"error":{"code":"not_found","message":"no such export"}}`. Without a session it answers `401`. +The export route runs the list or report's own JSON route inside the server, with the caller's own session or token. So each export takes exactly the query parameters of its JSON route and is guarded by exactly the same permission; a refusal or a bad parameter answers that route's own status and JSON error body. An unknown name answers `404` with `{"error":{"code":"not_found","message":"no such export"}}`. Without a session it answers `401`. All 22 JSON routes need `reports.read`, which every role holds (the viewer too), so today a signed-in user of any role gets every file; a role without that permission would get the route's `403`. -A list is read to the end: the export follows `nextCursor` (or `next`) page by page until it is empty, so the file holds every row, not the first page. `cursor` is ignored if given; `limit` only sets the page size. +A list is read to the end: the export follows `nextCursor` (or `next`) page by page until it is empty, so the file holds every row, not the first page. `cursor` is ignored if given; `limit` only sets the page size. The delivery note list pages by cursor like the document lists (`GET /api/delivery/notes?limit=&cursor=`, answering `nextCursor`, newest first with the id as the tie-break), so the delivery-notes export is complete past 500 rows. ## The file - RFC 4180 through Go `encoding/csv`: comma separated, CRLF line ends, a field with a comma, quote or line break is quoted and its quotes doubled. - UTF-8 with no byte order mark. - `Content-Type: text/csv; charset=utf-8` and `Content-Disposition: attachment; filename="NAME-YYYY-MM-DD.csv"`, the date being today in US Eastern time. -- One header row of lower_snake_case names, taken from the JSON field names in their JSON order (`taxTotal` becomes `tax_total`, `days1to30` becomes `days_1_to_30`). A nested object is spread into prefixed columns (`account` in the general ledger gives `account_code`, `account_name` and so on). Nested lists (document lines, allocations) are left out. +- One header row of lower_snake_case names, from a column list declared for each export (the table below, in file order), so the header is the same whether the list has no rows, one row or many, and a field the first row lacks is still a column. A JSON field `taxTotal` is column `tax_total`, `days1to30` is `days_1_to_30`. A nested object is spread into prefixed columns (`account` in the general ledger gives `account_code`, `account_name` and so on). Nested lists (document lines, allocations) are left out. A JSON field that is not in the declared list is not written: a new field reaches the file only when it is declared there with its kind. +- Each declared column has a kind: text, date, money, integer or quantity. The kind decides how the cell is written, never the field's name. - Report-wide values (`as_of`, `from`, `to`, `by`, the ledger's `account_*`) are repeated on every row so each row stands alone. -- Dates are YYYY-MM-DD. A time stamp field (`created_at`, `posted_at` and the like) is written as its US Eastern date; an empty one is an empty cell. -- Money is a plain decimal in major units of the row's currency, with a leading `-` when negative: never a thousands separator, never a currency sign. Every row with money carries a `currency` column. The money fields are `debit`, `credit`, `balance`, `amount`, `total`, `subtotal`, `tax_total`, `opening`, `closing`, `value`, `unit_cost`, `current`, the ageing buckets, `allocated`, `unallocated`, `outstanding` and any field ending in `price` or `amount`. -- Other numbers (`rate_bp`, `quantity_milli`, `payment_terms_days`, `line_count`) are written as the JSON integer. Booleans are `true` or `false`. -- Formula guard: a cell in a TEXT column (a JSON string, such as a name, memo or code) that starts with `=`, `+`, `-` or `@` is written with a single quote in front, so a spreadsheet shows it as text and does not run it as a formula. `=HYPERLINK("x")` is written `'=HYPERLINK("x")`. Numbers and amounts are never changed, so `-60.15` stays a number. -- A list with no rows has no field names to read, so its file is the single header `empty`. +- Dates (kind date) are YYYY-MM-DD. A time stamp field (`created_at`, `posted_at` and the like) is written as its US Eastern date; an empty one is an empty cell. +- Money (kind money, marked `*` below) is a plain decimal in major units of the row's currency, with a leading `-` when negative: never a thousands separator, never a currency sign. The number of decimals is the currency's own: `2468` minor units is `2468` in JPY (no decimals), `24.68` in USD and `2.468` in KWD (three). Every export with a money column carries a `currency` column. +- Integers and quantities (`rate_bp`, `payment_terms_days`, `line_count`, `line_no`, and the quantity `qty_milli`) are written as the JSON integer; quantities stay in thousandths, so `5000` is 5 units. Booleans (`active`, `is_group`) are `true` or `false`. +- Formula guard: a cell in a TEXT column (a name, memo, code or other string) that starts with `=`, `+`, `-` or `@` is written with a single quote in front, so a spreadsheet shows it as text and does not run it as a formula. `=HYPERLINK("x")` is written `'=HYPERLINK("x")`. Date, money, integer and quantity cells are never changed, so `-60.15` stays a number. +- A list with no rows still has its full header and no data rows. ## Names @@ -38,7 +39,7 @@ Columns are listed in file order. `*` marks money. | purchase-orders | `/api/purchase/docs?kind=order` | status, supplier, limit | as its JSON route | id, kind, number, date, due_date, supplier_id, supplier, supplier_name, currency, status, source_id, amends_id, warehouse_id, warehouse, supplier_ref, subtotal*, tax_total*, total*, journal_entry_id, memo, created_by, created_at, posted_by, posted_at, cancelled_by, cancelled_at, line_count | | purchase-invoices | `/api/purchase/docs?kind=invoice` | as purchase-orders | as purchase-orders | as purchase-orders | | goods-receipts | `/api/purchase/docs?kind=receipt` | as purchase-orders | as purchase-orders | as purchase-orders | -| delivery-notes | `/api/delivery/notes` | status, order, limit (default 500) | reports.read | id, number, date, sales_order_id, customer_id, warehouse_id, status, journal_entry_id, memo, created_by, created_at, posted_by, posted_at, cancelled_by, cancelled_at, value*, currency | +| delivery-notes | `/api/delivery/notes` | status, order, limit (page size, default 500) | reports.read | id, number, date, sales_order_id, customer_id, warehouse_id, status, journal_entry_id, memo, created_by, created_at, posted_by, posted_at, cancelled_by, cancelled_at, value*, currency | | payments-in | `/api/sales/payments` | as its JSON route | as its JSON route | id, number, date, customer_id, customer, currency, amount*, deposit_account_id, deposit, status, journal_entry_id, memo, created_by, created_at, posted_by, posted_at, cancelled_by, cancelled_at, allocated*, unallocated* | | payments-out | `/api/purchase/payments` | as its JSON route | as its JSON route | id, number, date, supplier_id, supplier, currency, amount*, paid_from_account_id, paid_from, status, journal_entry_id, memo, created_by, created_at, posted_by, posted_at, cancelled_by, cancelled_at, allocated*, unallocated* | | customers | `/api/customers` | as its JSON route | as its JSON route | id, code, name, email, phone, address, tax_id, currency, receivable_account_id, receivable_account, payment_terms_days, active, created_at, updated_at | @@ -51,7 +52,7 @@ Columns are listed in file order. `*` marks money. | general-ledger | `/api/reports/general-ledger` | account (required), from, to | reports.read | account_account_id, account_code, account_name, account_type, account_currency, account_is_group, from, to, date, number, entry_id, line_no, memo, debit*, credit*, balance*, currency | | receivables-ageing | `/api/receivables/ageing` | as its JSON route (asOf, by) | as its JSON route | as_of, by, customer_id, code, name, currency, current*, days_1_to_30*, days_31_to_60*, days_61_to_90*, over_90*, unallocated*, total* | | payables-ageing | `/api/payables/ageing` | as its JSON route (asOf, by) | as its JSON route | as_of, by, supplier_id, code, name, currency, current*, days_1_to_30*, days_31_to_60*, days_61_to_90*, over_90*, unallocated*, total* | -| stock-balance | `/api/stock/balances` | as its JSON route | as its JSON route | as_of, then the balance row fields | +| stock-balance | `/api/stock/balances` | as its JSON route | as its JSON route | as_of, item_id, item_code, item_name, warehouse_id, warehouse_code, qty_milli (quantity, thousandths) | | profit-and-loss | `/api/reports/profit-and-loss` | from, to | reports.read | from, to, section (income or expense), account_id, code, name, currency, amount* | | balance-sheet | `/api/reports/balance-sheet` | asOf | reports.read | as_of, section (asset, liability or equity), account_id, code, name, currency, amount* | diff --git a/docs/PRINT.md b/docs/PRINT.md new file mode 100644 index 0000000..2a352e4 --- /dev/null +++ b/docs/PRINT.md @@ -0,0 +1,36 @@ +# Printing documents as PDF + +FormLedger draws a plain PDF of a sales or purchase document itself, with no other program installed. + +## What can be printed + +| Kind | Document | +| --- | --- | +| `quote` | sales quote | +| `order` | sales order | +| `invoice` | sales invoice | +| `purchase-order` | purchase order | +| `purchase-invoice` | purchase invoice | +| `goods-receipt` | goods receipt | + +A customer statement prints at `GET /api/print/statement/{customer code or id}.pdf`. The query (`from`, `to`) passes through to `GET /api/receivables/statement` unchanged, and the page shows the customer, the period, the opening balance, one row per invoice, payment or cancellation (date, number, description, debit, credit, running balance) and the closing balance. The statement route gives no ageing, so the page has none. `./formledger cli print statement CODE [--from DATE] [--to DATE] [--out FILE]` writes the same bytes, and the file is named `statement-CODE-TO.pdf`. Its PDF dates are the `to` date, so reruns are byte-identical. + +## Address and command + +`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`. + +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. + +## The page + +Letter for documents in USD, A4 for every other currency; there is no page size setting yet. The page carries the company name (the instance name), the document kind, number, date, due date, currency and status, the customer or supplier, a line table (item, description, quantity, unit price, tax rate, amount before tax) whose header repeats on every page and whose rows wrap, the subtotal, tax and total from the document itself, the notes, and "Page N of M". Drafts carry "DRAFT" and cancelled documents "CANCELLED" across every page. Amounts use the app's own money formatting with thousands separators. + +## Fonts and characters + +The page uses the PDF core font Helvetica in the Windows-1252 code page, so Latin-1 letters and the usual quotes, dashes and the euro sign print as written. Any other character (Greek, Cyrillic, Chinese, Polish `ł` and so on) is printed visibly as its code, for example `[U+03A9]`, never dropped. No font file ships with FormLedger: the Inter files the window uses are WOFF2, which the PDF library cannot read, and form.md's approach (embedding the Go fonts from `golang.org/x/image`) would add a dependency. + +## 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. diff --git a/docs/SNAPSHOT.md b/docs/SNAPSHOT.md index 47587f8..eb691b2 100644 --- a/docs/SNAPSHOT.md +++ b/docs/SNAPSHOT.md @@ -74,6 +74,7 @@ Key and value pairs, both TEXT. | is_group | INTEGER | 1 for a group account that takes no postings | | currency | TEXT | account currency | | active | INTEGER | 1 when active | +| is_cash | INTEGER | 1 when the account is flagged as a cash or bank account, see `docs/ledger/cash-accounts.md` | ### fiscal_periods diff --git a/docs/ledger/cash-accounts.md b/docs/ledger/cash-accounts.md new file mode 100644 index 0000000..992d8e2 --- /dev/null +++ b/docs/ledger/cash-accounts.md @@ -0,0 +1,59 @@ +# Cash and bank accounts + +Home shows a "Cash and bank" figure. Which accounts it adds up is decided by a flag on each account and a company preference that chooses between the flag and the account names. + +## The flag + +Every account has `isCash` in its JSON (`is_cash` in the database, 0 or 1). It is returned by `GET /api/accounts`, set on `POST /api/accounts` and changed with `PATCH /api/accounts/{id}`: + +```json +{"isCash": true} +``` + +Only an asset account that is not a group can carry the flag. Anything else is refused with status 422 and code `bad_cash`: + +- a liability, equity, income or expense account: "only an asset account can be a cash or bank account" +- a group account: "a group account cannot be a cash or bank account; mark the accounts under it" + +The starter chart flags `1110 Cash on hand` and `1120 Bank account`. Migration `0018_account_cash.sql` adds the column with 0 for every account that already exists, so an older company has no flagged account until someone marks one. + +## The preference + +The company preference `cash.accounts` has three values: + +| value | accounts counted | +|---|---| +| `flagged` | only accounts with `isCash` | +| `named` | non-group asset accounts whose name contains "cash" or "bank", in any case | +| `auto` | the flagged accounts when at least one account is flagged, otherwise the `named` rule | + +`auto` is the default. A new company starts with 1110 and 1120 flagged, so `auto` counts the flags. An older company upgraded from before the flag has none, so `auto` falls back to the names and its figure does not change. As soon as one account is flagged, `auto` counts only the flagged accounts; flag every cash and bank account at once, or choose `named` until that is done. + +## Reading the figure + +`GET /api/reports/balances` keeps `asOf` and `accounts` (each row now also carries `isCash`) and adds `cash`: + +```json +"cash": { + "preference": "auto", + "rule": "flagged", + "total": 307500, + "accounts": [ + {"code": "1110", "name": "Cash on hand", "currency": "USD", "balance": 50000}, + {"code": "1120", "name": "Bank account", "currency": "USD", "balance": 250000}, + {"code": "1125", "name": "Petty float", "currency": "USD", "balance": 7500} + ] +} +``` + +`rule` is `flagged` or `named`, never `auto`: it says which rule `auto` resolved to. Amounts are minor units, debit minus credit, as of `asOf`. `total` adds balances across currencies as they are. + +## Switching + +Read the preference with `GET /api/reports/cash-rule` (permission `reports.read`) and change it with `PUT /api/reports/cash-rule` (permission `settings.manage`): + +```json +{"preference": "named"} +``` + +Both answer `{"preference": "...", "options": ["auto", "flagged", "named"]}`. Any other value is refused with 422 `bad_preference`. The change is stored in the `settings` table under `cash.accounts` and audited as `settings.update`. diff --git a/docs/window/DESIGN.md b/docs/window/DESIGN.md index 97ae9c0..59c211f 100644 --- a/docs/window/DESIGN.md +++ b/docs/window/DESIGN.md @@ -4,7 +4,8 @@ FormLedger is the financial counterpart of form.md. It uses form.md's tokens, sh ## The page -- A screen is one `.page`: a title row, one toolbar, then the content. Nothing floats in the middle of a row. +- A screen is one `.page`: the page head, one toolbar, then the content. Nothing floats in the middle of a row. +- The page head is form.md's (`web/src/styles/home.css` `.home__head`, `.home__eyebrow`, `.home__title`, `.home__lead`): an accent uppercase eyebrow naming the sidebar group (Selling, Buying, Stock, Ledger, Setup), the title at `--text-title`, and one muted line saying what the screen is for, from `web/src/ui/view-about.ts` keyed by view id. Actions trail at the foot of the head. The head has a fixed height, `--page-head` in `web/src/styles/parts.css` (eyebrow `--text-xs` times 1.4, title `--text-title` times 1.2, line `--text-md` times `--leading`, two `--space-1` gaps: 79.4 px with the current tokens), so nothing below it moves. Eyebrow, title and line each stay on one line and end in an ellipsis. - A list or ledger screen fills the window: `.page--fill` makes the page as tall as the sheet, and its table takes the rest (`.tbl--grow`, or `--tbl-block` for a table with totals). A table is never a short box on an empty page. - The title row holds the title on the leading side and the screen's one primary action on the trailing side (`.page__head`, `.page__actions`). One primary button per screen; every other button is quiet. - Space comes from the scale only (`--space-1` to `--space-8`). Sections are `--space-6` apart, controls in a row `--space-2`, a label and its field `--space-1`. @@ -31,6 +32,7 @@ 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. +- 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. @@ -40,6 +42,12 @@ FormLedger is the financial counterpart of form.md. It uses form.md's tokens, sh - The sidebar groups are the business areas. 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 + +- Tables are denser than form.md's database table: rows stay `--row` (30 px) and never stretch to fill the box, because a ledger is read as a column of numbers and more rows on screen is the point. Empty space under the rows is filler, and the totals row sits at the foot (`data-foot`, `--tbl-rows`, `.tbl-wrap`). +- Fields are `--control` (28 px) high, not form.md's 34 px, so setup forms, the document form and the toolbars keep their measured heights. +- form.md uses the large head on Home only; FormLedger puts it on every screen so each one says what it is for, since most people open a finance screen to do one job. + ## What never happens - Nothing moves when data arrives or when a row is added: space is reserved first (law two of the build rules). diff --git a/go.mod b/go.mod index 8a1d859..9937d52 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/nodemode-ai/formledger go 1.26.9 require ( + github.com/go-pdf/fpdf v0.9.0 golang.org/x/crypto v0.58.0 modernc.org/libc v1.77.1 modernc.org/sqlite v1.60.1 diff --git a/go.sum b/go.sum index ad3b991..8fda208 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-pdf/fpdf v0.9.0 h1:PPvSaUuo1iMi9KkaAn90NuKi+P4gwMedWPHhj8YlJQw= +github.com/go-pdf/fpdf v0.9.0/go.mod h1:oO8N111TkmKb9D7VvWGLvLJlaZUQVPM+6V42pp3iV4Y= github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo= github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= diff --git a/internal/HASHOUT_LOG.md b/internal/HASHOUT_LOG.md index 9af5876..ada8f7c 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.9.0 +Current build version: v0.10.0 Last updated: 2026-11-27 (US Eastern) · profit and loss and the balance sheet --- @@ -1798,3 +1798,24 @@ The live side is one `ReadOnly` transaction on a single connection of the store' - logged: v0.9.0 · 2026-11-27 Most list and report functions are unexported, so the export does not call them directly: it runs the JSON route itself through `rt.Handler()` with a clone of the caller's request (cookies or bearer token kept, `Accept-Encoding` dropped) into an `httptest.ResponseRecorder`. That keeps the parameters, the permission and the SQL exactly the route's, and a refusal passes through with the route's own status and body. The JSON is read with a token decoder so columns keep the struct's field order; the header is the union of fields in first-seen order. Money is found by field name (`isMoney`) because the JSON carries plain integers; a new money field with another name must be added to `moneyKeys`. Delivery notes have no cursor, so that export asks for the route's maximum `limit` of 500. No byte order mark: spreadsheets that need one to read UTF-8 are a window concern, and a BOM breaks `cut`, `csvkit` and most CSV parsers' first header. The CLI verb writes the HTTP body unchanged, so its bytes equal the route's. + +### internal/reports/cash.go · cashOf +- refers-to: internal/reports/cash.go :: cashPreference, cashOf, namedCash, mountCash; internal/reports/balances.go :: balances; internal/coa/account.go :: checkCash; internal/store/migrations/0018_account_cash.sql +- kind: rationale +- logged: v0.9.0 · 2026-11-27 + +The preference `cash.accounts` lives in the `settings` table but is not a `settings.Defs` entry, because internal/settings was outside this slice and there is no general settings route; reports reads and writes the row directly, so the settings service's in-memory cache never sees it. If `cash.accounts` is later added to `Defs` as an Enum, the cash-rule route should move to the settings service so both agree. An unknown stored value reads as `auto`. The named rule skips group accounts, matching the flag's own limit. The migration marks nothing on an existing company: `auto` then resolves to the name rule, so an upgraded company's figure is unchanged until someone flags an account. + +### internal/export/module.go · specs +- refers-to: internal/export/module.go :: specs, build; internal/export/writer.go :: declare, kind, table.add; internal/delivery/module.go :: Service.List, parseCursor +- kind: rationale +- logged: v0.10.0 · 2026-11-27 + +Supersedes the note on `build` about `isMoney`, `moneyKeys` and the header taken from first-seen fields. Each export now declares its columns as a string of names with a one-character kind suffix (`*` money, `@` date or time stamp, `#` integer or flag, `%` quantity, none text), parsed by `declare`. A JSON field that is not declared is dropped, so a new money field has to be added to the string with `*` or it never reaches the file, and it can never be written as a raw integer by name accident. The formula guard runs on text columns only. A `currency` column that the row lacks is filled from the route's currency. Delivery notes now page like the sales documents, ordered by date, created time and id descending, with the cursor holding the last row's created time and `date|id`; the export keeps asking for 500 per page and follows `nextCursor`. + +### internal/printout/plain.go · plain.Render +- refers-to: internal/printout/document.go :: Renderer, Render, renderers, Document.Stamp; internal/printout/plain.go :: plain.Render, PageSize; internal/printout/text.go :: printable, wrap; internal/printout/module.go :: Mount, fetch; internal/printout/command.go :: Command; internal/server/server.go :: Build (the printout line); internal/cli/cli.go :: groups (the print line) +- kind: rationale +- 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. diff --git a/internal/app/version.go b/internal/app/version.go index 0d54870..657a612 100644 --- a/internal/app/version.go +++ b/internal/app/version.go @@ -1,5 +1,5 @@ package app -var Version = "v0.9.0" +var Version = "v0.10.0" const Product = "FormLedger" diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 4c9b68a..60c0f85 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -9,6 +9,7 @@ import ( "strings" "github.com/nodemode-ai/formledger/internal/export" + "github.com/nodemode-ai/formledger/internal/printout" ) type env struct { @@ -52,6 +53,7 @@ func groups() []group { {"stock", "warehouses, item stock settings, balances, the stock ledger, valuation and its tie to the ledger", stockVerbs()}, {"report", "trial balance and general ledger", reportVerbs()}, {"export", "any list or report as CSV, the same bytes as GET /api/export/NAME.csv", []verb{{"export", export.Usage, "write one export to standard output or --out FILE", func(e *env, a []string) error { return export.Command(a, e.out) }}}}, + {"print", "a quote, order or invoice as a PDF, the same bytes as GET /api/print/KIND/NUMBER.pdf", []verb{{"print", printout.Usage, "write one PDF to standard output or --out FILE", func(e *env, a []string) error { return printout.Command(a, e.out) }}}}, {"statement", "profit and loss and the balance sheet", statementVerbs()}, {"whoami", "the user and role behind the app token", []verb{whoamiVerb()}}, {"token", "how to make an app token", []verb{tokenVerb()}}, diff --git a/internal/coa/account.go b/internal/coa/account.go index 1f08ea4..1116171 100644 --- a/internal/coa/account.go +++ b/internal/coa/account.go @@ -30,6 +30,7 @@ type Account struct { ParentID string `json:"parentId"` ParentCode string `json:"parentCode"` IsGroup bool `json:"isGroup"` + IsCash bool `json:"isCash"` Currency string `json:"currency"` Active bool `json:"active"` CreatedAt int64 `json:"createdAt"` @@ -76,6 +77,19 @@ func cleanName(name string) (string, error) { return name, nil } +func checkCash(cash bool, typ string, group bool) error { + if !cash { + return nil + } + if typ != Asset { + return invalid("bad_cash", "only an asset account can be a cash or bank account") + } + if group { + return invalid("bad_cash", "a group account cannot be a cash or bank account; mark the accounts under it") + } + return nil +} + func cleanCurrency(c string) (string, error) { c = strings.ToUpper(strings.TrimSpace(c)) if c == "" { diff --git a/internal/coa/create.go b/internal/coa/create.go index 21b29be..390d03e 100644 --- a/internal/coa/create.go +++ b/internal/coa/create.go @@ -16,6 +16,7 @@ type NewAccount struct { Type string `json:"type"` Parent string `json:"parent,omitempty"` IsGroup bool `json:"isGroup,omitempty"` + IsCash bool `json:"isCash,omitempty"` Currency string `json:"currency,omitempty"` } @@ -31,6 +32,9 @@ func (s *Service) Create(ctx context.Context, q store.Querier, in NewAccount) (A if !ValidType(in.Type) { return Account{}, invalid("bad_type", "type must be one of asset, liability, equity, income, expense") } + if err := checkCash(in.IsCash, in.Type, in.IsGroup); err != nil { + return Account{}, err + } cur, err := cleanCurrency(in.Currency) if err != nil { return Account{}, err @@ -57,8 +61,8 @@ func (s *Service) Create(ctx context.Context, q store.Querier, in NewAccount) (A return Account{}, httpx.Fail(http.StatusConflict, "code_taken", "an account with code "+code+" already exists") } id, now := ids.New(), store.NowMS() - _, err = q.ExecContext(ctx, `INSERT INTO accounts (id, code, name, type, parent_id, is_group, currency, active, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, 1, ?, ?)`, id, code, name, in.Type, parentID, store.Bool(in.IsGroup), cur, now, now) + _, err = q.ExecContext(ctx, `INSERT INTO accounts (id, code, name, type, parent_id, is_group, is_cash, currency, active, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?)`, id, code, name, in.Type, parentID, store.Bool(in.IsGroup), store.Bool(in.IsCash), cur, now, now) if err != nil { return Account{}, err } diff --git a/internal/coa/module.go b/internal/coa/module.go index 0d47687..1bb7a76 100644 --- a/internal/coa/module.go +++ b/internal/coa/module.go @@ -63,7 +63,7 @@ func (m module) update(w http.ResponseWriter, r *http.Request, p *policy.Princip } out = after return m.auth.Record(r, tx, m.auth.Actor(r, p), "account.update", "account", after.ID, audit.OK, - map[string]any{"code": after.Code, "name": [2]string{before.Name, after.Name}, "active": [2]bool{before.Active, after.Active}}) + map[string]any{"code": after.Code, "name": [2]string{before.Name, after.Name}, "active": [2]bool{before.Active, after.Active}, "isCash": [2]bool{before.IsCash, after.IsCash}}) }) if err != nil { return err @@ -85,7 +85,7 @@ func (m module) create(w http.ResponseWriter, r *http.Request, p *policy.Princip } out = a return m.auth.Record(r, tx, m.auth.Actor(r, p), "account.create", "account", a.ID, audit.OK, - map[string]any{"code": a.Code, "name": a.Name, "type": a.Type, "parent": a.ParentCode, "isGroup": a.IsGroup, "currency": a.Currency}) + map[string]any{"code": a.Code, "name": a.Name, "type": a.Type, "parent": a.ParentCode, "isGroup": a.IsGroup, "isCash": a.IsCash, "currency": a.Currency}) }) if err != nil { return err diff --git a/internal/coa/read.go b/internal/coa/read.go index 988be00..fc68a98 100644 --- a/internal/coa/read.go +++ b/internal/coa/read.go @@ -11,7 +11,7 @@ import ( ) const selectAccount = `SELECT a.id, a.code, a.name, a.type, COALESCE(a.parent_id, ''), COALESCE(p.code, ''), - a.is_group, a.currency, a.active, a.created_at, a.updated_at + a.is_group, a.is_cash, a.currency, a.active, a.created_at, a.updated_at FROM accounts a LEFT JOIN accounts p ON p.id = a.parent_id` type scanner interface { @@ -20,9 +20,9 @@ type scanner interface { func scan(row scanner) (Account, error) { var a Account - var group, active int - err := row.Scan(&a.ID, &a.Code, &a.Name, &a.Type, &a.ParentID, &a.ParentCode, &group, &a.Currency, &active, &a.CreatedAt, &a.UpdatedAt) - a.IsGroup, a.Active = group == 1, active == 1 + var group, cash, active int + err := row.Scan(&a.ID, &a.Code, &a.Name, &a.Type, &a.ParentID, &a.ParentCode, &group, &cash, &a.Currency, &active, &a.CreatedAt, &a.UpdatedAt) + a.IsGroup, a.IsCash, a.Active = group == 1, cash == 1, active == 1 return a, err } diff --git a/internal/coa/starter.json b/internal/coa/starter.json index db13695..9e0571f 100644 --- a/internal/coa/starter.json +++ b/internal/coa/starter.json @@ -1,8 +1,8 @@ [ {"code": "1000", "name": "Assets", "type": "asset", "isGroup": true}, {"code": "1100", "name": "Current assets", "type": "asset", "isGroup": true, "parent": "1000"}, - {"code": "1110", "name": "Cash on hand", "type": "asset", "parent": "1100"}, - {"code": "1120", "name": "Bank account", "type": "asset", "parent": "1100"}, + {"code": "1110", "name": "Cash on hand", "type": "asset", "parent": "1100", "isCash": true}, + {"code": "1120", "name": "Bank account", "type": "asset", "parent": "1100", "isCash": true}, {"code": "1200", "name": "Accounts receivable", "type": "asset", "parent": "1100"}, {"code": "1300", "name": "Inventory", "type": "asset", "parent": "1100"}, {"code": "1400", "name": "Prepaid expenses", "type": "asset", "parent": "1100"}, diff --git a/internal/coa/update.go b/internal/coa/update.go index b59d15d..e46f417 100644 --- a/internal/coa/update.go +++ b/internal/coa/update.go @@ -9,6 +9,7 @@ import ( type Patch struct { Name *string `json:"name,omitempty"` Active *bool `json:"active,omitempty"` + IsCash *bool `json:"isCash,omitempty"` } func (s *Service) Update(ctx context.Context, q store.Querier, id string, p Patch) (before, after Account, err error) { @@ -16,10 +17,10 @@ func (s *Service) Update(ctx context.Context, q store.Querier, id string, p Patc if err != nil { return } - if p.Name == nil && p.Active == nil { - return before, before, invalid("empty_patch", "give name or active") + if p.Name == nil && p.Active == nil && p.IsCash == nil { + return before, before, invalid("empty_patch", "give name, active or isCash") } - name, active := before.Name, before.Active + name, active, cash := before.Name, before.Active, before.IsCash if p.Name != nil { if name, err = cleanName(*p.Name); err != nil { return @@ -28,8 +29,14 @@ func (s *Service) Update(ctx context.Context, q store.Querier, id string, p Patc if p.Active != nil { active = *p.Active } - _, err = q.ExecContext(ctx, `UPDATE accounts SET name = ?, active = ?, updated_at = ? WHERE id = ?`, - name, store.Bool(active), store.NowMS(), id) + if p.IsCash != nil { + if err = checkCash(*p.IsCash, before.Type, before.IsGroup); err != nil { + return + } + cash = *p.IsCash + } + _, err = q.ExecContext(ctx, `UPDATE accounts SET name = ?, active = ?, is_cash = ?, updated_at = ? WHERE id = ?`, + name, store.Bool(active), store.Bool(cash), store.NowMS(), id) if err != nil { return } diff --git a/internal/delivery/module.go b/internal/delivery/module.go index b842c30..32ff9c2 100644 --- a/internal/delivery/module.go +++ b/internal/delivery/module.go @@ -4,6 +4,7 @@ import ( "context" "net/http" "strconv" + "strings" "github.com/nodemode-ai/formledger/internal/app" "github.com/nodemode-ai/formledger/internal/auth" @@ -42,23 +43,57 @@ func optional(r *http.Request) (body, error) { return b, nil } -func (s *Service) List(ctx context.Context, status, order string, limit int) ([]Note, error) { +func (s *Service) List(ctx context.Context, status, order string, limit int, after httpx.Cursor) ([]Note, string, error) { rows, err := s.st.R.QueryContext(ctx, `SELECT `+noteColumns+` FROM delivery_notes - WHERE (? = '' OR status = ?) AND (? = '' OR sales_order_id = ?) ORDER BY doc_date DESC, created_at DESC LIMIT ?`, - status, status, order, order, limit) + WHERE (? = '' OR status = ?) AND (? = '' OR sales_order_id = ?) + AND (? = '' OR (doc_date, created_at, id) < (?, ?, ?)) + ORDER BY doc_date DESC, created_at DESC, id DESC LIMIT ?`, + status, status, order, order, after.ID, afterDate(after), after.At, afterID(after), limit+1) if err != nil { - return nil, err + return nil, "", err } defer rows.Close() out := []Note{} for rows.Next() { var n Note if err := scanNote(rows, &n); err != nil { - return nil, err + return nil, "", err } out = append(out, n) } - return out, rows.Err() + if err := rows.Err(); err != nil { + return nil, "", err + } + next := "" + if len(out) > limit { + out = out[:limit] + last := out[len(out)-1] + next = httpx.EncodeCursor(httpx.Cursor{At: last.CreatedAt, ID: last.Date + "|" + last.ID}) + } + return out, next, nil +} + +func afterDate(c httpx.Cursor) string { + d, _, _ := strings.Cut(c.ID, "|") + return d +} + +func afterID(c httpx.Cursor) string { + _, id, _ := strings.Cut(c.ID, "|") + return id +} + +func parseCursor(s string) (httpx.Cursor, error) { + c, err := httpx.DecodeCursor(s) + if err != nil { + return c, err + } + if c.ID != "" { + if d, _, ok := strings.Cut(c.ID, "|"); !ok || len(d) != 10 { + return c, httpx.Fail(http.StatusBadRequest, "bad_cursor", "the cursor is not one this server gave out") + } + } + return c, nil } func (m module) Mount(r *httpx.Router, _ *app.Deps) error { @@ -72,11 +107,15 @@ func (m module) Mount(r *httpx.Router, _ *app.Deps) error { } limit = n } - list, err := m.svc.List(r.Context(), q.Get("status"), q.Get("order"), limit) + after, err := parseCursor(q.Get("cursor")) + if err != nil { + return err + } + list, next, err := m.svc.List(r.Context(), q.Get("status"), q.Get("order"), limit, after) if err != nil { return err } - httpx.JSON(w, http.StatusOK, map[string]any{"notes": list}) + httpx.JSON(w, http.StatusOK, map[string]any{"notes": list, "nextCursor": next}) return nil })) r.HandleFunc("GET /api/delivery/notes/{id}", m.auth.Require(policy.ReportsRead, func(w http.ResponseWriter, r *http.Request, _ *policy.Principal) error { diff --git a/internal/export/module.go b/internal/export/module.go index 40cbb88..82cb102 100644 --- a/internal/export/module.go +++ b/internal/export/module.go @@ -19,31 +19,54 @@ type spec struct { rows string parts bool top []string + cols []col } +const ( + stamps = "created_by created_at@ posted_by posted_at@ cancelled_by cancelled_at@" + salesCols = "id kind number date@ due_date@ customer_id customer customer_name currency status source_id amends_id subtotal* tax_total* total* journal_entry_id memo " + stamps + " line_count#" + buyCols = "id kind number date@ due_date@ supplier_id supplier supplier_name currency status source_id amends_id warehouse_id warehouse supplier_ref subtotal* tax_total* total* journal_entry_id memo " + stamps + " line_count#" + payInCols = "id number date@ customer_id customer currency amount* deposit_account_id deposit status journal_entry_id memo " + stamps + " allocated* unallocated*" + payOutCols = "id number date@ supplier_id supplier currency amount* paid_from_account_id paid_from status journal_entry_id memo " + stamps + " allocated* unallocated*" + ageCols = "current* days_1_to_30* days_31_to_60* days_61_to_90* over_90* unallocated* total*" +) + var specs = map[string]spec{ - "quotes": {path: "/api/sales/docs", fixed: map[string]string{"kind": "quote"}, rows: "docs"}, - "sales-orders": {path: "/api/sales/docs", fixed: map[string]string{"kind": "order"}, rows: "docs"}, - "sales-invoices": {path: "/api/sales/docs", fixed: map[string]string{"kind": "invoice"}, rows: "docs"}, - "purchase-orders": {path: "/api/purchase/docs", fixed: map[string]string{"kind": "order"}, rows: "docs"}, - "purchase-invoices": {path: "/api/purchase/docs", fixed: map[string]string{"kind": "invoice"}, rows: "docs"}, - "goods-receipts": {path: "/api/purchase/docs", fixed: map[string]string{"kind": "receipt"}, rows: "docs"}, - "delivery-notes": {path: "/api/delivery/notes", fixed: map[string]string{"limit": "500"}, rows: "notes"}, - "payments-in": {path: "/api/sales/payments", rows: "payments"}, - "payments-out": {path: "/api/purchase/payments", rows: "payments"}, - "customers": {path: "/api/customers", rows: "customers"}, - "suppliers": {path: "/api/suppliers", rows: "suppliers"}, - "items": {path: "/api/items", rows: "items"}, - "tax-rates": {path: "/api/tax-rates", rows: "taxRates"}, - "warehouses": {path: "/api/warehouses", rows: "warehouses"}, - "accounts": {path: "/api/accounts", rows: "accounts"}, - "trial-balance": {path: "/api/reports/trial-balance", rows: "rows", top: []string{"asOf"}}, - "general-ledger": {path: "/api/reports/general-ledger", rows: "lines", top: []string{"account", "from", "to"}}, - "receivables-ageing": {path: "/api/receivables/ageing", rows: "rows", top: []string{"asOf", "by"}}, - "payables-ageing": {path: "/api/payables/ageing", rows: "rows", top: []string{"asOf", "by"}}, - "stock-balance": {path: "/api/stock/balances", rows: "balances", top: []string{"asOf"}}, - "profit-and-loss": {path: "/api/reports/profit-and-loss", parts: true, top: []string{"from", "to"}}, - "balance-sheet": {path: "/api/reports/balance-sheet", parts: true, top: []string{"asOf"}}, + "quotes": {path: "/api/sales/docs", fixed: map[string]string{"kind": "quote"}, rows: "docs", cols: declare(salesCols)}, + "sales-orders": {path: "/api/sales/docs", fixed: map[string]string{"kind": "order"}, rows: "docs", cols: declare(salesCols)}, + "sales-invoices": {path: "/api/sales/docs", fixed: map[string]string{"kind": "invoice"}, rows: "docs", cols: declare(salesCols)}, + "purchase-orders": {path: "/api/purchase/docs", fixed: map[string]string{"kind": "order"}, rows: "docs", cols: declare(buyCols)}, + "purchase-invoices": {path: "/api/purchase/docs", fixed: map[string]string{"kind": "invoice"}, rows: "docs", cols: declare(buyCols)}, + "goods-receipts": {path: "/api/purchase/docs", fixed: map[string]string{"kind": "receipt"}, rows: "docs", cols: declare(buyCols)}, + "delivery-notes": {path: "/api/delivery/notes", fixed: map[string]string{"limit": "500"}, rows: "notes", + cols: declare("id number date@ sales_order_id customer_id warehouse_id status journal_entry_id memo " + stamps + " value* currency")}, + "payments-in": {path: "/api/sales/payments", rows: "payments", cols: declare(payInCols)}, + "payments-out": {path: "/api/purchase/payments", rows: "payments", cols: declare(payOutCols)}, + "customers": {path: "/api/customers", rows: "customers", + cols: declare("id code name email phone address tax_id currency receivable_account_id receivable_account payment_terms_days# active# created_at@ updated_at@")}, + "suppliers": {path: "/api/suppliers", rows: "suppliers", + cols: declare("id code name email phone address tax_id currency payable_account_id payable_account payment_terms_days# active# created_at@ updated_at@")}, + "items": {path: "/api/items", rows: "items", + cols: declare("id code name description unit sale_price* currency income_account_id income_account tax_rate_id tax_rate active# created_at@ updated_at@")}, + "tax-rates": {path: "/api/tax-rates", rows: "taxRates", + cols: declare("id code name rate_bp# payable_account_id payable_account active# created_at@ updated_at@")}, + "warehouses": {path: "/api/warehouses", rows: "warehouses", cols: declare("id code name active# created_at@ updated_at@")}, + "accounts": {path: "/api/accounts", rows: "accounts", + cols: declare("id code name type parent_id parent_code is_group# currency active# created_at@ updated_at@")}, + "trial-balance": {path: "/api/reports/trial-balance", rows: "rows", top: []string{"asOf"}, + cols: declare("as_of@ account_id code name type currency is_group# parent_id debit* credit*")}, + "general-ledger": {path: "/api/reports/general-ledger", rows: "lines", top: []string{"account", "from", "to"}, + cols: declare("account_account_id account_code account_name account_type account_currency account_is_group# from@ to@ date@ number entry_id line_no# memo debit* credit* balance* currency")}, + "receivables-ageing": {path: "/api/receivables/ageing", rows: "rows", top: []string{"asOf", "by"}, + cols: declare("as_of@ by customer_id code name currency " + ageCols)}, + "payables-ageing": {path: "/api/payables/ageing", rows: "rows", top: []string{"asOf", "by"}, + cols: declare("as_of@ by supplier_id code name currency " + ageCols)}, + "stock-balance": {path: "/api/stock/balances", rows: "balances", top: []string{"asOf"}, + cols: declare("as_of@ item_id item_code item_name warehouse_id warehouse_code qty_milli%")}, + "profit-and-loss": {path: "/api/reports/profit-and-loss", parts: true, top: []string{"from", "to"}, + cols: declare("from@ to@ section account_id code name currency amount*")}, + "balance-sheet": {path: "/api/reports/balance-sheet", parts: true, top: []string{"asOf"}, + cols: declare("as_of@ section account_id code name currency amount*")}, } func Names() []string { @@ -110,7 +133,7 @@ func build(next http.Handler, r *http.Request, sp spec) ([]byte, int, []byte) { } q.Set(k, v) } - t := newTable() + t := newTable(sp.cols) for pages := 0; pages < 100000; pages++ { raw, status := fetch(next, r, sp.path, q) if status != http.StatusOK { @@ -170,9 +193,6 @@ func build(next http.Handler, r *http.Request, sp spec) ([]byte, int, []byte) { } q.Set("cursor", next) } - if len(t.cols) == 0 { - t.cols = []string{"empty"} - } out, err := t.bytes() if err != nil { return nil, http.StatusInternalServerError, errBody("could not write the CSV") diff --git a/internal/export/writer.go b/internal/export/writer.go index 2bd03df..e479166 100644 --- a/internal/export/writer.go +++ b/internal/export/writer.go @@ -65,21 +65,41 @@ func snake(s string) string { return b.String() } -var moneyKeys = map[string]bool{ - "debit": true, "credit": true, "balance": true, "amount": true, "total": true, "subtotal": true, - "taxTotal": true, "salePrice": true, "purchasePrice": true, "unitPrice": true, "unitCost": true, - "value": true, "lineSubtotal": true, "lineTax": true, "lineTotal": true, "current": true, - "days1to30": true, "days31to60": true, "days61to90": true, "over90": true, "unallocated": true, - "allocated": true, "outstanding": true, "opening": true, "closing": true, "itemValueAfter": true, - "totalDebit": true, "totalCredit": true, "avgCost": true, "averageCost": true, "openAmount": true, +type kind int + +const ( + kText kind = iota + kDate + kMoney + kInteger + kQuantity +) + +type col struct { + name string + kind kind } -func isMoney(key string) bool { - if moneyKeys[key] { - return true +func declare(spec string) []col { + var out []col + for _, w := range strings.Fields(spec) { + k := kText + switch w[len(w)-1] { + case '@': + k = kDate + case '*': + k = kMoney + case '#': + k = kInteger + case '%': + k = kQuantity + } + if k != kText { + w = w[:len(w)-1] + } + out = append(out, col{w, k}) } - l := strings.ToLower(key) - return strings.HasSuffix(l, "price") || strings.HasSuffix(l, "amount") + return out } var eastern = func() *time.Location { @@ -98,18 +118,17 @@ type cell struct { } type table struct { - cols []string + cols []col index map[string]int rows []map[string]cell } -func newTable() *table { return &table{index: map[string]int{}} } - -func (t *table) col(name string) { - if _, ok := t.index[name]; !ok { - t.index[name] = len(t.cols) - t.cols = append(t.cols, name) +func newTable(cols []col) *table { + t := &table{cols: cols, index: map[string]int{}} + for i, c := range cols { + t.index[c.name] = i } + return t } func (t *table) add(prefix []field, row []field, currency string) { @@ -123,7 +142,6 @@ func (t *table) add(prefix []field, row []field, currency string) { } } } - hasMoney := false var put func(prefix string, fs []field) put = func(p string, fs []field) { for _, f := range fs { @@ -141,28 +159,35 @@ func (t *table) add(prefix []field, row []field, currency string) { } continue case 'n': - t.col(name) - out[name] = cell{} + if _, ok := t.index[name]; ok { + out[name] = cell{} + } case '"': + i, ok := t.index[name] + if !ok { + continue + } var s string _ = json.Unmarshal(raw, &s) - t.col(name) - out[name] = cell{s, true} + out[name] = cell{s, t.cols[i].kind == kText} case 't', 'f': - t.col(name) - out[name] = cell{string(raw), false} + if _, ok := t.index[name]; ok { + out[name] = cell{string(raw), false} + } default: - t.col(name) + i, ok := t.index[name] + if !ok { + continue + } n, err := strconv.ParseInt(string(raw), 10, 64) switch { - case err == nil && strings.HasSuffix(f.Key, "At"): + case err == nil && t.cols[i].kind == kDate: if n == 0 { out[name] = cell{} } else { out[name] = cell{time.UnixMilli(n).In(eastern).Format("2006-01-02"), false} } - case err == nil && isMoney(f.Key): - hasMoney = true + case err == nil && t.cols[i].kind == kMoney: out[name] = cell{money.Format(n, cur), false} default: out[name] = cell{string(raw), false} @@ -172,8 +197,7 @@ func (t *table) add(prefix []field, row []field, currency string) { } put("", prefix) put("", row) - if hasMoney { - t.col("currency") + if _, declared := t.index["currency"]; declared { if _, ok := out["currency"]; !ok { out["currency"] = cell{cur, true} } @@ -192,13 +216,17 @@ func (t *table) bytes() ([]byte, error) { var buf bytes.Buffer w := csv.NewWriter(&buf) w.UseCRLF = true - if err := w.Write(t.cols); err != nil { + head := make([]string, len(t.cols)) + for i, c := range t.cols { + head[i] = c.name + } + if err := w.Write(head); err != nil { return nil, err } rec := make([]string, len(t.cols)) for _, r := range t.rows { for i, c := range t.cols { - rec[i] = safe(r[c]) + rec[i] = safe(r[c.name]) } if err := w.Write(rec); err != nil { return nil, err diff --git a/internal/printout/command.go b/internal/printout/command.go new file mode 100644 index 0000000..d56daf6 --- /dev/null +++ b/internal/printout/command.go @@ -0,0 +1,94 @@ +package printout + +import ( + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "sort" + "strings" + "time" +) + +const Usage = "print KIND NUMBER [--out FILE] [--token-file FILE], or print statement CUSTOMER [--from DATE] [--to DATE]" + +func Command(args []string, out io.Writer) error { + var pos []string + var file, tokenFile string + q := url.Values{} + for i := 0; i < len(args); i++ { + a := args[i] + if !strings.HasPrefix(a, "-") { + pos = append(pos, a) + continue + } + k, v, has := strings.Cut(strings.TrimLeft(a, "-"), "=") + if !has { + if i+1 >= len(args) { + return fmt.Errorf("--%s needs a value", k) + } + i++ + v = args[i] + } + switch k { + case "out": + file = v + case "token-file": + tokenFile = v + case "from", "to": + q.Set(k, v) + default: + return fmt.Errorf("unknown flag --%s", k) + } + } + if len(pos) != 2 { + return errors.New("usage: " + Usage) + } + if _, ok := kinds[pos[0]]; !ok && pos[0] != "statement" { + names := make([]string, 0, len(kinds)) + for k := range kinds { + names = append(names, k) + } + sort.Strings(names) + return fmt.Errorf("KIND is one of: %s", strings.Join(names, ", ")) + } + base := strings.TrimRight(strings.TrimSpace(os.Getenv("FORMLEDGER_URL")), "/") + if base == "" { + base = "http://127.0.0.1:8340" + } + token := strings.TrimSpace(os.Getenv("FORMLEDGER_TOKEN")) + if tokenFile != "" { + b, err := os.ReadFile(tokenFile) + if err != nil { + return fmt.Errorf("cannot read the token file %s: %v", tokenFile, err) + } + token = strings.TrimSpace(string(b)) + } + if token == "" { + return errors.New("no app token: set FORMLEDGER_TOKEN or pass --token-file") + } + req, err := http.NewRequest(http.MethodGet, base+"/api/print/"+pos[0]+"/"+url.PathEscape(pos[1])+".pdf?"+q.Encode(), nil) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+token) + resp, err := (&http.Client{Timeout: 2 * time.Minute}).Do(req) + if err != nil { + return fmt.Errorf("the FormLedger server at %s does not answer", base) + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return err + } + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("print %s %s answered %d: %s", pos[0], pos[1], resp.StatusCode, strings.TrimSpace(string(body))) + } + if file == "" { + _, err = out.Write(body) + return err + } + return os.WriteFile(file, body, 0o644) +} diff --git a/internal/printout/document.go b/internal/printout/document.go new file mode 100644 index 0000000..c9518d7 --- /dev/null +++ b/internal/printout/document.go @@ -0,0 +1,89 @@ +package printout + +import ( + "encoding/json" + "errors" +) + +var ErrUnavailable = errors.New("renderer not available") + +type Renderer interface { + Render(d *Document) ([]byte, error) +} + +var renderers = []Renderer{plain{}} + +func Render(d *Document) ([]byte, error) { + for _, r := range renderers { + b, err := r.Render(d) + if errors.Is(err, ErrUnavailable) { + continue + } + return b, err + } + return nil, ErrUnavailable +} + +type Line struct { + Item string `json:"item"` + Description string `json:"description"` + QuantityMilli int64 `json:"quantityMilli"` + UnitPrice int64 `json:"unitPrice"` + TaxRate string `json:"taxRate"` + LineSubtotal int64 `json:"lineSubtotal"` +} + +type Document struct { + Company string `json:"-"` + Kind string `json:"kind"` + Side string `json:"-"` + Number string `json:"number"` + Date string `json:"date"` + DueDate string `json:"dueDate"` + Customer string `json:"customer"` + CustomerName string `json:"customerName"` + Supplier string `json:"supplier"` + SupplierName string `json:"supplierName"` + SupplierRef string `json:"supplierRef"` + Currency string `json:"currency"` + Status string `json:"status"` + Subtotal int64 `json:"subtotal"` + TaxTotal int64 `json:"taxTotal"` + Total int64 `json:"total"` + Memo string `json:"memo"` + CreatedAt int64 `json:"createdAt"` + PostedAt int64 `json:"postedAt"` + CancelledAt int64 `json:"cancelledAt"` + Lines []Line `json:"lines"` +} + +func Decode(raw []byte, side, company string) (*Document, error) { + var d Document + if err := json.Unmarshal(raw, &d); err != nil { + return nil, err + } + d.Side, d.Company = side, company + return &d, nil +} + +func (d *Document) Title() string { + t := map[string]string{"quote": "Quote", "order": "Sales order", "invoice": "Invoice"} + if d.Side == "purchase" { + t = map[string]string{"order": "Purchase order", "invoice": "Purchase invoice", "receipt": "Goods receipt"} + } + if s, ok := t[d.Kind]; ok { + return s + } + return d.Kind +} + +func (d *Document) Stamp() int64 { + s := d.CreatedAt + if d.PostedAt > s { + s = d.PostedAt + } + if d.CancelledAt > s { + s = d.CancelledAt + } + return s +} diff --git a/internal/printout/module.go b/internal/printout/module.go new file mode 100644 index 0000000..040796e --- /dev/null +++ b/internal/printout/module.go @@ -0,0 +1,136 @@ +package printout + +import ( + "database/sql" + "net/http" + "net/http/httptest" + "net/url" + "strings" + + "github.com/nodemode-ai/formledger/internal/app" + "github.com/nodemode-ai/formledger/internal/httpx" +) + +type kindSpec struct { + side, kind, path, table string +} + +var kinds = map[string]kindSpec{ + "quote": {"sales", "quote", "/api/sales/docs/", "sales_docs"}, + "order": {"sales", "order", "/api/sales/docs/", "sales_docs"}, + "invoice": {"sales", "invoice", "/api/sales/docs/", "sales_docs"}, + "purchase-order": {"purchase", "order", "/api/purchase/docs/", "purchase_docs"}, + "purchase-invoice": {"purchase", "invoice", "/api/purchase/docs/", "purchase_docs"}, + "goods-receipt": {"purchase", "receipt", "/api/purchase/docs/", "purchase_docs"}, +} + +type module struct{} + +func Module() app.Module { return module{} } + +func (module) ID() string { return "printout" } + +func (module) Mount(rt *httpx.Router, d *app.Deps) error { + db := d.Store.R + rt.HandleFunc("GET /api/print/{kind}/{file}", func(w http.ResponseWriter, r *http.Request) { + ref, isPDF := strings.CutSuffix(r.PathValue("file"), ".pdf") + if r.PathValue("kind") == "statement" && isPDF && ref != "" { + q := r.URL.Query() + q.Set("customer", ref) + raw, status := fetchQ(rt.Handler(), r, "/api/receivables/statement", q) + if status != http.StatusOK { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = w.Write(raw) + return + } + company := "FormLedger" + var v string + if err := db.QueryRowContext(r.Context(), `SELECT value FROM settings WHERE key = 'instance.name'`).Scan(&v); err == nil && strings.TrimSpace(v) != "" { + company = v + } + st, err := DecodeStatement(raw, company) + var body []byte + if err == nil { + body, err = RenderStatement(st) + } + if err != nil { + httpx.Error(w, http.StatusInternalServerError, "internal", "the PDF could not be drawn") + return + } + 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) + return + } + ks, ok := kinds[r.PathValue("kind")] + if !ok || !isPDF || ref == "" { + httpx.Error(w, http.StatusNotFound, "not_found", "print kind is one of quote, order, invoice, purchase-order, purchase-invoice, goods-receipt, and the file ends in .pdf") + return + } + id := ref + var byNumber string + if err := db.QueryRowContext(r.Context(), `SELECT id FROM `+ks.table+` WHERE number = ? AND kind = ?`, ref, ks.kind).Scan(&byNumber); err == nil { + id = byNumber + } else if err != sql.ErrNoRows { + httpx.Error(w, http.StatusInternalServerError, "internal", "the document could not be found") + return + } + raw, status := fetch(rt.Handler(), r, ks.path+url.PathEscape(id)) + if status != http.StatusOK { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = w.Write(raw) + return + } + company := "FormLedger" + var v string + if err := db.QueryRowContext(r.Context(), `SELECT value FROM settings WHERE key = 'instance.name'`).Scan(&v); err == nil && strings.TrimSpace(v) != "" { + company = v + } + doc, err := Decode(raw, ks.side, company) + if err != nil || doc.Kind != ks.kind { + httpx.Error(w, http.StatusNotFound, "not_found", "no "+r.PathValue("kind")+" with that id or number") + return + } + body, err := Render(doc) + if err != nil { + httpx.Error(w, http.StatusInternalServerError, "internal", "the PDF could not be drawn") + return + } + name := doc.Number + if name == "" { + name = doc.Kind + "-draft" + } + w.Header().Set("Content-Type", "application/pdf") + w.Header().Set("Content-Disposition", `attachment; filename="`+safeName(name)+`.pdf"`) + _, _ = w.Write(body) + }) + return nil +} + +func safeName(s string) string { + var b strings.Builder + for _, r := range s { + if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.' { + b.WriteRune(r) + } else { + b.WriteByte('-') + } + } + return b.String() +} + +func fetch(next http.Handler, outer *http.Request, path string) ([]byte, int) { + return fetchQ(next, outer, path, nil) +} + +func fetchQ(next http.Handler, outer *http.Request, path string, q url.Values) ([]byte, int) { + req := outer.Clone(outer.Context()) + req.URL = &url.URL{Path: path, RawQuery: q.Encode()} + req.RequestURI = req.URL.RequestURI() + req.Header.Del("Accept-Encoding") + rec := httptest.NewRecorder() + next.ServeHTTP(rec, req) + return rec.Body.Bytes(), rec.Code +} diff --git a/internal/printout/plain.go b/internal/printout/plain.go new file mode 100644 index 0000000..f5d4aaa --- /dev/null +++ b/internal/printout/plain.go @@ -0,0 +1,221 @@ +package printout + +import ( + "bytes" + "strconv" + "strings" + "time" + + "github.com/go-pdf/fpdf" + + "github.com/nodemode-ai/formledger/internal/money" +) + +const ( + margin = 15.0 + rowPad = 1.2 + lineH = 4.6 +) + +type plain struct{} + +func PageSize(currency string) string { + if currency == "USD" || currency == "" { + return "Letter" + } + return "A4" +} + +func amount(minor int64, cur string) string { return money.FormatGrouped(minor, cur, ",") } + +func quantity(milli int64) string { + s := strconv.FormatFloat(float64(milli)/1000, 'f', 3, 64) + s = strings.TrimRight(strings.TrimRight(s, "0"), ".") + return s +} + +func (plain) Render(d *Document) ([]byte, error) { + pdf := fpdf.New("P", "mm", PageSize(d.Currency), "") + tr := pdf.UnicodeTranslatorFromDescriptor("cp1252") + t := func(s string) string { return tr(printable(s)) } + stamp := time.Unix(d.Stamp(), 0).UTC() + if d.Stamp() > 1e11 { + stamp = time.UnixMilli(d.Stamp()).UTC() + } + pdf.SetCreationDate(stamp) + pdf.SetModificationDate(stamp) + pdf.SetCatalogSort(true) + pdf.SetCreator("FormLedger", true) + pdf.SetTitle(d.Title()+" "+d.Number, true) + pdf.SetMargins(margin, margin, margin) + pdf.SetAutoPageBreak(false, margin) + pdf.AliasNbPages("{nb}") + pw, ph := pdf.GetPageSize() + inner := pw - 2*margin + cols := []float64{22, inner - 22 - 18 - 26 - 16 - 28, 18, 26, 16, 28} + heads := []string{"Item", "Description", "Qty", "Unit price", "Tax", "Amount"} + align := []string{"L", "L", "R", "R", "L", "R"} + stampWord := map[string]string{"draft": "DRAFT", "cancelled": "CANCELLED"}[d.Status] + + pdf.SetHeaderFunc(func() { + if stampWord != "" { + pdf.SetFont("Helvetica", "B", 96) + pdf.SetTextColor(235, 225, 225) + pdf.TransformBegin() + pdf.TransformRotate(35, pw/2, ph/2) + sw := pdf.GetStringWidth(stampWord) + pdf.Text(pw/2-sw/2, ph/2+12, stampWord) + pdf.TransformEnd() + } + pdf.SetTextColor(30, 30, 30) + }) + pdf.SetFooterFunc(func() { + pdf.SetY(-11) + pdf.SetFont("Helvetica", "", 8) + pdf.SetTextColor(130, 130, 130) + pdf.CellFormat(inner/2, 4, t(d.Title()+" "+d.Number), "", 0, "L", false, 0, "") + pdf.CellFormat(inner/2, 4, "Page "+strconv.Itoa(pdf.PageNo())+" of {nb}", "", 0, "R", false, 0, "") + pdf.SetTextColor(30, 30, 30) + }) + + tableHead := func() { + pdf.SetFont("Helvetica", "B", 8.5) + pdf.SetFillColor(240, 240, 240) + pdf.SetDrawColor(200, 200, 200) + x := margin + y := pdf.GetY() + for i, h := range heads { + pdf.SetXY(x, y) + pdf.CellFormat(cols[i], 7, h, "B", 0, align[i], true, 0, "") + x += cols[i] + } + pdf.SetXY(margin, y+7) + } + + pdf.AddPage() + pdf.SetFont("Helvetica", "B", 15) + pdf.CellFormat(inner*0.6, 8, t(d.Company), "", 0, "L", false, 0, "") + pdf.SetFont("Helvetica", "B", 18) + pdf.CellFormat(inner*0.4, 8, t(d.Title()), "", 1, "R", false, 0, "") + pdf.Ln(4) + + pdf.SetFont("Helvetica", "", 9) + party, partyLabel := d.CustomerName, "Bill to" + code := d.Customer + if d.Side == "purchase" { + party, partyLabel, code = d.SupplierName, "Supplier", d.Supplier + } + topY := pdf.GetY() + pdf.SetFont("Helvetica", "B", 8.5) + pdf.SetTextColor(110, 110, 110) + pdf.CellFormat(inner*0.55, 5, partyLabel, "", 2, "L", false, 0, "") + pdf.SetTextColor(30, 30, 30) + pdf.SetFont("Helvetica", "B", 10.5) + for _, part := range wrap(pdf.GetStringWidth, t(party), inner*0.55) { + pdf.CellFormat(inner*0.55, 5, part, "", 1, "L", false, 0, "") + } + pdf.SetFont("Helvetica", "", 9) + if code != "" { + pdf.CellFormat(inner*0.55, 5, t(code), "", 1, "L", false, 0, "") + } + leftEnd := pdf.GetY() + + number := d.Number + if number == "" { + number = "not yet numbered" + } + meta := [][2]string{{"Number", number}, {"Date", d.Date}} + if d.DueDate != "" { + meta = append(meta, [2]string{"Due date", d.DueDate}) + } + if d.SupplierRef != "" { + meta = append(meta, [2]string{"Supplier ref", d.SupplierRef}) + } + meta = append(meta, [2]string{"Currency", d.Currency}, [2]string{"Status", d.Status}) + pdf.SetY(topY) + for _, m := range meta { + pdf.SetX(margin + inner*0.6) + pdf.SetFont("Helvetica", "", 9) + pdf.SetTextColor(110, 110, 110) + pdf.CellFormat(inner*0.18, 5, m[0], "", 0, "L", false, 0, "") + pdf.SetTextColor(30, 30, 30) + pdf.SetFont("Helvetica", "B", 9) + pdf.CellFormat(inner*0.22, 5, t(m[1]), "", 1, "R", false, 0, "") + } + pdf.SetY(max(leftEnd, pdf.GetY()) + 8) + + bottom := ph - margin - 6 + tableHead() + pdf.SetFont("Helvetica", "", 8.5) + pdf.SetDrawColor(225, 225, 225) + for _, l := range d.Lines { + cells := []string{t(l.Item), t(l.Description), quantity(l.QuantityMilli), amount(l.UnitPrice, d.Currency), t(l.TaxRate), amount(l.LineSubtotal, d.Currency)} + parts := make([][]string, len(cells)) + n := 1 + for i, c := range cells { + parts[i] = wrap(pdf.GetStringWidth, c, cols[i]-2) + n = max(n, len(parts[i])) + } + h := float64(n)*lineH + 2*rowPad + if pdf.GetY()+h > bottom { + pdf.AddPage() + pdf.SetY(margin) + tableHead() + pdf.SetFont("Helvetica", "", 8.5) + pdf.SetDrawColor(225, 225, 225) + } + y := pdf.GetY() + x := margin + for i := range cells { + for k, part := range parts[i] { + pdf.SetXY(x, y+rowPad+float64(k)*lineH) + pdf.CellFormat(cols[i], lineH, part, "", 0, align[i], false, 0, "") + } + x += cols[i] + } + pdf.Line(margin, y+h, margin+inner, y+h) + pdf.SetXY(margin, y+h) + } + + totals := [][2]string{{"Subtotal", amount(d.Subtotal, d.Currency)}, {"Tax", amount(d.TaxTotal, d.Currency)}, {"Total " + d.Currency, amount(d.Total, d.Currency)}} + if pdf.GetY()+24 > bottom { + pdf.AddPage() + pdf.SetY(margin) + } + pdf.Ln(3) + for i, tt := range totals { + pdf.SetX(margin + inner - 80) + style := "" + if i == len(totals)-1 { + style = "B" + pdf.SetDrawColor(120, 120, 120) + pdf.Line(margin+inner-80, pdf.GetY(), margin+inner, pdf.GetY()) + } + pdf.SetFont("Helvetica", style, 9.5) + pdf.CellFormat(46, 6.5, tt[0], "", 0, "L", false, 0, "") + pdf.CellFormat(34, 6.5, tt[1], "", 1, "R", false, 0, "") + } + + if strings.TrimSpace(d.Memo) != "" { + pdf.Ln(6) + pdf.SetFont("Helvetica", "B", 8.5) + pdf.SetTextColor(110, 110, 110) + pdf.CellFormat(inner, 5, "Notes", "", 1, "L", false, 0, "") + pdf.SetTextColor(30, 30, 30) + pdf.SetFont("Helvetica", "", 9) + for _, part := range wrap(pdf.GetStringWidth, t(d.Memo), inner) { + if pdf.GetY()+lineH > bottom { + pdf.AddPage() + pdf.SetY(margin) + pdf.SetFont("Helvetica", "", 9) + } + pdf.CellFormat(inner, lineH, part, "", 1, "L", false, 0, "") + } + } + + var buf bytes.Buffer + if err := pdf.Output(&buf); err != nil { + return nil, err + } + return buf.Bytes(), nil +} diff --git a/internal/printout/statement.go b/internal/printout/statement.go new file mode 100644 index 0000000..e9ba21d --- /dev/null +++ b/internal/printout/statement.go @@ -0,0 +1,168 @@ +package printout + +import ( + "bytes" + "encoding/json" + "strconv" + "time" + + "github.com/go-pdf/fpdf" +) + +type StatementLine struct { + Date string `json:"date"` + Kind string `json:"kind"` + Number string `json:"number"` + Debit int64 `json:"debit"` + Credit int64 `json:"credit"` + Balance int64 `json:"balance"` +} + +type Statement struct { + Company string `json:"-"` + Customer struct { + Code string `json:"code"` + Name string `json:"name"` + } `json:"customer"` + Currency string `json:"currency"` + From string `json:"from"` + To string `json:"to"` + Opening int64 `json:"opening"` + Lines []StatementLine `json:"lines"` + Closing int64 `json:"closing"` +} + +func DecodeStatement(raw []byte, company string) (*Statement, error) { + var s Statement + if err := json.Unmarshal(raw, &s); err != nil { + return nil, err + } + s.Company = company + return &s, nil +} + +var eventWords = map[string]string{"invoice": "Invoice", "payment": "Payment", "invoice_cancelled": "Invoice cancelled", "payment_cancelled": "Payment cancelled"} + +func RenderStatement(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)) } + stamp, err := time.Parse("2006-01-02", s.To) + if err != nil { + stamp = time.Unix(0, 0) + } + pdf.SetCreationDate(stamp.UTC()) + pdf.SetModificationDate(stamp.UTC()) + pdf.SetCatalogSort(true) + pdf.SetCreator("FormLedger", true) + pdf.SetTitle("Statement "+s.Customer.Code, true) + pdf.SetMargins(margin, margin, margin) + pdf.SetAutoPageBreak(false, margin) + pdf.AliasNbPages("{nb}") + pw, ph := pdf.GetPageSize() + inner := pw - 2*margin + cols := []float64{24, 34, inner - 24 - 34 - 30 - 30 - 32, 30, 30, 32} + heads := []string{"Date", "Number", "Description", "Debit", "Credit", "Balance"} + align := []string{"L", "L", "L", "R", "R", "R"} + pdf.SetFooterFunc(func() { + pdf.SetY(-11) + pdf.SetFont("Helvetica", "", 8) + pdf.SetTextColor(130, 130, 130) + pdf.CellFormat(inner/2, 4, t("Statement "+s.Customer.Code), "", 0, "L", false, 0, "") + pdf.CellFormat(inner/2, 4, "Page "+strconv.Itoa(pdf.PageNo())+" of {nb}", "", 0, "R", false, 0, "") + pdf.SetTextColor(30, 30, 30) + }) + head := func() { + pdf.SetFont("Helvetica", "B", 8.5) + pdf.SetFillColor(240, 240, 240) + pdf.SetDrawColor(200, 200, 200) + x, y := margin, pdf.GetY() + for i, h := range heads { + pdf.SetXY(x, y) + pdf.CellFormat(cols[i], 7, h, "B", 0, align[i], true, 0, "") + x += cols[i] + } + pdf.SetXY(margin, y+7) + pdf.SetFont("Helvetica", "", 8.5) + pdf.SetDrawColor(225, 225, 225) + } + cur := s.Currency + blank := func(v int64) string { + if v == 0 { + return "" + } + return amount(v, cur) + } + bottom := ph - margin - 6 + row := func(cells []string, bold bool) { + h := lineH + 2*rowPad + if pdf.GetY()+h > bottom { + pdf.AddPage() + pdf.SetY(margin) + head() + } + style := "" + if bold { + style = "B" + } + pdf.SetFont("Helvetica", style, 8.5) + y, x := pdf.GetY(), margin + for i, c := range cells { + pdf.SetXY(x, y+rowPad) + pdf.CellFormat(cols[i], lineH, c, "", 0, align[i], false, 0, "") + x += cols[i] + } + pdf.Line(margin, y+h, margin+inner, y+h) + pdf.SetXY(margin, y+h) + } + + pdf.AddPage() + pdf.SetFont("Helvetica", "B", 15) + pdf.CellFormat(inner*0.6, 8, t(s.Company), "", 0, "L", false, 0, "") + pdf.SetFont("Helvetica", "B", 18) + pdf.CellFormat(inner*0.4, 8, "Statement", "", 1, "R", false, 0, "") + pdf.Ln(4) + topY := pdf.GetY() + pdf.SetFont("Helvetica", "B", 8.5) + pdf.SetTextColor(110, 110, 110) + pdf.CellFormat(inner*0.55, 5, "Customer", "", 2, "L", false, 0, "") + pdf.SetTextColor(30, 30, 30) + pdf.SetFont("Helvetica", "B", 10.5) + for _, part := range wrap(pdf.GetStringWidth, t(s.Customer.Name), inner*0.55) { + pdf.CellFormat(inner*0.55, 5, part, "", 1, "L", false, 0, "") + } + pdf.SetFont("Helvetica", "", 9) + pdf.CellFormat(inner*0.55, 5, t(s.Customer.Code), "", 1, "L", false, 0, "") + leftEnd := pdf.GetY() + from := s.From + if from == "" { + from = "first entry" + } + pdf.SetY(topY) + for _, m := range [][2]string{{"From", from}, {"To", s.To}, {"Currency", cur}, {"Balance due", amount(s.Closing, cur)}} { + pdf.SetX(margin + inner*0.6) + pdf.SetFont("Helvetica", "", 9) + pdf.SetTextColor(110, 110, 110) + pdf.CellFormat(inner*0.18, 5, m[0], "", 0, "L", false, 0, "") + pdf.SetTextColor(30, 30, 30) + pdf.SetFont("Helvetica", "B", 9) + pdf.CellFormat(inner*0.22, 5, t(m[1]), "", 1, "R", false, 0, "") + } + pdf.SetY(max(leftEnd, pdf.GetY()) + 8) + head() + row([]string{s.From, "", "Opening balance", "", "", amount(s.Opening, cur)}, true) + for _, l := range s.Lines { + word := eventWords[l.Kind] + if word == "" { + word = l.Kind + } + row([]string{l.Date, t(l.Number), word, blank(l.Debit), blank(l.Credit), amount(l.Balance, cur)}, false) + } + row([]string{s.To, "", "Closing balance", "", "", amount(s.Closing, cur)}, true) + + var buf bytes.Buffer + if err := pdf.Output(&buf); err != nil { + return nil, err + } + return buf.Bytes(), nil +} diff --git a/internal/printout/text.go b/internal/printout/text.go new file mode 100644 index 0000000..b817735 --- /dev/null +++ b/internal/printout/text.go @@ -0,0 +1,60 @@ +package printout + +import ( + "fmt" + "strings" +) + +var cp1252Extra = map[rune]bool{ + '€': true, '‚': true, 'ƒ': true, '„': true, '…': true, '†': true, '‡': true, 'ˆ': true, '‰': true, + 'Š': true, '‹': true, 'Œ': true, 'Ž': true, '‘': true, '’': true, '“': true, '”': true, '•': true, + '–': true, '—': true, '˜': true, '™': true, 'š': true, '›': true, 'œ': true, 'ž': true, 'Ÿ': true, +} + +func wrap(width func(string) float64, s string, w float64) []string { + var out []string + for _, para := range strings.Split(s, "\n") { + line := "" + for _, word := range strings.Split(para, " ") { + for width(word) > w && len(word) > 1 { + if line != "" { + out = append(out, line) + line = "" + } + n := len(word) - 1 + for n > 1 && width(word[:n]) > w { + n-- + } + out = append(out, word[:n]) + word = word[n:] + } + switch { + case line == "": + line = word + case width(line+" "+word) <= w: + line += " " + word + default: + out = append(out, line) + line = word + } + } + out = append(out, line) + } + return out +} + +func printable(s string) string { + var b strings.Builder + for _, r := range s { + switch { + case r == '\t': + b.WriteByte(' ') + case r == '\n' || (r >= 0x20 && r <= 0x7e) || (r >= 0xa0 && r <= 0xff) || cp1252Extra[r]: + b.WriteRune(r) + case r < 0x20 || (r >= 0x7f && r < 0xa0): + default: + fmt.Fprintf(&b, "[U+%04X]", r) + } + } + return b.String() +} diff --git a/internal/reports/balances.go b/internal/reports/balances.go index c320d13..28371cd 100644 --- a/internal/reports/balances.go +++ b/internal/reports/balances.go @@ -13,6 +13,7 @@ type balanceRow struct { Type string `json:"type"` Currency string `json:"currency"` IsGroup bool `json:"isGroup"` + IsCash bool `json:"isCash"` Active bool `json:"active"` Debit int64 `json:"debit"` Credit int64 `json:"credit"` @@ -20,7 +21,7 @@ type balanceRow struct { } const balancesSQL = ` -SELECT a.id, a.code, a.name, a.type, a.currency, a.is_group, a.active, +SELECT a.id, a.code, a.name, a.type, a.currency, a.is_group, a.is_cash, a.active, COALESCE(mv.debit, 0), COALESCE(mv.credit, 0), COALESCE(mv.debit - mv.credit, 0) FROM accounts a LEFT JOIN ( SELECT l.account_id, SUM(l.debit) AS debit, SUM(l.credit) AS credit @@ -43,7 +44,7 @@ func balances(ctx context.Context, db *sql.DB, r *http.Request) (any, error) { 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.Active, &b.Debit, &b.Credit, &b.Balance); err != nil { + 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) @@ -51,5 +52,9 @@ func balances(ctx context.Context, db *sql.DB, r *http.Request) (any, error) { if err := rows.Err(); err != nil { return nil, err } - return map[string]any{"asOf": asOf, "accounts": out}, nil + pref, err := cashPreference(ctx, db) + if err != nil { + return nil, err + } + return map[string]any{"asOf": asOf, "accounts": out, "cash": cashOf(pref, out)}, nil } diff --git a/internal/reports/cash.go b/internal/reports/cash.go new file mode 100644 index 0000000..6b3092a --- /dev/null +++ b/internal/reports/cash.go @@ -0,0 +1,125 @@ +package reports + +import ( + "context" + "database/sql" + "errors" + "net/http" + "strings" + + "github.com/nodemode-ai/formledger/internal/audit" + "github.com/nodemode-ai/formledger/internal/httpx" + "github.com/nodemode-ai/formledger/internal/policy" + "github.com/nodemode-ai/formledger/internal/store" +) + +const ( + CashKey = "cash.accounts" + CashFlagged = "flagged" + CashNamed = "named" + CashAuto = "auto" +) + +var cashRules = []string{CashAuto, CashFlagged, CashNamed} + +type cashAccount struct { + Code string `json:"code"` + Name string `json:"name"` + Currency string `json:"currency"` + Balance int64 `json:"balance"` +} + +type cashFigure struct { + Preference string `json:"preference"` + Rule string `json:"rule"` + Total int64 `json:"total"` + Accounts []cashAccount `json:"accounts"` +} + +func cashPreference(ctx context.Context, q store.Querier) (string, error) { + var v string + err := q.QueryRowContext(ctx, `SELECT value FROM settings WHERE key = ?`, CashKey).Scan(&v) + if errors.Is(err, sql.ErrNoRows) { + return CashAuto, nil + } + if err != nil { + return "", err + } + for _, r := range cashRules { + if v == r { + return v, nil + } + } + return CashAuto, nil +} + +func namedCash(b balanceRow) bool { + n := strings.ToLower(b.Name) + return b.Type == "asset" && !b.IsGroup && (strings.Contains(n, "cash") || strings.Contains(n, "bank")) +} + +func cashOf(pref string, rows []balanceRow) cashFigure { + rule := pref + if rule == CashAuto { + rule = CashNamed + for _, b := range rows { + if b.IsCash { + rule = CashFlagged + break + } + } + } + out := cashFigure{Preference: pref, Rule: rule, Accounts: []cashAccount{}} + for _, b := range rows { + if rule == CashFlagged && !b.IsCash || rule == CashNamed && !namedCash(b) { + continue + } + out.Total += b.Balance + out.Accounts = append(out.Accounts, cashAccount{b.Code, b.Name, b.Currency, b.Balance}) + } + return out +} + +func (m module) mountCash(rt *httpx.Router, st *store.Store) { + rt.HandleFunc("GET /api/reports/cash-rule", m.auth.Require(policy.ReportsRead, func(w http.ResponseWriter, r *http.Request, _ *policy.Principal) error { + v, err := cashPreference(r.Context(), st.R) + if err != nil { + return err + } + w.Header().Set("Cache-Control", "no-store") + httpx.JSON(w, http.StatusOK, map[string]any{"preference": v, "options": cashRules}) + return nil + })) + rt.HandleFunc("PUT /api/reports/cash-rule", m.auth.Require(policy.SettingsManage, func(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + var in struct { + Preference string `json:"preference"` + } + if err := httpx.Decode(r, &in); err != nil { + return err + } + ok := false + for _, x := range cashRules { + ok = ok || x == in.Preference + } + if !ok { + return httpx.Fail(http.StatusUnprocessableEntity, "bad_preference", "preference must be one of auto, flagged, named") + } + err := st.Tx(r.Context(), func(tx *sql.Tx) error { + before, err := cashPreference(r.Context(), tx) + if err != nil { + return err + } + if _, err := tx.ExecContext(r.Context(), `INSERT INTO settings (key, value, updated_at) VALUES (?, ?, ?) + ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`, CashKey, in.Preference, store.NowMS()); err != nil { + return err + } + return m.auth.Record(r, tx, m.auth.Actor(r, p), "settings.update", "setting", CashKey, audit.OK, + map[string]any{CashKey: [2]string{before, in.Preference}}) + }) + if err != nil { + return err + } + httpx.JSON(w, http.StatusOK, map[string]any{"preference": in.Preference, "options": cashRules}) + return nil + })) +} diff --git a/internal/reports/reports.go b/internal/reports/reports.go index d80420f..3038567 100644 --- a/internal/reports/reports.go +++ b/internal/reports/reports.go @@ -46,6 +46,7 @@ func (m module) Mount(rt *httpx.Router, d *app.Deps) error { m.route(rt, db, "GET /api/reports/trial-balance", trial) m.route(rt, db, "GET /api/reports/general-ledger", ledger) m.route(rt, db, "GET /api/reports/balances", balances) + m.mountCash(rt, d.Store) m.route(rt, db, "GET /api/reports/period-activity", activity) m.route(rt, db, "GET /api/reports/verify", verify) m.mountStatements(rt, db) diff --git a/internal/server/server.go b/internal/server/server.go index e6d2139..c3f88db 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -22,6 +22,7 @@ import ( "github.com/nodemode-ai/formledger/internal/payments" "github.com/nodemode-ai/formledger/internal/paymentsmade" "github.com/nodemode-ai/formledger/internal/posting" + "github.com/nodemode-ai/formledger/internal/printout" "github.com/nodemode-ai/formledger/internal/purchase" "github.com/nodemode-ai/formledger/internal/purchaseflow" "github.com/nodemode-ai/formledger/internal/receivables" @@ -57,6 +58,7 @@ func Build(ctx context.Context, cfg config.Config, log *slog.Logger, st *store.S customers.Module(st, accounts), delivery.Module(st, accounts), export.Module(), + printout.Module(), fiscal.Module(accounts), invoicing.Module(st, accounts), items.Module(accounts), diff --git a/internal/snapshot/queries.go b/internal/snapshot/queries.go index 213040a..f0f1f49 100644 --- a/internal/snapshot/queries.go +++ b/internal/snapshot/queries.go @@ -19,9 +19,9 @@ const partyNameSQL = `CASE r.party_kind WHEN 'customer' THEN c.code ELSE s.code CASE r.party_kind WHEN 'customer' THEN c.name ELSE s.name END` var copies = []copySpec{ - {"accounts", "code, name, type, normal_side, parent_code, is_group, currency, active", ` + {"accounts", "code, name, type, normal_side, parent_code, is_group, currency, active, is_cash", ` SELECT a.code, a.name, a.type, CASE WHEN a.type IN ('asset', 'expense') THEN 'debit' ELSE 'credit' END, - p.code, a.is_group, a.currency, a.active + p.code, a.is_group, a.currency, a.active, a.is_cash FROM accounts a LEFT JOIN accounts p ON p.id = a.parent_id ORDER BY a.code`}, {"fiscal_periods", "fiscal_year, period, start_date, end_date, status", ` diff --git a/internal/snapshot/schema.go b/internal/snapshot/schema.go index 298a1ee..d1b18d4 100644 --- a/internal/snapshot/schema.go +++ b/internal/snapshot/schema.go @@ -22,7 +22,8 @@ CREATE TABLE accounts ( parent_code TEXT, is_group INTEGER NOT NULL, currency TEXT NOT NULL, - active INTEGER NOT NULL + active INTEGER NOT NULL, + is_cash INTEGER NOT NULL ); CREATE TABLE fiscal_periods ( diff --git a/internal/store/migrations/0018_account_cash.sql b/internal/store/migrations/0018_account_cash.sql new file mode 100644 index 0000000..9612bfa --- /dev/null +++ b/internal/store/migrations/0018_account_cash.sql @@ -0,0 +1 @@ +ALTER TABLE accounts ADD COLUMN is_cash INTEGER NOT NULL DEFAULT 0 CHECK (is_cash IN (0, 1)); diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index bd92fbe..6d95670 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1106,7 +1106,7 @@ dependencies = [ [[package]] name = "formledger-desktop" -version = "0.9.0" +version = "0.10.0" dependencies = [ "objc2", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 0dbb27d..452e3db 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formledger-desktop" -version = "0.9.0" +version = "0.10.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 f994430..fce7b1b 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.9.0 +Current build version: v0.10.0 Last updated: 2026-11-26 (US Eastern) · the shell ported from form.md's src-tauri and renamed for FormLedger --- diff --git a/src-tauri/splash/icon.png b/src-tauri/splash/icon.png new file mode 100644 index 0000000..facd1ba Binary files /dev/null and b/src-tauri/splash/icon.png differ diff --git a/src-tauri/splash/index.html b/src-tauri/splash/index.html index 2bb0203..6282631 100644 --- a/src-tauri/splash/index.html +++ b/src-tauri/splash/index.html @@ -6,7 +6,7 @@ -
FormLedger

Starting FormLedger

+ @@ -16,20 +16,21 @@
- -

Set up FormLedger

-

Create the owner of this copy. The owner manages people and settings.

+ FormLedger +

Create your account

+

Welcome! You will be the owner of these books and can invite others later.

- + - +
- -

Sign in to FormLedger

+ FormLedger +

Sign in

+

Welcome back. Sign in to open your books.

@@ -38,8 +39,8 @@

Sign in to FormLedger

- -

FormLedger is locked

+ FormLedger +

Locked

Enter the owner's password to open this window.

@@ -48,12 +49,12 @@

FormLedger is locked

- -

Join FormLedger

+ FormLedger +

Join these books

- + @@ -62,38 +63,62 @@

Join FormLedger

- Home - - + + + + +
-

Home

+
+
+

FormLedger

+

Good morningGood afternoonGood evening

+

What customers owe you, what you owe suppliers, your cash, and the last invoices on each side.

+
+ +

Nothing here yet

-

- - - -

+
diff --git a/web/package-lock.json b/web/package-lock.json index ef5bb3f..1f6a7b1 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "formledger", - "version": "0.9.0", + "version": "0.10.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formledger", - "version": "0.9.0", + "version": "0.10.0", "license": "Apache-2.0", "devDependencies": { "@types/node": "^22.20.5", diff --git a/web/package.json b/web/package.json index e34073f..fc4b5c6 100644 --- a/web/package.json +++ b/web/package.json @@ -1,7 +1,7 @@ { "name": "formledger", "private": true, - "version": "0.9.0", + "version": "0.10.0", "license": "Apache-2.0", "type": "module", "scripts": { diff --git a/web/src/engine/masters.ts b/web/src/engine/masters.ts index dd4f5fa..318cacd 100644 --- a/web/src/engine/masters.ts +++ b/web/src/engine/masters.ts @@ -160,6 +160,7 @@ export const MASTERS: Master[] = [ { key: "name", label: "Name", width: "auto" }, { key: "type", label: "Type", width: "12ch", badge: true }, { key: "parentCode", label: "Parent", width: "9ch", mono: true }, + { key: "isCash", label: "Cash", width: "10ch", badge: true }, ACTIVE_COL, ], fields: [ @@ -169,6 +170,7 @@ export const MASTERS: Master[] = [ { key: "parent", label: "Parent", kind: "text", from: "parentCode", createOnly: true, span: 1 }, CURRENCY, { key: "isGroup", label: "Group account", kind: "bool", createOnly: true, span: 4 }, + { key: "isCash", label: "Cash or bank account", kind: "bool", span: 4 }, ACTIVE, ], }, @@ -177,6 +179,7 @@ export const MASTERS: Master[] = [ export function cell(row: Row, key: string): string { const v = row[key]; if (key === "active") return v ? "Active" : "Inactive"; + if (key === "isCash") return v === true ? "Cash" : ""; if (key === "salePrice" && typeof v === "number") return money(v); if (key === "rateBp" && typeof v === "number") return percent(v); return v === undefined || v === null ? "" : String(v); @@ -220,6 +223,10 @@ export function boolValue(f: Field, row: Row | null): boolean { export type Raw = Record; +export function cashAllowed(type: string, isGroup: boolean): boolean { + return type === "asset" && !isGroup; +} + function convert(f: Field, text: string): { ok: true; value: unknown } | { ok: false; error: string } { if (f.kind === "money") { const n = parseMoney(text); @@ -237,6 +244,11 @@ export function buildBody(m: Master, raw: Raw, current: Row | null): { body: Row for (const f of m.fields) { if (current && f.createOnly) continue; if (f.key === "active" && !current) continue; + if (f.key === "isCash") { + const next = cashAllowed(String(raw.type ?? ""), Boolean(raw.isGroup)) && Boolean(raw.isCash); + if (next !== (current?.isCash === true)) body.isCash = next; + continue; + } if (f.kind === "bool") { const next = Boolean(raw[f.key]); if (!current || next !== Boolean(current[f.key])) body[f.key] = next; diff --git a/web/src/styles/account.css b/web/src/styles/account.css index 1b4160a..e8ed22c 100644 --- a/web/src/styles/account.css +++ b/web/src/styles/account.css @@ -4,9 +4,10 @@ .gate { display: none; - place-items: center; + place-items: start center; min-block-size: 100dvh; - padding: var(--space-6); + overflow: auto; + padding: var(--space-8) var(--space-4); } :root[data-screen="setup"] .gate--setup, @@ -19,24 +20,92 @@ .card { display: grid; row-gap: var(--space-3); - inline-size: min(calc(var(--doc-w) / 2), 100%); - padding: var(--space-6); - background: var(--surface); + inline-size: min(400px, 100%); + margin-block-start: 8vh; + padding: var(--space-8); + background: var(--sheet); border: 1px solid var(--border); - border-radius: var(--radius); + border-radius: var(--radius-sheet); + box-shadow: inset 0 1px 0 var(--sheet-highlight), var(--shadow-sheet); } -.card__title { - font-size: var(--text-lg); +.auth__brand { + display: inline-grid; + grid-auto-flow: column; + justify-content: start; + align-items: center; + column-gap: var(--space-2); + margin-block-end: var(--space-3); font-weight: var(--weight-semibold); + letter-spacing: -0.01em; +} + +.auth__mark { + inline-size: 20px; + block-size: 20px; + border-radius: var(--radius-sm); +} + +.card__title { + font-size: var(--text-xl); + font-weight: var(--weight-bold); line-height: var(--leading-tight); + letter-spacing: -0.02em; } .card__lead { + margin-block-end: var(--space-1); font-size: var(--text-sm); color: var(--text-muted); } +.card .input, +.card .btn--primary { + block-size: calc(var(--control) + var(--space-1)); +} + +.card .btn--primary { + inline-size: 100%; +} + +.field__hint { + font-size: var(--text-xs); + color: var(--text-faint); +} + +.auth__pw { + position: relative; + display: grid; +} + +.auth__pw > .input { + padding-inline-end: var(--space-10); +} + +.auth__pw-toggle { + position: absolute; + inset-block: 0; + inset-inline-end: 0; + display: grid; + place-items: center; + inline-size: var(--space-10); + padding: 0; + color: var(--text-muted); + background: transparent; + border: 0; + border-radius: var(--radius-sm); + cursor: pointer; +} + +.auth__pw-toggle:hover { + color: var(--text); +} + +.auth__pw-toggle:focus-visible { + outline: 2px solid var(--accent); + outline-offset: -2px; +} + .form { display: grid; row-gap: var(--space-3); @@ -122,42 +191,10 @@ opacity: 0.55; } -.topbar { - grid-template-columns: minmax(0, 1fr) auto auto; - column-gap: var(--space-3); -} - -.topbar [data-ref="signout"][data-off] { - visibility: hidden; -} - -.who { - display: flex; - align-items: center; - justify-content: end; - gap: var(--space-2); - min-inline-size: 0; - max-inline-size: var(--sidebar-w); - font-size: var(--text-sm); - white-space: nowrap; -} - -.who__name { - overflow: hidden; - text-overflow: ellipsis; - color: var(--text); -} - -.who__role { - order: 1; - flex: none; +.menu__hint[data-ref="who-role"] { text-transform: capitalize; } -.who__role:empty { - display: none; -} - :root[data-route="account"] .view--account { display: block; } diff --git a/web/src/styles/base.css b/web/src/styles/base.css index 1e77dcb..f693d53 100644 --- a/web/src/styles/base.css +++ b/web/src/styles/base.css @@ -104,6 +104,67 @@ kbd { white-space: nowrap; } +input.input, +select.input, +textarea.input { + padding-inline: var(--space-3); + font-size: var(--text-md); + background-color: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius-sm); + transition: border-color var(--dur-fast) var(--ease), box-shadow var(--dur-fast) var(--ease); +} + +input.input:hover:not(:disabled, :focus), +select.input:hover:not(:disabled, :focus), +textarea.input:hover:not(:disabled, :focus) { + border-color: var(--border-strong); +} + +input.input:focus, +select.input:focus, +textarea.input:focus { + outline: none; + border-color: var(--accent); + box-shadow: 0 0 0 3px var(--accent-wash); +} + +input.input:disabled, +select.input:disabled, +textarea.input:disabled { + color: var(--text-muted); + background-color: var(--surface-2); + cursor: not-allowed; +} + +input.input[aria-invalid="true"] { + border-color: var(--danger); +} + +input.input::placeholder, +textarea.input::placeholder { + color: var(--text-faint); +} + +select.input { + padding-inline-end: var(--space-8); + appearance: none; + background-image: linear-gradient(45deg, transparent 50%, var(--text-muted) 50%), linear-gradient(135deg, var(--text-muted) 50%, transparent 50%); + background-position: calc(100% - 15px) 50%, calc(100% - 10px) 50%; + background-size: 5px 5px, 5px 5px; + background-repeat: no-repeat; +} + +input[type="checkbox"], +input[type="radio"] { + accent-color: var(--accent); +} + +input[type="date"].input::-webkit-calendar-picker-indicator { + opacity: 0.6; + cursor: pointer; +} + @media (prefers-reduced-motion: reduce) { *, *::before, diff --git a/web/src/styles/overlays.css b/web/src/styles/overlays.css index 76c83d8..bf8cd3e 100644 --- a/web/src/styles/overlays.css +++ b/web/src/styles/overlays.css @@ -108,3 +108,85 @@ .toast__action:hover { background: var(--accent-wash); } + +.menu { + position: fixed; + z-index: var(--z-popover); + display: grid; + min-inline-size: 220px; + max-inline-size: 320px; + max-block-size: calc(100dvh - var(--space-4)); + overflow: auto; + padding: var(--space-1); + background: var(--surface-2); + border-radius: var(--radius); + box-shadow: var(--shadow-pop); + opacity: 0; + transform: translateY(2px); + transition: opacity var(--dur-fast) var(--ease), transform var(--dur-fast) var(--ease); +} + +.menu[hidden] { + display: none; +} + +.menu.is-visible { + opacity: 1; + transform: none; +} + +.menu__item { + display: grid; + grid-template-columns: var(--icon) minmax(0, 1fr) auto; + align-items: center; + column-gap: var(--space-2); + min-block-size: var(--row); + padding: 0 var(--space-2); + font-size: var(--text-sm); + text-align: start; + color: var(--text); + background: transparent; + border: 0; + border-radius: var(--radius-sm); + cursor: pointer; +} + +.menu__item:hover, +.menu__item:focus-visible { + background: var(--hover); + outline: none; +} + +.menu__item .icon { + color: var(--text-muted); +} + +.menu__label { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.menu__hint { + font-size: var(--text-xs); + color: var(--text-faint); +} + +.menu__check { + color: var(--accent); + visibility: hidden; +} + +.menu__item[aria-checked="true"] .menu__check { + visibility: visible; +} + +.menu__sep { + block-size: 1px; + margin: var(--space-1) calc(var(--space-1) * -1); + background: var(--border); +} + +.menu__item[data-off] { + display: none; +} diff --git a/web/src/styles/parts.css b/web/src/styles/parts.css index 5c7c3d1..be56a36 100644 --- a/web/src/styles/parts.css +++ b/web/src/styles/parts.css @@ -29,8 +29,10 @@ .page__title { margin: 0; - font-size: var(--text-lg); + font-size: var(--text-title); font-weight: var(--weight-semibold); + line-height: var(--page-title-h); + letter-spacing: -0.02em; } .page__body { @@ -105,22 +107,56 @@ --tbl-block: max(calc(var(--row) * 6), 100cqb); } +:root { + --page-eyebrow-h: calc(var(--text-xs) * 1.4); + --page-title-h: calc(var(--text-title) * 1.2); + --page-lead-h: calc(var(--text-md) * var(--leading)); + --page-head: calc(var(--page-eyebrow-h) + var(--page-title-h) + var(--page-lead-h) + var(--space-1) * 2); +} + .page__head { display: flex; - align-items: center; - gap: var(--space-2); - min-block-size: var(--control); + align-items: flex-end; + gap: var(--space-4); + flex: none; + block-size: var(--page-head); min-inline-size: 0; } -.page__head > .page__title { +.page__heading { + display: grid; + grid-template-rows: var(--page-eyebrow-h) var(--page-title-h) var(--page-lead-h); + row-gap: var(--space-1); flex: 1 1 auto; min-inline-size: 0; +} + +.page__eyebrow, +.page__lead, +.page__heading > .page__title { + margin: 0; + min-inline-size: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.page__eyebrow { + font-size: var(--text-xs); + font-weight: var(--weight-semibold); + line-height: var(--page-eyebrow-h); + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--accent); +} + +.page__lead { + max-inline-size: 72ch; + font-size: var(--text-md); + line-height: var(--page-lead-h); + color: var(--text-muted); +} + .page__actions { display: flex; align-items: center; diff --git a/web/src/styles/shell.css b/web/src/styles/shell.css index 04cd27c..6bde568 100644 --- a/web/src/styles/shell.css +++ b/web/src/styles/shell.css @@ -15,7 +15,7 @@ .sidebar__inner { display: grid; - grid-template-rows: auto minmax(0, 1fr); + grid-template-rows: auto auto minmax(0, 1fr) auto; inline-size: var(--sidebar-w); block-size: 100%; padding: 0 var(--space-2) var(--space-2); @@ -23,26 +23,127 @@ .sidebar__head { display: grid; - grid-template-columns: var(--icon) minmax(0, 1fr); + grid-template-columns: minmax(0, 1fr) auto; align-items: center; - column-gap: var(--space-2); + column-gap: var(--space-1); block-size: var(--topbar-h); padding-inline: var(--space-2); } -.brand__mark { +.sidebar__top, +.sidebar__foot { display: grid; - color: var(--accent); + row-gap: 1px; } -.brand__name { - overflow: hidden; - font-size: var(--text-md); +.sidebar__top { + padding-block-end: var(--space-2); +} + +.sidebar__foot { + padding-block-start: var(--space-1); + border-block-start: 1px solid var(--border); +} + +.ws-switch, +.user-chip { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + align-items: center; + column-gap: var(--space-2); + min-inline-size: 0; + padding: var(--space-1) var(--space-2); + margin-inline-start: calc(var(--space-2) * -1); + color: var(--text); + text-align: start; + background: transparent; + border: 0; + border-radius: var(--radius-sm); + transition: background-color var(--dur-fast) var(--ease); +} + +.ws-switch { + justify-self: start; + max-inline-size: 100%; font-weight: var(--weight-semibold); + letter-spacing: -0.01em; +} + +.ws-tile { + inline-size: var(--space-6); + block-size: var(--space-6); + border-radius: var(--radius-sm); +} + +.ws-switch__name, +.user-chip__name { + overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.user-chip { + margin: var(--space-1) 0 0; + font-size: var(--text-sm); + cursor: pointer; +} + +.user-chip:hover, +.user-chip[aria-expanded="true"] { + background: var(--hover); +} + +.user-chip__more { + color: var(--text-faint); +} + +.avatar { + display: inline-grid; + place-items: center; + inline-size: var(--space-6); + block-size: var(--space-6); + font-size: var(--text-xs); + font-weight: var(--weight-semibold); + line-height: 1; + color: var(--accent); + background: var(--accent-wash); + border-radius: 50%; + user-select: none; +} + +.sidebar__version { + display: inline-grid; + grid-auto-flow: column; + align-items: center; + column-gap: var(--space-1); + min-inline-size: var(--version-w); + justify-content: end; + font-family: var(--font-mono); + font-size: var(--text-xs); + color: var(--text-faint); + font-variant-numeric: tabular-nums; +} + +.live-dot { + inline-size: 6px; + block-size: 6px; + border-radius: 50%; + background: var(--text-faint); + transition: background-color var(--dur) var(--ease); +} + +.sidebar__version[data-phase="ok"] .live-dot { + background: var(--success); +} + +.sidebar__version[data-phase="degraded"] .live-dot { + background: var(--warning); +} + +.sidebar__version[data-phase="down"] .live-dot { + background: var(--danger); +} + .sidebar__nav { display: grid; align-content: start; @@ -118,19 +219,62 @@ .topbar { display: grid; - grid-template-columns: minmax(0, 1fr); + grid-template-columns: auto minmax(0, 1fr); align-items: center; - padding: 0 var(--space-4); + column-gap: var(--space-2); + padding: 0 var(--space-4) 0 var(--space-2); border-block-end: 1px solid var(--border); } +.topbar__nav { + display: inline-grid; + grid-auto-flow: column; + column-gap: 2px; +} + +.topbar__nav .icon-btn:disabled { + color: var(--text-faint); + background: transparent; + opacity: 0.55; + cursor: default; +} + +.crumbs { + display: flex; + align-items: center; + column-gap: var(--space-1); + min-inline-size: 0; + font-size: var(--text-sm); + color: var(--text-muted); +} + +.crumbs__group { + flex: none; + white-space: nowrap; +} + +.crumbs__group:not(:empty)::after { + padding-inline-start: var(--space-1); + color: var(--text-faint); + content: "/"; +} + +.crumbs__tile { + flex: none; + inline-size: var(--space-4); + block-size: var(--space-4); + background: var(--accent-wash); + border: 1px solid var(--accent); + border-radius: var(--radius-sm); +} + .topbar__title { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; font-size: var(--text-sm); font-weight: var(--weight-medium); - color: var(--text-muted); + color: var(--text); } .scroller { @@ -167,8 +311,64 @@ padding: var(--space-6); } +.home__head { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: var(--space-4); +} + +.home__intro { + display: grid; + row-gap: var(--space-1); + min-inline-size: 0; +} + +.home__eyebrow { + min-block-size: 1.4em; + overflow: hidden; + font-size: var(--text-xs); + font-weight: var(--weight-semibold); + letter-spacing: 0.08em; + white-space: nowrap; + text-overflow: ellipsis; + text-transform: uppercase; + color: var(--accent); +} + .home--dash .home__title { - font-size: var(--text-lg); + letter-spacing: -0.02em; +} + +.home__title > span { + display: none; +} + +:root[data-daypart="morning"] .home__title > [data-daypart="morning"], +:root[data-daypart="afternoon"] .home__title > [data-daypart="afternoon"], +:root[data-daypart="evening"] .home__title > [data-daypart="evening"], +:root:not([data-daypart]) .home__title > [data-daypart="afternoon"] { + display: inline; +} + +.home__lead { + max-inline-size: 62ch; + margin-block-start: var(--space-1); + font-size: var(--text-md); + color: var(--text-muted); +} + +.home__actions { + display: flex; + flex: none; + align-items: center; + gap: var(--space-2); +} + +.home__actions .btn { + display: inline-grid; + place-items: center; + block-size: calc(var(--control) + var(--space-1)); } .tiles { @@ -347,52 +547,6 @@ color: var(--text-muted); } -.status { - display: grid; - grid-template-columns: var(--space-2) minmax(0, 1fr) var(--version-w); - align-items: center; - column-gap: var(--space-2); - block-size: var(--status-h); - font-size: var(--text-sm); - color: var(--text-muted); - font-variant-numeric: tabular-nums; -} - -.status__dot { - inline-size: var(--space-2); - block-size: var(--space-2); - border-radius: 50%; - background: var(--text-faint); - transition: background-color var(--dur) var(--ease); -} - -.status[data-phase="ok"] .status__dot { - background: var(--success); -} - -.status[data-phase="degraded"] .status__dot { - background: var(--warning); -} - -.status[data-phase="down"] .status__dot { - background: var(--danger); -} - -.status__text { - overflow: hidden; - white-space: nowrap; - text-overflow: ellipsis; -} - -.status__version { - overflow: hidden; - font-family: var(--font-mono); - font-size: var(--text-xs); - color: var(--text-faint); - text-align: end; - white-space: nowrap; -} - @media (max-width: 640px) { .app { grid-template-columns: minmax(0, 1fr); diff --git a/web/src/styles/views/docform.css b/web/src/styles/views/docform.css index aec1d79..33149da 100644 --- a/web/src/styles/views/docform.css +++ b/web/src/styles/views/docform.css @@ -8,7 +8,7 @@ --df-party-w: 280px; --df-error-h: calc(var(--text-sm) * var(--leading) * 2); --df-actions-h: calc(var(--control) + var(--space-4)); - --df-chrome: calc(var(--topbar-h) + var(--space-6) * 2 + var(--space-4) + max(var(--control), var(--text-lg) * var(--leading))); + --df-chrome: calc(var(--topbar-h) + var(--space-6) * 2 + var(--space-4) + var(--page-head, max(var(--control), var(--text-lg) * var(--leading)))); display: grid; grid-template-rows: auto minmax(0, 1fr) auto auto; row-gap: var(--space-3); @@ -24,8 +24,33 @@ block-size: var(--df-head-h); } -.page__head > .page__title.df-number { +.page__heading:has(> .df-title) { + grid-template-columns: auto minmax(0, 1fr); + column-gap: var(--space-3); + align-items: center; +} + +.page__heading > .page__eyebrow { + grid-area: 1 / 1 / 2 / 3; +} + +.page__heading > .page__lead { + grid-area: 3 / 1 / 4 / 3; +} + +.page__heading > .page__title.df-number { + grid-area: 2 / 1 / 3 / 2; flex: none; + inline-size: 30ch; + max-inline-size: 34ch; + font-family: inherit; + font-size: var(--text-title); + line-height: var(--page-title-h); +} + +.page__heading > .df-title { + grid-area: 2 / 2 / 3 / 3; + margin: 0; } .df-title { @@ -102,6 +127,10 @@ block-size: var(--control); } +.df-fields input[type="date"].input { + padding-inline: var(--space-2); +} + .df-field--party { grid-column: span 3; } @@ -137,12 +166,13 @@ .df-actions { display: flex; - flex-wrap: nowrap; + flex-wrap: wrap; + justify-content: flex-end; align-items: center; column-gap: var(--space-2); - block-size: var(--df-actions-h); + row-gap: var(--space-2); + min-block-size: var(--df-actions-h); padding: var(--space-2) 0; - overflow-x: auto; border-block-start: 1px solid var(--border); } diff --git a/web/src/styles/views/payments.css b/web/src/styles/views/payments.css index 28598e7..ee41203 100644 --- a/web/src/styles/views/payments.css +++ b/web/src/styles/views/payments.css @@ -23,6 +23,41 @@ min-block-size: 0; } +.pay--stock, +.pay--form { + --pay-chrome: calc(var(--topbar-h) + var(--space-6) * 2 + var(--space-4) + var(--page-head, var(--control))); + block-size: max(calc(100dvh - var(--pay-chrome)), calc(var(--row) * 16)); + box-sizing: border-box; +} + +.pay--stock { + display: grid; + grid-template-rows: auto auto minmax(0, 1fr) auto auto; + min-block-size: 0; + overflow: hidden; +} + +.pay--stock > .pay__table { + display: grid; + grid-template-rows: minmax(0, 1fr); + min-block-size: 0; +} + +.pay--stock > .pay__table > .tbl { + block-size: 100%; +} + +.pay--form { + min-block-size: 0; + overflow-y: auto; +} + +.pay--form .pay__actions { + position: sticky; + inset-block-end: 0; + background: var(--sheet); +} + .pay--list > .pay__table { display: grid; grid-template-rows: minmax(0, 1fr); @@ -166,7 +201,6 @@ gap: var(--space-2); } -.pay--form .pay__actions, .pay--stock .pay__actions { position: static; background: none; diff --git a/web/src/ui/account.ts b/web/src/ui/account.ts index 8ab556e..1774de0 100644 --- a/web/src/ui/account.ts +++ b/web/src/ui/account.ts @@ -1,5 +1,6 @@ import { ApiError, type Engine, type Invite } from "../engine"; import { h, ref, setAttr, setText } from "./dom"; +import { iconNode } from "./icons"; function formOf(name: string): HTMLFormElement { const el = document.querySelector(`form[data-form="${name}"]`); @@ -83,8 +84,6 @@ function bindGates(engine: Engine): void { function bindFrame(engine: Engine): void { const name = ref("who-name"); const role = ref("who-role"); - role.classList.add("badge"); - setAttr(role, "data-tone", "muted"); const signout = ref("signout"); const title = ref("topbar-title"); const navAccount = ref("nav-account"); @@ -215,7 +214,24 @@ function bindAccountForms(engine: Engine): void { }); } +function bindPasswordToggles(): void { + for (const pw of document.querySelectorAll('form[data-form] input[type="password"]')) { + const shown = h("button", { class: "auth__pw-toggle", attrs: { type: "button", "aria-pressed": "false", "aria-label": "Show password" } }, iconNode("eye")); + const wrap = h("span", { class: "auth__pw" }); + pw.before(wrap); + wrap.append(pw, shown); + shown.addEventListener("click", () => { + const on = pw.type === "password"; + pw.type = on ? "text" : "password"; + setAttr(shown, "aria-pressed", on ? "true" : "false"); + setAttr(shown, "aria-label", on ? "Hide password" : "Show password"); + shown.replaceChildren(iconNode(on ? "eyeOff" : "eye")); + }); + } +} + export function mountAccount(engine: Engine): void { + bindPasswordToggles(); bindGates(engine); bindFrame(engine); bindAccountForms(engine); diff --git a/web/src/ui/app.ts b/web/src/ui/app.ts index 1a06f65..670b80b 100644 --- a/web/src/ui/app.ts +++ b/web/src/ui/app.ts @@ -53,6 +53,107 @@ function bindStatus(engine: Engine): void { }); } +const THEME_KEY = "formledger.theme"; + +function applyTheme(pref: string): void { + const d = document.documentElement; + const light = pref === "light" || (pref === "auto" && matchMedia("(prefers-color-scheme: light)").matches); + d.setAttribute("data-theme", light ? "light" : "dark"); + d.setAttribute("data-theme-pref", pref); + document.querySelector('meta[name="theme-color"]')?.setAttribute("content", light ? "#f3f1ed" : "#08080a"); + document.querySelectorAll("[data-theme-choice]").forEach((b) => setAttr(b, "aria-checked", b.dataset.themeChoice === pref ? "true" : "false")); +} + +function bindUserMenu(engine: Engine): void { + const chip = ref("user-chip"); + const menu = ref("user-menu"); + const avatar = ref("user-avatar"); + const close = () => { + menu.classList.remove("is-visible"); + menu.hidden = true; + setAttr(chip, "aria-expanded", "false"); + }; + const open = () => { + menu.hidden = false; + const r = chip.getBoundingClientRect(); + menu.style.insetInlineStart = `${r.left}px`; + menu.style.insetBlockEnd = `${window.innerHeight - r.top + 4}px`; + menu.style.inlineSize = `${Math.max(r.width, 220)}px`; + setAttr(chip, "aria-expanded", "true"); + requestAnimationFrame(() => menu.classList.add("is-visible")); + }; + chip.addEventListener("click", () => (menu.hidden ? open() : close())); + menu.addEventListener("click", (e) => { + const choice = (e.target as HTMLElement).closest("[data-theme-choice]")?.dataset.themeChoice; + if (choice) { + try { + localStorage.setItem(THEME_KEY, choice); + } catch { + /* storage off */ + } + applyTheme(choice); + } + close(); + }); + document.addEventListener("pointerdown", (e) => { + if (!menu.hidden && !menu.contains(e.target as Node) && !chip.contains(e.target as Node)) close(); + }); + document.addEventListener("keydown", (e) => { + if (e.key === "Escape" && !menu.hidden) { + close(); + chip.focus(); + } + }); + matchMedia("(prefers-color-scheme: light)").addEventListener("change", () => { + const pref = document.documentElement.getAttribute("data-theme-pref") || "auto"; + if (pref === "auto") applyTheme(pref); + }); + applyTheme(document.documentElement.getAttribute("data-theme-pref") || "auto"); + engine.state.watch( + "me", + (me) => { + const n = me ? me.user.name || me.user.email || "Owner" : ""; + const parts = n.split(/[\s@.]+/).filter(Boolean); + setText(avatar, ((parts[0]?.[0] ?? "") + (parts[1]?.[0] ?? "")).toUpperCase()); + }, + { immediate: true }, + ); +} + +function bindHistory(engine: Engine): void { + const back = ref("nav-back"); + const fwd = ref("nav-forward"); + const group = ref("topbar-group"); + let depth = 0; + let max = 0; + history.replaceState({ ...(history.state as object | null), flDepth: 0 }, ""); + const sync = () => { + back.disabled = depth <= 0; + fwd.disabled = depth >= max; + }; + window.addEventListener("hashchange", () => { + const st = history.state as { flDepth?: number } | null; + if (st && typeof st.flDepth === "number") depth = st.flDepth; + else { + depth += 1; + max = depth; + history.replaceState({ flDepth: depth }, ""); + } + sync(); + }); + back.addEventListener("click", () => history.back()); + fwd.addEventListener("click", () => history.forward()); + engine.state.watch( + "route", + (route) => { + const eyebrow = document.querySelector(`[data-view="${route}"] .page__eyebrow`); + setText(group, eyebrow?.textContent ?? ""); + }, + { immediate: true }, + ); + sync(); +} + function bindNav(engine: Engine): void { const home = ref("nav-home"); home.addEventListener("click", (e) => { @@ -165,9 +266,7 @@ function mountHome(engine: Engine): void { void amount(oweEl[1], api.call<{ suppliers: number }>("GET", "/api/payables/reconcile").then((r) => r.suppliers)); void amount( cashEl[1], - api.call<{ accounts: { name: string; type: string; isGroup: boolean; balance: number }[] }>("GET", "/api/reports/balances").then((r) => - r.accounts.filter((a) => a.type === "asset" && !a.isGroup && /cash|bank/i.test(a.name)).reduce((s, a) => s + a.balance, 0), - ), + api.call<{ cash: { total: number } }>("GET", "/api/reports/balances").then((r) => r.cash.total), ); api .call<{ docs: RecentDoc[] }>("GET", `/api/sales/docs?kind=invoice&limit=${RECENT_ROWS}`) @@ -183,6 +282,8 @@ function mountHome(engine: Engine): void { export function mountApp(engine: Engine): void { bindNav(engine); + bindUserMenu(engine); + bindHistory(engine); bindStatus(engine); mountHome(engine); mountAccount(engine); diff --git a/web/src/ui/icons.ts b/web/src/ui/icons.ts index 6622d2f..2216567 100644 --- a/web/src/ui/icons.ts +++ b/web/src/ui/icons.ts @@ -3,6 +3,16 @@ const PATHS = { home: '', lock: '', user: '', + sun: '', + moon: '', + monitor: '', + chevron: '', + more: '', + logout: '', + eye: '', + eyeOff: '', + back: '', + forward: '', quote: '', clipboardCheck: '', document: '', diff --git a/web/src/ui/parts/exportbtn.ts b/web/src/ui/parts/exportbtn.ts new file mode 100644 index 0000000..9f72d18 --- /dev/null +++ b/web/src/ui/parts/exportbtn.ts @@ -0,0 +1,67 @@ +import { h, setAttr } from "../dom"; +import { iconNode } from "../icons"; +import { toast } from "../toast"; + +export interface ExportSpec { + name: string; + params?: () => Record; + can?: () => boolean; +} + +function fileName(res: Response, name: string): string { + const m = /filename="([^"]+)"/.exec(res.headers.get("content-disposition") ?? ""); + return m?.[1] ?? `${name}.csv`; +} + +async function failure(res: Response): Promise { + const data = (await res.json().catch(() => null)) as { error?: { message?: string } } | null; + const msg = data?.error?.message; + if (res.status === 401) return "Your session has ended. Sign in again to export."; + if (res.status === 403) return "Your role cannot export this list."; + return msg ? `Export failed: ${msg}` : `Export failed: the server answered ${res.status}.`; +} + +export function exportUrl(name: string, params: Record = {}): string { + const q = new URLSearchParams(); + for (const [k, v] of Object.entries(params)) if (v) q.set(k, v); + const s = q.toString(); + return `/api/export/${encodeURIComponent(name)}.csv${s ? `?${s}` : ""}`; +} + +export function mountExport(actions: HTMLElement, spec: ExportSpec): HTMLButtonElement { + const btn = h("button", { class: "btn btn--quiet exportbtn", attrs: { type: "button", title: "Download what this screen shows as a CSV file", "data-export": spec.name } }, iconNode("trayIn"), h("span", { text: "Export CSV" })); + btn.style.cssText = "display:inline-flex;align-items:center;gap:var(--space-1);white-space:nowrap;flex:none"; + if (spec.can && !spec.can()) btn.hidden = true; + let busy = false; + btn.addEventListener("click", async () => { + if (busy) return; + busy = true; + btn.disabled = true; + setAttr(btn, "aria-busy", "true"); + try { + let res: Response; + try { + res = await fetch(exportUrl(spec.name, spec.params?.() ?? {}), { credentials: "same-origin", cache: "no-store" }); + } catch { + toast({ id: "export", tone: "danger", message: "The server does not answer. Try the export again in a moment." }); + return; + } + if (!res.ok) { + toast({ id: "export", tone: "danger", message: await failure(res) }); + return; + } + const url = URL.createObjectURL(await res.blob()); + const a = h("a", { attrs: { href: url, download: fileName(res, spec.name), hidden: "" } }); + document.body.append(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + } finally { + busy = false; + btn.disabled = false; + setAttr(btn, "aria-busy", null); + } + }); + actions.prepend(btn); + return btn; +} diff --git a/web/src/ui/theme/tokens.css b/web/src/ui/theme/tokens.css index 7b6e401..a50c774 100644 --- a/web/src/ui/theme/tokens.css +++ b/web/src/ui/theme/tokens.css @@ -40,6 +40,9 @@ --info: #7dd3fc; --shadow-pop: 0 16px 40px rgba(0, 0, 0, 0.55), 0 0 0 1px var(--border-strong); + --shadow-sheet: 0 10px 30px rgba(0, 0, 0, 0.35); + --sheet-highlight: rgba(255, 255, 255, 0.035); + --radius-sheet: 14px; --font-system-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; --font-system-mono: ui-monospace, "SF Mono", "Cascadia Code", Menlo, Consolas, monospace; @@ -50,11 +53,13 @@ --text-sm: 12.5px; --text-md: 14px; --text-lg: 16px; + --text-xl: 22px; --text-title: 28px; --leading: 1.55; --leading-tight: 1.15; --weight-medium: 500; --weight-semibold: 600; + --weight-bold: 700; --space-1: 4px; --space-2: 8px; @@ -62,6 +67,7 @@ --space-4: 16px; --space-6: 24px; --space-8: 32px; + --space-10: 40px; --space-14: 56px; --radius-xs: 4px; @@ -71,7 +77,7 @@ --icon: 16px; --control: 28px; --row: 30px; - --sidebar-w: 240px; + --sidebar-w: 264px; --topbar-h: 44px; --text-nav: 13.5px; --doc-w: 720px; @@ -112,4 +118,6 @@ --info: #0369a1; --shadow-pop: 0 16px 40px rgba(40, 30, 10, 0.16), 0 0 0 1px var(--border-strong); + --shadow-sheet: 0 1px 2px rgba(40, 30, 10, 0.05), 0 10px 30px rgba(40, 30, 10, 0.06); + --sheet-highlight: rgba(255, 255, 255, 0.8); } diff --git a/web/src/ui/view-about.ts b/web/src/ui/view-about.ts new file mode 100644 index 0000000..60dbe90 --- /dev/null +++ b/web/src/ui/view-about.ts @@ -0,0 +1,30 @@ +export const VIEW_ABOUT: Record = { + quotes: "Prices offered to customers, before anything is ordered or owed.", + "sales-orders": "What customers have ordered and what is still to deliver or bill.", + "sales-invoices": "Bills sent to customers, what each one comes to and what is still unpaid.", + "sales-doc": "One quote, order or invoice for a customer, line by line.", + "payments-in": "Money received from customers and the invoices it settles.", + "payment-in": "One receipt of money, and how it is set against open invoices.", + "receivables-ageing": "What each customer owes, sorted by how long it has been due.", + "purchase-orders": "What you have ordered from suppliers and what is still to arrive.", + "goods-receipts": "Stock that has arrived from suppliers, against their orders.", + "goods-receipt": "One delivery from a supplier, item by item, into a warehouse.", + "purchase-invoices": "Bills from suppliers, what each one comes to and what is still to pay.", + "purchase-doc": "One purchase order or supplier invoice, line by line.", + "payments-out": "Money paid to suppliers and the bills it settles.", + "payment-out": "One payment to a supplier, and how it is set against open bills.", + "payables-ageing": "What you owe each supplier, sorted by how long it has been due.", + "delivery-notes": "Stock sent out to customers, against their orders.", + "delivery-note": "One shipment to a customer, item by item, out of a warehouse.", + "stock-balance": "How much of each item is on hand in each warehouse, and what it is worth.", + "trial-balance": "Every account's debit and credit total for the period; the two columns must agree.", + "general-ledger": "Every posting to one account in date order, with the running balance.", + "profit-and-loss": "Income less expenses for a date range, ending in the net result.", + "balance-sheet": "What the company owns, owes and is worth on a given date.", + customers: "The people and companies you sell to, with their terms and contact details.", + suppliers: "The people and companies you buy from, with their terms and contact details.", + items: "The goods and services you buy and sell, with their units and prices.", + "tax-rates": "The tax codes applied to document lines, and the rate each one charges.", + warehouses: "The places stock is kept; every stock movement names one.", + accounts: "The chart of accounts every posting lands in, grouped by type.", +}; diff --git a/web/src/ui/views.ts b/web/src/ui/views.ts index d9da5d2..ed4bdeb 100644 --- a/web/src/ui/views.ts +++ b/web/src/ui/views.ts @@ -1,6 +1,7 @@ import type { Api, Engine } from "../engine"; import { h, ref, setAttr, setText } from "./dom"; import { iconNode, type IconName } from "./icons"; +import { VIEW_ABOUT } from "./view-about"; import { VIEW_ICONS } from "./view-icons"; import { ALL_VIEWS } from "./views/index"; @@ -72,7 +73,23 @@ export function mountViews(engine: Engine): void { const section = h( "section", { class: "view view--page", attrs: { "data-view": def.id, "aria-label": def.title } }, - h("div", { class: "page" }, h("header", { class: "page__head" }, h("h1", { class: "page__title", text: def.title }), actions), body), + h( + "div", + { class: "page" }, + h( + "header", + { class: "page__head" }, + h( + "div", + { class: "page__heading" }, + h("p", { class: "page__eyebrow", text: def.group }), + h("h1", { class: "page__title", text: def.title }), + h("p", { class: "page__lead", text: VIEW_ABOUT[def.id] ?? "" }), + ), + actions, + ), + body, + ), ); scroller.append(section); let link: HTMLAnchorElement | null = null; diff --git a/web/src/ui/views/doclists.ts b/web/src/ui/views/doclists.ts index 120f8b9..cfbae85 100644 --- a/web/src/ui/views/doclists.ts +++ b/web/src/ui/views/doclists.ts @@ -1,6 +1,7 @@ import { DOC_LISTS, STATUSES, isStatus, loadPage, type DocListSpec, type DocRow, type DocStatus } from "../../engine/doclists"; import { money } from "../../engine/format"; import { h, setAttr, setText } from "../dom"; +import { mountExport } from "../parts/exportbtn"; import { mountTable, type TableHandle } from "../parts/table"; import type { ViewContext, ViewDef } from "../views"; @@ -63,6 +64,7 @@ function listView(spec: DocListSpec): ViewDef { nav: true, mount(host, c, actions) { ctx = c; + mountExport(actions, { name: spec.id, params: () => (status ? { status } : {}), can: () => ctx.can("reports.read") }); if (spec.newAction && ctx.can(spec.newAction)) { const add = h("button", { class: "btn btn--primary dl__new", attrs: { type: "button" } }, plusIcon(), h("span", { text: "New" })); add.addEventListener("click", () => ctx.go(spec.form, { kind: spec.kind })); diff --git a/web/src/ui/views/ledger-screens.ts b/web/src/ui/views/ledger-screens.ts index 6515e60..eaa230a 100644 --- a/web/src/ui/views/ledger-screens.ts +++ b/web/src/ui/views/ledger-screens.ts @@ -4,6 +4,7 @@ import { qty, today } from "../../engine/format"; import { h, setAttr, setText } from "../dom"; import type { ViewContext, ViewDef, ViewGroup } from "../views"; import { mountTable, type Column, type TableHandle } from "../parts/table"; +import { mountExport } from "../parts/exportbtn"; interface Control { el: HTMLInputElement | HTMLSelectElement; @@ -87,8 +88,9 @@ function trialScreen(): ViewDef { title: "Trial balance", group: "Ledger", nav: true, - mount(host, ctx) { + mount(host, ctx, actions) { const asOf = date(today()); + mountExport(actions, { name: "trial-balance", params: () => ({ asOf: asOf.read() }), can: () => ctx.can("reports.read") }); const { status, badge, tableHost } = shell(host, [{ label: "As of", control: asOf }], () => reload()); const cols: Column[] = [ { key: "code", label: "Code", width: "110px", mono: true, text: (r) => r.code }, @@ -121,10 +123,11 @@ function ledgerScreen(): ViewDef { title: "General ledger", group: "Ledger", nav: true, - mount(host, ctx) { + mount(host, ctx, actions) { const account = choose([["", "Choose an account"]]); const from = date(""); const to = date(today()); + mountExport(actions, { name: "general-ledger", params: () => ({ account: account.read(), from: from.read(), to: to.read() }), can: () => ctx.can("reports.read") }); const { status, tableHost } = shell( host, [ @@ -176,7 +179,7 @@ function ageingScreen(id: string, title: string, group: ViewGroup, side: "receiv title, group, nav: true, - mount(host, ctx) { + mount(host, ctx, actions) { const asOf = date(today()); const by = choose([ ["due", "Due date"], @@ -191,6 +194,7 @@ function ageingScreen(id: string, title: string, group: ViewGroup, side: "receiv () => reload(), ); tableHost.dataset.ageing = "true"; + mountExport(actions, { name: id, params: () => ({ asOf: asOf.read(), by: by.read() }), can: () => ctx.can("reports.read") }); const cols: Column[] = [ { key: "code", label: "Code", width: "100px", mono: true, text: (r) => r.code }, { key: "name", label: party, width: "auto", text: (r) => r.name }, @@ -231,8 +235,9 @@ function stockScreen(): ViewDef { title: "Stock balance and valuation", group: "Stock", nav: true, - mount(host, ctx) { + mount(host, ctx, actions) { const asOf = date(today()); + mountExport(actions, { name: "stock-balance", params: () => ({ asOf: asOf.read() }), can: () => ctx.can("reports.read") }); const { status, badge, tableHost } = shell(host, [{ label: "As of", control: asOf }], () => reload()); const cols: Column[] = [ { key: "code", label: "Item", width: "120px", mono: true, text: (r) => r.code }, diff --git a/web/src/ui/views/masters.ts b/web/src/ui/views/masters.ts index 025698d..8444695 100644 --- a/web/src/ui/views/masters.ts +++ b/web/src/ui/views/masters.ts @@ -1,7 +1,8 @@ -import { boolValue, buildBody, cell, create, depthOf, fieldText, listAll, MASTERS, title, update, type Field, type Master, type Raw, type Row } from "../../engine/masters"; +import { boolValue, buildBody, cashAllowed, cell, create, depthOf, fieldText, listAll, MASTERS, title, update, type Field, type Master, type Raw, type Row } from "../../engine/masters"; import { ApiError } from "../../engine/session"; import { h, setAttr, setText } from "../dom"; import type { IconName } from "../icons"; +import { mountExport } from "../parts/exportbtn"; import { mountTable, type TableHandle } from "../parts/table"; import type { ViewContext, ViewDef } from "../views"; @@ -74,6 +75,19 @@ function mountMaster(m: Master, host: HTMLElement, ctx: ViewContext): { show(): fieldsBox.append(wrap); } + const cash = inputs.get("isCash"); + const syncCash = () => { + if (!cash) return; + const type = inputs.get("type")?.input.value ?? ""; + const group = inputs.get("isGroup")?.input; + const show = cashAllowed(type, group instanceof HTMLInputElement && group.checked); + const want = show ? "" : "hidden"; + if (cash.wrap.style.visibility !== want) cash.wrap.style.visibility = want; + setAttr(cash.wrap, "aria-hidden", show ? null : "true"); + }; + inputs.get("type")?.input.addEventListener("change", syncCash); + inputs.get("isGroup")?.input.addEventListener("change", syncCash); + let current: Row | null = null; const fill = (row: Row | null) => { current = row; @@ -87,6 +101,7 @@ function mountMaster(m: Master, host: HTMLElement, ctx: ViewContext): { show(): const locked = Boolean(row) && field.createOnly === true; if (input.disabled !== locked) input.disabled = locked; } + syncCash(); setText(heading, title(m, row)); setText(error, ""); for (const tr of listHost.querySelectorAll("tr[data-selected]")) { @@ -194,7 +209,8 @@ export const views: ViewDef[] = MASTERS.map((m) => { group: "Setup", nav: true, icon: ICONS[m.id] ?? "logo", - mount(host, ctx) { + mount(host, ctx, actions) { + mountExport(actions, { name: m.id, can: () => ctx.can("reports.read") }); mounted = mountMaster(m, host, ctx); }, show() { diff --git a/web/src/ui/views/payments.ts b/web/src/ui/views/payments.ts index b7b44c2..15735b3 100644 --- a/web/src/ui/views/payments.ts +++ b/web/src/ui/views/payments.ts @@ -27,6 +27,7 @@ import { type PaymentDraft, } from "../../engine/payments"; import { delayedIndicator, h, setAttr, setText } from "../dom"; +import { mountExport } from "../parts/exportbtn"; import { mountPicker } from "../parts/picker"; import { mountTable, statusTone } from "../parts/table"; import type { ViewContext, ViewDef } from "../views"; @@ -45,6 +46,7 @@ function mountList(dir: PayDir, host: HTMLElement, ctx: ViewContext, head: HTMLE const count = h("span", { class: "pay__count num" }); const bar = h("div", { class: "bar pay__bar" }, h("label", { class: "pay__filter", text: "Status", attrs: { for: statusId } }), status, h("span", { class: "bar__grow" }), count); head.append(add); + mountExport(head, { name: dir === "in" ? "payments-in" : "payments-out", params: () => (status.value ? { status: status.value } : {}), can: () => ctx.can("reports.read") }); const tableHost = h("div", { class: "pay__table" }); root.append(bar, tableHost); host.append(root); diff --git a/web/src/ui/views/statements.ts b/web/src/ui/views/statements.ts index e077be1..50a43ae 100644 --- a/web/src/ui/views/statements.ts +++ b/web/src/ui/views/statements.ts @@ -9,6 +9,7 @@ import { type StatementSection, } from "../../engine/statements"; import { delayedIndicator, h, setAttr, setText } from "../dom"; +import { mountExport } from "../parts/exportbtn"; import { hashFor, type ViewContext, type ViewDef } from "../views"; function goOrRefresh(ctx: ViewContext | null, id: string, params: Record, refresh: () => void): void { @@ -137,8 +138,9 @@ function profitAndLossView(): ViewDef { title: "Profit and loss", group: "Ledger", nav: true, - mount(host, c) { + mount(host, c, actions) { ctx = c; + mountExport(actions, { name: "profit-and-loss", params: () => ({ from: from.value, to: to.value }), can: () => c.can("reports.read") }); const shell = mountShell(host, [dateField("From", from), dateField("To", to)], "Net profit"); const income = mountSection(shell.sheet, "Income"); const expenses = mountSection(shell.sheet, "Expenses"); @@ -188,8 +190,9 @@ function balanceSheetView(): ViewDef { title: "Balance sheet", group: "Ledger", nav: true, - mount(host, c) { + mount(host, c, actions) { ctx = c; + mountExport(actions, { name: "balance-sheet", params: () => ({ asOf: asOf.value }), can: () => c.can("reports.read") }); const shell = mountShell(host, [dateField("As of", asOf)], "Total liabilities and equity"); const assets = mountSection(shell.sheet, "Assets", "on this day"); const liabilities = mountSection(shell.sheet, "Liabilities", "on this day");