diff --git a/CHANGELOG.md b/CHANGELOG.md index b495e76..531d543 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,39 @@ # Changelog +## 0.9.0 + +The window has had its first design pass, and two ways to take your figures out have arrived. + +### New +- Home is a working page: what customers owe you, what you owe suppliers, cash and bank, and your last five sales and purchase invoices, each a link to its screen. +- CSV export for every list and statement, from the server and from the command line (`./formledger cli export NAME`). `docs/EXPORT.md` lists every name and its columns. The window has no export buttons yet. +- `./formledger report snapshot` writes a plain, read-only SQLite file of your books for a spreadsheet to open, with the server stopped. `docs/SNAPSHOT.md` describes every table and gives ready queries. +- The trial balance, the stock screen and the balance sheet say with a badge whether they agree. + +### Changed +- Every list and ledger screen fills the window, with its filters in one bar, and its main button on the title row. +- A status is a coloured badge everywhere. Codes and document numbers use the fixed-width face; amounts line up on the right. +- The document form reads like the paper: one heading with the number and status, a tidy header block, the lines, totals under the amount column, then the buttons with the main one last. A posted document shows as read-only. +- Profit and loss and the balance sheet are laid out as statements, with the result as the one large number at the foot. +- The setup screens show the list beside a form panel that scrolls, with its buttons always in view. The chart of accounts is indented by level. +- The top bar shows where you are on the left and who you are on the right. The sidebar scrolls on a short window. +- A zero in a debit or credit column is left blank. + +### Fixed +- The setup form no longer cuts off its lower fields. +- A document line with a quantity or price but no item is now pointed out when you save, where it used to be dropped without a word. + +### Known issues +- The design pass followed rules written for this app on form.md's colours and type; it has not been compared with form.md's own screens side by side. +- The light theme, windows narrower than 1400 px and the purchase form were not looked at in this pass. +- Totals on a draft document show 0.00 until it is saved. +- An exported delivery note list stops at 500 notes. +- Invoice and statement PDFs are not built yet. +- The desktop app has not been built yet; the window runs in a browser against the server. + +### Under the hood +- One page of design rules, `docs/window/DESIGN.md`, and shared page, bar, badge, field and table classes that every screen now uses. + ## 0.8.0 The window has now been run as a whole: a twenty-line invoice typed, posted and followed through three ledger screens, with nothing on screen moving. diff --git a/Makefile b/Makefile index 6873bfb..8320c28 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -VERSION := v0.8.0 +VERSION := v0.9.0 GO_BUILD := CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" .PHONY: build web server check clean diff --git a/cmd/HASHOUT_LOG.md b/cmd/HASHOUT_LOG.md index 7fc8da9..07aa9c1 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.8.0 +Current build version: v0.9.0 Last updated: 2026-11-26 (US Eastern) · skeleton port from form.md --- diff --git a/cmd/formledger/main.go b/cmd/formledger/main.go index a05038a..615b67a 100644 --- a/cmd/formledger/main.go +++ b/cmd/formledger/main.go @@ -18,6 +18,7 @@ import ( "github.com/nodemode-ai/formledger/internal/config" "github.com/nodemode-ai/formledger/internal/nowindow" "github.com/nodemode-ai/formledger/internal/server" + "github.com/nodemode-ai/formledger/internal/snapshot" "github.com/nodemode-ai/formledger/internal/startup" "github.com/nodemode-ai/formledger/internal/store" ) @@ -36,6 +37,8 @@ func run(args []string) int { return serve() case "cli": return cli.Run(args[1:], os.Stdout, os.Stderr) + case "report": + return snapshot.Main(args[1:], os.Stdout, os.Stderr) case "version", "--version", "-v": fmt.Println(app.Version) return 0 @@ -135,6 +138,7 @@ func usage(w io.Writer) { fmt.Fprintf(w, "%s %s\n\nUsage: formledger [command]\n\nCommands:\n", app.Product, app.Version) fmt.Fprintln(w, " serve run the server (default)") fmt.Fprintln(w, " cli ledger commands against the running server (formledger cli --help)") + fmt.Fprintln(w, " report snapshot write a plain read-only SQLite snapshot (--out FILE, --force; server stopped)") fmt.Fprintln(w, " version print the version") fmt.Fprintln(w, " help show this help") fmt.Fprintln(w, "\nEnvironment:") diff --git a/docs/EXPORT.md b/docs/EXPORT.md new file mode 100644 index 0000000..1d0349b --- /dev/null +++ b/docs/EXPORT.md @@ -0,0 +1,58 @@ +# CSV export + +Every list and report can be downloaded as CSV. + + GET /api/export/NAME.csv?PARAM=VALUE... + ./formledger cli export NAME [--out FILE] [--token-file FILE] [--PARAM VALUE]... + +The command line fetches the same route with the app token (`FORMLEDGER_TOKEN` or `--token-file`, server from `FORMLEDGER_URL`) and writes the bytes unchanged, to standard output or to `--out FILE`. Every flag other than `--out` and `--token-file` is passed on as a query parameter: `--account 1110` becomes `?account=1110`. + +## 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`. + +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 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. +- 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`. + +## Names + +Columns are listed in file order. `*` marks money. + +| Name | JSON route | Parameters | Permission | Columns | +|---|---|---|---|---| +| quotes | `/api/sales/docs?kind=quote` | status, customer, limit | reports.read | 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, created_by, created_at, posted_by, posted_at, cancelled_by, cancelled_at, line_count | +| sales-orders | `/api/sales/docs?kind=order` | as quotes | as quotes | as quotes | +| sales-invoices | `/api/sales/docs?kind=invoice` | as quotes | as quotes | as quotes | +| 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 | +| 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 | +| suppliers | `/api/suppliers` | as its JSON route | as its JSON route | id, code, name, email, phone, address, tax_id, currency, payable_account_id, payable_account, payment_terms_days, active, created_at, updated_at | +| items | `/api/items` | as its JSON route | as its JSON route | 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 | `/api/tax-rates` | as its JSON route | as its JSON route | id, code, name, rate_bp, payable_account_id, payable_account, active, created_at, updated_at | +| warehouses | `/api/warehouses` | as its JSON route | as its JSON route | id, code, name, active, created_at, updated_at | +| accounts | `/api/accounts` | as its JSON route | as its JSON route | id, code, name, type, parent_id, parent_code, is_group, currency, active, created_at, updated_at | +| trial-balance | `/api/reports/trial-balance` | asOf, groups | reports.read | as_of, account_id, code, name, type, currency, is_group, parent_id, debit*, credit* | +| 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 | +| 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* | + +Report totals are not written as rows: the sum of a money column over the file equals the JSON route's total (trial balance debit and credit, each statement section, each ageing currency). diff --git a/docs/SNAPSHOT.md b/docs/SNAPSHOT.md new file mode 100644 index 0000000..47587f8 --- /dev/null +++ b/docs/SNAPSHOT.md @@ -0,0 +1,281 @@ +# The FormCel snapshot + +`./formledger report snapshot` writes a plain SQLite file with its own flat schema, made for analysis in FormCel or any other tool that opens SQLite. It is not a copy of the live tables: names are resolved (account codes, party codes, item codes, document numbers), so one `SELECT` with a `GROUP BY` gives rows ready to pivot. + +## Command + +``` +FORMLEDGER_DATA=/path/to/data ./formledger report snapshot [--out FILE] [--force] +``` + +- `--out FILE` · where to write. Default `formledger-snapshot-YYYY-MM-DD.sqlite` in the current folder, dated in the company's time zone. +- `--force` · replace FILE if it exists. Without it an existing file is refused (exit 2). +- The data folder is read from `FORMLEDGER_DATA`, as for `serve`. +- The command opens the database itself, so it refuses while a FormLedger server holds the data folder (exit 2, "FormLedger is already running on ..."). Stop the server, write the snapshot, start it again. The command holds the same lock while it works, so a server cannot start halfway through. +- It prints the file path and the row count of each table. + +## Guarantees + +- Consistent: every table is read inside one read transaction on the live database, so all tables show the same moment. +- Whole or nothing: the file is written under a hidden temporary name in the same folder (`.FILE.partPID`) and renamed into place only when complete. A reader never sees half a file; a failed run leaves no file. +- Plain: never encrypted, `journal_mode=DELETE`, no `-wal` or `-shm` files left behind, `ANALYZE` and `VACUUM` run. Any SQLite reader opens it read only (`file:FILE?mode=ro`). +- `PRAGMA user_version` holds the snapshot schema version. +- File mode `0600`. +- Nothing private: no users, sessions, API tokens, invites, password or token hashes, audit rows, secrets, or settings other than the company name. Who created or posted a record is left out. + +## Schema version rule + +The schema version is `1`, in `meta.schema_version` and `PRAGMA user_version`. It goes up by one when a table or column is removed or renamed, or when the meaning or unit of a column changes. Adding a new table, a new column at the end of a table, or a new value in a text column such as `doc_type` does not bump it, so a reader should name its columns and not use `SELECT *` by position. `meta.ledger_schema` is the live database migration number at the time of the snapshot and is for support only. + +## Money and quantities + +- Every amount comes twice. `X_minor` is an exact INTEGER in minor units (cents for USD). `X` without the suffix is REAL in major units: `X_minor / currencies.scale`. Pivot on `X`; when an exact total matters, sum `X_minor` and divide once. +- Every row that holds money has a `currency` column. The base currency is in `meta.base_currency`. +- Quantities: `quantity_milli` is an exact INTEGER in thousandths; `quantity` is `quantity_milli / 1000.0`. +- Dates are TEXT `YYYY-MM-DD`; `month` is TEXT `YYYY-MM`, ready to pivot on. + +## Tables + +### meta + +Key and value pairs, both TEXT. + +| key | meaning | +|---|---| +| schema_version | snapshot schema version, see the rule above | +| app_name | `FormLedger` | +| app_version | version of the program that wrote the file | +| ledger_schema | live migration number | +| company_name | the company name setting | +| base_currency | the currency most accounts use | +| time_zone | the company's time zone (`America/New_York`) | +| created_at | when the snapshot was written, local time, `YYYY-MM-DD HH:MM:SS ZZZ` | +| created_at_iso | the same moment, RFC 3339 with offset | +| created_at_utc | the same moment, RFC 3339 in UTC | +| money_rule | one line restating the money rule | + +### currencies + +| column | type | meaning | +|---|---|---| +| code | TEXT | ISO 4217 code | +| exponent | INTEGER | digits after the decimal point | +| scale | INTEGER | `10 ^ exponent`, the divisor from minor to major units | + +### accounts + +| column | type | meaning | +|---|---|---| +| code | TEXT | account code, the key used everywhere else | +| name | TEXT | account name | +| type | TEXT | `asset`, `liability`, `equity`, `income` or `expense` | +| normal_side | TEXT | `debit` for asset and expense, `credit` for the rest | +| parent_code | TEXT | code of the parent group, NULL at the top | +| is_group | INTEGER | 1 for a group account that takes no postings | +| currency | TEXT | account currency | +| active | INTEGER | 1 when active | + +### fiscal_periods + +| column | type | meaning | +|---|---|---| +| fiscal_year | TEXT | fiscal year name | +| period | TEXT | period name | +| start_date | TEXT | first day | +| end_date | TEXT | last day | +| status | TEXT | `open` or `locked` | + +### warehouses + +| column | type | meaning | +|---|---|---| +| code | TEXT | warehouse code | +| name | TEXT | warehouse name | +| active | INTEGER | 1 when active | + +### parties + +Customers and suppliers in one table. + +| column | type | meaning | +|---|---|---| +| kind | TEXT | `customer` or `supplier` | +| code | TEXT | party code, unique within a kind | +| name | TEXT | party name | +| email, phone, address, tax_id | TEXT | contact details as entered | +| currency | TEXT | party currency | +| account_code | TEXT | receivable account of a customer, payable account of a supplier | +| payment_terms_days | INTEGER | days from document date to due date | +| active | INTEGER | 1 when active | + +### items + +| column | type | meaning | +|---|---|---| +| code | TEXT | item code | +| name, description, unit | TEXT | as entered | +| currency | TEXT | price currency | +| sale_price, sale_price_minor | REAL, INTEGER | list sale price | +| purchase_price, purchase_price_minor | REAL, INTEGER | standard purchase price, NULL when the item has no stock settings | +| income_account_code | TEXT | income account for sales | +| tax_code | TEXT | default tax rate code, NULL for none | +| tax_rate_percent | REAL | that rate in percent | +| stocked | INTEGER | 1 when stock is tracked | +| inventory_account_code, cogs_account_code | TEXT | stock accounts, NULL when not set | +| active | INTEGER | 1 when active | + +### ledger_lines + +One row per line of every journal entry that counts in the ledger: posted entries, and cancelled entries together with the reversal that cancelled them (the pair nets to zero, as in the app's trial balance). Drafts are left out. + +| column | type | meaning | +|---|---|---| +| entry_number | TEXT | journal entry number | +| entry_date | TEXT | posting date | +| month | TEXT | `YYYY-MM` of entry_date | +| fiscal_year, period | TEXT | fiscal year and period names | +| line_no | INTEGER | line number inside the entry | +| account_code, account_name, account_type | TEXT | the account posted to | +| doc_type | TEXT | the document that made the entry: `sales_invoice`, `purchase_receipt`, `purchase_invoice`, `payment_received`, `payment_made`, `delivery_note`, or `journal` for a manual entry | +| doc_number | TEXT | that document's number, or the entry number for a manual entry; a reversal carries the number of what it reverses, so the pair groups together | +| party_kind, party_code, party_name | TEXT | the customer or supplier of the document, NULL for a manual entry | +| description | TEXT | line memo, or the entry memo when the line has none | +| currency | TEXT | entry currency | +| debit, credit, amount | REAL | major units; `amount = debit - credit` | +| debit_minor, credit_minor, amount_minor | INTEGER | the same in minor units | +| entry_status | TEXT | `posted` or `cancelled` | +| is_reversal | INTEGER | 1 when the entry reverses a cancelled one | + +Indexes: `entry_date`; `account_code, entry_date`; `month, account_code`; `party_kind, party_code`. + +### documents + +One row per sales and purchase document and delivery note, every status. + +| column | type | meaning | +|---|---|---| +| doc_id | TEXT | stable internal id, joins to document_lines and allocations | +| doc_type | TEXT | `sales_quote`, `sales_order`, `sales_invoice`, `purchase_order`, `purchase_receipt`, `purchase_invoice`, `delivery_note` | +| number | TEXT | document number, NULL for a draft | +| doc_date, month, due_date | TEXT | dates | +| party_kind, party_code, party_name | TEXT | customer or supplier | +| warehouse_code | TEXT | warehouse of a purchase document or delivery note | +| source_number | TEXT | number of the document it was made from (order of a receipt or delivery note) | +| status | TEXT | `draft`, `posted` or `cancelled` | +| currency | TEXT | document currency | +| subtotal, tax_total, total (and `_minor`) | REAL, INTEGER | totals; for a delivery note the stock value at cost, with no tax | +| memo | TEXT | as entered | + +### document_lines + +| column | type | meaning | +|---|---|---| +| doc_id, doc_type, doc_number, doc_date, month, status | | copied from the document so a line pivots alone | +| party_kind, party_code | TEXT | copied from the document | +| line_no | INTEGER | line number | +| item_code, item_name | TEXT | item, NULL for a free text line | +| description | TEXT | line text | +| account_code | TEXT | income account (sales) or expense account (purchase), NULL for a delivery note | +| tax_code | TEXT | tax rate code | +| currency | TEXT | document currency | +| quantity, quantity_milli | REAL, INTEGER | quantity | +| unit_price, line_subtotal, line_tax, line_total (and `_minor`) | REAL, INTEGER | line money; for a delivery note the unit cost and value | + +### payments + +Payments received from customers and made to suppliers. + +| column | type | meaning | +|---|---|---| +| payment_id | TEXT | stable internal id | +| direction | TEXT | `received` or `made` | +| number | TEXT | payment number, NULL for a draft | +| pay_date, month | TEXT | dates | +| party_kind, party_code, party_name | TEXT | customer or supplier | +| account_code | TEXT | bank or cash account | +| status | TEXT | `draft`, `posted` or `cancelled` | +| currency | TEXT | payment currency | +| amount, allocated, unallocated (and `_minor`) | REAL, INTEGER | amount, the part allocated to invoices, the rest | +| memo | TEXT | as entered | + +### allocations + +| column | type | meaning | +|---|---|---| +| direction | TEXT | `received` or `made` | +| payment_id, payment_number, payment_status, pay_date | | the payment | +| invoice_id, invoice_number | TEXT | the invoice it settles (doc_id and number in documents) | +| party_kind, party_code | TEXT | customer or supplier | +| currency | TEXT | payment currency | +| amount, amount_minor | REAL, INTEGER | amount allocated | + +### stock_moves + +One row per stock move, append only, in order. + +| column | type | meaning | +|---|---|---| +| seq | INTEGER | global order of moves | +| move_date, month | TEXT | dates | +| item_code, item_name | TEXT | item | +| warehouse_code, warehouse_name | TEXT | warehouse | +| source_kind | TEXT | what made the move, as the app records it | +| source_number | TEXT | number of the receipt, delivery note or document behind it | +| is_reversal | INTEGER | 1 when the move reverses another | +| currency | TEXT | item currency | +| quantity, quantity_milli | REAL, INTEGER | signed: in is positive, out is negative | +| unit_cost, value (and `_minor`) | REAL, INTEGER | cost per unit and signed value of the move | + +## Example SELECTs to pivot + +Profit and loss by month (income positive, expense negative; pivot month across, account down): + +```sql +SELECT month, account_type, account_code, account_name, ROUND(SUM(credit - debit), 2) AS amount +FROM ledger_lines WHERE account_type IN ('income', 'expense') +GROUP BY month, account_code ORDER BY month, account_code; +``` + +Receivables by customer: + +```sql +SELECT l.party_code, l.party_name, ROUND(SUM(l.amount), 2) AS balance +FROM ledger_lines l +JOIN parties p ON p.kind = 'customer' AND p.code = l.party_code AND p.account_code = l.account_code +GROUP BY l.party_code, l.party_name HAVING SUM(l.amount_minor) <> 0 ORDER BY balance DESC; +``` + +Sales by item and month: + +```sql +SELECT month, item_code, item_name, SUM(quantity) AS quantity, ROUND(SUM(line_subtotal), 2) AS net_sales +FROM document_lines WHERE doc_type = 'sales_invoice' AND status = 'posted' +GROUP BY month, item_code ORDER BY month, item_code; +``` + +Stock on hand and value by warehouse: + +```sql +SELECT warehouse_code, warehouse_name, item_code, SUM(quantity) AS quantity, ROUND(SUM(value), 2) AS value +FROM stock_moves GROUP BY warehouse_code, item_code +HAVING SUM(quantity_milli) <> 0 ORDER BY warehouse_code, item_code; +``` + +Sales by customer by month (posted invoices only, so a cancelled invoice drops out; pivot month across, customer down): + +```sql +SELECT month, party_code AS customer_code, party_name AS customer_name, COUNT(*) AS invoices, + ROUND(SUM(subtotal), 2) AS net_sales, ROUND(SUM(tax_total), 2) AS tax, ROUND(SUM(total), 2) AS gross_sales +FROM documents WHERE doc_type = 'sales_invoice' AND status = 'posted' +GROUP BY month, party_code ORDER BY month, party_code; +``` + +Trial balance as of a date, equal to the app's own: + +```sql +SELECT account_code, account_name, SUM(debit_minor) - SUM(credit_minor) AS net_minor +FROM ledger_lines WHERE entry_date <= '2026-12-31' +GROUP BY account_code HAVING net_minor <> 0 ORDER BY account_code; +``` + +`ROUND(..., 2)` suits two digit currencies; for an exact total sum the `_minor` column and divide by `currencies.scale`. diff --git a/docs/window/DESIGN.md b/docs/window/DESIGN.md new file mode 100644 index 0000000..97ae9c0 --- /dev/null +++ b/docs/window/DESIGN.md @@ -0,0 +1,47 @@ +# FormLedger window · design rules + +FormLedger is the financial counterpart of form.md. It uses form.md's tokens, shell and type as they are (`web/src/ui/theme/tokens.css`); this page says how a finance screen is laid out with them. A screen that follows these rules should read as calm, dense and exact: a person scans a column of numbers and finds the one they want. + +## The page + +- A screen is one `.page`: a title row, one toolbar, then the content. Nothing floats in the middle of a row. +- 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`. + +## The toolbar + +- `.bar` is one row at control height: filters on the leading side, then `.bar__grow`, then counts and secondary actions on the trailing side. +- A filter is a label and a control side by side; labels are `--text-sm`, muted. +- A count ("114 of 127") is muted text with tabular figures and a reserved width. "Load more" sits beside it as a quiet button and keeps its place. + +## Tables + +- Rows are `--row` high, always. Header cells are `--text-xs`, muted, medium weight, not uppercase. The header and the totals row stay in view while the body scrolls. +- Text is leading aligned; amounts, quantities and counts are trailing aligned with tabular figures (`.num`, or a column with `align: "end"`). Codes and document numbers use the mono face; names use the sans face. +- An amount shows its digits; the currency code is shown once, in the column header or the totals, not on every row, unless rows can differ in currency. +- A zero in a debit or credit column is blank, not "0.00". A negative amount has a leading minus sign and takes `--danger` only in a result (a loss, an overdue balance), never in ordinary rows. +- A status is a `.badge` with a tone, never bold text: `muted` for a draft, `info` for confirmed or open, `ok` for posted or paid, `warn` for part paid or overdue, `bad` for cancelled. +- A row that opens shows the pointer and the hover wash across the whole row; the document number is the row's first cell. +- An empty table says what the list is for and how to add the first row, centred in the box (`.tbl__empty`), in muted text. +- Totals rows are semibold with a strong top border. Section subtotals in a statement are medium weight; the result line (net profit, total assets) is the only large number on the screen. + +## Forms + +- 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. +- Required fields are marked in the label. An error names the field and says what to do. +- A document form reads top to bottom as the paper would: who and when in a header block, the lines, then totals trailing aligned under the amount column, then the actions. + +## The shell + +- The top bar shows where you are on the leading side and who you are on the trailing side (name, then role as a muted badge, then sign out). Nothing sits in its middle. +- The sidebar groups are the business areas. The current screen is marked with the accent wash and an accent icon. +- Home is a working page: what is owed to you, what you owe, cash, and the last documents, each a link to its screen. + +## What never happens + +- Nothing moves when data arrives or when a row is added: space is reserved first (law two of the build rules). +- No raw colours, sizes or stacking numbers in a screen's CSS: tokens only. +- No icon without `currentColor`, no icon library. diff --git a/internal/HASHOUT_LOG.md b/internal/HASHOUT_LOG.md index c5139dd..9af5876 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.8.0 +Current build version: v0.9.0 Last updated: 2026-11-27 (US Eastern) · profit and loss and the balance sheet --- @@ -1784,3 +1784,17 @@ There is no closing entry yet, so the balance sheet adds income minus expenses o - logged: v0.7.0 · 2026-11-27 `from` defaults to the first of January of `to`, not the fiscal year start, to keep the route free of the fiscal tables. The balance sheet query key is `as_of` as the brief names it, unlike the trial balance's `asOf`. + +### internal/snapshot/snapshot.go · Write +- refers-to: internal/snapshot/snapshot.go :: Write, writeMeta, writeCurrencies, copyRows; internal/snapshot/queries.go :: copies, docRefsSQL; internal/snapshot/command.go :: Main; cmd/formledger/main.go :: run (the report line) +- kind: rationale +- logged: v0.9.0 · 2026-11-27 + +The live side is one `ReadOnly` transaction on a single connection of the store's reader pool, so every table comes from the same WAL snapshot; rows are copied in Go into a second database opened on a hidden `.NAME.partPID` file with `journal_mode(DELETE)`, because the reader pool is `query_only` and cannot write an attached file. Each copy query returns exactly the listed columns in order and `copyRows` checks the count. Major-unit REAL columns are filled after the copy from `X_minor` and the snapshot's own `currencies.scale`, and quantities from `_milli`, so the SQL stays integer-only. Ledger lines take the same `posted, cancelled` filter as the trial balance and find their document through `COALESCE(reverses_id, id)`, so a reversal carries the cancelled document's number and party. Base currency is the currency most accounts use, since there is no setting for it; the time zone is the same fixed `America/New_York` that internal/reports uses. The command claims the data folder lock (`startup.Claim` with no shell) and refuses while a server holds it, because `store.Open` migrates and opens a writer; it sits at the top level as `report` because `cli` talks to a running server over HTTP. `user_version`, `ANALYZE` and `VACUUM` run after the copy commits and before the rename; the existence check runs twice so a file that appears meanwhile is not replaced without `--force`. + +### internal/export/module.go · build +- refers-to: internal/export/module.go :: specs, build, fetch, Mount; internal/export/writer.go :: table.add, safe, snake, isMoney; internal/export/command.go :: Command; internal/server/server.go :: Build (the export line); internal/cli/cli.go :: groups (the export line) +- kind: rationale +- 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. diff --git a/internal/app/version.go b/internal/app/version.go index 3ece448..0d54870 100644 --- a/internal/app/version.go +++ b/internal/app/version.go @@ -1,5 +1,5 @@ package app -var Version = "v0.8.0" +var Version = "v0.9.0" const Product = "FormLedger" diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 7f3f8d8..4c9b68a 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -7,6 +7,8 @@ import ( "fmt" "io" "strings" + + "github.com/nodemode-ai/formledger/internal/export" ) type env struct { @@ -49,6 +51,7 @@ func groups() []group { {"delivery", "delivery notes: stock out of a warehouse against a confirmed sales order", deliveryVerbs()}, {"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) }}}}, {"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/export/command.go b/internal/export/command.go new file mode 100644 index 0000000..51da5c2 --- /dev/null +++ b/internal/export/command.go @@ -0,0 +1,92 @@ +package export + +import ( + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "sort" + "strings" + "time" +) + +const Usage = "NAME [--out FILE] [--token-file FILE] [--PARAM VALUE]..." + +func Command(args []string, out io.Writer) error { + var name, file, tokenFile string + q := url.Values{} + for i := 0; i < len(args); i++ { + a := args[i] + if !strings.HasPrefix(a, "-") { + if name != "" { + return errors.New("name only one export") + } + name = 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 + default: + q.Set(k, v) + } + } + if _, ok := specs[name]; !ok { + names := Names() + sort.Strings(names) + return fmt.Errorf("name 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") + } + u := base + "/api/export/" + name + ".csv" + if len(q) > 0 { + u += "?" + q.Encode() + } + req, err := http.NewRequest(http.MethodGet, u, nil) + if err != nil { + return err + } + req.Header.Set("Authorization", "Bearer "+token) + resp, err := (&http.Client{Timeout: 5 * 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("export %s answered %d: %s", name, resp.StatusCode, strings.TrimSpace(string(body))) + } + if file == "" { + _, err = out.Write(body) + return err + } + return os.WriteFile(file, body, 0o644) +} diff --git a/internal/export/module.go b/internal/export/module.go new file mode 100644 index 0000000..40cbb88 --- /dev/null +++ b/internal/export/module.go @@ -0,0 +1,187 @@ +package export + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "strings" + + "github.com/nodemode-ai/formledger/internal/app" + "github.com/nodemode-ai/formledger/internal/httpx" + "github.com/nodemode-ai/formledger/internal/money" +) + +type spec struct { + path string + fixed map[string]string + rows string + parts bool + top []string +} + +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"}}, +} + +func Names() []string { + out := make([]string, 0, len(specs)) + for k := range specs { + out = append(out, k) + } + return out +} + +type module struct{} + +func Module() app.Module { return module{} } + +func (module) ID() string { return "export" } + +func (module) Mount(rt *httpx.Router, _ *app.Deps) error { + rt.HandleFunc("GET /api/export/{file}", func(w http.ResponseWriter, r *http.Request) { + name, ok := strings.CutSuffix(r.PathValue("file"), ".csv") + sp, known := specs[name] + if !ok || !known { + httpx.Error(w, http.StatusNotFound, "not_found", "no such export") + return + } + body, status, failure := build(rt.Handler(), r, sp) + if failure != nil { + h := w.Header() + h.Set("Content-Type", "application/json; charset=utf-8") + h.Set("Cache-Control", "no-store") + w.WriteHeader(status) + _, _ = w.Write(failure) + return + } + h := w.Header() + h.Set("Content-Type", "text/csv; charset=utf-8") + h.Set("Cache-Control", "no-store") + h.Set("Content-Disposition", `attachment; filename="`+name+"-"+Today()+`.csv"`) + w.WriteHeader(http.StatusOK) + _, _ = w.Write(body) + }) + return nil +} + +func fetch(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 +} + +func build(next http.Handler, r *http.Request, sp spec) ([]byte, int, []byte) { + q := url.Values{} + for k, v := range r.URL.Query() { + if k != "cursor" { + q[k] = v + } + } + for k, v := range sp.fixed { + if k == "limit" && q.Get("limit") != "" { + continue + } + q.Set(k, v) + } + t := newTable() + for pages := 0; pages < 100000; pages++ { + raw, status := fetch(next, r, sp.path, q) + if status != http.StatusOK { + return nil, status, raw + } + top, ok := ordered(raw) + if !ok { + return nil, http.StatusInternalServerError, errBody("the list did not answer an object") + } + cur := money.DefaultCurrency + var prefix []field + for _, k := range sp.top { + if v := lookup(top, k); v != nil { + prefix = append(prefix, field{k, v}) + if sub, ok := ordered(v); ok { + if c := lookup(sub, "currency"); c != nil { + var s string + if json.Unmarshal(c, &s) == nil && s != "" { + cur = s + } + } + } + } + } + if sp.parts { + for _, f := range top { + sec, ok := ordered(f.Raw) + if !ok || lookup(sec, "lines") == nil { + continue + } + var lines []json.RawMessage + _ = json.Unmarshal(lookup(sec, "lines"), &lines) + pre := append(append([]field(nil), prefix...), field{"section", lookup(sec, "type")}) + for _, l := range lines { + if row, ok := ordered(l); ok { + t.add(pre, row, cur) + } + } + } + } else { + var rows []json.RawMessage + _ = json.Unmarshal(lookup(top, sp.rows), &rows) + for _, l := range rows { + if row, ok := ordered(l); ok { + t.add(prefix, row, cur) + } + } + } + next := "" + for _, k := range []string{"nextCursor", "next"} { + if v := lookup(top, k); v != nil { + _ = json.Unmarshal(v, &next) + } + } + if next == "" { + break + } + 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") + } + return out, 0, nil +} + +func errBody(msg string) []byte { + var b bytes.Buffer + _ = json.NewEncoder(&b).Encode(map[string]any{"error": map[string]string{"code": "internal", "message": msg}}) + return b.Bytes() +} diff --git a/internal/export/writer.go b/internal/export/writer.go new file mode 100644 index 0000000..2bd03df --- /dev/null +++ b/internal/export/writer.go @@ -0,0 +1,209 @@ +package export + +import ( + "bytes" + "encoding/csv" + "encoding/json" + "strconv" + "strings" + "time" + "unicode" + + "github.com/nodemode-ai/formledger/internal/money" +) + +type field struct { + Key string + Raw json.RawMessage +} + +func ordered(raw json.RawMessage) ([]field, bool) { + dec := json.NewDecoder(bytes.NewReader(raw)) + dec.UseNumber() + t, err := dec.Token() + if err != nil || t != json.Delim('{') { + return nil, false + } + var out []field + for dec.More() { + k, err := dec.Token() + if err != nil { + return nil, false + } + var v json.RawMessage + if err := dec.Decode(&v); err != nil { + return nil, false + } + out = append(out, field{k.(string), v}) + } + return out, true +} + +func lookup(fs []field, key string) json.RawMessage { + for _, f := range fs { + if f.Key == key { + return f.Raw + } + } + return nil +} + +func snake(s string) string { + var b strings.Builder + rs := []rune(s) + for i, r := range rs { + if unicode.IsUpper(r) { + if i > 0 && (unicode.IsLower(rs[i-1]) || unicode.IsDigit(rs[i-1]) || (i+1 < len(rs) && unicode.IsLower(rs[i+1]))) { + b.WriteByte('_') + } + r = unicode.ToLower(r) + } else if i > 0 && unicode.IsDigit(r) != unicode.IsDigit(rs[i-1]) && unicode.IsLetter(rs[i-1]) != unicode.IsLetter(r) { + b.WriteByte('_') + } + b.WriteRune(r) + } + 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, +} + +func isMoney(key string) bool { + if moneyKeys[key] { + return true + } + l := strings.ToLower(key) + return strings.HasSuffix(l, "price") || strings.HasSuffix(l, "amount") +} + +var eastern = func() *time.Location { + loc, err := time.LoadLocation("America/New_York") + if err != nil { + return time.Local + } + return loc +}() + +func Today() string { return time.Now().In(eastern).Format("2006-01-02") } + +type cell struct { + text string + isText bool +} + +type table struct { + cols []string + 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 (t *table) add(prefix []field, row []field, currency string) { + out := map[string]cell{} + cur := currency + for _, f := range append(append([]field(nil), prefix...), row...) { + if f.Key == "currency" { + var s string + if json.Unmarshal(f.Raw, &s) == nil && s != "" { + cur = s + } + } + } + hasMoney := false + var put func(prefix string, fs []field) + put = func(p string, fs []field) { + for _, f := range fs { + name := p + snake(f.Key) + raw := bytes.TrimSpace(f.Raw) + if len(raw) == 0 { + continue + } + switch raw[0] { + case '[': + continue + case '{': + if sub, ok := ordered(raw); ok { + put(name+"_", sub) + } + continue + case 'n': + t.col(name) + out[name] = cell{} + case '"': + var s string + _ = json.Unmarshal(raw, &s) + t.col(name) + out[name] = cell{s, true} + case 't', 'f': + t.col(name) + out[name] = cell{string(raw), false} + default: + t.col(name) + n, err := strconv.ParseInt(string(raw), 10, 64) + switch { + case err == nil && strings.HasSuffix(f.Key, "At"): + 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 + out[name] = cell{money.Format(n, cur), false} + default: + out[name] = cell{string(raw), false} + } + } + } + } + put("", prefix) + put("", row) + if hasMoney { + t.col("currency") + if _, ok := out["currency"]; !ok { + out["currency"] = cell{cur, true} + } + } + t.rows = append(t.rows, out) +} + +func safe(c cell) string { + if c.isText && c.text != "" && strings.ContainsRune("=+-@", rune(c.text[0])) { + return "'" + c.text + } + return c.text +} + +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 { + 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]) + } + if err := w.Write(rec); err != nil { + return nil, err + } + } + w.Flush() + return buf.Bytes(), w.Error() +} diff --git a/internal/server/server.go b/internal/server/server.go index 12c55a8..e6d2139 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -13,6 +13,7 @@ import ( "github.com/nodemode-ai/formledger/internal/config" "github.com/nodemode-ai/formledger/internal/customers" "github.com/nodemode-ai/formledger/internal/delivery" + "github.com/nodemode-ai/formledger/internal/export" "github.com/nodemode-ai/formledger/internal/fiscal" "github.com/nodemode-ai/formledger/internal/invoicing" "github.com/nodemode-ai/formledger/internal/items" @@ -55,6 +56,7 @@ func Build(ctx context.Context, cfg config.Config, log *slog.Logger, st *store.S coa.Module(st, accounts), customers.Module(st, accounts), delivery.Module(st, accounts), + export.Module(), fiscal.Module(accounts), invoicing.Module(st, accounts), items.Module(accounts), diff --git a/internal/snapshot/command.go b/internal/snapshot/command.go new file mode 100644 index 0000000..7bf8f89 --- /dev/null +++ b/internal/snapshot/command.go @@ -0,0 +1,93 @@ +package snapshot + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "sort" + "time" + + "github.com/nodemode-ai/formledger/internal/config" + "github.com/nodemode-ai/formledger/internal/startup" + "github.com/nodemode-ai/formledger/internal/store" +) + +func Main(args []string, stdout, stderr io.Writer) int { + if len(args) == 0 || args[0] != "snapshot" { + fmt.Fprintln(stderr, "usage: formledger report snapshot [--out FILE] [--force]") + if len(args) == 0 { + return 2 + } + if args[0] == "help" || args[0] == "--help" || args[0] == "-h" { + return 0 + } + return 2 + } + fs := flag.NewFlagSet("report snapshot", flag.ContinueOnError) + fs.SetOutput(stderr) + out := fs.String("out", "", "file to write (default: formledger-snapshot-YYYY-MM-DD.sqlite in the current folder)") + force := fs.Bool("force", false, "replace the file if it exists") + if err := fs.Parse(args[1:]); err != nil { + return 2 + } + cfg, err := config.Load() + if err != nil { + fmt.Fprintln(stderr, "formledger: config:", err) + return 2 + } + if !store.HasData(cfg.DataDir) { + fmt.Fprintf(stderr, "formledger: no ledger in %s\n", cfg.DataDir) + return 1 + } + release, _, err := startup.Claim(cfg.DataDir, 0) + if err != nil { + var held *startup.Busy + if errors.As(err, &held) { + fmt.Fprintln(stderr, "formledger:", held.Error(), "Stop it, then write the snapshot.") + return 2 + } + fmt.Fprintln(stderr, "formledger: data directory:", err) + return 1 + } + defer release() + ctx := context.Background() + st, err := store.Open(ctx, cfg.DataDir) + if err != nil { + fmt.Fprintln(stderr, "formledger: storage:", err) + return 1 + } + defer st.Close() + now := time.Now() + path := *out + if path == "" { + path = "formledger-snapshot-" + localDate(now) + ".sqlite" + } + res, err := Write(ctx, st, path, Options{Force: *force, Now: now}) + if err != nil { + fmt.Fprintln(stderr, "formledger:", err) + if errors.Is(err, ErrExists) { + return 2 + } + return 1 + } + names := make([]string, 0, len(res.Tables)) + for k := range res.Tables { + names = append(names, k) + } + sort.Strings(names) + fmt.Fprintf(stdout, "wrote %s (schema %d)\n", res.Path, SchemaVersion) + for _, k := range names { + fmt.Fprintf(stdout, " %-16s %d rows\n", k, res.Tables[k]) + } + return 0 +} + +func localDate(t time.Time) string { + loc, err := time.LoadLocation(TimeZone) + if err != nil { + loc = time.Local + } + return t.In(loc).Format("2006-01-02") +} diff --git a/internal/snapshot/queries.go b/internal/snapshot/queries.go new file mode 100644 index 0000000..213040a --- /dev/null +++ b/internal/snapshot/queries.go @@ -0,0 +1,133 @@ +package snapshot + +type copySpec struct { + table string + columns string + query string +} + +const docRefsSQL = ` +WITH refs(je, doc_type, number, party_kind, party_id) AS ( + SELECT journal_entry_id, 'sales_' || kind, number, 'customer', customer_id FROM sales_docs WHERE journal_entry_id IS NOT NULL + UNION ALL SELECT journal_entry_id, 'purchase_' || kind, number, 'supplier', supplier_id FROM purchase_docs WHERE journal_entry_id IS NOT NULL + UNION ALL SELECT journal_entry_id, 'payment_received', number, 'customer', customer_id FROM payments WHERE journal_entry_id IS NOT NULL + UNION ALL SELECT journal_entry_id, 'payment_made', number, 'supplier', supplier_id FROM payments_made WHERE journal_entry_id IS NOT NULL + UNION ALL SELECT journal_entry_id, 'delivery_note', number, 'customer', customer_id FROM delivery_notes WHERE journal_entry_id IS NOT NULL +)` + +const partyNameSQL = `CASE r.party_kind WHEN 'customer' THEN c.code ELSE s.code END, + 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", ` +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 +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", ` +SELECT y.name, p.name, p.start_date, p.end_date, p.status +FROM periods p JOIN fiscal_years y ON y.id = p.fiscal_year_id ORDER BY p.start_date`}, + + {"warehouses", "code, name, active", `SELECT code, name, active FROM warehouses ORDER BY code`}, + + {"parties", "kind, code, name, email, phone, address, tax_id, currency, account_code, payment_terms_days, active", ` +SELECT 'customer', c.code, c.name, c.email, c.phone, c.address, c.tax_id, c.currency, a.code, c.payment_terms_days, c.active +FROM customers c JOIN accounts a ON a.id = c.receivable_account_id +UNION ALL +SELECT 'supplier', s.code, s.name, s.email, s.phone, s.address, s.tax_id, s.currency, a.code, s.payment_terms_days, s.active +FROM suppliers s JOIN accounts a ON a.id = s.payable_account_id +ORDER BY 1, 2`}, + + {"items", "code, name, description, unit, currency, sale_price_minor, purchase_price_minor, income_account_code, tax_code, tax_rate_percent, stocked, inventory_account_code, cogs_account_code, active", ` +SELECT i.code, i.name, i.description, i.unit, i.currency, i.sale_price, st.purchase_price, ia.code, t.code, + CASE WHEN t.rate_bp IS NULL THEN NULL ELSE t.rate_bp / 100.0 END, + COALESCE(st.stocked, 0), inv.code, cg.code, i.active +FROM items i +JOIN accounts ia ON ia.id = i.income_account_id +LEFT JOIN tax_rates t ON t.id = i.tax_rate_id +LEFT JOIN item_stock st ON st.item_id = i.id +LEFT JOIN accounts inv ON inv.id = st.inventory_account_id +LEFT JOIN accounts cg ON cg.id = st.cogs_account_id +ORDER BY i.code`}, + + {"ledger_lines", "entry_number, entry_date, month, fiscal_year, period, line_no, account_code, account_name, account_type, doc_type, doc_number, party_kind, party_code, party_name, description, currency, debit_minor, credit_minor, amount_minor, entry_status, is_reversal", docRefsSQL + ` +SELECT e.number, e.entry_date, substr(e.entry_date, 1, 7), y.name, p.name, l.line_no, + a.code, a.name, a.type, COALESCE(r.doc_type, 'journal'), COALESCE(r.number, o.number, e.number), r.party_kind, ` + partyNameSQL + `, + COALESCE(NULLIF(l.memo, ''), e.memo), e.currency, l.debit, l.credit, l.debit - l.credit, + e.status, CASE WHEN e.reverses_id IS NULL THEN 0 ELSE 1 END +FROM journal_lines l +JOIN journal_entries e ON e.id = l.entry_id +JOIN accounts a ON a.id = l.account_id +LEFT JOIN periods p ON p.id = e.period_id +LEFT JOIN fiscal_years y ON y.id = p.fiscal_year_id +LEFT JOIN journal_entries o ON o.id = e.reverses_id +LEFT JOIN refs r ON r.je = COALESCE(e.reverses_id, e.id) +LEFT JOIN customers c ON r.party_kind = 'customer' AND c.id = r.party_id +LEFT JOIN suppliers s ON r.party_kind = 'supplier' AND s.id = r.party_id +WHERE e.status IN ('posted', 'cancelled') +ORDER BY e.entry_date, e.number, l.line_no`}, + + {"documents", "doc_id, doc_type, number, doc_date, month, due_date, party_kind, party_code, party_name, warehouse_code, source_number, status, currency, subtotal_minor, tax_total_minor, total_minor, memo", ` +SELECT d.id, 'sales_' || d.kind, d.number, d.doc_date, substr(d.doc_date, 1, 7), d.due_date, 'customer', c.code, c.name, + NULL, src.number, d.status, d.currency, d.subtotal, d.tax_total, d.total, d.memo +FROM sales_docs d JOIN customers c ON c.id = d.customer_id LEFT JOIN sales_docs src ON src.id = d.source_id +UNION ALL +SELECT d.id, 'purchase_' || d.kind, d.number, d.doc_date, substr(d.doc_date, 1, 7), d.due_date, 'supplier', s.code, s.name, + w.code, src.number, d.status, d.currency, d.subtotal, d.tax_total, d.total, d.memo +FROM purchase_docs d JOIN suppliers s ON s.id = d.supplier_id LEFT JOIN purchase_docs src ON src.id = d.source_id +LEFT JOIN warehouses w ON w.id = d.warehouse_id +UNION ALL +SELECT n.id, 'delivery_note', n.number, n.doc_date, substr(n.doc_date, 1, 7), NULL, 'customer', c.code, c.name, + w.code, o.number, n.status, o.currency, COALESCE(v.value, 0), 0, COALESCE(v.value, 0), n.memo +FROM delivery_notes n JOIN customers c ON c.id = n.customer_id JOIN warehouses w ON w.id = n.warehouse_id +JOIN sales_docs o ON o.id = n.sales_order_id +LEFT JOIN (SELECT note_id, SUM(value) AS value FROM delivery_lines GROUP BY note_id) v ON v.note_id = n.id +ORDER BY 4, 2, 3`}, + + {"document_lines", "doc_id, doc_type, doc_number, doc_date, month, status, party_kind, party_code, line_no, item_code, item_name, description, account_code, tax_code, currency, quantity_milli, unit_price_minor, line_subtotal_minor, line_tax_minor, line_total_minor", ` +SELECT d.id, 'sales_' || d.kind, d.number, d.doc_date, substr(d.doc_date, 1, 7), d.status, 'customer', c.code, l.line_no, + i.code, i.name, l.description, a.code, t.code, d.currency, l.quantity_milli, l.unit_price, l.line_subtotal, l.line_tax, l.line_total +FROM sales_lines l JOIN sales_docs d ON d.id = l.doc_id JOIN customers c ON c.id = d.customer_id +LEFT JOIN items i ON i.id = l.item_id LEFT JOIN accounts a ON a.id = l.income_account_id LEFT JOIN tax_rates t ON t.id = l.tax_rate_id +UNION ALL +SELECT d.id, 'purchase_' || d.kind, d.number, d.doc_date, substr(d.doc_date, 1, 7), d.status, 'supplier', s.code, l.line_no, + i.code, i.name, l.description, a.code, t.code, d.currency, l.quantity_milli, l.unit_price, l.line_subtotal, l.line_tax, l.line_total +FROM purchase_lines l JOIN purchase_docs d ON d.id = l.doc_id JOIN suppliers s ON s.id = d.supplier_id +LEFT JOIN items i ON i.id = l.item_id LEFT JOIN accounts a ON a.id = l.expense_account_id LEFT JOIN tax_rates t ON t.id = l.tax_rate_id +UNION ALL +SELECT n.id, 'delivery_note', n.number, n.doc_date, substr(n.doc_date, 1, 7), n.status, 'customer', c.code, l.line_no, + i.code, i.name, l.description, NULL, NULL, o.currency, l.quantity_milli, l.unit_cost, l.value, 0, l.value +FROM delivery_lines l JOIN delivery_notes n ON n.id = l.note_id JOIN customers c ON c.id = n.customer_id +JOIN sales_docs o ON o.id = n.sales_order_id JOIN items i ON i.id = l.item_id +ORDER BY 4, 1, 9`}, + + {"payments", "payment_id, direction, number, pay_date, month, party_kind, party_code, party_name, account_code, status, currency, amount_minor, allocated_minor, unallocated_minor, memo", ` +SELECT p.id, 'received', p.number, p.pay_date, substr(p.pay_date, 1, 7), 'customer', c.code, c.name, a.code, p.status, p.currency, + p.amount, COALESCE(al.amount, 0), p.amount - COALESCE(al.amount, 0), p.memo +FROM payments p JOIN customers c ON c.id = p.customer_id JOIN accounts a ON a.id = p.deposit_account_id +LEFT JOIN (SELECT payment_id, SUM(amount) AS amount FROM payment_allocations GROUP BY payment_id) al ON al.payment_id = p.id +UNION ALL +SELECT p.id, 'made', p.number, p.pay_date, substr(p.pay_date, 1, 7), 'supplier', s.code, s.name, a.code, p.status, p.currency, + p.amount, COALESCE(al.amount, 0), p.amount - COALESCE(al.amount, 0), p.memo +FROM payments_made p JOIN suppliers s ON s.id = p.supplier_id JOIN accounts a ON a.id = p.paid_from_account_id +LEFT JOIN (SELECT payment_id, SUM(amount) AS amount FROM payment_made_allocations GROUP BY payment_id) al ON al.payment_id = p.id +ORDER BY 4, 3`}, + + {"allocations", "direction, payment_id, payment_number, payment_status, pay_date, invoice_id, invoice_number, party_kind, party_code, currency, amount_minor", ` +SELECT 'received', p.id, p.number, p.status, p.pay_date, d.id, d.number, 'customer', c.code, p.currency, x.amount +FROM payment_allocations x JOIN payments p ON p.id = x.payment_id JOIN sales_docs d ON d.id = x.invoice_id JOIN customers c ON c.id = p.customer_id +UNION ALL +SELECT 'made', p.id, p.number, p.status, p.pay_date, d.id, d.number, 'supplier', s.code, p.currency, x.amount +FROM payment_made_allocations x JOIN payments_made p ON p.id = x.payment_id JOIN purchase_docs d ON d.id = x.invoice_id JOIN suppliers s ON s.id = p.supplier_id +ORDER BY 5, 3`}, + + {"stock_moves", "seq, move_date, month, item_code, item_name, warehouse_code, warehouse_name, source_kind, source_number, is_reversal, currency, quantity_milli, unit_cost_minor, value_minor", ` +SELECT m.seq, m.move_date, substr(m.move_date, 1, 7), i.code, i.name, w.code, w.name, m.source_kind, + COALESCE(pd.number, dn.number, sd.number), + CASE WHEN m.reverses_id IS NULL THEN 0 ELSE 1 END, i.currency, m.qty_milli, m.unit_cost, m.value +FROM stock_moves m JOIN items i ON i.id = m.item_id JOIN warehouses w ON w.id = m.warehouse_id +LEFT JOIN purchase_docs pd ON pd.id = m.source_id +LEFT JOIN delivery_notes dn ON dn.id = m.source_id +LEFT JOIN sales_docs sd ON sd.id = m.source_id +ORDER BY m.seq`}, +} diff --git a/internal/snapshot/schema.go b/internal/snapshot/schema.go new file mode 100644 index 0000000..298a1ee --- /dev/null +++ b/internal/snapshot/schema.go @@ -0,0 +1,239 @@ +package snapshot + +const SchemaVersion = 1 + +const schemaSQL = ` +CREATE TABLE meta ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL +); + +CREATE TABLE currencies ( + code TEXT PRIMARY KEY, + exponent INTEGER NOT NULL, + scale INTEGER NOT NULL +); + +CREATE TABLE accounts ( + code TEXT PRIMARY KEY, + name TEXT NOT NULL, + type TEXT NOT NULL, + normal_side TEXT NOT NULL, + parent_code TEXT, + is_group INTEGER NOT NULL, + currency TEXT NOT NULL, + active INTEGER NOT NULL +); + +CREATE TABLE fiscal_periods ( + fiscal_year TEXT NOT NULL, + period TEXT NOT NULL, + start_date TEXT NOT NULL, + end_date TEXT NOT NULL, + status TEXT NOT NULL, + PRIMARY KEY (fiscal_year, period) +); + +CREATE TABLE warehouses ( + code TEXT PRIMARY KEY, + name TEXT NOT NULL, + active INTEGER NOT NULL +); + +CREATE TABLE parties ( + kind TEXT NOT NULL, + code TEXT NOT NULL, + name TEXT NOT NULL, + email TEXT NOT NULL, + phone TEXT NOT NULL, + address TEXT NOT NULL, + tax_id TEXT NOT NULL, + currency TEXT NOT NULL, + account_code TEXT NOT NULL, + payment_terms_days INTEGER NOT NULL, + active INTEGER NOT NULL, + PRIMARY KEY (kind, code) +); + +CREATE TABLE items ( + code TEXT PRIMARY KEY, + name TEXT NOT NULL, + description TEXT NOT NULL, + unit TEXT NOT NULL, + currency TEXT NOT NULL, + sale_price REAL, + sale_price_minor INTEGER NOT NULL, + purchase_price REAL, + purchase_price_minor INTEGER, + income_account_code TEXT NOT NULL, + tax_code TEXT, + tax_rate_percent REAL, + stocked INTEGER NOT NULL, + inventory_account_code TEXT, + cogs_account_code TEXT, + active INTEGER NOT NULL +); + +CREATE TABLE ledger_lines ( + entry_number TEXT, + entry_date TEXT NOT NULL, + month TEXT NOT NULL, + fiscal_year TEXT, + period TEXT, + line_no INTEGER NOT NULL, + account_code TEXT NOT NULL, + account_name TEXT NOT NULL, + account_type TEXT NOT NULL, + doc_type TEXT NOT NULL, + doc_number TEXT, + party_kind TEXT, + party_code TEXT, + party_name TEXT, + description TEXT NOT NULL, + currency TEXT NOT NULL, + debit REAL, + credit REAL, + amount REAL, + debit_minor INTEGER NOT NULL, + credit_minor INTEGER NOT NULL, + amount_minor INTEGER NOT NULL, + entry_status TEXT NOT NULL, + is_reversal INTEGER NOT NULL +); + +CREATE TABLE documents ( + doc_id TEXT PRIMARY KEY, + doc_type TEXT NOT NULL, + number TEXT, + doc_date TEXT NOT NULL, + month TEXT NOT NULL, + due_date TEXT, + party_kind TEXT NOT NULL, + party_code TEXT NOT NULL, + party_name TEXT NOT NULL, + warehouse_code TEXT, + source_number TEXT, + status TEXT NOT NULL, + currency TEXT NOT NULL, + subtotal REAL, + tax_total REAL, + total REAL, + subtotal_minor INTEGER NOT NULL, + tax_total_minor INTEGER NOT NULL, + total_minor INTEGER NOT NULL, + memo TEXT NOT NULL +); + +CREATE TABLE document_lines ( + doc_id TEXT NOT NULL, + doc_type TEXT NOT NULL, + doc_number TEXT, + doc_date TEXT NOT NULL, + month TEXT NOT NULL, + status TEXT NOT NULL, + party_kind TEXT NOT NULL, + party_code TEXT NOT NULL, + line_no INTEGER NOT NULL, + item_code TEXT, + item_name TEXT, + description TEXT NOT NULL, + account_code TEXT, + tax_code TEXT, + currency TEXT NOT NULL, + quantity REAL, + quantity_milli INTEGER NOT NULL, + unit_price REAL, + line_subtotal REAL, + line_tax REAL, + line_total REAL, + unit_price_minor INTEGER NOT NULL, + line_subtotal_minor INTEGER NOT NULL, + line_tax_minor INTEGER NOT NULL, + line_total_minor INTEGER NOT NULL, + PRIMARY KEY (doc_id, line_no) +); + +CREATE TABLE payments ( + payment_id TEXT PRIMARY KEY, + direction TEXT NOT NULL, + number TEXT, + pay_date TEXT NOT NULL, + month TEXT NOT NULL, + party_kind TEXT NOT NULL, + party_code TEXT NOT NULL, + party_name TEXT NOT NULL, + account_code TEXT NOT NULL, + status TEXT NOT NULL, + currency TEXT NOT NULL, + amount REAL, + allocated REAL, + unallocated REAL, + amount_minor INTEGER NOT NULL, + allocated_minor INTEGER NOT NULL, + unallocated_minor INTEGER NOT NULL, + memo TEXT NOT NULL +); + +CREATE TABLE allocations ( + direction TEXT NOT NULL, + payment_id TEXT NOT NULL, + payment_number TEXT, + payment_status TEXT NOT NULL, + pay_date TEXT NOT NULL, + invoice_id TEXT NOT NULL, + invoice_number TEXT, + party_kind TEXT NOT NULL, + party_code TEXT NOT NULL, + currency TEXT NOT NULL, + amount REAL, + amount_minor INTEGER NOT NULL +); + +CREATE TABLE stock_moves ( + seq INTEGER PRIMARY KEY, + move_date TEXT NOT NULL, + month TEXT NOT NULL, + item_code TEXT NOT NULL, + item_name TEXT NOT NULL, + warehouse_code TEXT NOT NULL, + warehouse_name TEXT NOT NULL, + source_kind TEXT NOT NULL, + source_number TEXT, + is_reversal INTEGER NOT NULL, + currency TEXT NOT NULL, + quantity REAL, + quantity_milli INTEGER NOT NULL, + unit_cost REAL, + value REAL, + unit_cost_minor INTEGER NOT NULL, + value_minor INTEGER NOT NULL +); + +CREATE INDEX ledger_lines_date ON ledger_lines (entry_date); +CREATE INDEX ledger_lines_account ON ledger_lines (account_code, entry_date); +CREATE INDEX ledger_lines_month ON ledger_lines (month, account_code); +CREATE INDEX ledger_lines_party ON ledger_lines (party_kind, party_code); +CREATE INDEX documents_date ON documents (doc_date); +CREATE INDEX documents_party ON documents (party_kind, party_code); +CREATE INDEX document_lines_date ON document_lines (doc_date); +CREATE INDEX document_lines_item ON document_lines (item_code); +CREATE INDEX payments_date ON payments (pay_date); +CREATE INDEX allocations_invoice ON allocations (invoice_id); +CREATE INDEX stock_moves_date ON stock_moves (move_date); +CREATE INDEX stock_moves_item ON stock_moves (item_code, warehouse_code); +` + +var majorColumns = map[string][]string{ + "items": {"sale_price", "purchase_price"}, + "ledger_lines": {"debit", "credit", "amount"}, + "documents": {"subtotal", "tax_total", "total"}, + "document_lines": {"unit_price", "line_subtotal", "line_tax", "line_total"}, + "payments": {"amount", "allocated", "unallocated"}, + "allocations": {"amount"}, + "stock_moves": {"unit_cost", "value"}, +} + +var quantityColumns = map[string]string{ + "document_lines": "quantity", + "stock_moves": "quantity", +} diff --git a/internal/snapshot/snapshot.go b/internal/snapshot/snapshot.go new file mode 100644 index 0000000..2fd64bd --- /dev/null +++ b/internal/snapshot/snapshot.go @@ -0,0 +1,259 @@ +package snapshot + +import ( + "context" + "database/sql" + "errors" + "fmt" + "os" + "path/filepath" + "strconv" + "strings" + "time" + + "github.com/nodemode-ai/formledger/internal/app" + "github.com/nodemode-ai/formledger/internal/money" + "github.com/nodemode-ai/formledger/internal/store" +) + +const TimeZone = "America/New_York" + +var ErrExists = errors.New("snapshot: the file already exists; pass --force to replace it") + +type Options struct { + Force bool + Now time.Time +} + +type Result struct { + Path string + Tables map[string]int64 +} + +func Write(ctx context.Context, st *store.Store, path string, opts Options) (Result, error) { + res := Result{Path: path, Tables: map[string]int64{}} + abs, err := filepath.Abs(path) + if err != nil { + return res, err + } + res.Path = abs + if same, _ := filepath.Abs(st.Path); same == abs { + return res, errors.New("snapshot: the snapshot cannot replace the live database") + } + if _, err := os.Stat(abs); err == nil && !opts.Force { + return res, ErrExists + } + tmp := filepath.Join(filepath.Dir(abs), "."+filepath.Base(abs)+".part"+strconv.Itoa(os.Getpid())) + cleanup := func() { + for _, s := range []string{"", "-journal", "-wal", "-shm"} { + os.Remove(tmp + s) + } + } + cleanup() + defer cleanup() + + conn, err := st.R.Conn(ctx) + if err != nil { + return res, err + } + defer conn.Close() + src, err := conn.BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) + if err != nil { + return res, err + } + defer src.Rollback() + + dst, err := sql.Open("sqlite", tmp+"?_pragma=journal_mode(DELETE)&_pragma=synchronous(FULL)") + if err != nil { + return res, err + } + defer dst.Close() + dst.SetMaxOpenConns(1) + if _, err := dst.ExecContext(ctx, schemaSQL); err != nil { + return res, fmt.Errorf("snapshot schema: %w", err) + } + out, err := dst.BeginTx(ctx, nil) + if err != nil { + return res, err + } + defer out.Rollback() + + if err := writeMeta(ctx, src, out, opts.Now); err != nil { + return res, err + } + for _, c := range copies { + n, err := copyRows(ctx, src, out, c) + if err != nil { + return res, fmt.Errorf("snapshot %s: %w", c.table, err) + } + res.Tables[c.table] = n + } + if err := writeCurrencies(ctx, out); err != nil { + return res, err + } + for table, cols := range majorColumns { + for _, col := range cols { + q := fmt.Sprintf(`UPDATE %s SET %s = %s_minor * 1.0 / (SELECT scale FROM currencies WHERE code = %s.currency) WHERE %s_minor IS NOT NULL`, table, col, col, table, col) + if _, err := out.ExecContext(ctx, q); err != nil { + return res, fmt.Errorf("snapshot %s.%s: %w", table, col, err) + } + } + } + for table, col := range quantityColumns { + if _, err := out.ExecContext(ctx, fmt.Sprintf(`UPDATE %s SET %s = %s_milli / 1000.0`, table, col, col)); err != nil { + return res, err + } + } + for _, t := range []string{"meta", "currencies"} { + var n int64 + if err := out.QueryRowContext(ctx, "SELECT count(*) FROM "+t).Scan(&n); err != nil { + return res, err + } + res.Tables[t] = n + } + if err := out.Commit(); err != nil { + return res, err + } + if err := src.Rollback(); err != nil && !errors.Is(err, sql.ErrTxDone) { + return res, err + } + for _, q := range []string{"PRAGMA user_version = " + strconv.Itoa(SchemaVersion), "ANALYZE", "VACUUM", "PRAGMA journal_mode = DELETE"} { + if _, err := dst.ExecContext(ctx, q); err != nil { + return res, fmt.Errorf("snapshot %s: %w", q, err) + } + } + if err := dst.Close(); err != nil { + return res, err + } + if err := os.Chmod(tmp, 0o600); err != nil { + return res, err + } + if !opts.Force { + if _, err := os.Stat(abs); err == nil { + return res, ErrExists + } + } + if err := os.Rename(tmp, abs); err != nil { + return res, err + } + return res, nil +} + +func writeMeta(ctx context.Context, src *sql.Tx, out *sql.Tx, now time.Time) error { + if now.IsZero() { + now = time.Now() + } + loc, err := time.LoadLocation(TimeZone) + if err != nil { + loc = time.Local + } + local := now.In(loc) + company := "FormLedger" + var v string + if err := src.QueryRowContext(ctx, `SELECT value FROM settings WHERE key = 'instance.name'`).Scan(&v); err == nil && strings.TrimSpace(v) != "" { + company = v + } else if err != nil && !errors.Is(err, sql.ErrNoRows) { + return err + } + base := "" + if err := src.QueryRowContext(ctx, `SELECT currency FROM accounts GROUP BY currency ORDER BY count(*) DESC, currency LIMIT 1`).Scan(&base); err != nil && !errors.Is(err, sql.ErrNoRows) { + return err + } + var ledgerVersion int + if err := src.QueryRowContext(ctx, `SELECT COALESCE(MAX(version), 0) FROM schema_migrations`).Scan(&ledgerVersion); err != nil { + ledgerVersion = store.LatestMigration() + } + rows := [][2]string{ + {"schema_version", strconv.Itoa(SchemaVersion)}, + {"app_name", app.Product}, + {"app_version", app.Version}, + {"ledger_schema", strconv.Itoa(ledgerVersion)}, + {"company_name", company}, + {"base_currency", base}, + {"time_zone", loc.String()}, + {"created_at", local.Format("2006-01-02 15:04:05 MST")}, + {"created_at_iso", local.Format(time.RFC3339)}, + {"created_at_utc", now.UTC().Format(time.RFC3339)}, + {"money_rule", "*_minor columns are exact integers in minor units; the matching column without _minor is minor / currencies.scale"}, + } + for _, r := range rows { + if _, err := out.ExecContext(ctx, `INSERT INTO meta (key, value) VALUES (?, ?)`, r[0], r[1]); err != nil { + return err + } + } + return nil +} + +func writeCurrencies(ctx context.Context, out *sql.Tx) error { + rows, err := out.QueryContext(ctx, ` +SELECT currency FROM accounts UNION SELECT currency FROM items UNION SELECT currency FROM parties +UNION SELECT currency FROM ledger_lines UNION SELECT currency FROM documents UNION SELECT currency FROM payments +UNION SELECT value FROM meta WHERE key = 'base_currency' AND value <> ''`) + if err != nil { + return err + } + var codes []string + for rows.Next() { + var c string + if err := rows.Scan(&c); err != nil { + rows.Close() + return err + } + codes = append(codes, c) + } + rows.Close() + if err := rows.Err(); err != nil { + return err + } + for _, c := range codes { + exp, ok := money.Exponent(c) + if !ok { + return fmt.Errorf("snapshot: unknown currency %q", c) + } + scale := int64(1) + for range exp { + scale *= 10 + } + if _, err := out.ExecContext(ctx, `INSERT INTO currencies (code, exponent, scale) VALUES (?, ?, ?)`, c, exp, scale); err != nil { + return err + } + } + return nil +} + +func copyRows(ctx context.Context, src *sql.Tx, out *sql.Tx, c copySpec) (int64, error) { + rows, err := src.QueryContext(ctx, c.query) + if err != nil { + return 0, err + } + defer rows.Close() + cols, err := rows.Columns() + if err != nil { + return 0, err + } + want := strings.Count(c.columns, ",") + 1 + if len(cols) != want { + return 0, fmt.Errorf("query gives %d columns, table takes %d", len(cols), want) + } + ins, err := out.PrepareContext(ctx, fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", c.table, c.columns, strings.TrimSuffix(strings.Repeat("?, ", want), ", "))) + if err != nil { + return 0, err + } + defer ins.Close() + vals := make([]any, want) + ptrs := make([]any, want) + for i := range vals { + ptrs[i] = &vals[i] + } + var n int64 + for rows.Next() { + if err := rows.Scan(ptrs...); err != nil { + return n, err + } + if _, err := ins.ExecContext(ctx, vals...); err != nil { + return n, err + } + n++ + } + return n, rows.Err() +} diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 954b1ba..bd92fbe 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1106,7 +1106,7 @@ dependencies = [ [[package]] name = "formledger-desktop" -version = "0.8.0" +version = "0.9.0" dependencies = [ "objc2", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index c60503d..0dbb27d 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formledger-desktop" -version = "0.8.0" +version = "0.9.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 37e44a8..f994430 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.8.0 +Current build version: v0.9.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/tauri.conf.json b/src-tauri/tauri.conf.json index 00a3fc9..46f69c5 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "FormLedger", "mainBinaryName": "formledger-desktop", - "version": "0.8.0", + "version": "0.9.0", "identifier": "ai.nodemode.formledger", "build": { "frontendDist": "splash" }, "app": { diff --git a/web/HASHOUT_LOG.md b/web/HASHOUT_LOG.md index 9309442..b5418f9 100644 --- a/web/HASHOUT_LOG.md +++ b/web/HASHOUT_LOG.md @@ -2,7 +2,7 @@ Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the web client. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of the web side: read it first, then edit code surgically. -Current build version: v0.8.0 +Current build version: v0.9.0 Last updated: 2026-11-26 (US Eastern) · account screens, and the fixes from the throttled browser check --- @@ -621,3 +621,38 @@ Each invoice load takes its own number and only the latest may write rows, and a - logged: v0.8.0 · 2026-11-27 The count beside Load more went from empty to "114 shown, more to load", and the button after it moved sideways on every page (0.00063 then 0.00035 per load, sources the button, 0.0011 to 0.0013 over a list). The count now has a fixed 24ch box, right aligned, so the button stays put: 0.0 on quotes, sales orders and purchase orders afterwards, 0.0001 on the invoice lists from the form's buttons, not from the list. The 0.09 seen on delivery notes and goods receipts is the filler row on their forms, not on the lists. + +### src/ui/parts/table.ts · badges, grow and the fill page +- refers-to: src/ui/parts/table.ts :: statusTone, writeCell, grow, mono; src/styles/parts.css :: .page--fill, .page__head, .bar, .badge, .tbl--grow, .tbl__empty; src/ui/views/doclists.ts :: listView +- kind: rationale +- logged: v0.8.0 · 2026-11-27 + +A column tone of `muted` or `danger` still colours the cell as before (ledger screens and statements use them); any other tone value renders a `span.badge` whose `data-tone` is `statusTone(value)`, written in place on patch, so payments' status column turned into badges with no change there. The shell mounts each view into `.page > h1 + .page__body`, so a `.page--fill` mounted into the body makes the page, body and section fill the sheet through `:has`, and a `.page__head` without its own title is lifted into the title row by one control height plus the gap: the New button sits beside the shell's title without a second heading. The lists show "N shown" because the list API returns no total. Rows can differ in currency (each document has its own), so the code stays per row, in a muted mono `Cur` column, and the amount column holds digits only. Measured on a 130 invoice copy at 1400 by 900, CPU 4x, 400 ms and 50 kB/s: table box 720px tall with 100 rows of 30px scrolling inside, load more added exactly 30 rows, filter to cancelled showed 14, layout shift 0 without input and 0 with input on first paint, load more and filter; the trial balance kept 30px rows and its totals at the foot. + +### src/ui/parts/linegrid.ts · the document form fills the window +- refers-to: src/ui/parts/linegrid.ts :: flagMissing, idle, emit; src/ui/views/docform.ts :: save, TONES; src/styles/views/docform.css :: .df, .df-number, .df-actions; src/styles/views/grid.css :: .grid__scroll, .grid__row, .grid__totals +- kind: rationale +- logged: v0.8.0 · 2026-11-27 + +The form is one fixed-height grid (`100dvh` less the top bar, page padding and the shell title, never under sixteen rows) and the line box takes what is left, so the header, totals and actions never move and only the lines scroll: at 1400 by 900 that is eight lines visible instead of a box that pushed the actions off screen. The subtotal and tax amount cells stay in the DOM but sit in zero-width hidden columns, so `setTotals` and the row shape are unchanged; the amount column is the line's net (quantity times price while typing, the server's subtotal once saved) so it adds up to the subtotal under it. The number has a fixed 34ch box and both totals columns are a fixed amount width: with `auto` the badge and the totals moved on post (0.00041, sources `.df-status` and `.grid__totals`), now 0. Actions keep DOM order save, post, cancel, amend for the exit run and are reordered by CSS `order` only. A line counts as typed once its quantity or price is edited; a typed line with no item and no description is no longer dropped by `collect` but stops the save, rings the item cell and names the line in `.df-error`. Measured on a private copy at CPU 4x, 400 ms and 50 kB/s after a hard reload: twenty lines by keyboard, 20 of 20 held their item, posted as SI-2026-000001 with 20 lines through the API, total 675.00, layout shift 0 with and 0 without input on load, entry and post. + +### src/ui/views/ledger-screens.ts · table box from its container, statements as a sheet +- refers-to: src/ui/views/ledger-screens.ts :: shell, mark; src/styles/views/ledger-screens.css :: .ls__table, --tbl-block; src/ui/views/statements.ts :: mountSection, mountShell; src/styles/views/statements.css :: .st__sheet, .st__result +- kind: rationale +- logged: v0.8.0 · 2026-11-27 + +The old 250px `--ls-above` guess is gone: the last child of the page is `.ls__table`, a size container, and the table inside takes `--tbl-block: max(6 rows, 100cqb)`, so the fixed-height totals table fills whatever the page gives it. The general ledger puts the opening balance in as the first row and closing in the foot; the ageing foot colours the 1 to 30 through over 90 columns in the warn tone by column position. The trial balance and stock screens show a balanced or agrees badge in a reserved 18ch slot in the bar. The two statements no longer use the table: each is a sheet (heading, indented lines, medium subtotal) in a scrolling box with the one large result pinned under it; the result value has a fixed 14ch box because it grew from 0.00 and shifted by 0.0001. Measured at 1400 by 900 with 45 invoices and 25 bills, plain and at CPU 4x with 400 ms and 50 kB/s: layout shift 0 on all seven screens without input. + +### src/ui/app.ts · home tiles and recent invoices +- refers-to: src/ui/app.ts :: mountHome, tile, recentBlock; src/styles/shell.css :: .home--dash, .tiles, .recent; src/ui/views.ts :: mountViews; src/styles/account.css :: .who +- kind: rationale +- logged: v0.8.0 · 2026-11-27 + +Home replaces the index.html placeholder once at start with three tiles and two five-row invoice lists, all at final size: the tile value row is a fixed `--space-8`, the lists are five `--row` rows built idle and only written into. Owed to you is the customers total of `/api/receivables/reconcile`, you owe is the suppliers total of `/api/payables/reconcile`, cash is the sum of leaf asset accounts in `/api/reports/balances` whose name holds cash or bank (the chart has no cash flag). Data reloads each time Home is shown; a sequence number stops an old load from writing the lists. Screens now get a `.page__head` with the title and a `.page__actions` box, passed to `mount` as a third argument. The top bar role is the shared `.badge` in the muted tone, placed after the name with `order`, since index.html puts it first. Measured in a built copy at 1400 by 900 and 1400 by 700, CPU 4x, 400 ms and 50 kB/s, after a hard reload: layout shift 0 on Home and 0 on switching to the trial balance and sales invoices, with and without input. + +### src/ui/views/masters.ts · setup lists beside a pinned form panel +- refers-to: src/ui/views/masters.ts :: mountMaster, decorate; src/engine/masters.ts :: party, depthOf, title, Field.span; src/styles/views/masters.css :: .masters, .masters__scroll, .masters--tree; src/ui/views/payments.ts :: mountList, mountForm, mountStock +- kind: rationale +- logged: v0.8.0 · 2026-11-27 + +The six setup screens add `.page--fill` to their page and lay a list that takes the window beside a form panel `--space-14` times 7 wide; the panel is a three-row grid (title, a scroll box holding the fields and the reserved error line, `.form__actions`) so the actions never clip. Fields sit on four columns and carry a span: code, currency and terms take one, names and addresses four. Status and account type are badges through the table's tone, codes are mono through its `mono` column option, and the chart of accounts is indented by a `data-depth` written on each row from the parent chain, since the table has no indent option. A saved row is patched in place, placed by code when new, and stays selected; the title reads `Edit CODE · Name`. Payment lists fill the window with a `.bar` (status, grow, count, one primary); payment and stock forms show status as a `.badge` and order actions quiet first, primary last. Measured in a built copy at CPU 4x, 400 ms and 50 kB/s after a hard reload: shift 0 without input on Customers, the chart, tax rates, payments-in and the payment form; 0.00072 without input when a new tax rate row is placed above an existing one about a second after Enter. diff --git a/web/package-lock.json b/web/package-lock.json index 6240d93..ef5bb3f 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "formledger", - "version": "0.8.0", + "version": "0.9.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formledger", - "version": "0.8.0", + "version": "0.9.0", "license": "Apache-2.0", "devDependencies": { "@types/node": "^22.20.5", diff --git a/web/package.json b/web/package.json index bc572cc..e34073f 100644 --- a/web/package.json +++ b/web/package.json @@ -1,7 +1,7 @@ { "name": "formledger", "private": true, - "version": "0.8.0", + "version": "0.9.0", "license": "Apache-2.0", "type": "module", "scripts": { diff --git a/web/src/engine/doclists.ts b/web/src/engine/doclists.ts index dc726c1..87e7567 100644 --- a/web/src/engine/doclists.ts +++ b/web/src/engine/doclists.ts @@ -32,16 +32,17 @@ export interface DocListSpec { paged: boolean; form: string; newAction: string | null; + empty: string; } export const DOC_LISTS: readonly DocListSpec[] = [ - { id: "quotes", title: "Quotes", group: "Selling", path: "/api/sales/docs", kind: "quote", key: "docs", party: "customer", totalLabel: "Total", paged: true, form: "sales-doc", newAction: "sales.draft" }, - { id: "sales-orders", title: "Sales orders", group: "Selling", path: "/api/sales/docs", kind: "order", key: "docs", party: "customer", totalLabel: "Total", paged: true, form: "sales-doc", newAction: "sales.draft" }, - { id: "sales-invoices", title: "Sales invoices", group: "Selling", path: "/api/sales/docs", kind: "invoice", key: "docs", party: "customer", totalLabel: "Total", paged: true, form: "sales-doc", newAction: "sales.draft" }, - { id: "delivery-notes", title: "Delivery notes", group: "Stock", path: "/api/delivery/notes", kind: "", key: "notes", party: "customer", totalLabel: "Stock value", paged: false, form: "delivery-note", newAction: null }, - { id: "purchase-orders", title: "Purchase orders", group: "Buying", path: "/api/purchase/docs", kind: "order", key: "docs", party: "supplier", totalLabel: "Total", paged: true, form: "purchase-doc", newAction: "purchase.draft" }, - { id: "goods-receipts", title: "Goods receipts", group: "Buying", path: "/api/purchase/docs", kind: "receipt", key: "docs", party: "supplier", totalLabel: "Total", paged: true, form: "goods-receipt", newAction: null }, - { id: "purchase-invoices", title: "Purchase invoices", group: "Buying", path: "/api/purchase/docs", kind: "invoice", key: "docs", party: "supplier", totalLabel: "Total", paged: true, form: "purchase-doc", newAction: "purchase.draft" }, + { id: "quotes", title: "Quotes", group: "Selling", path: "/api/sales/docs", kind: "quote", key: "docs", party: "customer", totalLabel: "Total", paged: true, form: "sales-doc", newAction: "sales.draft", empty: "Quotes you send to customers appear here. Use New to draft the first one." }, + { id: "sales-orders", title: "Sales orders", group: "Selling", path: "/api/sales/docs", kind: "order", key: "docs", party: "customer", totalLabel: "Total", paged: true, form: "sales-doc", newAction: "sales.draft", empty: "Orders customers have placed appear here. Use New, or make one from a quote." }, + { id: "sales-invoices", title: "Sales invoices", group: "Selling", path: "/api/sales/docs", kind: "invoice", key: "docs", party: "customer", totalLabel: "Total", paged: true, form: "sales-doc", newAction: "sales.draft", empty: "Invoices you bill to customers appear here. Use New to draft the first one." }, + { id: "delivery-notes", title: "Delivery notes", group: "Stock", path: "/api/delivery/notes", kind: "", key: "notes", party: "customer", totalLabel: "Stock value", paged: false, form: "delivery-note", newAction: null, empty: "Goods sent to customers appear here. Make a delivery note from a confirmed sales order." }, + { id: "purchase-orders", title: "Purchase orders", group: "Buying", path: "/api/purchase/docs", kind: "order", key: "docs", party: "supplier", totalLabel: "Total", paged: true, form: "purchase-doc", newAction: "purchase.draft", empty: "Orders you place with suppliers appear here. Use New to draft the first one." }, + { id: "goods-receipts", title: "Goods receipts", group: "Buying", path: "/api/purchase/docs", kind: "receipt", key: "docs", party: "supplier", totalLabel: "Total", paged: true, form: "goods-receipt", newAction: null, empty: "Goods received from suppliers appear here. Make a receipt from a confirmed purchase order." }, + { id: "purchase-invoices", title: "Purchase invoices", group: "Buying", path: "/api/purchase/docs", kind: "invoice", key: "docs", party: "supplier", totalLabel: "Total", paged: true, form: "purchase-doc", newAction: "purchase.draft", empty: "Bills from suppliers appear here. Use New to enter the first one." }, ]; export const PAGE_SIZE = 100; diff --git a/web/src/engine/masters.ts b/web/src/engine/masters.ts index a4a8985..dd4f5fa 100644 --- a/web/src/engine/masters.ts +++ b/web/src/engine/masters.ts @@ -13,6 +13,7 @@ export interface Field { createOnly?: boolean; options?: string[]; fallback?: string; + span?: 1 | 2 | 3 | 4; } export interface Column { @@ -20,6 +21,8 @@ export interface Column { label: string; width: string; end?: boolean; + mono?: boolean; + badge?: boolean; } export interface Master { @@ -33,8 +36,37 @@ export interface Master { fields: Field[]; } -const CURRENCY: Field = { key: "currency", label: "Currency", kind: "text", createOnly: true, fallback: "USD" }; -const ACTIVE: Field = { key: "active", label: "Active", kind: "bool" }; +const CURRENCY: Field = { key: "currency", label: "Currency", kind: "text", createOnly: true, fallback: "USD", span: 1 }; +const ACTIVE: Field = { key: "active", label: "Active", kind: "bool", span: 4 }; +const CODE: Field = { key: "code", label: "Code", kind: "text", required: true, createOnly: true, span: 1 }; +const NAME: Field = { key: "name", label: "Name", kind: "text", required: true, span: 3 }; +const CODE_COL: Column = { key: "code", label: "Code", width: "10ch", mono: true }; +const ACTIVE_COL: Column = { key: "active", label: "Status", width: "11ch", badge: true }; + +function party(receivable: boolean): Field[] { + return [ + CODE, + NAME, + { key: "email", label: "Email", kind: "text", span: 2 }, + { key: "phone", label: "Phone", kind: "text", span: 2 }, + { key: "address", label: "Address", kind: "text", span: 4 }, + { key: "taxId", label: "Tax id", kind: "text", span: 2 }, + CURRENCY, + { key: "paymentTermsDays", label: "Terms (days)", kind: "int", fallback: "30", span: 1 }, + receivable + ? { key: "receivableAccount", label: "Receivable account", kind: "text", createOnly: true, span: 2 } + : { key: "payableAccount", label: "Payable account", kind: "text", createOnly: true, span: 2 }, + ACTIVE, + ]; +} + +const PARTY_COLS: Column[] = [ + CODE_COL, + { key: "name", label: "Name", width: "auto" }, + { key: "email", label: "Email", width: "24ch" }, + { key: "paymentTermsDays", label: "Terms", width: "8ch", end: true }, + ACTIVE_COL, +]; export const MASTERS: Master[] = [ { @@ -44,25 +76,8 @@ export const MASTERS: Master[] = [ path: "/api/customers", listKey: "customers", paged: true, - columns: [ - { key: "code", label: "Code", width: "9ch" }, - { key: "name", label: "Name", width: "auto" }, - { key: "email", label: "Email", width: "22ch" }, - { key: "paymentTermsDays", label: "Terms", width: "8ch", end: true }, - { key: "active", label: "Active", width: "8ch" }, - ], - fields: [ - { key: "code", label: "Code", kind: "text", required: true, createOnly: true }, - { key: "name", label: "Name", kind: "text", required: true }, - { key: "email", label: "Email", kind: "text" }, - { key: "phone", label: "Phone", kind: "text" }, - { key: "address", label: "Address", kind: "text" }, - { key: "taxId", label: "Tax id", kind: "text" }, - CURRENCY, - { key: "receivableAccount", label: "Receivable account code", kind: "text", createOnly: true }, - { key: "paymentTermsDays", label: "Payment terms (days)", kind: "int", fallback: "30" }, - ACTIVE, - ], + columns: PARTY_COLS, + fields: party(true), }, { id: "suppliers", @@ -71,25 +86,8 @@ export const MASTERS: Master[] = [ path: "/api/suppliers", listKey: "suppliers", paged: true, - columns: [ - { key: "code", label: "Code", width: "9ch" }, - { key: "name", label: "Name", width: "auto" }, - { key: "email", label: "Email", width: "22ch" }, - { key: "paymentTermsDays", label: "Terms", width: "8ch", end: true }, - { key: "active", label: "Active", width: "8ch" }, - ], - fields: [ - { key: "code", label: "Code", kind: "text", required: true, createOnly: true }, - { key: "name", label: "Name", kind: "text", required: true }, - { key: "email", label: "Email", kind: "text" }, - { key: "phone", label: "Phone", kind: "text" }, - { key: "address", label: "Address", kind: "text" }, - { key: "taxId", label: "Tax id", kind: "text" }, - CURRENCY, - { key: "payableAccount", label: "Payable account code", kind: "text", createOnly: true }, - { key: "paymentTermsDays", label: "Payment terms (days)", kind: "int", fallback: "30" }, - ACTIVE, - ], + columns: PARTY_COLS, + fields: party(false), }, { id: "items", @@ -99,22 +97,22 @@ export const MASTERS: Master[] = [ listKey: "items", paged: true, columns: [ - { key: "code", label: "Code", width: "10ch" }, + CODE_COL, { key: "name", label: "Name", width: "auto" }, { key: "unit", label: "Unit", width: "8ch" }, { key: "salePrice", label: "Price", width: "12ch", end: true }, - { key: "taxRate", label: "Tax", width: "8ch" }, - { key: "active", label: "Active", width: "8ch" }, + { key: "taxRate", label: "Tax", width: "8ch", mono: true }, + ACTIVE_COL, ], fields: [ - { key: "code", label: "Code", kind: "text", required: true, createOnly: true }, - { key: "name", label: "Name", kind: "text", required: true }, - { key: "description", label: "Description", kind: "text" }, - { key: "unit", label: "Unit", kind: "text", fallback: "each" }, - { key: "salePrice", label: "Sale price", kind: "money" }, + CODE, + NAME, + { key: "description", label: "Description", kind: "text", span: 4 }, + { key: "unit", label: "Unit", kind: "text", fallback: "each", span: 1 }, + { key: "salePrice", label: "Sale price", kind: "money", span: 2 }, CURRENCY, - { key: "incomeAccount", label: "Income account code", kind: "text" }, - { key: "taxRate", label: "Tax rate code", kind: "text" }, + { key: "incomeAccount", label: "Income account", kind: "text", span: 2 }, + { key: "taxRate", label: "Tax rate", kind: "text", span: 2 }, ACTIVE, ], }, @@ -126,17 +124,17 @@ export const MASTERS: Master[] = [ listKey: "taxRates", paged: false, columns: [ - { key: "code", label: "Code", width: "10ch" }, + CODE_COL, { key: "name", label: "Name", width: "auto" }, { key: "rateBp", label: "Rate", width: "10ch", end: true }, - { key: "payableAccount", label: "Payable", width: "10ch" }, - { key: "active", label: "Active", width: "8ch" }, + { key: "payableAccount", label: "Payable", width: "10ch", mono: true }, + ACTIVE_COL, ], fields: [ - { key: "code", label: "Code", kind: "text", required: true, createOnly: true }, - { key: "name", label: "Name", kind: "text", required: true }, - { key: "rateBp", label: "Rate (basis points)", kind: "bp", required: true }, - { key: "payableAccount", label: "Payable account code", kind: "text", required: true, createOnly: true }, + CODE, + NAME, + { key: "rateBp", label: "Rate (basis points)", kind: "bp", required: true, span: 2 }, + { key: "payableAccount", label: "Payable account", kind: "text", required: true, createOnly: true, span: 2 }, ACTIVE, ], }, @@ -147,16 +145,8 @@ export const MASTERS: Master[] = [ path: "/api/warehouses", listKey: "warehouses", paged: false, - columns: [ - { key: "code", label: "Code", width: "12ch" }, - { key: "name", label: "Name", width: "auto" }, - { key: "active", label: "Active", width: "8ch" }, - ], - fields: [ - { key: "code", label: "Code", kind: "text", required: true, createOnly: true }, - { key: "name", label: "Name", kind: "text", required: true }, - ACTIVE, - ], + columns: [CODE_COL, { key: "name", label: "Name", width: "auto" }, ACTIVE_COL], + fields: [CODE, NAME, ACTIVE], }, { id: "accounts", @@ -166,19 +156,19 @@ export const MASTERS: Master[] = [ listKey: "accounts", paged: false, columns: [ - { key: "code", label: "Code", width: "9ch" }, + CODE_COL, { key: "name", label: "Name", width: "auto" }, - { key: "type", label: "Type", width: "11ch" }, - { key: "parentCode", label: "Parent", width: "9ch" }, - { key: "active", label: "Active", width: "8ch" }, + { key: "type", label: "Type", width: "12ch", badge: true }, + { key: "parentCode", label: "Parent", width: "9ch", mono: true }, + ACTIVE_COL, ], fields: [ - { key: "code", label: "Code", kind: "text", required: true, createOnly: true }, - { key: "name", label: "Name", kind: "text", required: true }, - { key: "type", label: "Type", kind: "select", options: ["asset", "liability", "equity", "income", "expense"], required: true, createOnly: true }, - { key: "parent", label: "Parent account code", kind: "text", from: "parentCode", createOnly: true }, + CODE, + NAME, + { key: "type", label: "Type", kind: "select", options: ["asset", "liability", "equity", "income", "expense"], required: true, createOnly: true, fallback: "asset", span: 2 }, + { key: "parent", label: "Parent", kind: "text", from: "parentCode", createOnly: true, span: 1 }, CURRENCY, - { key: "isGroup", label: "Group account", kind: "bool", createOnly: true }, + { key: "isGroup", label: "Group account", kind: "bool", createOnly: true, span: 4 }, ACTIVE, ], }, @@ -186,12 +176,35 @@ export const MASTERS: Master[] = [ export function cell(row: Row, key: string): string { const v = row[key]; - if (key === "active") return v ? "yes" : "no"; + if (key === "active") return v ? "Active" : "Inactive"; 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); } +export function depthOf(rows: Row[]): Map { + const parent = new Map(); + for (const r of rows) parent.set(String(r.code ?? ""), String(r.parentCode ?? "")); + const out = new Map(); + for (const code of parent.keys()) { + let d = 0; + let at = parent.get(code) ?? ""; + while (at && parent.has(at) && d < 6) { + d++; + at = parent.get(at) ?? ""; + } + out.set(code, d); + } + return out; +} + +export function title(m: Master, row: Row | null): string { + if (!row) return `New ${m.singular}`; + const code = String(row.code ?? ""); + const name = String(row.name ?? ""); + return `Edit ${code}${code && name ? " · " : ""}${name}`; +} + export function fieldText(f: Field, row: Row | null): string { if (!row) return f.fallback ?? (f.kind === "money" ? "0.00" : ""); const v = row[f.from ?? f.key]; diff --git a/web/src/styles/account.css b/web/src/styles/account.css index d6e95ee..1b4160a 100644 --- a/web/src/styles/account.css +++ b/web/src/styles/account.css @@ -123,7 +123,7 @@ } .topbar { - grid-template-columns: var(--sidebar-w) minmax(0, 1fr) auto; + grid-template-columns: minmax(0, 1fr) auto auto; column-gap: var(--space-3); } @@ -132,17 +132,30 @@ } .who { - display: grid; - grid-auto-flow: column; - justify-content: start; - column-gap: var(--space-2); - overflow: hidden; + 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 { - color: var(--text-faint); + order: 1; + flex: none; + text-transform: capitalize; +} + +.who__role:empty { + display: none; } :root[data-route="account"] .view--account { diff --git a/web/src/styles/parts.css b/web/src/styles/parts.css index 44652cc..5c7c3d1 100644 --- a/web/src/styles/parts.css +++ b/web/src/styles/parts.css @@ -40,6 +40,186 @@ min-inline-size: 0; } +.view--page[data-active]:has(> .page--fill) { + block-size: 100%; +} + +.page--fill { + display: flex; + flex-direction: column; + gap: var(--space-4); + block-size: 100%; + min-block-size: 0; +} + +.page--fill > * { + flex: none; +} + +.page--fill > :last-child { + flex: 1 1 0; + min-block-size: 0; +} + +.page--fill > .tbl[data-foot]:last-child { + flex: none; +} + +.view--page[data-active]:has(.page__body > .page--fill) { + block-size: 100%; +} + +.page:has(> .page__body > .page--fill) { + display: flex; + flex-direction: column; + block-size: 100%; + min-block-size: 0; +} + +.page:has(> .page__body > .page--fill) > .page__title { + display: flex; + align-items: center; + flex: none; + min-block-size: var(--control); +} + +.page__body:has(> .page--fill) { + display: flex; + flex-direction: column; + flex: 1 1 0; + min-block-size: 0; +} + +.page__body > .page--fill { + flex: 1 1 0; + padding: 0; +} + +.tbl-wrap { + container-type: size; + min-block-size: calc(var(--row) * 6); + min-inline-size: 0; +} + +.tbl-wrap > .tbl--grow[data-foot] { + --tbl-block: max(calc(var(--row) * 6), 100cqb); +} + +.page__head { + display: flex; + align-items: center; + gap: var(--space-2); + min-block-size: var(--control); + min-inline-size: 0; +} + +.page__head > .page__title { + flex: 1 1 auto; + min-inline-size: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.page__actions { + display: flex; + align-items: center; + justify-content: flex-end; + gap: var(--space-2); + flex: none; + margin-inline-start: auto; +} + +.bar { + display: flex; + align-items: center; + gap: var(--space-2); + block-size: var(--control); + min-inline-size: 0; + white-space: nowrap; +} + +.bar__grow { + flex: 1 1 auto; + min-inline-size: 0; +} + +.badge { + --badge-tone: var(--text-muted); + display: inline-flex; + align-items: center; + block-size: calc(var(--row) - var(--space-3)); + padding: 0 var(--space-2); + border-radius: calc(var(--row) - var(--space-3)); + font-size: var(--text-xs); + font-weight: var(--weight-medium); + line-height: 1; + vertical-align: middle; + white-space: nowrap; + color: var(--badge-tone); + background: color-mix(in srgb, var(--badge-tone) 16%, transparent); +} + +.badge[data-tone="info"] { + --badge-tone: var(--info); +} + +.badge[data-tone="ok"] { + --badge-tone: var(--success); +} + +.badge[data-tone="warn"] { + --badge-tone: var(--warning); +} + +.badge[data-tone="bad"] { + --badge-tone: var(--danger); +} + +.num { + text-align: end; + font-variant-numeric: tabular-nums; +} + +.field { + display: grid; + grid-template-rows: auto auto auto; + row-gap: var(--space-1); + min-inline-size: 0; +} + +.field > label, +.field__label { + font-size: var(--text-sm); + color: var(--text-muted); +} + +.field__hint { + min-block-size: calc(var(--text-xs) * 1.4); + font-size: var(--text-xs); + line-height: 1.4; + color: var(--text-muted); + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.field__hint[data-tone="bad"] { + color: var(--danger); +} + +.form__actions { + position: sticky; + inset-block-end: 0; + display: flex; + align-items: center; + justify-content: flex-end; + gap: var(--space-2); + padding-block: var(--space-3); + border-block-start: 1px solid var(--border); + background: var(--surface); +} + .tbl { position: relative; min-block-size: calc(var(--row) * 4); @@ -79,6 +259,15 @@ text-align: end; } +.tbl__table { + font-family: var(--font-sans); +} + +.tbl__table td[data-mono] { + font-family: var(--font-mono); + font-size: var(--text-xs); +} + .tbl__table tbody tr:last-child td { border-block-end: 0; } @@ -156,9 +345,24 @@ } .tbl__empty { + inset-block: var(--row) 0; + display: grid; + place-items: center; + padding: var(--space-6); visibility: hidden; } +.tbl--grow { + overflow: auto; + min-block-size: calc(var(--row) * 6); +} + +.tbl--grow .tbl__table thead th { + position: sticky; + inset-block-start: 0; + z-index: var(--z-raised); +} + .tbl[data-empty] .tbl__empty { visibility: visible; } diff --git a/web/src/styles/shell.css b/web/src/styles/shell.css index 81b9684..04cd27c 100644 --- a/web/src/styles/shell.css +++ b/web/src/styles/shell.css @@ -46,7 +46,26 @@ .sidebar__nav { display: grid; align-content: start; - row-gap: var(--space-1); + row-gap: 0; + min-block-size: 0; + padding-block-end: var(--space-4); + overflow-y: auto; + overscroll-behavior: contain; + scrollbar-width: thin; + scrollbar-color: var(--border-strong) transparent; + scrollbar-gutter: stable; +} + +.sidebar__nav .sb-views { + row-gap: 0; +} + +.sidebar__nav .sb-group { + padding: var(--space-4) var(--space-2) var(--space-1); +} + +.sidebar__nav .sb-group:first-child { + padding-block-start: var(--space-3); } .sb-item { @@ -74,7 +93,18 @@ .sb-item[aria-current="page"] { color: var(--text); - background: var(--active); + font-weight: var(--weight-medium); + background: var(--accent-wash); +} + +.sb-item[aria-current="page"] .sb-icon { + color: var(--accent); +} + +.sb-label { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; } .sheet { @@ -95,6 +125,9 @@ } .topbar__title { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; font-size: var(--text-sm); font-weight: var(--weight-medium); color: var(--text-muted); @@ -128,6 +161,179 @@ line-height: var(--leading-tight); } +.home--dash { + inline-size: 100%; + max-inline-size: calc(var(--doc-w) * 1.5); + padding: var(--space-6); +} + +.home--dash .home__title { + font-size: var(--text-lg); +} + +.tiles { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: var(--space-4); +} + +.tile { + display: grid; + grid-template-rows: auto var(--space-8) auto; + align-items: center; + row-gap: var(--space-1); + padding: var(--space-4); + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius); + transition: border-color var(--dur-fast) var(--ease), background-color var(--dur-fast) var(--ease); +} + +.tile:hover { + background: var(--surface-2); + border-color: var(--border-strong); +} + +.tile__label { + font-size: var(--text-sm); + font-weight: var(--weight-medium); + color: var(--text-muted); +} + +.tile .tile__value { + overflow: hidden; + font-size: var(--text-title); + font-weight: var(--weight-semibold); + line-height: var(--leading-tight); + font-variant-numeric: tabular-nums; + text-align: start; + white-space: nowrap; + text-overflow: ellipsis; +} + +.tile__note { + font-size: var(--text-xs); + color: var(--text-faint); +} + +.recents { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: var(--space-4); +} + +.recent { + display: grid; + grid-template-rows: var(--row) auto; + row-gap: var(--space-2); + min-inline-size: 0; +} + +.recent__head { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); +} + +.recent__title { + margin: 0; + font-size: var(--text-md); + font-weight: var(--weight-semibold); +} + +.recent__all { + font-size: var(--text-sm); + color: var(--accent); +} + +.recent__all:hover { + text-decoration: underline; +} + +.recent__list { + position: relative; + display: grid; + grid-auto-rows: var(--row); + background: var(--surface); + border: 1px solid var(--border); + border-radius: var(--radius); + overflow: hidden; +} + +.recent__row { + display: grid; + grid-template-columns: 14ch minmax(0, 1fr) 11ch 9ch 12ch; + align-items: center; + column-gap: var(--space-2); + padding-inline: var(--space-3); + font-size: var(--text-sm); + border-block-start: 1px solid var(--border); +} + +.recent__row:first-child { + border-block-start: 0; +} + +.recent__row:hover { + background: var(--hover); +} + +.recent__row[data-idle] { + pointer-events: none; + border-color: transparent; +} + +.recent__row[data-idle] .badge { + visibility: hidden; +} + +.recent__num { + overflow: hidden; + font-family: var(--font-mono); + font-size: var(--text-xs); + white-space: nowrap; + text-overflow: ellipsis; +} + +.recent__party, +.recent__date { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + color: var(--text-muted); +} + +.recent__date { + font-variant-numeric: tabular-nums; +} + +.recent .badge { + justify-self: start; +} + +.recent__total { + text-align: end; + font-variant-numeric: tabular-nums; +} + +.recent__empty { + position: absolute; + inset: 0; + display: grid; + place-items: center; + margin: 0; + padding: var(--space-4); + font-size: var(--text-sm); + color: var(--text-muted); + text-align: center; + pointer-events: none; +} + +.recent__empty:empty { + display: none; +} + .empty { display: grid; padding: var(--space-8) var(--space-6); diff --git a/web/src/styles/views/docform.css b/web/src/styles/views/docform.css index 615a860..aec1d79 100644 --- a/web/src/styles/views/docform.css +++ b/web/src/styles/views/docform.css @@ -8,47 +8,69 @@ --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))); display: grid; - row-gap: var(--space-4); + grid-template-rows: auto minmax(0, 1fr) auto auto; + row-gap: var(--space-3); + block-size: max(calc(100dvh - var(--df-chrome)), calc(var(--row) * 16)); min-inline-size: 0; } .df-head { - display: grid; - grid-template-columns: var(--df-kind-w) var(--df-number-w) var(--df-status-w) var(--df-busy-w); + display: flex; align-items: center; + justify-content: space-between; column-gap: var(--space-3); block-size: var(--df-head-h); } +.page__head > .page__title.df-number { + flex: none; +} + +.df-title { + --df-busy-w: calc(var(--space-14) + var(--space-4)); + flex: none; + margin-inline-end: auto; + inline-size: calc(var(--df-busy-w) * 2 + var(--space-8)); + display: flex; + align-items: center; + column-gap: var(--space-3); + min-inline-size: 0; +} + +.df-kind { + inline-size: var(--df-kind-w); +} + .df-number, -.df-status, .df-busy { overflow: hidden; - font-size: var(--text-sm); white-space: nowrap; text-overflow: ellipsis; } .df-number { + flex: none; + margin: 0; + inline-size: 34ch; + font-family: var(--font-mono); + font-size: var(--text-lg); + font-weight: var(--weight-semibold); font-variant-numeric: tabular-nums; - font-weight: var(--weight-medium); -} - -.df-status { - color: var(--text-muted); - font-variant-numeric: tabular-nums; -} - -.df-status[data-status="posted"] { - color: var(--success); } -.df-status[data-status="cancelled"] { - color: var(--danger); +.badge.df-status { + flex: none; + display: inline-flex; + box-sizing: border-box; + inline-size: var(--df-busy-w); + justify-content: center; } .df-busy { + inline-size: var(--df-busy-w); + font-size: var(--text-sm); color: var(--text-muted); visibility: hidden; } @@ -59,20 +81,48 @@ .df-fields { display: grid; - grid-template-columns: var(--df-party-w) repeat(auto-fill, minmax(var(--df-field-min), 1fr)); - align-items: end; - gap: var(--space-3); + grid-template-columns: repeat(8, minmax(0, 1fr)); + align-items: start; + gap: var(--space-2) var(--space-3); } .df-field { + display: grid; + row-gap: var(--space-1); min-inline-size: 0; } +.df-field > .picker { + display: grid; + row-gap: var(--space-1); + margin: 0; +} + +.df-fields .input { + block-size: var(--control); +} + +.df-field--party { + grid-column: span 3; +} + .df-field--notes { - grid-column: 1 / -1; + grid-column: span 2; +} + +.df-fields--ref .df-field--party { + grid-column: span 2; +} + +.df[data-readonly] .df-fields .input { + border-color: transparent; + background: transparent; } .df-lines { + display: flex; + flex-direction: column; + min-block-size: 0; min-inline-size: 0; } @@ -98,6 +148,28 @@ .df-actions__gap { flex: 1 1 auto; + order: 1; +} + +.df-actions .df-btn--cancel { + order: 2; +} + +.df-actions .df-btn--amend { + order: 3; +} + +.df-actions .df-btn--save { + order: 4; +} + +.df-actions .btn--primary { + order: 5; +} + +.df-btn--cancel:not(:disabled):hover { + color: var(--danger); + border-color: var(--danger); } .df-btn { diff --git a/web/src/styles/views/doclists.css b/web/src/styles/views/doclists.css index d9fd205..0eea88b 100644 --- a/web/src/styles/views/doclists.css +++ b/web/src/styles/views/doclists.css @@ -1,31 +1,23 @@ .dl { - --dl-bar-height: 36px; - --dl-col-number: 160px; - --dl-col-date: 112px; + --dl-col-number: 148px; + --dl-col-date: 120px; --dl-col-status: 112px; - --dl-col-total: 168px; - --dl-filter-width: 160px; - --dl-count-width: 24ch; - display: flex; - flex-direction: column; - gap: var(--space-3); + --dl-col-cur: 56px; + --dl-col-total: 152px; + --dl-filter-width: 152px; + --dl-count-width: 12ch; + --dl-more-width: 96px; } -.dl__bar { - display: flex; - align-items: center; - gap: var(--space-2); - block-size: var(--dl-bar-height); +.dl__label { + font-size: var(--text-sm); + color: var(--text-muted); } .dl__filter { inline-size: var(--dl-filter-width); } -.dl__gap { - flex: 1; -} - .dl__new { display: inline-flex; align-items: center; @@ -34,20 +26,13 @@ .dl__count { inline-size: var(--dl-count-width); - white-space: nowrap; + font-size: var(--text-sm); + color: var(--text-muted); text-align: end; font-variant-numeric: tabular-nums; } -.dl .tbl__table td[data-tone="muted"], -.dl .tbl__table td[data-tone="cancelled"] { - opacity: 0.6; -} - -.dl .tbl__table td[data-tone="posted"] { - font-weight: 600; -} - -.dl .tbl__table td[data-align="end"] { - font-variant-numeric: tabular-nums; +.dl__more { + inline-size: var(--dl-more-width); + justify-content: center; } diff --git a/web/src/styles/views/grid.css b/web/src/styles/views/grid.css index 8626c0d..6104b45 100644 --- a/web/src/styles/views/grid.css +++ b/web/src/styles/views/grid.css @@ -65,50 +65,67 @@ } .grid { - --grid-row: 40px; - --grid-err: 18px; - --grid-c-item: 200px; - --grid-c-desc: 240px; - --grid-c-qty: 96px; + --grid-row: var(--row); + --grid-err: var(--space-4); + --grid-c-item: 168px; + --grid-c-qty: 80px; --grid-c-price: 112px; - --grid-c-tax: 120px; - --grid-c-num: 112px; - --grid-c-rm: 40px; - --grid-totals-w: 280px; + --grid-c-tax: 136px; + --grid-c-num: 120px; + --grid-c-rm: var(--control); display: flex; + flex: 1 1 0; flex-direction: column; gap: var(--space-3); + min-block-size: 0; min-inline-size: 0; } .grid__scroll { + flex: 1 1 0; + min-block-size: calc(var(--grid-row) + 4 * (var(--grid-row) + var(--grid-err))); overflow: auto; - block-size: calc(var(--grid-row) + 8 * (var(--grid-row) + var(--grid-err)) + 2px); overscroll-behavior: contain; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); } .grid__table { - inline-size: max-content; + inline-size: 100%; + min-inline-size: calc(var(--grid-c-item) * 3 +var(--grid-c-qty) + var(--grid-c-price) + var(--grid-c-tax) + var(--grid-c-num) + var(--grid-c-rm)); } .grid__row { display: grid; grid-template-columns: - var(--grid-c-item) var(--grid-c-desc) var(--grid-c-qty) var(--grid-c-price) var(--grid-c-tax) - var(--grid-c-num) var(--grid-c-num) var(--grid-c-num) var(--grid-c-rm); + var(--grid-c-item) minmax(0, 1fr) var(--grid-c-qty) var(--grid-c-price) var(--grid-c-tax) + 0 0 var(--grid-c-num) var(--grid-c-rm); column-gap: var(--space-1); align-items: center; + padding-inline: var(--space-1); +} + +.grid__row > :nth-child(6), +.grid__row > :nth-child(7) { + visibility: hidden; + padding: 0; } .grid__head { + position: sticky; + inset-block-start: 0; + z-index: var(--z-sticky); block-size: var(--grid-row); - border-block-end: 1px solid var(--border, GrayText); + background: var(--surface); + border-block-end: 1px solid var(--border); } .grid__th { padding: 0 var(--space-2); - color: var(--text-muted, GrayText); - font-size: 0.85em; + color: var(--text-muted); + font-size: var(--text-xs); + font-weight: var(--weight-medium); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; @@ -124,6 +141,48 @@ border-block-end: 1px solid var(--border-subtle, transparent); } +.grid__line:focus-within { + background: var(--hover); +} + +.grid__input:focus, +.grid__line .picker__input:focus { + outline: 2px solid var(--accent); + outline-offset: -1px; +} + +.grid__c-item .picker__input { + font-family: var(--font-mono); + font-size: var(--text-sm); +} + +.grid[data-readonly] .grid__input, +.grid[data-readonly] .picker__input { + border-color: transparent; + background: transparent; +} + +.grid[data-readonly] .grid__rm, +.grid[data-readonly] .grid__add, +.grid[data-readonly] .grid__line.is-idle { + visibility: hidden; +} + +.grid__rm { + color: var(--text-faint); + opacity: 0; +} + +.grid__line:hover .grid__rm, +.grid__line:focus-within .grid__rm, +.grid__rm:focus-visible { + opacity: 1; +} + +.grid__rm:hover { + color: var(--danger); +} + .grid__td { min-inline-size: 0; overflow: hidden; @@ -138,8 +197,9 @@ font-variant-numeric: tabular-nums; } -.grid__input.is-invalid { - outline: 1px solid var(--danger, red); +.grid__input.is-invalid, +.grid__line.needs-item .grid__c-item .picker__input { + outline: 1px solid var(--danger); } .grid__c-num { @@ -150,7 +210,7 @@ } .grid__c-total { - font-weight: 600; + font-weight: var(--weight-medium); } .grid__c-rm { @@ -172,30 +232,53 @@ .grid__foot { display: flex; + flex: none; justify-content: space-between; align-items: flex-start; gap: var(--space-4); + padding-inline: var(--space-1) calc(var(--space-1) * 2 + var(--grid-c-rm) + 1px); +} + +.grid__add { + display: inline-flex; + align-items: center; + column-gap: var(--space-1); } .grid__totals { display: grid; - grid-template-columns: minmax(0, 1fr) 16ch; + grid-template-columns: var(--grid-c-num) var(--grid-c-num); + align-items: baseline; column-gap: var(--space-4); row-gap: var(--space-1); - inline-size: var(--grid-totals-w); margin: 0; } .grid__totals dt { - color: var(--text-muted, GrayText); + color: var(--text-muted); + font-size: var(--text-sm); + text-align: end; } .grid__totals dd { margin: 0; + padding-inline-end: var(--space-2); text-align: end; font-variant-numeric: tabular-nums; } +.grid__totals dt:last-of-type { + padding-block-start: var(--space-1); + color: var(--text); + font-weight: var(--weight-semibold); +} + +.grid__totals dd:last-of-type { + padding-block-start: var(--space-1); + border-block-start: 1px solid var(--border); +} + .grid__sum-value--total { - font-weight: 600; + font-size: var(--text-lg); + font-weight: var(--weight-semibold); } diff --git a/web/src/styles/views/ledger-screens.css b/web/src/styles/views/ledger-screens.css index ac26428..3c2679b 100644 --- a/web/src/styles/views/ledger-screens.css +++ b/web/src/styles/views/ledger-screens.css @@ -1,46 +1,60 @@ .ls { - --ls-field: 36px; - --ls-label: 20px; - --ls-status: 24px; - --ls-above: 250px; - --tbl-block: max(calc(var(--row) * 8), calc(100dvh - var(--ls-above))); - display: flex; - flex-direction: column; - row-gap: var(--space-3); -} - -.ls__bar { - display: flex; - flex-wrap: wrap; - align-items: end; - gap: var(--space-3); - block-size: calc(var(--ls-field) + var(--ls-label) + var(--space-1)); - overflow: hidden; + --ls-date: 144px; + --ls-select: 240px; + --ls-status: 22ch; + --ls-badge: 18ch; } .ls__field { - display: flex; - flex-direction: column; - row-gap: var(--space-1); + display: inline-flex; + align-items: center; + gap: var(--space-2); } .ls__label { - block-size: var(--ls-label); font-size: var(--text-sm); color: var(--text-muted); } -.ls__input { - inline-size: 220px; - block-size: var(--ls-field); +.ls__date { + inline-size: var(--ls-date); +} + +.ls__select { + inline-size: var(--ls-select); +} + +.ls__bar { + column-gap: var(--space-4); } .ls__status { - margin: 0; - block-size: var(--ls-status); - line-height: var(--ls-status); + inline-size: var(--ls-status); font-size: var(--text-sm); - white-space: nowrap; + color: var(--text-muted); + text-align: end; + font-variant-numeric: tabular-nums; overflow: hidden; text-overflow: ellipsis; } + +.ls__badge { + inline-size: var(--ls-badge); + justify-content: center; +} + +.ls__badge:empty { + visibility: hidden; +} + +.ls__table { + container-type: size; +} + +.ls__table .tbl { + --tbl-block: max(calc(var(--row) * 6), 100cqb); +} + +.ls__table[data-ageing] .tbl tfoot td:nth-child(n + 5):nth-child(-n + 8) { + color: var(--warning); +} diff --git a/web/src/styles/views/masters.css b/web/src/styles/views/masters.css index c622645..a5bce69 100644 --- a/web/src/styles/views/masters.css +++ b/web/src/styles/views/masters.css @@ -1,36 +1,108 @@ +.page__body:has(> .masters) { + display: grid; + grid-template-rows: minmax(0, 1fr); +} + .masters { - --masters-panel-w: 340px; - --masters-table-h: 62dvh; - --masters-form-h: 62dvh; + --masters-panel-w: calc(var(--space-14) * 7); display: grid; grid-template-columns: minmax(0, 1fr) var(--masters-panel-w); + grid-template-rows: minmax(0, 1fr); column-gap: var(--space-4); - align-items: start; + block-size: 100%; + min-block-size: 0; } .masters__list { - block-size: var(--masters-table-h); + display: grid; + grid-template-rows: minmax(0, 1fr); min-inline-size: 0; - overflow: auto; + min-block-size: 0; +} + +.masters__list > .tbl { + block-size: 100%; } .masters__form { - block-size: var(--masters-form-h); - grid-template-rows: auto minmax(0, 1fr) auto auto; + grid-template-rows: auto minmax(0, 1fr) auto; + row-gap: 0; + padding: 0; + min-block-size: 0; overflow: hidden; } -.masters__fields { +.masters__title { + margin: 0; + padding: var(--space-3) var(--space-4); + border-block-end: 1px solid var(--border); + font-size: var(--text-md); + font-weight: var(--weight-semibold); + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.masters__scroll { + display: grid; align-content: start; row-gap: var(--space-2); + padding: var(--space-4); min-block-size: 0; overflow: auto; +} + +.masters__fields { display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + align-content: start; + gap: var(--space-3) var(--space-2); } .masters__field { - row-gap: var(--space-1); - display: grid; + grid-column: span 4; + min-inline-size: 0; +} + +.masters__field[data-span="1"] { + grid-column: span 1; +} + +.masters__field[data-span="2"] { + grid-column: span 2; +} + +.masters__field[data-span="3"] { + grid-column: span 3; +} + +.masters__req { + color: var(--danger); +} + +.masters__form .form__actions { + padding-inline: var(--space-4); + background: var(--surface); +} + +.masters--tree .tbl__table tr:not([data-depth]) td:nth-child(2) { + font-weight: var(--weight-medium); +} + +.masters .tbl__table tr[data-depth="1"] td:nth-child(2) { + padding-inline-start: calc(var(--space-3) + var(--space-4)); +} + +.masters .tbl__table tr[data-depth="2"] td:nth-child(2) { + padding-inline-start: calc(var(--space-3) + var(--space-4) * 2); +} + +.masters .tbl__table tr[data-depth="3"] td:nth-child(2) { + padding-inline-start: calc(var(--space-3) + var(--space-4) * 3); +} + +.masters .tbl__table tr[data-depth="4"] td:nth-child(2) { + padding-inline-start: calc(var(--space-3) + var(--space-4) * 4); } .masters__field--bool { @@ -42,17 +114,7 @@ .masters__field .input { inline-size: 100%; -} - -.masters__actions { - column-gap: var(--space-2); - grid-template-columns: minmax(0, 1fr) auto; - display: grid; -} - -.masters__mode { - font-size: var(--text-sm); - color: var(--text-muted); + min-inline-size: 0; } .masters .tbl__table tr[data-selected] td { @@ -62,6 +124,7 @@ @media (max-width: 900px) { .masters { grid-template-columns: minmax(0, 1fr); + grid-template-rows: minmax(0, 1fr) minmax(0, 1fr); row-gap: var(--space-4); } } diff --git a/web/src/styles/views/payments.css b/web/src/styles/views/payments.css index 3bbb085..28598e7 100644 --- a/web/src/styles/views/payments.css +++ b/web/src/styles/views/payments.css @@ -13,12 +13,36 @@ gap: var(--space-4); } -.pay__bar { - display: flex; - align-items: center; - justify-content: space-between; - gap: var(--space-3); - block-size: var(--row); +.page__body:has(> .pay--list) { + display: grid; + grid-template-rows: minmax(0, 1fr); +} + +.pay--list { + block-size: 100%; + min-block-size: 0; +} + +.pay--list > .pay__table { + display: grid; + grid-template-rows: minmax(0, 1fr); + flex: 1 1 0; + min-block-size: 0; +} + +.pay--list > .pay__table > .tbl { + block-size: 100%; +} + +.pay__filter { + font-size: var(--text-sm); + color: var(--text-muted); +} + +.pay__count { + min-inline-size: 12ch; + font-size: var(--text-sm); + color: var(--text-muted); } .pay__status { @@ -39,20 +63,8 @@ font-variant-numeric: tabular-nums; } -.pay__badge { - min-inline-size: 6rem; - padding: 0 var(--space-2); - font-size: var(--text-xs); - color: var(--text-muted); - text-transform: capitalize; -} - -.pay[data-status="posted"] .pay__badge { - color: var(--success); -} - -.pay[data-status="cancelled"] .pay__badge { - color: var(--danger); +.pay__badge[hidden] { + display: none; } .pay__grid { @@ -150,8 +162,18 @@ .pay__actions { display: flex; + justify-content: flex-end; gap: var(--space-2); - block-size: var(--row); +} + +.pay--form .pay__actions, +.pay--stock .pay__actions { + position: static; + background: none; +} + +.pay__field--party .pay__picker { + block-size: auto; } .pay[data-busy] .pay__actions, diff --git a/web/src/styles/views/statements.css b/web/src/styles/views/statements.css index 6b35460..93f78f5 100644 --- a/web/src/styles/views/statements.css +++ b/web/src/styles/views/statements.css @@ -1,55 +1,39 @@ .st { - --st-field: 36px; - --st-label: 20px; - --st-status: 24px; --st-code: 6rem; --st-amount: 10rem; - --st-rows: 9; - --st-date: 11rem; - display: flex; - flex-direction: column; - row-gap: var(--space-3); -} - -.st__bar { - display: flex; - align-items: end; - gap: var(--space-3); - block-size: calc(var(--st-field) + var(--st-label) + var(--space-1)); - overflow: hidden; + --st-date: 144px; + --st-status: 30ch; + --st-badge: 14ch; + --st-indent: var(--space-6); } .st__field { - display: flex; - flex-direction: column; - row-gap: var(--space-1); + display: inline-flex; + align-items: center; + gap: var(--space-2); } .st__label { - block-size: var(--st-label); font-size: var(--text-sm); color: var(--text-muted); } .st__date { inline-size: var(--st-date); - block-size: var(--st-field); } .st__run { display: inline-flex; align-items: center; column-gap: var(--space-2); - block-size: var(--st-field); } .st__status { - block-size: var(--st-status); - line-height: var(--st-status); - margin: 0; + inline-size: var(--st-status); font-size: var(--text-sm); color: var(--text-muted); - white-space: nowrap; + text-align: end; + font-variant-numeric: tabular-nums; overflow: hidden; text-overflow: ellipsis; } @@ -58,53 +42,115 @@ color: var(--danger); } -.st__sections { +.st__badge { + inline-size: var(--st-badge); + justify-content: center; +} + +.st__badge:empty { + visibility: hidden; +} + +.st__body { display: flex; flex-direction: column; - row-gap: var(--space-4); + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); + overflow: hidden; +} + +.st__sheet { + flex: 1 1 0; + min-block-size: 0; + overflow: auto; + padding: var(--space-3) var(--space-4); +} + +.st__sheet[data-ready="false"] > * { + visibility: hidden; +} + +.st__section + .st__section { + margin-block-start: var(--space-6); } .st__heading { - block-size: var(--st-label); - margin: 0 0 var(--space-2); - font-size: var(--text-sm); + display: flex; + align-items: center; + block-size: var(--row); + margin: 0; + font-size: var(--text-md); font-weight: var(--weight-semibold); } -.st .tbl { - --tbl-block: calc(var(--row) * var(--st-rows)); - min-block-size: var(--tbl-block); +.st__line, +.st__sub { + display: grid; + grid-template-columns: var(--st-code) 1fr var(--st-amount); + align-items: center; + block-size: var(--row); + margin: 0; + padding-inline-start: var(--st-indent); + border-block-end: 1px solid var(--border); } -.st .tbl__fill { - visibility: hidden; +.st__code { + font-family: var(--font-mono); + font-size: var(--text-sm); + color: var(--text-muted); } -.st__summary { - display: flex; - flex-direction: column; - row-gap: var(--space-1); - padding: var(--space-3); - border: 1px solid var(--border); - border-radius: var(--radius); - background: var(--surface-2); +.st__line .num, +.st__sub .num { + font-variant-numeric: tabular-nums; +} + +.st__sub { + grid-template-columns: 1fr var(--st-amount); + padding-inline-start: 0; + border-block-end: 0; + font-weight: var(--weight-medium); + border-block-start: 1px solid var(--border-strong); } -.st__sum { +.st__none { display: flex; - justify-content: space-between; + align-items: center; block-size: var(--row); - line-height: var(--row); margin: 0; + padding-inline-start: var(--st-indent); + font-size: var(--text-sm); + color: var(--text-muted); +} + +.st__none[hidden] { + display: none; +} + +.st__result { + display: flex; + align-items: center; + justify-content: space-between; + flex: none; + block-size: calc(var(--row) * 2); + padding-inline: var(--space-4); + border-block-start: 1px solid var(--border-strong); + background: var(--surface-2); +} + +.st__result-label { + font-size: var(--text-md); font-weight: var(--weight-semibold); - font-variant-numeric: tabular-nums; } -.st__sum-value { - inline-size: var(--st-amount); - text-align: end; +.st__result-value { + inline-size: 14ch; + font-size: var(--text-title); + font-weight: var(--weight-semibold); + line-height: 1; } -.st__sum-value[data-tone="danger"] { +.st__result-value[data-tone="danger"] { color: var(--danger); } diff --git a/web/src/ui/account.ts b/web/src/ui/account.ts index e54f3c3..8ab556e 100644 --- a/web/src/ui/account.ts +++ b/web/src/ui/account.ts @@ -83,6 +83,8 @@ 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"); diff --git a/web/src/ui/app.ts b/web/src/ui/app.ts index 1022aae..1a06f65 100644 --- a/web/src/ui/app.ts +++ b/web/src/ui/app.ts @@ -1,8 +1,9 @@ import type { Engine, Health } from "../engine"; -import { delayedIndicator, ref, setAttr, setText } from "./dom"; +import { money } from "../engine/format"; +import { delayedIndicator, h, ref, setAttr, setText } from "./dom"; import { dismissToast, toast } from "./toast"; import { mountAccount } from "./account"; -import { mountViews } from "./views"; +import { hashFor, mountViews } from "./views"; const SERVER_TOAST = "server-health"; @@ -69,9 +70,121 @@ function bindNav(engine: Engine): void { ); } +interface Tile { + value: HTMLElement; + note: HTMLElement; +} + +interface RecentDoc { + id: string; + number?: string | null; + date: string; + status: string; + total: number; + currency: string; + customerName?: string; + supplierName?: string; +} + +const RECENT_ROWS = 5; + +const TONES: Record = { draft: "muted", confirmed: "info", open: "info", posted: "ok", paid: "ok", part_paid: "warn", partly_paid: "warn", overdue: "warn", cancelled: "bad" }; + +function tile(label: string, view: string, note: string): [HTMLAnchorElement, Tile] { + const value = h("span", { class: "tile__value num" }); + const noteEl = h("span", { class: "tile__note", text: note }); + const el = h("a", { class: "tile", attrs: { href: `#/${view}` } }, h("span", { class: "tile__label", text: label }), value, noteEl); + return [el, { value, note: noteEl }]; +} + +function recentBlock(title: string, view: string, form: string, emptyText: string): { el: HTMLElement; fill(docs: RecentDoc[]): void; fail(): void } { + const rows = Array.from({ length: RECENT_ROWS }, () => { + const num = h("span", { class: "recent__num" }); + const party = h("span", { class: "recent__party" }); + const date = h("span", { class: "recent__date" }); + const badge = h("span", { class: "badge", attrs: { "data-tone": "muted" } }); + const total = h("span", { class: "recent__total num" }); + const a = h("a", { class: "recent__row", attrs: { href: `#/${view}`, "data-idle": "" } }, num, party, date, badge, total); + return { a, num, party, date, badge, total }; + }); + const empty = h("p", { class: "recent__empty", text: "" }); + const list = h("div", { class: "recent__list" }, ...rows.map((r) => r.a), empty); + const el = h( + "section", + { class: "recent" }, + h("header", { class: "recent__head" }, h("h2", { class: "recent__title", text: title }), h("a", { class: "recent__all", attrs: { href: `#/${view}` }, text: "View all" })), + list, + ); + const fill = (docs: RecentDoc[]) => { + rows.forEach((r, i) => { + const d = docs[i]; + setAttr(r.a, "data-idle", d ? null : ""); + setAttr(r.a, "href", d ? hashFor(form, { id: d.id }) : `#/${view}`); + setText(r.num, d ? d.number || "Draft" : ""); + setText(r.party, d ? d.customerName || d.supplierName || "" : ""); + setText(r.date, d ? d.date : ""); + const status = d ? d.status.replace(/_/g, " ") : ""; + setText(r.badge, status.charAt(0).toUpperCase() + status.slice(1)); + setAttr(r.badge, "data-tone", d ? TONES[d.status] ?? "muted" : "muted"); + setText(r.total, d ? money(d.total) : ""); + }); + setText(empty, docs.length ? "" : emptyText); + }; + const fail = () => { + fill([]); + setText(empty, "This list could not be loaded."); + }; + return { el, fill, fail }; +} + +function mountHome(engine: Engine): void { + const home = document.querySelector(".view--home .home"); + const placeholder = home?.querySelector(".empty"); + if (!home || !placeholder) return; + home.classList.add("home--dash"); + const [owedEl, owed] = tile("Owed to you", "receivables-ageing", "Open customer balances"); + const oweEl = tile("You owe", "payables-ageing", "Open supplier balances"); + const cashEl = tile("Cash and bank", "balance-sheet", "Cash and bank accounts"); + const sales = recentBlock("Last sales invoices", "sales-invoices", "sales-doc", "No sales invoices yet. Start one from Sales invoices."); + const buys = recentBlock("Last purchase invoices", "purchase-invoices", "purchase-doc", "No purchase invoices yet. Start one from Purchase invoices."); + placeholder.replaceWith(h("div", { class: "tiles" }, owedEl, oweEl[0], cashEl[0]), h("div", { class: "recents" }, sales.el, buys.el)); + + const api = engine.api; + const amount = (t: Tile, p: Promise) => + p.then( + (v) => setText(t.value, money(v)), + () => setText(t.value, "Not available"), + ); + let seq = 0; + const load = () => { + const me = engine.state.get("me"); + if (engine.state.get("screen") !== "app" || engine.state.get("route") !== "home" || !me || me.claimRequired) return; + const mine = ++seq; + const live = () => mine === seq; + void amount(owed, api.call<{ customers: number }>("GET", "/api/receivables/reconcile").then((r) => r.customers)); + 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<{ docs: RecentDoc[] }>("GET", `/api/sales/docs?kind=invoice&limit=${RECENT_ROWS}`) + .then((r) => live() && sales.fill(r.docs), () => live() && sales.fail()); + api + .call<{ docs: RecentDoc[] }>("GET", `/api/purchase/docs?kind=invoice&limit=${RECENT_ROWS}`) + .then((r) => live() && buys.fill(r.docs), () => live() && buys.fail()); + }; + engine.state.watch("route", load); + engine.state.watch("screen", load); + engine.state.watch("me", load); +} + export function mountApp(engine: Engine): void { bindNav(engine); bindStatus(engine); + mountHome(engine); mountAccount(engine); mountViews(engine); } diff --git a/web/src/ui/parts/linegrid.ts b/web/src/ui/parts/linegrid.ts index 0e81a9a..81be994 100644 --- a/web/src/ui/parts/linegrid.ts +++ b/web/src/ui/parts/linegrid.ts @@ -40,6 +40,7 @@ export interface LineGridHandle { setLineError(index: number, message: string): void; focusFirst(): void; setCurrency(code: string): void; + flagMissing(): number[]; } const ZERO_DECIMAL = new Set(["JPY", "KRW", "VND", "CLP", "ISK", "UGX", "XAF", "XOF"]); @@ -60,6 +61,7 @@ interface Row { remove: HTMLButtonElement; error: HTMLElement; line: GridLine; + touched: boolean; } function removeIcon(): SVGSVGElement { @@ -98,10 +100,23 @@ export function mountLineGrid(host: HTMLElement, ctx: ViewContext, o: LineGridOp const head = h( "div", { class: "grid__row grid__head", attrs: { role: "row" } }, - ...["Item", "Description", "Quantity", "Unit price", "Tax", "Subtotal", "Tax amount", "Total", ""].map((t) => h("div", { class: "grid__th", attrs: { role: "columnheader" }, text: t })), + ...["Item", "Description", "Quantity", "Unit price", "Tax", "Subtotal", "Tax amount", "Amount", ""].map((t) => h("div", { class: "grid__th", attrs: { role: "columnheader" }, text: t })), ); const body = h("div", { class: "grid__body", attrs: { role: "rowgroup" } }); - const addBtn = h("button", { class: "btn grid__add", attrs: { type: "button" }, text: "Add line" }); + const addBtn = h("button", { class: "btn grid__add", attrs: { type: "button", title: "Add line (Enter on the last line)" } }); + const plus = document.createElementNS(SVG, "svg"); + plus.setAttribute("viewBox", "0 0 16 16"); + plus.setAttribute("width", "16"); + plus.setAttribute("height", "16"); + plus.setAttribute("fill", "none"); + plus.setAttribute("stroke", "currentColor"); + plus.setAttribute("stroke-width", "1.5"); + plus.setAttribute("stroke-linecap", "round"); + plus.setAttribute("aria-hidden", "true"); + const plusPath = document.createElementNS(SVG, "path"); + plusPath.setAttribute("d", "M8 3v10M3 8h10"); + plus.append(plusPath); + addBtn.append(plus, h("span", { text: "Add line" })); const sumSub = h("span", { class: "grid__sum-value", text: fmt(0) }); const sumTax = h("span", { class: "grid__sum-value", text: fmt(0) }); const sumTotal = h("span", { class: "grid__sum-value grid__sum-value--total", text: fmt(0) }); @@ -125,16 +140,39 @@ export function mountLineGrid(host: HTMLElement, ctx: ViewContext, o: LineGridOp host.append(root); function emit(): void { + for (const r of rows) { + const net = isBlank(r.line) ? "" : fmt(Math.round((r.line.qtyMilli * r.line.unitPrice) / 1000)); + if (r.total.textContent !== net) setText(r.total, net); + } o.onChange(collect()); } + function idle(r: Row): boolean { + return isBlank(r.line) && !r.touched; + } + function collect(): GridLine[] { - emitted = rows.filter((r) => !isBlank(r.line)); + for (const r of rows) r.el.classList.toggle("is-idle", idle(r)); + emitted = rows.filter((r) => !idle(r)); return emitted.map((r) => ({ ...r.line })); } + function flagMissing(): number[] { + const out: number[] = []; + rows.forEach((r, i) => { + const bad = !idle(r) && isBlank(r.line); + if (bad) out.push(i + 1); + if (bad) setText(r.error, "Needs an item: pick one or remove the line"); + else if (r.el.classList.contains("needs-item")) setText(r.error, ""); + r.el.classList.toggle("needs-item", bad); + }); + return out; + } + function writeLine(r: Row, l: GridLine): void { r.line = { ...l }; + r.touched = false; + r.el.classList.remove("needs-item"); if (r.desc.value !== l.description) r.desc.value = l.description; const q = qty(l.qtyMilli); if (r.qty.value !== q) r.qty.value = q; @@ -207,6 +245,10 @@ export function mountLineGrid(host: HTMLElement, ctx: ViewContext, o: LineGridOp bare: true, onPick: (picked) => { r.line.itemId = picked?.id ?? ""; + if (picked && r.el.classList.contains("needs-item")) { + r.el.classList.remove("needs-item"); + setText(r.error, ""); + } if (picked) { const rec = picked.record; if (!r.line.description.trim()) { @@ -235,13 +277,14 @@ export function mountLineGrid(host: HTMLElement, ctx: ViewContext, o: LineGridOp emit(); }, }); - Object.assign(r, { el, item, desc, qty: qtyIn, price, tax, sub, taxAmt, total, remove, error, line: { ...l } }); + Object.assign(r, { el, item, desc, qty: qtyIn, price, tax, sub, taxAmt, total, remove, error, line: { ...l }, touched: false }); desc.addEventListener("input", () => { r.line.description = desc.value; emit(); }); qtyIn.addEventListener("input", () => { + r.touched = qtyIn.value.trim() !== ""; const v = parseQty(qtyIn.value); const ok = v !== null && v > 0; qtyIn.classList.toggle("is-invalid", !ok); @@ -254,6 +297,7 @@ export function mountLineGrid(host: HTMLElement, ctx: ViewContext, o: LineGridOp if (!qtyIn.classList.contains("is-invalid")) qtyIn.value = qty(r.line.qtyMilli); }); price.addEventListener("input", () => { + r.touched = price.value.trim() !== ""; const v = parseMoney(price.value, places); const ok = v !== null && v >= 0; price.classList.toggle("is-invalid", !ok); @@ -350,7 +394,7 @@ export function mountLineGrid(host: HTMLElement, ctx: ViewContext, o: LineGridOp if (lt) { setText(r.sub, fmt(lt.subtotal)); setText(r.taxAmt, fmt(lt.tax)); - setText(r.total, fmt(lt.total)); + setText(r.total, fmt(lt.subtotal)); } else clearTotals(r); } setText(sumSub, fmt(t.subtotal)); @@ -370,6 +414,7 @@ export function mountLineGrid(host: HTMLElement, ctx: ViewContext, o: LineGridOp r.el.classList.toggle("has-error", Boolean(message)); }, focusFirst: () => focusCell(rows[0], "item"), + flagMissing, setCurrency: (code) => { if (code === currency) return; currency = code; diff --git a/web/src/ui/parts/table.ts b/web/src/ui/parts/table.ts index ed9632f..9df2bf6 100644 --- a/web/src/ui/parts/table.ts +++ b/web/src/ui/parts/table.ts @@ -7,6 +7,7 @@ export interface Column { align?: "start" | "end"; text(row: T): string; tone?(row: T): string; + mono?: boolean; } export interface TableOptions { @@ -15,9 +16,53 @@ export interface TableOptions { rowKey(row: T): string; empty: string; foot?: boolean; + grow?: boolean; onOpen?(row: T): void; } +export type BadgeTone = "muted" | "info" | "ok" | "warn" | "bad"; + +const BADGE_TONES: Record = { + muted: "muted", + info: "info", + ok: "ok", + warn: "warn", + bad: "bad", + draft: "muted", + confirmed: "info", + open: "info", + posted: "ok", + paid: "ok", + partpaid: "warn", + partiallypaid: "warn", + partial: "warn", + overdue: "warn", + cancelled: "bad", + canceled: "bad", + void: "bad", +}; + +export function statusTone(status: string): BadgeTone { + return BADGE_TONES[status.toLowerCase().replace(/[\s_-]+/g, "")] ?? "muted"; +} + +const CELL_TONES = new Set(["muted", "danger"]); + +function writeCell(cell: HTMLTableCellElement, text: string, tone: string) { + const badge = cell.firstElementChild instanceof HTMLSpanElement && cell.firstElementChild.classList.contains("badge") ? cell.firstElementChild : null; + if (tone && !CELL_TONES.has(tone)) { + setAttr(cell, "data-tone", null); + const el = badge ?? h("span", { class: "badge" }); + if (!badge) cell.replaceChildren(el); + setText(el, text.charAt(0).toUpperCase() + text.slice(1)); + setAttr(el, "data-tone", statusTone(tone)); + return; + } + if (badge) cell.replaceChildren(); + setText(cell, text); + setAttr(cell, "data-tone", tone || null); +} + export interface TableHandle { root: HTMLElement; setRows(rows: T[]): void; @@ -51,8 +96,8 @@ export function mountTable(host: HTMLElement, o: TableOptions): TableHandl const fill = h("td", { attrs: { colspan: String(o.columns.length), "aria-hidden": "true" } }); table.append(h("tbody", { class: "tbl__fill" }, h("tr", {}, fill)), h("tfoot", {}, row)); } - const root = h("div", { class: "tbl", attrs: o.foot ? { "data-empty": "true", "data-foot": "true" } : { "data-empty": "true" } }, table, empty, error); - host.append(root); + const root = h("div", { class: o.grow ? "tbl tbl--grow" : "tbl", attrs: o.foot ? { "data-empty": "true", "data-foot": "true" } : { "data-empty": "true" } }, table, empty, error); + host.append(o.grow && o.foot ? h("div", { class: "tbl-wrap" }, root) : root); const rows = new Map(); @@ -60,14 +105,13 @@ export function mountTable(host: HTMLElement, o: TableOptions): TableHandl o.columns.forEach((c, i) => { const cell = el.cells[i]; if (!cell) return; - setText(cell, c.text(row)); - setAttr(cell, "data-tone", c.tone?.(row) || null); + writeCell(cell, c.text(row), c.tone?.(row) || ""); }); }; const make = (key: string, row: T): HTMLTableRowElement => { const el = h("tr", { attrs: o.onOpen ? { "data-key": key, tabindex: "0" } : { "data-key": key } }); - for (const c of o.columns) el.append(h("td", { attrs: align(c) })); + for (const c of o.columns) el.append(h("td", { attrs: c.mono ? { ...align(c), "data-mono": "true" } : align(c) })); fill(el, row); return el; }; diff --git a/web/src/ui/views.ts b/web/src/ui/views.ts index 2b49151..d9da5d2 100644 --- a/web/src/ui/views.ts +++ b/web/src/ui/views.ts @@ -21,7 +21,7 @@ export interface ViewDef { group: ViewGroup; nav: boolean; icon?: IconName; - mount(host: HTMLElement, ctx: ViewContext): void; + mount(host: HTMLElement, ctx: ViewContext, actions: HTMLElement): void; show?(params: URLSearchParams): void; hide?(): void; } @@ -30,6 +30,7 @@ interface Mounted { def: ViewDef; section: HTMLElement; body: HTMLElement; + actions: HTMLElement; link: HTMLAnchorElement | null; ready: boolean; } @@ -67,10 +68,11 @@ export function mountViews(engine: Engine): void { if (defs.some((d) => d.nav)) nav.append(h("p", { class: "sb-group", text: group })); for (const def of defs) { const body = h("div", { class: "page__body" }); + const actions = h("div", { class: "page__actions" }); const section = h( "section", { class: "view view--page", attrs: { "data-view": def.id, "aria-label": def.title } }, - h("div", { class: "page" }, h("h1", { class: "page__title", text: def.title }), body), + h("div", { class: "page" }, h("header", { class: "page__head" }, h("h1", { class: "page__title", text: def.title }), actions), body), ); scroller.append(section); let link: HTMLAnchorElement | null = null; @@ -81,7 +83,7 @@ export function mountViews(engine: Engine): void { link = h("a", { class: "sb-item", attrs: { href: hashFor(def.id) } }, mark, h("span", { class: "sb-label", text: def.title })); nav.append(link); } - views.set(def.id, { def, section, body, link, ready: false }); + views.set(def.id, { def, section, body, actions, link, ready: false }); } } @@ -102,7 +104,7 @@ export function mountViews(engine: Engine): void { return; } if (!next.ready) { - next.def.mount(next.body, ctx); + next.def.mount(next.body, ctx, next.actions); next.ready = true; } if (active !== next) { @@ -110,7 +112,10 @@ export function mountViews(engine: Engine): void { active = next; engine.state.set("route", id); setAttr(next.section, "data-active", "true"); - if (next.link) setAttr(next.link, "aria-current", "page"); + if (next.link) { + setAttr(next.link, "aria-current", "page"); + next.link.scrollIntoView({ block: "nearest" }); + } setText(title, next.def.title); } next.def.show?.(params); diff --git a/web/src/ui/views/docform.ts b/web/src/ui/views/docform.ts index 0251bb7..a8963ef 100644 --- a/web/src/ui/views/docform.ts +++ b/web/src/ui/views/docform.ts @@ -15,7 +15,7 @@ import { type Family, type FamilySpec, } from "../../engine/docform"; -import { money, today } from "../../engine/format"; +import { today } from "../../engine/format"; import { delayedIndicator, h, setAttr, setText } from "../dom"; import { mountLineGrid, type GridLine, type GridTotals, type LineGridHandle } from "../parts/linegrid"; import { mountPicker, type PickerHandle } from "../parts/picker"; @@ -48,6 +48,8 @@ const GLYPHS = { make: "M3 8h9 M9 4.5l3.5 3.5-3.5 3.5", }; +const TONES: Record = { draft: "muted", confirmed: "info", open: "info", posted: "ok", paid: "ok", cancelled: "bad" }; + function button(label: string, d: string, primary = false): HTMLButtonElement { const b = h("button", { class: primary ? "btn btn--primary df-btn" : "btn df-btn", attrs: { type: "button" } }); b.append(glyph(d), h("span", { class: "df-btn__label", text: label })); @@ -72,7 +74,7 @@ function emptyTotals(): GridTotals { return { lines: [], subtotal: 0, tax: 0, total: 0 }; } -function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext): (params: URLSearchParams) => void { +function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext, headActions: HTMLElement): (params: URLSearchParams) => void { const firstKind = spec.kinds[0]?.id ?? "order"; let doc: Doc | null = null; let newKind = firstKind; @@ -82,10 +84,15 @@ function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext): (para const kindSelect = h("select", { class: "input df-kind", attrs: { "aria-label": "Kind" } }); for (const k of spec.kinds) kindSelect.append(h("option", { attrs: { value: k.id }, text: k.label })); - const numberText = h("span", { class: "df-number", text: "New draft" }); - const statusText = h("span", { class: "df-status", attrs: { "data-status": "draft" }, text: "Draft" }); + const shellTitle = host.closest(".page")?.querySelector(".page__title") ?? null; + const numberText = shellTitle ?? h("h2", { class: "df-number", text: "New draft" }); + numberText.classList.add("df-number"); + const statusText = h("span", { class: "badge df-status", attrs: { "data-status": "draft", "data-tone": "muted" }, text: "Draft" }); const busyText = h("span", { class: "df-busy", attrs: { "aria-live": "polite" }, text: "Working" }); - const head = h("div", { class: "df-head" }, kindSelect, numberText, statusText, busyText); + const title = h("div", { class: "df-title" }, statusText, busyText); + if (shellTitle) shellTitle.after(title); + else title.prepend(numberText); + headActions.append(kindSelect); const partyHost = h("div", { class: "df-picker" }); const dateInput = h("input", { class: "input", attrs: { type: "date", required: "" } }); @@ -95,7 +102,7 @@ function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext): (para const memoInput = h("input", { class: "input", attrs: { type: "text", maxlength: "500", autocomplete: "off" } }); const fields = h( "div", - { class: "df-fields" }, + { class: spec.hasReference ? "df-fields df-fields--ref" : "df-fields" }, h("div", { class: "field df-field df-field--party" }, partyHost), field("Date", dateInput), field("Due date", dueInput), @@ -109,12 +116,15 @@ function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext): (para const saveBtn = button("Save draft", GLYPHS.save); const confirmBtn = button("Confirm", GLYPHS.confirm, true); - const cancelBtn = button("Cancel", GLYPHS.cancel); + const cancelBtn = button("Cancel document", GLYPHS.cancel); const amendBtn = button("Amend", GLYPHS.amend); + saveBtn.classList.add("df-btn--save"); + cancelBtn.classList.add("df-btn--cancel"); + amendBtn.classList.add("df-btn--amend"); const makeBtns = new Map(spec.makes.map((m) => [m.key, button(m.label, GLYPHS.make)])); const actions = h("div", { class: "df-actions" }, saveBtn, confirmBtn, cancelBtn, amendBtn, h("span", { class: "df-actions__gap" }), ...makeBtns.values()); - root.append(head, fields, gridHost, errorLine, actions); + root.append(fields, gridHost, errorLine, actions); host.append(root); const party = mountPicker(partyHost, ctx, { kind: spec.partyKind, label: spec.partyLabel, required: true, onPick: () => refresh() }); @@ -155,10 +165,12 @@ function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext): (para for (const input of [dateInput, dueInput, refInput, memoInput]) input.readOnly = !editable; party.setDisabled(!editable); warehouse.setDisabled(!editable && spec.family === "purchase"); - setText(numberText, doc ? doc.number || "Draft, not numbered" : "New draft"); + setText(numberText, `${kindLabel(spec, kind)} ${doc ? doc.number || "draft" : "new"}`); const status = doc?.status ?? "draft"; setAttr(statusText, "data-status", status); - setText(statusText, `${kindLabel(spec, kind)} · ${statusLabel(kind, status)}${doc ? ` · ${doc.currency} ${money(doc.total)}` : ""}`); + setAttr(statusText, "data-tone", TONES[status] ?? "muted"); + setText(statusText, statusLabel(kind, status)); + setAttr(root, "data-readonly", editable ? null : ""); }; const writeTotals = (d: Doc) => { @@ -240,6 +252,8 @@ function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext): (para const save = async (): Promise => { const wasNew = !doc; + const missing = grid.flagMissing(); + if (missing.length) throw new Error(`${missing.length === 1 ? "Line" : "Lines"} ${missing.join(", ")} ${missing.length === 1 ? "needs" : "need"} an item. Pick an item or remove the line.`); const saved = await saveDraft(ctx.api, spec, doc?.id ?? null, draft()); await fill(saved); if (wasNew) ctx.go(spec.view, { id: saved.id }); @@ -308,8 +322,8 @@ function formView(family: Family): ViewDef { title: spec.title, group: family === "sales" ? "Selling" : "Buying", nav: false, - mount(host, ctx) { - show = mountForm(spec, host, ctx); + mount(host, ctx, actions) { + show = mountForm(spec, host, ctx, actions); }, show(params) { show?.(params); diff --git a/web/src/ui/views/doclists.ts b/web/src/ui/views/doclists.ts index fdf00a0..120f8b9 100644 --- a/web/src/ui/views/doclists.ts +++ b/web/src/ui/views/doclists.ts @@ -17,9 +17,8 @@ function plusIcon(): SVGSVGElement { const STATUS_LABEL: Record = { draft: "Draft", posted: "Posted", cancelled: "Cancelled" }; -function countText(shown: number, more: boolean): string { - if (!shown) return ""; - return `${shown} shown${more ? ", more to load" : ""}`; +function countText(shown: number): string { + return shown ? `${shown} shown` : ""; } function listView(spec: DocListSpec): ViewDef { @@ -52,7 +51,7 @@ function listView(spec: DocListSpec): ViewDef { if (mine === seq) { table.setBusy(false); setAttr(more, "disabled", cursor ? null : ""); - setText(count, countText(shown, cursor !== "")); + setText(count, countText(shown)); } } }; @@ -62,38 +61,36 @@ function listView(spec: DocListSpec): ViewDef { title: spec.title, group: spec.group, nav: true, - mount(host, c) { + mount(host, c, actions) { ctx = c; - const root = h("div", { class: "dl" }); - filter = h("select", { class: "input dl__filter", attrs: { id: `dl-status-${spec.id}` } },h("option", { attrs: { value: "" }, text: "All statuses" }), ...STATUSES.map((s) => h("option", { attrs: { value: s }, text: STATUS_LABEL[s] }))); - filter.addEventListener("change", () => ctx.go(spec.id, filter.value ? { status: filter.value } : {})); - const bar = h("div", { class: "dl__bar" }, h("label", { class: "dl__label", attrs: { for: `dl-status-${spec.id}` }, text: "Status" }), filter, h("span", { class: "dl__gap" })); 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 })); - bar.append(add); + actions.append(add); } - root.append(bar); - const tableHost = h("div", { class: "dl__table" }); - root.append(tableHost); - table = mountTable(tableHost, { + filter = h("select", { class: "input dl__filter", attrs: { id: `dl-status-${spec.id}` } }, h("option", { attrs: { value: "" }, text: "All statuses" }), ...STATUSES.map((s) => h("option", { attrs: { value: s }, text: STATUS_LABEL[s] }))); + filter.addEventListener("change", () => ctx.go(spec.id, filter.value ? { status: filter.value } : {})); + count = h("span", { class: "dl__count", attrs: { "aria-live": "polite" } }); + const bar = h("div", { class: "bar dl__bar" }, h("label", { class: "dl__label", attrs: { for: `dl-status-${spec.id}` }, text: "Status" }), filter, h("span", { class: "bar__grow" }), count); + more = h("button", { class: "btn btn--quiet dl__more", attrs: { type: "button", disabled: "" }, text: "Load more" }); + more.addEventListener("click", () => void run(true)); + if (spec.paged) bar.append(more); + const root = h("div", { class: "page page--fill dl" }, bar); + table = mountTable(root, { label: spec.title, rowKey: (r) => r.id, - empty: `No ${spec.title.toLowerCase()} yet.`, + empty: spec.empty, + grow: true, onOpen: (r) => ctx.go(spec.form, { id: r.id }), columns: [ - { key: "number", label: "Number", width: "var(--dl-col-number)", text: (r) => r.number || "Draft", tone: (r) => (r.number ? "" : "muted") }, + { key: "number", label: "Number", width: "var(--dl-col-number)", mono: true, text: (r) => r.number || "Draft", tone: (r) => (r.number ? "" : "muted") }, { key: "date", label: "Date", width: "var(--dl-col-date)", text: (r) => r.date }, { key: "party", label: spec.party === "customer" ? "Customer" : "Supplier", width: "auto", text: (r) => r.party }, { key: "status", label: "Status", width: "var(--dl-col-status)", text: (r) => STATUS_LABEL[r.status] ?? r.status, tone: (r) => r.status }, - { key: "total", label: spec.totalLabel, width: "var(--dl-col-total)", align: "end", text: (r) => (r.currency ? `${money(r.total)} ${r.currency}` : money(r.total)) }, + { key: "currency", label: "Cur", width: "var(--dl-col-cur)", mono: true, text: (r) => r.currency, tone: () => "muted" }, + { key: "total", label: spec.totalLabel, width: "var(--dl-col-total)", align: "end", text: (r) => money(r.total) }, ], }); - count = h("span", { class: "dl__count", attrs: { "aria-live": "polite" } }); - more = h("button", { class: "btn btn--quiet dl__more", attrs: { type: "button", disabled: "" }, text: "Load more" }); - more.addEventListener("click", () => void run(true)); - bar.insertBefore(count, bar.querySelector(".dl__gap")); - if (spec.paged) bar.insertBefore(more, bar.querySelector(".dl__gap")); host.append(root); }, show(params) { diff --git a/web/src/ui/views/ledger-screens.ts b/web/src/ui/views/ledger-screens.ts index 1939204..6515e60 100644 --- a/web/src/ui/views/ledger-screens.ts +++ b/web/src/ui/views/ledger-screens.ts @@ -1,7 +1,7 @@ import { ApiError } from "../../engine/session"; -import { amount, balanceLine, loadAccounts, loadAgeing, loadLedger, loadStock, loadTrial, tieLine, type AgeingRow, type LedgerLine, type StockRow, type TrialRow } from "../../engine/ledger-screens"; +import { amount, loadAccounts, loadAgeing, loadLedger, loadStock, loadTrial, type AgeingRow, type LedgerLine, type StockRow, type TrialRow } from "../../engine/ledger-screens"; import { qty, today } from "../../engine/format"; -import { h, setText } from "../dom"; +import { h, setAttr, setText } from "../dom"; import type { ViewContext, ViewDef, ViewGroup } from "../views"; import { mountTable, type Column, type TableHandle } from "../parts/table"; @@ -18,30 +18,38 @@ interface Screen { } const date = (value: string): Control => { - const el = h("input", { class: "input ls__input", attrs: { type: "date", value } }); + const el = h("input", { class: "input ls__date", attrs: { type: "date", value } }); return { el, read: () => el.value }; }; const choose = (options: [string, string][]): Control => { - const el = h("select", { class: "input ls__input" }); + const el = h("select", { class: "input ls__select" }); for (const [value, label] of options) el.append(h("option", { text: label, attrs: { value } })); return { el, read: () => el.value }; }; const dash = (n: number) => (n ? amount(n) : ""); +const OPENING = "opening"; +const PICK = "Pick an account to see its ledger lines."; function shell(host: HTMLElement, controls: { label: string; control: Control }[], onChange: () => void) { - const bar = h("div", { class: "ls__bar" }); + const bar = h("div", { class: "bar ls__bar" }); for (const { label, control } of controls) { const field = h("label", { class: "ls__field" }, h("span", { class: "ls__label", text: label }), control.el); control.el.addEventListener("change", onChange); bar.append(field); } - const status = h("p", { class: "ls__status", attrs: { role: "status" } }); + const status = h("span", { class: "ls__status", attrs: { role: "status" } }); + const badge = h("span", { class: "badge ls__badge", attrs: { "data-tone": "muted" } }); + bar.append(h("span", { class: "bar__grow" }), status, badge); const tableHost = h("div", { class: "ls__table" }); - host.classList.add("ls"); - host.append(bar, status, tableHost); - return { status, tableHost }; + host.append(h("div", { class: "page page--fill ls" }, bar, tableHost)); + return { status, badge, tableHost }; +} + +function mark(badge: HTMLElement, tone: string, text: string) { + setAttr(badge, "data-tone", tone); + setText(badge, text); } function guard(table: TableHandle, status: HTMLElement) { @@ -81,9 +89,9 @@ function trialScreen(): ViewDef { nav: true, mount(host, ctx) { const asOf = date(today()); - const { status, tableHost } = shell(host, [{ label: "As of", control: asOf }], () => reload()); + const { status, badge, tableHost } = shell(host, [{ label: "As of", control: asOf }], () => reload()); const cols: Column[] = [ - { key: "code", label: "Code", width: "110px", text: (r) => r.code }, + { key: "code", label: "Code", width: "110px", mono: true, text: (r) => r.code }, { key: "name", label: "Account", width: "auto", text: (r) => r.name }, { key: "type", label: "Type", width: "110px", text: (r) => r.type, tone: () => "muted" }, num("debit", "Debit", (r) => r.debit, "130px", true), @@ -96,7 +104,8 @@ function trialScreen(): ViewDef { const t = await loadTrial(ctx.api, asOf.read()); table.setRows(t.rows); table.setFoot({ name: "Total", debit: amount(t.totalDebit), credit: amount(t.totalCredit) }); - return balanceLine(t); + mark(badge, t.balanced ? "ok" : "bad", t.balanced ? "Balanced" : `Out by ${amount(Math.abs(t.totalDebit - t.totalCredit))}`); + return `${t.rows.length} accounts with a balance`; }); }, show() { @@ -126,22 +135,26 @@ function ledgerScreen(): ViewDef { () => reload(), ); const cols: Column[] = [ - { key: "date", label: "Date", width: "110px", text: (r) => r.date }, - { key: "number", label: "Entry", width: "150px", text: (r) => r.number }, - { key: "memo", label: "Memo", width: "auto", text: (r) => r.memo }, + { key: "date", label: "Date", width: "110px", mono: true, text: (r) => r.date }, + { key: "number", label: "Entry", width: "150px", mono: true, text: (r) => r.number }, + { key: "memo", label: "Memo", width: "auto", text: (r) => r.memo, tone: (r) => (r.entryId === OPENING ? "muted" : "") }, num("debit", "Debit", (r) => r.debit, "120px", true), num("credit", "Credit", (r) => r.credit, "120px", true), num("balance", "Balance", (r) => r.balance, "130px"), ]; - const table = mountTable(tableHost, { label: "General ledger", columns: cols, rowKey: (r) => `${r.entryId}:${r.lineNo}`, empty: "No lines in this range.", foot: true }); + const table = mountTable(tableHost, { label: "General ledger", columns: cols, rowKey: (r) => `${r.entryId}:${r.lineNo}`, empty: PICK, foot: true }); + const hint = table.root.querySelector(".tbl__empty"); const run = guard(table as TableHandle, status); reload = () => { if (!account.read()) return; void run(async () => { const l = await loadLedger(ctx.api, account.read(), from.read(), to.read()); - table.setRows(l.lines); - table.setFoot({ memo: "Opening", balance: amount(l.opening) }); - return `Opening ${amount(l.opening)}, closing ${amount(l.closing)}, ${l.totalLines} lines${l.totalLines > l.lines.length ? ` (first ${l.lines.length} shown)` : ""}.`; + if (hint) setText(hint, "No lines in this range."); + const first: LedgerLine = { date: from.read(), number: "", entryId: OPENING, lineNo: 0, memo: "Opening balance", debit: 0, credit: 0, balance: l.opening }; + table.setRows([first, ...l.lines]); + const sum = (pick: (r: LedgerLine) => number) => l.lines.reduce((s, r) => s + pick(r), 0); + table.setFoot({ memo: "Closing balance", debit: dash(sum((r) => r.debit)), credit: dash(sum((r) => r.credit)), balance: amount(l.closing) }); + return `${l.totalLines} lines${l.totalLines > l.lines.length ? `, first ${l.lines.length} shown` : ""}`; }); }; void loadAccounts(ctx.api) @@ -177,9 +190,11 @@ function ageingScreen(id: string, title: string, group: ViewGroup, side: "receiv ], () => reload(), ); + tableHost.dataset.ageing = "true"; const cols: Column[] = [ - { key: "name", label: party, width: "auto", text: (r) => `${r.code} ${r.name}` }, - { key: "cur", label: "Cur", width: "56px", text: (r) => r.currency, tone: () => "muted" }, + { key: "code", label: "Code", width: "100px", mono: true, text: (r) => r.code }, + { key: "name", label: party, width: "auto", text: (r) => r.name }, + { key: "cur", label: "Cur", width: "56px", mono: true, text: (r) => r.currency, tone: () => "muted" }, num("current", "Current", (r) => r.current, "104px", true), num("d30", "1 to 30", (r) => r.days1to30, "104px", true), num("d60", "31 to 60", (r) => r.days31to60, "104px", true), @@ -200,7 +215,7 @@ function ageingScreen(id: string, title: string, group: ViewGroup, side: "receiv ? { name: "Total", cur: one.currency, current: dash(one.current), d30: dash(one.days1to30), d60: dash(one.days31to60), d90: dash(one.days61to90), over: dash(one.over90), un: dash(one.unallocated), total: amount(one.total) } : { name: a.totals.length ? "Several currencies, see the line above" : "Total" }, ); - return a.totals.length > 1 ? a.totals.map((t) => `${t.currency} ${amount(t.total)}`).join(" · ") : `${a.rows.length} ${party.toLowerCase()}s with a balance.`; + return a.totals.length > 1 ? a.totals.map((t) => `${t.currency} ${amount(t.total)}`).join(" · ") : `${a.rows.length} ${party.toLowerCase()}s with a balance`; }); }, show() { @@ -218,9 +233,9 @@ function stockScreen(): ViewDef { nav: true, mount(host, ctx) { const asOf = date(today()); - const { status, tableHost } = shell(host, [{ label: "As of", control: asOf }], () => reload()); + const { status, badge, tableHost } = shell(host, [{ label: "As of", control: asOf }], () => reload()); const cols: Column[] = [ - { key: "code", label: "Item", width: "120px", text: (r) => r.code }, + { key: "code", label: "Item", width: "120px", mono: true, text: (r) => r.code }, { key: "name", label: "Name", width: "auto", text: (r) => r.name }, { key: "where", label: "Warehouses", width: "220px", text: (r) => r.where, tone: () => "muted" }, { key: "qty", label: "Quantity", width: "110px", align: "end", text: (r) => qty(r.qtyMilli) }, @@ -234,7 +249,8 @@ function stockScreen(): ViewDef { const s = await loadStock(ctx.api, asOf.read()); table.setRows(s.rows); table.setFoot({ name: "Total", value: amount(s.total) }); - return tieLine(s); + mark(badge, s.matched ? "ok" : "bad", s.matched ? "Agrees with ledger" : `Differs by ${amount(Math.abs(s.difference))}`); + return `${s.rows.length} items`; }); }, show() { diff --git a/web/src/ui/views/masters.ts b/web/src/ui/views/masters.ts index 0324a03..025698d 100644 --- a/web/src/ui/views/masters.ts +++ b/web/src/ui/views/masters.ts @@ -1,4 +1,4 @@ -import { boolValue, buildBody, cell, create, fieldText, listAll, MASTERS, update, type Field, type Master, type Raw, type Row } from "../../engine/masters"; +import { boolValue, buildBody, 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"; @@ -8,46 +8,68 @@ import type { ViewContext, ViewDef } from "../views"; const ICONS: Record = { customers: "user", suppliers: "user" }; function mountMaster(m: Master, host: HTMLElement, ctx: ViewContext): { show(): void } { - const root = h("div", { class: "masters" }); + host.parentElement?.classList.add("page--fill"); + const root = h("div", { class: m.id === "accounts" ? "masters masters--tree" : "masters" }); const listHost = h("div", { class: "masters__list" }); root.append(listHost); host.append(root); + let depth = new Map(); + const tree = m.id === "accounts"; const table: TableHandle = mountTable(listHost, { label: m.title, - columns: m.columns.map((c) => ({ key: c.key, label: c.label, width: c.width, align: c.end ? "end" : "start", text: (r: Row) => cell(r, c.key) })), + columns: m.columns.map((c) => ({ + key: c.key, + label: c.label, + width: c.width, + align: c.end ? "end" : "start", + mono: c.mono === true, + text: (r: Row) => cell(r, c.key), + tone: (r: Row) => (!c.badge ? "" : c.key === "active" ? (r.active ? "ok" : "inactive") : cell(r, c.key) ? "inactive" : ""), + })), rowKey: (r) => String(r.id), - empty: `No ${m.title.toLowerCase()} yet.`, + empty: `No ${m.title.toLowerCase()} yet. Fill in the form at the right and press Save to add the first one.`, + grow: true, onOpen: (r) => fill(r), }); - const mode = h("p", { class: "masters__mode" }); + const decorate = (tr: Element | null | undefined) => { + if (!tree || !(tr instanceof HTMLElement)) return; + const code = tr.firstElementChild?.textContent ?? ""; + const d = Math.min(depth.get(code) ?? 0, 4); + setAttr(tr, "data-depth", d ? String(d) : null); + }; + const rowEl = (id: string) => listHost.querySelector(`tr[data-key="${CSS.escape(id)}"]`); + + const heading = h("h2", { class: "masters__title" }); const fieldsBox = h("div", { class: "masters__fields" }); const error = h("p", { class: "form__error", attrs: { role: "alert" } }); const save = h("button", { class: "btn btn--primary", text: "Save", attrs: { type: "button" } }); - const fresh = h("button", { class: "btn", text: "New", attrs: { type: "button" } }); + const fresh = h("button", { class: "btn btn--quiet", text: "New", attrs: { type: "button", title: `Clear the form to add a new ${m.singular}` } }); const panel = h( - "div", - { class: "panel masters__form" }, - mode, - fieldsBox, - error, - h("div", { class: "masters__actions" }, h("span"), h("span", {}, fresh, " ", save)), + "section", + { class: "panel masters__form", attrs: { "aria-label": `${m.title} form` } }, + heading, + h("div", { class: "masters__scroll" }, fieldsBox, error), + h("div", { class: "form__actions masters__actions" }, fresh, save), ); root.append(panel); const inputs = new Map(); for (const f of m.fields) { const boolean = f.kind === "bool"; + const id = `${m.id}-${f.key}`; let input: HTMLInputElement | HTMLSelectElement; if (f.kind === "select") { - input = h("select", { class: "input", attrs: { id: `${m.id}-${f.key}` } }); + input = h("select", { class: "input", attrs: { id } }); for (const o of f.options ?? []) input.append(h("option", { text: o, attrs: { value: o } })); } else { - input = h("input", { class: boolean ? "" : "input", attrs: { id: `${m.id}-${f.key}`, type: boolean ? "checkbox" : "text", autocomplete: "off" } }); + input = h("input", { class: boolean ? "" : "input", attrs: { id, type: boolean ? "checkbox" : "text", autocomplete: "off", spellcheck: "false" } }); } - const label = h("label", { class: "field__label", text: f.label, attrs: { for: `${m.id}-${f.key}` } }); - const wrap = h("div", { class: boolean ? "masters__field masters__field--bool" : "masters__field" }, ...(boolean ? [input, label] : [label, input])); + if (f.required) setAttr(input, "aria-required", "true"); + const label = h("label", { class: "field__label", text: f.label, attrs: { for: id } }); + if (f.required) label.append(h("span", { class: "masters__req", text: " *", attrs: { "aria-hidden": "true" } })); + const wrap = h("div", { class: boolean ? "masters__field masters__field--bool" : "field masters__field", attrs: { "data-span": String(f.span ?? 4) } }, ...(boolean ? [input, label] : [label, input])); inputs.set(f.key, { field: f, input, wrap }); fieldsBox.append(wrap); } @@ -65,11 +87,13 @@ function mountMaster(m: Master, host: HTMLElement, ctx: ViewContext): { show(): const locked = Boolean(row) && field.createOnly === true; if (input.disabled !== locked) input.disabled = locked; } - setText(mode, row ? `Editing ${String(row.code ?? row.name ?? "")}` : `New ${m.singular}`); + setText(heading, title(m, row)); setText(error, ""); - for (const tr of listHost.querySelectorAll("tr[data-selected]")) setAttr(tr, "data-selected", null); + for (const tr of listHost.querySelectorAll("tr[data-selected]")) { + if (!row || tr.dataset.key !== String(row.id)) setAttr(tr, "data-selected", null); + } if (row) { - const tr = listHost.querySelector(`tr[data-key="${CSS.escape(String(row.id))}"]`); + const tr = rowEl(String(row.id)); if (tr) setAttr(tr, "data-selected", "true"); } }; @@ -117,7 +141,9 @@ function mountMaster(m: Master, host: HTMLElement, ctx: ViewContext): { show(): try { const isNew = !current; const row = current ? await update(ctx.api, m, String(current.id), built.body) : await create(ctx.api, m, built.body); + if (tree && isNew) depth.set(String(row.code ?? ""), row.parentCode ? (depth.get(String(row.parentCode)) ?? 0) + 1 : 0); table.patchRow(row); + decorate(rowEl(String(row.id))); if (isNew) place(row); fill(row); } catch (e) { @@ -139,7 +165,10 @@ function mountMaster(m: Master, host: HTMLElement, ctx: ViewContext): { show(): const load = async () => { table.setBusy(true); try { - table.setRows(await listAll(ctx.api, m)); + const rows = await listAll(ctx.api, m); + if (tree) depth = depthOf(rows); + table.setRows(rows); + for (const tr of listHost.querySelectorAll("tbody tr[data-key]")) decorate(tr); table.setError(""); loaded = true; } catch (e) { diff --git a/web/src/ui/views/payments.ts b/web/src/ui/views/payments.ts index c6dc920..b7b44c2 100644 --- a/web/src/ui/views/payments.ts +++ b/web/src/ui/views/payments.ts @@ -28,19 +28,23 @@ import { } from "../../engine/payments"; import { delayedIndicator, h, setAttr, setText } from "../dom"; import { mountPicker } from "../parts/picker"; -import { mountTable } from "../parts/table"; +import { mountTable, statusTone } from "../parts/table"; import type { ViewContext, ViewDef } from "../views"; const STATUSES = ["", "draft", "posted", "cancelled"]; -function mountList(dir: PayDir, host: HTMLElement, ctx: ViewContext): (params: URLSearchParams) => void { +function mountList(dir: PayDir, host: HTMLElement, ctx: ViewContext, head: HTMLElement): (params: URLSearchParams) => void { const f: PayFamily = FAMILIES[dir]; + host.parentElement?.classList.add("page--fill"); const root = h("div", { class: "pay pay--list" }); - const status = h("select", { class: "input pay__status", attrs: { "aria-label": "Status" } }); + const statusId = `pay-${dir}-status`; + const status = h("select", { class: "input pay__status", attrs: { id: statusId } }); for (const v of STATUSES) status.append(h("option", { attrs: { value: v }, text: v ? v.charAt(0).toUpperCase() + v.slice(1) : "All" })); - const add = h("button", { class: "btn btn--primary", attrs: { type: "button" }, text: "New payment" }); + const add = h("button", { class: "btn btn--primary", attrs: { type: "button" }, text: dir === "in" ? "Receive payment" : "Make payment" }); if (!ctx.can(f.draftPerm)) add.hidden = true; - const bar = h("div", { class: "pay__bar" }, status, add); + 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); const tableHost = h("div", { class: "pay__table" }); root.append(bar, tableHost); host.append(root); @@ -48,16 +52,17 @@ function mountList(dir: PayDir, host: HTMLElement, ctx: ViewContext): (params: U const table = mountTable(tableHost, { label: dir === "in" ? "Payments received" : "Payments made", columns: [ - { key: "number", label: "Number", width: "var(--pay-col-number)", text: (p) => p.number ?? "Draft" }, + { key: "number", label: "Number", width: "var(--pay-col-number)", mono: true, text: (p) => p.number ?? "Draft" }, { key: "date", label: "Date", width: "var(--pay-col-date)", text: (p) => p.date }, { key: "party", label: dir === "in" ? "Customer" : "Supplier", width: "auto", text: (p) => p.party }, { key: "status", label: "Status", width: "var(--pay-col-status)", text: (p) => p.status, tone: (p) => p.status }, - { key: "unallocated", label: "Unallocated", width: "var(--pay-col-money)", align: "end", text: (p) => money(p.unallocated) }, + { key: "unallocated", label: "Unallocated", width: "var(--pay-col-money)", align: "end", text: (p) => (p.unallocated ? money(p.unallocated) : "") }, { key: "amount", label: "Amount", width: "var(--pay-col-money)", align: "end", text: (p) => money(p.amount) }, ], rowKey: (p) => p.id, - empty: "No payments yet.", + empty: dir === "in" ? "Payments received from customers appear here. Press Receive payment to record the first one." : "Payments made to suppliers appear here. Press Make payment to record the first one.", foot: true, + grow: true, onOpen: (p) => ctx.go(form, { id: p.id }), }); let seq = 0; @@ -70,7 +75,8 @@ function mountList(dir: PayDir, host: HTMLElement, ctx: ViewContext): (params: U table.setRows(rows); table.setError(""); const total = rows.filter((p) => p.status !== "cancelled").reduce((a, p) => a + p.amount, 0); - table.setFoot({ number: `${rows.length} shown`, amount: money(total) }); + table.setFoot({ number: "Total", amount: money(total) }); + setText(count, `${rows.length} ${rows.length === 1 ? "payment" : "payments"}`); } catch (e) { if (mine === seq) table.setError(e instanceof Error ? e.message : String(e)); } finally { @@ -95,8 +101,8 @@ function listView(dir: PayDir): ViewDef { title: dir === "in" ? "Payments received" : "Payments made", group: dir === "in" ? "Selling" : "Buying", nav: true, - mount(host, ctx) { - show = mountList(dir, host, ctx); + mount(host, ctx, actions) { + show = mountList(dir, host, ctx, actions); }, show(params) { show?.(params); @@ -128,12 +134,12 @@ function mountForm(dir: PayDir, host: HTMLElement, ctx: ViewContext): (params: U account.append(h("option", { attrs: { value: "" }, text: dir === "in" ? "Default (1120)" : "Default" })); const memo = h("input", { class: "input", attrs: { autocomplete: "off" } }); const number = h("span", { class: "pay__number" }); - const status = h("span", { class: "pay__badge" }); + const status = h("span", { class: "badge pay__badge", attrs: { "data-tone": "muted" } }); const head = h("div", { class: "pay__head" }, number, status); const grid = h( "div", { class: "pay__grid" }, - h("div", { class: "field pay__field" }, h("span", { class: "field__label", text: dir === "in" ? "Customer" : "Supplier" }), partyHost), + h("div", { class: "pay__field pay__field--party" }, partyHost), field("Date", date), field("Amount", amount), field(dir === "in" ? "Deposit to" : "Paid from", account), @@ -178,7 +184,7 @@ function mountForm(dir: PayDir, host: HTMLElement, ctx: ViewContext): (params: U const post = h("button", { class: "btn btn--primary", attrs: { type: "button" }, text: "Post" }); const allocate = h("button", { class: "btn", attrs: { type: "button" }, text: "Allocate" }); const cancel = h("button", { class: "btn btn--quiet", attrs: { type: "button" }, text: "Cancel payment" }); - const actions = h("div", { class: "pay__actions" }, save, post, allocate, cancel); + const actions = h("div", { class: "form__actions pay__actions" }, cancel, allocate, save, post); const error = h("p", { class: "form__error pay__error", attrs: { role: "alert" } }); const root = h("div", { class: "pay pay--form panel", attrs: { "data-status": "new" } }, head, grid, h("h2", { class: "panel__title pay__sub", text: "Allocation" }), allocBox, error, actions); host.append(root); @@ -321,7 +327,9 @@ function mountForm(dir: PayDir, host: HTMLElement, ctx: ViewContext): (params: U party.setDisabled(!draft || !canDraft); for (const c of [date, amount, account, memo]) c.disabled = !draft || !canDraft; setText(number, current?.number ?? (current ? "Draft" : "New payment")); - setText(status, st === "new" ? "" : st); + setText(status, st === "new" ? "" : st.charAt(0).toUpperCase() + st.slice(1)); + setAttr(status, "data-tone", statusTone(st)); + status.hidden = st === "new"; }; const fill = (p: Payment | null) => { @@ -458,7 +466,7 @@ function formView(dir: PayDir): ViewDef { function mountStock(kind: StockKind, host: HTMLElement, ctx: ViewContext): (params: URLSearchParams) => void { const perm = "stock.post"; const number = h("span", { class: "pay__number" }); - const status = h("span", { class: "pay__badge" }); + const status = h("span", { class: "badge pay__badge", attrs: { "data-tone": "muted" } }); const value = (label: string) => { const v = h("span", { class: "pay__value" }); return { v, el: h("div", { class: "field pay__field" }, h("span", { class: "field__label", text: label }), v) }; @@ -478,7 +486,7 @@ function mountStock(kind: StockKind, host: HTMLElement, ctx: ViewContext): (para h("div", { class: "pay__grid" }, party.el, date.el, warehouse.el, memo.el), tableHost, error, - h("div", { class: "pay__actions" }, post, cancel, back), + h("div", { class: "form__actions pay__actions" }, back, cancel, post), ); host.append(root); const table = mountTable(tableHost, { @@ -504,7 +512,9 @@ function mountStock(kind: StockKind, host: HTMLElement, ctx: ViewContext): (para post.disabled = st !== "draft" || !canPost; cancel.disabled = st !== "posted" || !canPost; setText(number, current ? current.number || "Draft" : ""); - setText(status, st); + setText(status, st.charAt(0).toUpperCase() + st.slice(1)); + setAttr(status, "data-tone", statusTone(st)); + status.hidden = !st; }; const open = async (id: string | null) => { const mine = ++seq; diff --git a/web/src/ui/views/statements.ts b/web/src/ui/views/statements.ts index 7932a85..e077be1 100644 --- a/web/src/ui/views/statements.ts +++ b/web/src/ui/views/statements.ts @@ -9,7 +9,6 @@ import { type StatementSection, } from "../../engine/statements"; import { delayedIndicator, h, setAttr, setText } from "../dom"; -import { mountTable, type TableHandle } from "../parts/table"; import { hashFor, type ViewContext, type ViewDef } from "../views"; function goOrRefresh(ctx: ViewContext | null, id: string, params: Record, refresh: () => void): void { @@ -37,40 +36,44 @@ function runIcon(): SVGSVGElement { } interface Section { - table: TableHandle; - title: string; + list: HTMLElement; + none: HTMLElement; + total: HTMLElement; } function mountSection(host: HTMLElement, title: string, span = "in this range"): Section { - const wrap = h("div", { class: "st__section" }, h("h2", { class: "st__heading", text: title })); - host.append(wrap); - const table = mountTable(wrap, { - label: title, - columns: [ - { key: "code", label: "Code", width: "var(--st-code)", text: (r) => r.code }, - { key: "name", label: "Account", width: "auto", text: (r) => r.name }, - { key: "amount", label: "Amount", width: "var(--st-amount)", align: "end", text: (r) => money(r.amount), tone: (r) => (r.amount < 0 ? "danger" : "") }, - ], - rowKey: (r) => r.accountId, - empty: `No ${title.toLowerCase()} ${span}.`, - foot: true, - }); - table.setFoot({ name: `Total ${title.toLowerCase()}`, amount: money(0) }); - return { table, title }; + const list = h("div", { class: "st__lines" }); + const none = h("p", { class: "st__none", text: `No ${title.toLowerCase()} ${span}.` }); + const total = h("span", { class: "num", text: money(0) }); + const sub = h("p", { class: "st__sub" }, h("span", { text: `Total ${title.toLowerCase()}` }), total); + host.append(h("section", { class: "st__section", attrs: { "aria-label": title } }, h("h2", { class: "st__heading", text: title }), list, none, sub)); + return { list, none, total }; } -function fillSection(s: Section, data: StatementSection): void { - s.table.setRows(data.lines); - s.table.setFoot({ name: `Total ${s.title.toLowerCase()}`, amount: money(data.total) }); +function lineRow(l: StatementLine): HTMLElement { + return h( + "div", + { class: "st__line" }, + h("span", { class: "st__code", text: l.code }), + h("span", { class: "st__name", text: l.name }), + h("span", { class: "st__amount num", text: money(l.amount) }), + ); +} + +function fillSection(s: Section, data: StatementSection, extra: StatementLine[] = [], total = data.total): void { + const all = [...data.lines, ...extra]; + s.list.replaceChildren(...all.map(lineRow)); + setAttr(s.none, "hidden", all.length ? "" : null); + setText(s.total, money(total)); } interface Shell { root: HTMLElement; bar: HTMLFormElement; status: HTMLElement; - summary: HTMLElement; - sections: HTMLElement; - run: HTMLButtonElement; + badge: HTMLElement; + sheet: HTMLElement; + result: { label: HTMLElement; value: HTMLElement }; } function dateField(label: string, input: HTMLInputElement): HTMLElement { @@ -81,46 +84,36 @@ function dateInput(name: string): HTMLInputElement { return h("input", { class: "input st__date", attrs: { type: "date", name, required: "" } }); } -function mountShell(host: HTMLElement, fields: HTMLElement[]): Shell { +function mountShell(host: HTMLElement, fields: HTMLElement[], resultLabelText: string): Shell { const run = h("button", { class: "btn btn--primary st__run", attrs: { type: "submit" } }, runIcon(), h("span", { text: "Show" })); - const bar = h("form", { class: "st__bar", attrs: { role: "search" } }, ...fields, run); - const status = h("p", { class: "st__status", attrs: { role: "status", "aria-live": "polite" } }); - const sections = h("div", { class: "st__sections" }); - const summary = h("div", { class: "st__summary" }); - const root = h("div", { class: "st" }, bar, status, sections, summary); + const status = h("span", { class: "st__status", attrs: { role: "status", "aria-live": "polite" } }); + const badge = h("span", { class: "badge st__badge", attrs: { "data-tone": "muted" } }); + const bar = h("form", { class: "bar st__bar", attrs: { role: "search" } }, ...fields, run, h("span", { class: "bar__grow" }), status, badge); + const sheet = h("div", { class: "st__sheet", attrs: { "data-ready": "false" } }); + const label = h("span", { class: "st__result-label", text: resultLabelText }); + const value = h("span", { class: "st__result-value num", text: money(0) }); + const body = h("div", { class: "st__body" }, sheet, h("div", { class: "st__result" }, label, value)); + const root = h("div", { class: "page page--fill st" }, bar, body); host.append(root); - return { root, bar, status, summary, sections, run }; -} - -function summaryLine(host: HTMLElement, label: string): { label: HTMLElement; value: HTMLElement } { - const l = h("span", { class: "st__sum-label", text: label }); - const v = h("span", { class: "st__sum-value", text: money(0) }); - host.append(h("p", { class: "st__sum" }, l, v)); - return { label: l, value: v }; + return { root, bar, status, badge, sheet, result: { label, value } }; } function failText(err: unknown): string { return err instanceof ApiError || err instanceof Error ? err.message : "The statement could not be loaded."; } -function runner(shell: Shell, sections: Section[], load: () => Promise): () => void { +function runner(shell: Shell, load: () => Promise): () => void { let seq = 0; return () => { const mine = ++seq; const stop = delayedIndicator( - () => { - setAttr(shell.root, "aria-busy", "true"); - for (const s of sections) s.table.setBusy(true); - }, - () => { - setAttr(shell.root, "aria-busy", null); - for (const s of sections) s.table.setBusy(false); - }, + () => setAttr(shell.root, "aria-busy", "true"), + () => setAttr(shell.root, "aria-busy", null), ); load() .then((line) => { if (mine !== seq) return; - for (const s of sections) s.table.setError(""); + setAttr(shell.sheet, "data-ready", "true"); setText(shell.status, line); setAttr(shell.status, "data-tone", null); }) @@ -146,19 +139,18 @@ function profitAndLossView(): ViewDef { nav: true, mount(host, c) { ctx = c; - const shell = mountShell(host, [dateField("From", from), dateField("To", to)]); - const income = mountSection(shell.sections, "Income"); - const expenses = mountSection(shell.sections, "Expenses"); - const net = summaryLine(shell.summary, "Net profit"); - refresh = runner(shell, [income, expenses], async () => { + const shell = mountShell(host, [dateField("From", from), dateField("To", to)], "Net profit"); + const income = mountSection(shell.sheet, "Income"); + const expenses = mountSection(shell.sheet, "Expenses"); + refresh = runner(shell, async () => { if (!ctx) return ""; const p = await profitAndLoss(ctx.api, from.value, to.value); fillSection(income, p.income); fillSection(expenses, p.expenses); - setText(net.label, resultLabel(p.netProfit)); - setText(net.value, money(p.netProfit)); - setAttr(net.value, "data-tone", p.netProfit < 0 ? "danger" : null); - return `From ${p.from} to ${p.to}, posted entries and the reversals of cancelled ones.`; + setText(shell.result.label, resultLabel(p.netProfit)); + setText(shell.result.value, money(p.netProfit)); + setAttr(shell.result.value, "data-tone", p.netProfit < 0 ? "danger" : null); + return `${p.from} to ${p.to}`; }); shell.bar.addEventListener("submit", (e) => { e.preventDefault(); @@ -198,26 +190,21 @@ function balanceSheetView(): ViewDef { nav: true, mount(host, c) { ctx = c; - const shell = mountShell(host, [dateField("As of", asOf)]); - const assets = mountSection(shell.sections, "Assets", "on this day"); - const liabilities = mountSection(shell.sections, "Liabilities", "on this day"); - const equity = mountSection(shell.sections, "Equity", "on this day"); - const result = summaryLine(shell.summary, "Unclosed result in equity"); - const totalEquity = summaryLine(shell.summary, "Total equity"); - const both = summaryLine(shell.summary, "Total liabilities and equity"); - refresh = runner(shell, [assets, liabilities, equity], async () => { + 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"); + const equity = mountSection(shell.sheet, "Equity", "on this day"); + refresh = runner(shell, async () => { if (!ctx) return ""; const b = await balanceSheet(ctx.api, asOf.value); fillSection(assets, b.assets); fillSection(liabilities, b.liabilities); - fillSection(equity, b.equity); - setText(result.value, money(b.unclosedResult)); - setText(totalEquity.value, money(b.totalEquity)); - setText(both.value, money(b.totalLiabilitiesAndEquity)); - setAttr(both.value, "data-tone", b.balanced ? null : "danger"); - return b.balanced - ? `As of ${b.asOf}: assets equal liabilities plus equity.` - : `As of ${b.asOf}: assets and liabilities plus equity differ by ${money(b.assets.total - b.totalLiabilitiesAndEquity)}.`; + const unclosed: StatementLine[] = b.unclosedResult ? [{ accountId: "", code: "", name: "Unclosed result", currency: "", amount: b.unclosedResult }] : []; + fillSection(equity, b.equity, unclosed, b.totalEquity); + setText(shell.result.value, money(b.totalLiabilitiesAndEquity)); + setAttr(shell.badge, "data-tone", b.balanced ? "ok" : "bad"); + setText(shell.badge, b.balanced ? "Balanced" : `Out by ${money(Math.abs(b.assets.total - b.totalLiabilitiesAndEquity))}`); + return `As of ${b.asOf}`; }); shell.bar.addEventListener("submit", (e) => { e.preventDefault();