diff --git a/CHANGELOG.md b/CHANGELOG.md index 834f4c0..e76b302 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ # Changelog +## 0.13.0 + +FormLedger ships its own FormTxt templates, and a document started from a template shows where each line posts. + +### New +- **FormTxt templates in the box:** `formledger formtxt-template` writes FormLedger's invoice template as a file, and `formledger formtxt-template statement` writes the statement one. Open the file once in FormTxt (File > Open or import file). After that FormLedger finds the template in FormTxt by its name, with nothing to set. `FORMLEDGER_FORMTXT_TEMPLATE_INVOICE` still works and wins when set. +- **Account names on template lines:** in a document started from a template, each free line shows the account it posts to, for example "4100 Sales", at the end of its description. + +### Changed +- **FormLedger waits 13 seconds for FormTxt,** down from 100, then prints the plain page and says why. + +### Fixed +- Opening a document from a template no longer nudges the buttons at the bottom as "Confirm" becomes "Post". +- Dashboard figures and chart axes follow the currency's decimal places, so a currency with no minor unit is no longer shown 100 times too small. + +### Known issues +- FormLedger cannot put its template into FormTxt for you: FormTxt gives an outside program no way to create a document, so you open the file there once (`docs/PRINT.md`). +- Quotes, orders and the buying documents have no FormTxt template yet; they print with the plain renderer. +- FormTxt keeps each page it draws as a document in its own library. + +### Under the hood +- Checked for this version: an invoice and a statement drawn by FormTxt 0.38.0 from the shipped templates, and the plain page after an unanswered question at 13 seconds. Not run: the dashboard change with a currency that has no minor unit; the desktop app was not compiled, and nothing ran on macOS or Windows. + ## 0.12.0 FormLedger writes a snapshot from the window, keeps its own key on the desktop, tells you when FormTxt did not draw a page, and names the accounts its templates post to. diff --git a/Makefile b/Makefile index 9b1b7a2..d0d25cb 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -VERSION := v0.12.0 +VERSION := v0.13.0 GO_BUILD := CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" .PHONY: build web server check clean diff --git a/README.md b/README.md index d6d91c9..b624d1d 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@

- version v0.12.0 + version v0.13.0 Go 1.26+ TypeScript and Vite License: Apache-2.0 diff --git a/cmd/HASHOUT_LOG.md b/cmd/HASHOUT_LOG.md index f60d49b..76d6020 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.12.0 +Current build version: v0.13.0 Last updated: 2026-11-26 (US Eastern) · skeleton port from form.md --- @@ -217,3 +217,12 @@ Import path changed to `formledger/internal/nowindow`. No entries. ## internal/startup/proc_other.go {#internal-startup-proc-other-go} Verbatim from the donor. No entries. + +--- + +### cmd/formledger/main.go · formtxt-template +- refers-to: cmd/formledger/main.go :: run (case "formtxt-template"), usage; internal/printout/template.go :: TemplateCommand +- kind: rationale +- logged: v0.13.0 · 2026-11-27 + +A top-level command rather than `cli`, because it needs no server and no token: it only writes the embedded template as a `.ftxt` file (`--out FILE`, `-` for standard output, default `formledger-invoice.ftxt` in the current folder) and says to open it in FormTxt with File > Open or import file. Errors exit 2 like an unknown command. diff --git a/cmd/formledger/main.go b/cmd/formledger/main.go index 87f418f..e568413 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/crypt" "github.com/nodemode-ai/formledger/internal/nowindow" + "github.com/nodemode-ai/formledger/internal/printout" "github.com/nodemode-ai/formledger/internal/server" "github.com/nodemode-ai/formledger/internal/snapshot" "github.com/nodemode-ai/formledger/internal/startup" @@ -40,6 +41,12 @@ func run(args []string) int { return cli.Run(args[1:], os.Stdout, os.Stderr) case "report": return snapshot.Main(args[1:], os.Stdout, os.Stderr) + case "formtxt-template": + if err := printout.TemplateCommand(args[1:], os.Stdout); err != nil { + fmt.Fprintln(os.Stderr, "formledger:", err) + return 2 + } + return 0 case "keygen": fmt.Println(crypt.Generate()) return 0 @@ -205,6 +212,7 @@ func usage(w io.Writer) { fmt.Fprintln(w, " serve run the server (default)") fmt.Fprintln(w, " cli ledger commands against the running server (formledger cli --help)") fmt.Fprintln(w, " report snapshot write a plain read-only SQLite snapshot (--out FILE, --force; server stopped)") + fmt.Fprintln(w, " formtxt-template write FormLedger's invoice (or statement) template for FormTxt (--out FILE, default formledger-KIND.ftxt)") fmt.Fprintln(w, " keygen print a new at-rest encryption key") fmt.Fprintln(w, " encrypt encrypt an existing plain ledger with FORMLEDGER_KEY_FILE (server stopped)") fmt.Fprintln(w, " version print the version") diff --git a/docs/PRINT.md b/docs/PRINT.md index 46cc64e..2527748 100644 --- a/docs/PRINT.md +++ b/docs/PRINT.md @@ -39,15 +39,21 @@ Rendering goes through a list of renderers, each of which draws a document and a - It finds FormTxt the way FormTxt's own tools do (`setup/report.py`, `setup/catalogue.py`): the engine at `http://127.0.0.1:$FORMTXT_ENGINE_PORT`, port `8210` when unset. There is no discovery file. - It posts to `/api/reports/run` with the data as `records` (one record per line, the document's header fields repeated on each: `company`, `title`, `number`, `date`, `dueDate`, `customer`, `customerName`, `supplier`, `supplierName`, `currency`, `status`, `memo`, `subtotal`, `taxTotal`, `total`, then `item`, `description`, `quantity`, `unitPrice`, `taxRate`, `lineSubtotal`; a statement's are `customer`, `customerName`, `currency`, `from`, `to`, `opening`, `closing`, then `lineDate`, `event`, `reference`, `debit`, `credit`, `balance`), `mode` `list`, `format` `pdf`, and `out` a file in a fresh temporary folder that it reads back and removes. Amounts arrive formatted, as on the plain page. -- The template is a FormTxt document id, named per kind in the server's environment: `FORMLEDGER_FORMTXT_TEMPLATE_INVOICE`, `_QUOTE`, `_ORDER`, `_PURCHASE_ORDER`, `_PURCHASE_INVOICE`, `_GOODS_RECEIPT`, `_STATEMENT`. A kind with no template goes to the plain renderer. -- Any failure (no engine, a refusal, a timeout of 100 seconds, a file that is not a PDF) goes to the plain renderer. When FormTxt answered but did not draw, the response carries the reason in `X-FormLedger-Renderer-Note` (path-escaped) and `cli print` writes it on standard error under the renderer line. A 403 reads: `FormTxt refused to draw the page, so FormLedger drew the plain page. FormTxt said: No FormTxt window is open. Start it with ./formtxt and open the app, then retry. Open FormTxt, allow outside agents when it asks, or turn on Allow outside agents in its Preferences under Privacy, then print again.` A template id FormTxt does not hold (404) names the environment variable to set. The wait is 100 seconds so the person can answer FormTxt's question, and stays under `cli print`'s own two minutes; FormTxt itself waits up to 180 seconds for the answer. +- The template is a FormTxt document. FormLedger ships one for invoices (below). When `FORMLEDGER_FORMTXT_TEMPLATE_INVOICE` is unset, FormLedger reads FormTxt's document list (`GET /api/documents`, a read FormTxt answers any local caller) and uses the newest document titled `FormLedger invoice template`. A set id always wins, per kind: `FORMLEDGER_FORMTXT_TEMPLATE_INVOICE`, `_QUOTE`, `_ORDER`, `_PURCHASE_ORDER`, `_PURCHASE_INVOICE`, `_GOODS_RECEIPT`, `_STATEMENT`. Any other kind with no id set goes to the plain renderer. +- Any failure (no engine, a refusal, a timeout of 13 seconds, a file that is not a PDF) goes to the plain renderer. When FormTxt answered but did not draw, the response carries the reason in `X-FormLedger-Renderer-Note` (path-escaped) and `cli print` writes it on standard error under the renderer line. A 403 reads: `FormTxt refused to draw the page, so FormLedger drew the plain page. FormTxt said: No FormTxt window is open. Start it with ./formtxt and open the app, then retry. Open FormTxt, allow outside agents when it asks, or turn on Allow outside agents in its Preferences under Privacy, then print again.` A template id FormTxt does not hold (404) names the environment variable to set. The wait is 13 seconds, the owner's choice: a person who has not answered FormTxt's question by then gets the plain page and prints again after answering. FormTxt itself waits up to 180 seconds for the answer and withdraws the question when FormLedger hangs up. -### Setting it up +### The shipped invoice template -No templates ship: FormTxt's report route merges into a document in FormTxt's own store, and only the FormTxt window can create one (`POST /api/documents` without the window's key answers `Only the FormTxt window can do this`). +FormLedger carries an invoice template as its own data, written in FormTxt's `.ftxt` document format (`internal/printout/formtxt_invoice.json`, embedded in the binary). It is titled `FormLedger invoice template` and holds the company name, the document title and number, date, due date, currency and status, the bill-to customer name and code, a line table whose header row repeats on every page and whose second row is marked to repeat once per line (`item`, `description`, `quantity`, `unitPrice` as Rate, `taxRate`, `lineSubtotal` as Amount), then subtotal, tax, total with the currency, the notes, and "Page N of M" in the footer. A statement template ships the same way (`internal/printout/formtxt_statement.json`, titled `FormLedger statement template`, written by `./formledger formtxt-template statement`): company, period, customer name and code, currency, opening balance, one repeating row per event (`lineDate`, `event`, `reference`, `debit`, `credit`, `balance`) and the closing balance. With no `from` the heading reads "Statement to" and the end date. The two lookups are separate, so each kind uses its template once it is in FormTxt. -1. Open the FormTxt window. Make a document with the header fields as merge fields and a table whose line row is marked to repeat (`merge.repeatRow`), its cells holding `item`, `description`, `quantity`, `unitPrice`, `taxRate`, `lineSubtotal`. A list merge refuses a template with no repeating row. -2. Set `FORMLEDGER_FORMTXT_TEMPLATE_INVOICE` (and the other kinds) to that document's id, and `FORMTXT_ENGINE_PORT` when FormTxt is not on 8210, in FormLedger's server environment. -3. Print once with the window open. FormTxt asks **Allow an outside agent to make changes in FormTxt?**, naming the temporary file it will write, with Deny, Allow once and Always allow all outside agents. Always allow saves `agentsAllowed` in FormTxt's own `settings.json` in its data folder (not the system password store), so later prints draw with no window open. Allow once lets that one print through without saving the answer (read from FormTxt's `consent`, not tried here). +FormLedger does not put the template into FormTxt by itself. FormTxt gives an outside program no way to create a document: every write but `/mcp` and `/api/reports/run` needs the key only FormTxt's own window holds for that launch, `/mcp` runs the window's editing commands (none of which types text or opens a file from a path), and `/api/reports/run` merges into a document that must already be in FormTxt's library. Taking the window's key from its session storage, or writing into FormTxt's data folder, would get past FormTxt's consent, so FormLedger does neither. The person adds it once: + +1. Run `./formledger formtxt-template` (or `--out FILE`). It writes `formledger-invoice.ftxt` and names the full path. +2. In the FormTxt window, choose File > Open or import file and pick that file. FormTxt adds it to its library as `FormLedger invoice template`. Set `FORMTXT_ENGINE_PORT` in FormLedger's server environment when FormTxt is not on 8210; no template id is needed. +3. Print once with the window open. FormTxt asks **Allow an outside agent to make changes in FormTxt?**, naming the temporary file it will write, with Deny, Allow once and Always allow all outside agents. Answer within 13 seconds, or print again after answering. Always allow saves `agentsAllowed` in FormTxt's own `settings.json` in its data folder (not the system password store), so later prints draw with no window open. Allow once lets that one print through without saving the answer (read from FormTxt's `consent`, not tried here). + +Until step 2 is done, printing goes to the plain renderer with the note: `FormTxt holds no document named FormLedger invoice template, so FormLedger drew the plain page. Run ./formledger formtxt-template, open the file it writes in FormTxt with File > Open or import file, then print again.` + +**Run on 2026-11-27 against FormTxt 0.38.0** (a copy with its own engine on port 8701 and data folder, its window built from its own frontend and opened in headless Chrome; FormLedger's server had no `FORMLEDGER_FORMTXT_TEMPLATE_*` variable set). On the fresh FormTxt library, `cli print invoice SI-2026-000001` printed plain in 0.32 seconds with the note above. The file from `formledger formtxt-template` was then opened through File > Open or import file; the next print raised FormTxt's question, Always allow was clicked 2.15 seconds in, and the page was drawn by FormTxt from the shipped template in 2.87 seconds (`printed by the formtxt renderer`): every field, the three lines, subtotal 68.13, tax 5.45 and total USD 73.58 were filled. With the window open but the question left unanswered, FormLedger gave up after 13.13 seconds and printed plain with the 13 second note. With FormTxt's engine stopped it printed plain in 0.35 seconds, since nothing answered on the port. Then `cli print statement ACME` printed plain with the statement note, the statement file was opened the same way, and the next statement print was drawn by FormTxt in 0.20 seconds with outside agents already allowed. FormTxt's report route also keeps each merged result in its own library (here `Invoice SI-2026-000001`); that is FormTxt's behavior and FormLedger does not remove it. With the engine running and no window, and outside agents not allowed, FormTxt answers 403 `No FormTxt window is open`, and FormLedger prints with the plain renderer and the note above. diff --git a/internal/HASHOUT_LOG.md b/internal/HASHOUT_LOG.md index e53d954..474308f 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.12.0 +Current build version: v0.13.0 Last updated: 2026-11-27 (US Eastern) · profit and loss and the balance sheet --- @@ -1875,3 +1875,10 @@ The owner said yes to both: the desktop app makes and keeps its own key, and `fo - logged: v0.12.0 · 2026-11-27 Run against a copy of FormTxt 0.38.0 (engine on 8504, its window built from its own frontend and opened in headless Chrome). The route, the `records` payload, `mode list`, `format pdf` and the fresh `out` path were right as written; FormTxt answered 200 and the page came out with every merge field filled. What was wrong was the silence: a template id FormTxt does not hold came back 404 and FormLedger printed plain with no word why, and a 403 did the same. `refused` carries a sentence and still `Is` `ErrUnavailable`, so the chain falls through unchanged; `pick` keeps the first such sentence and the route sends it path-escaped in `X-FormLedger-Renderer-Note`, because a header cannot hold every character a FormTxt detail may contain. The wait went from 45 to 100 seconds: the first print blocks on FormTxt's Allow question (FormTxt waits up to 180 seconds and withdraws the question when the caller hangs up), and 100 stays inside `cli print`'s two minute client. Always allow all outside agents saved `agentsAllowed: true` in FormTxt's data-folder `settings.json`; no system password store is involved, so the sandbox had nothing to refuse. + +### internal/printout/template.go · shipped FormTxt invoice template, found by name +- refers-to: internal/printout/template.go :: invoiceTemplate, InvoiceTemplateTitle, shipped, InvoiceTemplate, TemplateCommand, findShipped; internal/printout/formtxt.go :: run (http.Client Timeout, findShipped); internal/printout/formtxt_invoice.json +- kind: rationale +- logged: v0.13.0 · 2026-11-27 + +The owner chose a 13 second wait (down from 100) and a shipped template. The template is FormLedger's own data in FormTxt's `.ftxt` format (docs/FORMAT.md in FormTxt): `document.json` is embedded and packed on demand with `mimetype` stored first, as the format requires, with zip times fixed at 1970 so the file is the same bytes every run. FormTxt gives outside programs no create route: every write but `/mcp` and `/api/reports/run` needs the window's per-launch key, and none of the window commands `/mcp` runs types text or opens a path. So FormLedger never creates the document; the person opens the file once with File > Open or import file, and `findShipped` matches the exact title on FormTxt's open `GET /api/documents` (newest `modified` wins, so a re-import replaces an older copy without clearing it). A set `FORMLEDGER_FORMTXT_TEMPLATE_*` id still wins, and only `invoice` has a shipped title; the list read shares the 13 second limit. Ids in the JSON are FormTxt-style prefixes with 4 or more letters because the format says so, though the merge re-ids every block. Proven on 2026-11-27 against FormTxt 0.38.0 on port 8701: plain with the missing-template note before import, FormTxt-drawn after import and Always allow (2.87 s), plain after 13.13 s with the question unanswered, plain in 0.35 s with the engine stopped. diff --git a/internal/app/version.go b/internal/app/version.go index 1737f8e..c346089 100644 --- a/internal/app/version.go +++ b/internal/app/version.go @@ -1,5 +1,5 @@ package app -var Version = "v0.12.0" +var Version = "v0.13.0" const Product = "FormLedger" diff --git a/internal/printout/formtxt.go b/internal/printout/formtxt.go index 847c61e..b5f4ca4 100644 --- a/internal/printout/formtxt.go +++ b/internal/printout/formtxt.go @@ -79,9 +79,16 @@ func (f formtxt) Statement(s *Statement) ([]byte, error) { func (formtxt) run(kind, title string, rows []map[string]any) ([]byte, error) { base, template := formtxtBase(), formtxtTemplate(kind) - if base == "" || template == "" { + if base == "" { return nil, ErrUnavailable } + if template == "" { + found, err := findShipped(base, kind) + if err != nil { + return nil, err + } + template = found + } dir, err := os.MkdirTemp("", "formledger-print-") if err != nil { return nil, ErrUnavailable @@ -95,11 +102,11 @@ func (formtxt) run(kind, title string, rows []map[string]any) ([]byte, error) { if err != nil { return nil, ErrUnavailable } - resp, err := (&http.Client{Timeout: 100 * time.Second}).Post(base+"/api/reports/run", "application/json", bytes.NewReader(body)) + resp, err := (&http.Client{Timeout: 13 * time.Second}).Post(base+"/api/reports/run", "application/json", bytes.NewReader(body)) if err != nil { var late interface{ Timeout() bool } if errors.As(err, &late) && late.Timeout() { - return nil, refused{"FormTxt did not answer within 100 seconds, so FormLedger drew the plain page. If FormTxt is asking Allow outside agents?, answer it and print again."} + return nil, refused{"FormTxt did not answer within 13 seconds, so FormLedger drew the plain page. If FormTxt is asking Allow outside agents?, answer it and print again."} } return nil, ErrUnavailable } diff --git a/internal/printout/formtxt_invoice.json b/internal/printout/formtxt_invoice.json new file mode 100644 index 0000000..5d4c275 --- /dev/null +++ b/internal/printout/formtxt_invoice.json @@ -0,0 +1,85 @@ +{ + "format": "ftxt", + "formatVersion": 1, + "id": "d_formledgerinvoice", + "title": "FormLedger invoice template", + "meta": {"author": "FormLedger", "created": 0, "modified": 0, "subject": "FormLedger invoice", "keywords": ["formledger"], "language": "en-US"}, + "settings": { + "pageless": false, "defaultTab": 36.0, "trackChanges": false, + "mailMerge": {"source": "FormLedger", "columns": ["company", "title", "number", "date", "dueDate", "customer", "customerName", "currency", "status", "memo", "subtotal", "taxTotal", "total", "item", "description", "quantity", "unitPrice", "taxRate", "lineSubtotal"], "rows": []} + }, + "styles": { + "Normal": {"type": "paragraph", "name": "Normal", "basedOn": null, "next": "Normal", "run": {"font": "Inter", "size": 10.0, "color": "#1f2328"}, "para": {"spaceBefore": 0.0, "spaceAfter": 4.0, "lineSpacing": 1.15, "align": "left"}}, + "Title": {"type": "paragraph", "name": "Title", "basedOn": "Normal", "next": "Normal", "run": {"size": 22.0, "bold": true}, "para": {"spaceAfter": 2.0}}, + "Subtitle": {"type": "paragraph", "name": "Subtitle", "basedOn": "Normal", "next": "Normal", "run": {"size": 14.0, "color": "#57606a"}, "para": {"spaceAfter": 14.0}}, + "Heading3": {"type": "paragraph", "name": "Heading 3", "basedOn": "Normal", "next": "Normal", "run": {"size": 9.0, "bold": true, "color": "#57606a", "allCaps": true}, "para": {"spaceBefore": 10.0, "spaceAfter": 2.0, "keepWithNext": true, "outlineLevel": 3}} + }, + "numbering": {}, + "sections": [{ + "id": "sec_formledger", + "page": {"size": "letter", "width": 612.0, "height": 792.0, "orientation": "portrait"}, + "margins": {"top": 60.0, "right": 60.0, "bottom": 60.0, "left": 60.0, "header": 30.0, "footer": 30.0, "gutter": 0.0}, + "columns": {"count": 1, "gap": 36.0}, + "headers": {}, "footers": {"default": {"text": "Page {PAGE} of {NUMPAGES}", "align": "center"}}, + "titlePage": false, "start": "nextPage" + }], + "tabs": [{"id": "tab_formledger", "title": "Invoice", "parent": null, "body": [ + {"type": "paragraph", "id": "p_company", "style": "Title", "section": "sec_formledger", "content": [{"type": "mergefield", "name": "company"}]}, + {"type": "paragraph", "id": "p_heading", "style": "Subtitle", "section": "sec_formledger", "content": [{"type": "mergefield", "name": "title"}, {"type": "text", "text": " "}, {"type": "mergefield", "name": "number"}]}, + {"type": "table", "id": "t_head", "look": "plain", "columns": [246.0, 246.0], "rows": [ + {"cells": [ + {"body": [ + {"type": "paragraph", "id": "p_billto", "style": "Heading3", "content": [{"type": "text", "text": "Bill to"}]}, + {"type": "paragraph", "id": "p_custname", "style": "Normal", "content": [{"type": "mergefield", "name": "customerName", "marks": {"bold": true}}]}, + {"type": "paragraph", "id": "p_custcode", "style": "Normal", "content": [{"type": "text", "text": "Customer "}, {"type": "mergefield", "name": "customer"}]} + ]}, + {"body": [ + {"type": "paragraph", "id": "p_date", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Date ", "marks": {"bold": true}}, {"type": "mergefield", "name": "date"}]}, + {"type": "paragraph", "id": "p_duedate", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Due ", "marks": {"bold": true}}, {"type": "mergefield", "name": "dueDate"}]}, + {"type": "paragraph", "id": "p_currency", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Currency ", "marks": {"bold": true}}, {"type": "mergefield", "name": "currency"}]}, + {"type": "paragraph", "id": "p_status", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Status ", "marks": {"bold": true}}, {"type": "mergefield", "name": "status"}]} + ]} + ]} + ]}, + {"type": "paragraph", "id": "p_space", "style": "Normal", "section": "sec_formledger", "content": []}, + {"type": "table", "id": "t_lines", "look": "rows", "repeatHeader": true, "columns": [62.0, 170.0, 60.0, 70.0, 50.0, 80.0], "rows": [ + {"cells": [ + {"header": true, "shading": "#eef1f4", "body": [{"type": "paragraph", "id": "p_hitem", "style": "Normal", "content": [{"type": "text", "text": "Item", "marks": {"bold": true}}]}]}, + {"header": true, "shading": "#eef1f4", "body": [{"type": "paragraph", "id": "p_hdesc", "style": "Normal", "content": [{"type": "text", "text": "Description", "marks": {"bold": true}}]}]}, + {"header": true, "shading": "#eef1f4", "body": [{"type": "paragraph", "id": "p_hqty", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Quantity", "marks": {"bold": true}}]}]}, + {"header": true, "shading": "#eef1f4", "body": [{"type": "paragraph", "id": "p_hrate", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Rate", "marks": {"bold": true}}]}]}, + {"header": true, "shading": "#eef1f4", "body": [{"type": "paragraph", "id": "p_htax", "style": "Normal", "content": [{"type": "text", "text": "Tax", "marks": {"bold": true}}]}]}, + {"header": true, "shading": "#eef1f4", "body": [{"type": "paragraph", "id": "p_hamt", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Amount", "marks": {"bold": true}}]}]} + ]}, + {"repeat": true, "cells": [ + {"body": [{"type": "paragraph", "id": "p_item", "style": "Normal", "content": [{"type": "mergefield", "name": "item"}]}]}, + {"body": [{"type": "paragraph", "id": "p_desc", "style": "Normal", "content": [{"type": "mergefield", "name": "description"}]}]}, + {"body": [{"type": "paragraph", "id": "p_quantity","style": "Normal", "props": {"align": "right"}, "content": [{"type": "mergefield", "name": "quantity"}]}]}, + {"body": [{"type": "paragraph", "id": "p_rate", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "mergefield", "name": "unitPrice"}]}]}, + {"body": [{"type": "paragraph", "id": "p_taxrate","style": "Normal", "content": [{"type": "mergefield", "name": "taxRate"}]}]}, + {"body": [{"type": "paragraph", "id": "p_amount","style": "Normal", "props": {"align": "right"}, "content": [{"type": "mergefield", "name": "lineSubtotal"}]}]} + ]} + ]}, + {"type": "table", "id": "t_totals", "look": "plain", "columns": [312.0, 100.0, 80.0], "rows": [ + {"cells": [ + {"body": [{"type": "paragraph", "id": "p_subblank", "style": "Normal", "content": []}]}, + {"body": [{"type": "paragraph", "id": "p_sublabel", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Subtotal"}]}]}, + {"body": [{"type": "paragraph", "id": "p_subvalue", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "mergefield", "name": "subtotal"}]}]} + ]}, + {"cells": [ + {"body": [{"type": "paragraph", "id": "p_taxblank", "style": "Normal", "content": []}]}, + {"body": [{"type": "paragraph", "id": "p_taxlabel", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Tax"}]}]}, + {"body": [{"type": "paragraph", "id": "p_taxvalue", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "mergefield", "name": "taxTotal"}]}]} + ]}, + {"cells": [ + {"body": [{"type": "paragraph", "id": "p_totblank", "style": "Normal", "content": []}]}, + {"body": [{"type": "paragraph", "id": "p_totlabel", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Total", "marks": {"bold": true}}]}]}, + {"body": [{"type": "paragraph", "id": "p_totvalue", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "mergefield", "name": "currency", "marks": {"bold": true}}, {"type": "text", "text": " ", "marks": {"bold": true}}, {"type": "mergefield", "name": "total", "marks": {"bold": true}}]}]} + ]} + ]}, + {"type": "paragraph", "id": "p_memo", "style": "Normal", "section": "sec_formledger", "props": {"spaceBefore": 14.0}, "content": [{"type": "mergefield", "name": "memo"}]} + ]}], + "notes": {"footnotes": {}, "endnotes": {}}, + "comments": {}, + "media": {} +} diff --git a/internal/printout/formtxt_statement.json b/internal/printout/formtxt_statement.json new file mode 100644 index 0000000..67c726a --- /dev/null +++ b/internal/printout/formtxt_statement.json @@ -0,0 +1,66 @@ +{ + "format": "ftxt", + "formatVersion": 1, + "id": "d_formledgerstatement", + "title": "FormLedger statement template", + "meta": {"author": "FormLedger", "created": 0, "modified": 0, "subject": "FormLedger customer statement", "keywords": ["formledger"], "language": "en-US"}, + "settings": { + "pageless": false, "defaultTab": 36.0, "trackChanges": false, + "mailMerge": {"source": "FormLedger", "columns": ["company", "customer", "customerName", "currency", "from", "to", "opening", "closing", "lineDate", "event", "reference", "debit", "credit", "balance"], "rows": []} + }, + "styles": { + "Normal": {"type": "paragraph", "name": "Normal", "basedOn": null, "next": "Normal", "run": {"font": "Inter", "size": 10.0, "color": "#1f2328"}, "para": {"spaceBefore": 0.0, "spaceAfter": 4.0, "lineSpacing": 1.15, "align": "left"}}, + "Title": {"type": "paragraph", "name": "Title", "basedOn": "Normal", "next": "Normal", "run": {"size": 22.0, "bold": true}, "para": {"spaceAfter": 2.0}}, + "Subtitle": {"type": "paragraph", "name": "Subtitle", "basedOn": "Normal", "next": "Normal", "run": {"size": 14.0, "color": "#57606a"}, "para": {"spaceAfter": 14.0}}, + "Heading3": {"type": "paragraph", "name": "Heading 3", "basedOn": "Normal", "next": "Normal", "run": {"size": 9.0, "bold": true, "color": "#57606a", "allCaps": true}, "para": {"spaceBefore": 10.0, "spaceAfter": 2.0, "keepWithNext": true, "outlineLevel": 3}} + }, + "numbering": {}, + "sections": [{ + "id": "sec_formledger", + "page": {"size": "letter", "width": 612.0, "height": 792.0, "orientation": "portrait"}, + "margins": {"top": 60.0, "right": 60.0, "bottom": 60.0, "left": 60.0, "header": 30.0, "footer": 30.0, "gutter": 0.0}, + "columns": {"count": 1, "gap": 36.0}, + "headers": {}, "footers": {"default": {"text": "Page {PAGE} of {NUMPAGES}", "align": "center"}}, + "titlePage": false, "start": "nextPage" + }], + "tabs": [{"id": "tab_formledger", "title": "Statement", "parent": null, "body": [ + {"type": "paragraph", "id": "p_company", "style": "Title", "section": "sec_formledger", "content": [{"type": "mergefield", "name": "company"}]}, + {"type": "paragraph", "id": "p_heading", "style": "Subtitle", "section": "sec_formledger", "content": [{"type": "text", "text": "Statement "}, {"type": "mergefield", "name": "from"}, {"type": "text", "text": " to "}, {"type": "mergefield", "name": "to"}]}, + {"type": "table", "id": "t_head", "look": "plain", "columns": [246.0, 246.0], "rows": [ + {"cells": [ + {"body": [ + {"type": "paragraph", "id": "p_custlabel", "style": "Heading3", "content": [{"type": "text", "text": "Customer"}]}, + {"type": "paragraph", "id": "p_custname", "style": "Normal", "content": [{"type": "mergefield", "name": "customerName", "marks": {"bold": true}}]}, + {"type": "paragraph", "id": "p_custcode", "style": "Normal", "content": [{"type": "text", "text": "Customer "}, {"type": "mergefield", "name": "customer"}]} + ]}, + {"body": [ + {"type": "paragraph", "id": "p_currency", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Currency ", "marks": {"bold": true}}, {"type": "mergefield", "name": "currency"}]}, + {"type": "paragraph", "id": "p_opening", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Opening balance ", "marks": {"bold": true}}, {"type": "mergefield", "name": "opening"}]} + ]} + ]} + ]}, + {"type": "paragraph", "id": "p_space", "style": "Normal", "section": "sec_formledger", "content": []}, + {"type": "table", "id": "t_lines", "look": "rows", "repeatHeader": true, "columns": [70.0, 100.0, 112.0, 70.0, 70.0, 70.0], "rows": [ + {"cells": [ + {"header": true, "shading": "#eef1f4", "body": [{"type": "paragraph", "id": "p_hdate", "style": "Normal", "content": [{"type": "text", "text": "Date", "marks": {"bold": true}}]}]}, + {"header": true, "shading": "#eef1f4", "body": [{"type": "paragraph", "id": "p_hevent", "style": "Normal", "content": [{"type": "text", "text": "Description", "marks": {"bold": true}}]}]}, + {"header": true, "shading": "#eef1f4", "body": [{"type": "paragraph", "id": "p_href", "style": "Normal", "content": [{"type": "text", "text": "Number", "marks": {"bold": true}}]}]}, + {"header": true, "shading": "#eef1f4", "body": [{"type": "paragraph", "id": "p_hdebit", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Debit", "marks": {"bold": true}}]}]}, + {"header": true, "shading": "#eef1f4", "body": [{"type": "paragraph", "id": "p_hcredit", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Credit", "marks": {"bold": true}}]}]}, + {"header": true, "shading": "#eef1f4", "body": [{"type": "paragraph", "id": "p_hbalance", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "text", "text": "Balance", "marks": {"bold": true}}]}]} + ]}, + {"repeat": true, "cells": [ + {"body": [{"type": "paragraph", "id": "p_date", "style": "Normal", "content": [{"type": "mergefield", "name": "lineDate"}]}]}, + {"body": [{"type": "paragraph", "id": "p_event", "style": "Normal", "content": [{"type": "mergefield", "name": "event"}]}]}, + {"body": [{"type": "paragraph", "id": "p_reference", "style": "Normal", "content": [{"type": "mergefield", "name": "reference"}]}]}, + {"body": [{"type": "paragraph", "id": "p_debit", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "mergefield", "name": "debit"}]}]}, + {"body": [{"type": "paragraph", "id": "p_credit", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "mergefield", "name": "credit"}]}]}, + {"body": [{"type": "paragraph", "id": "p_balance", "style": "Normal", "props": {"align": "right"}, "content": [{"type": "mergefield", "name": "balance"}]}]} + ]} + ]}, + {"type": "paragraph", "id": "p_closing", "style": "Normal", "section": "sec_formledger", "props": {"align": "right", "spaceBefore": 8.0}, "content": [{"type": "text", "text": "Closing balance ", "marks": {"bold": true}}, {"type": "mergefield", "name": "currency", "marks": {"bold": true}}, {"type": "text", "text": " ", "marks": {"bold": true}}, {"type": "mergefield", "name": "closing", "marks": {"bold": true}}]} + ]}], + "notes": {"footnotes": {}, "endnotes": {}}, + "comments": {}, + "media": {} +} diff --git a/internal/printout/template.go b/internal/printout/template.go new file mode 100644 index 0000000..5318161 --- /dev/null +++ b/internal/printout/template.go @@ -0,0 +1,130 @@ +package printout + +import ( + "archive/zip" + "bytes" + _ "embed" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "path/filepath" + "time" +) + +//go:embed formtxt_invoice.json +var invoiceTemplate []byte + +//go:embed formtxt_statement.json +var statementTemplate []byte + +const TemplateUsage = "formtxt-template [invoice|statement] [--out FILE]" + +type shippedTemplate struct { + title string + doc []byte +} + +var shipped = map[string]shippedTemplate{ + "invoice": {"FormLedger invoice template", invoiceTemplate}, + "statement": {"FormLedger statement template", statementTemplate}, +} + +func Template(kind string) ([]byte, error) { + t, ok := shipped[kind] + if !ok { + return nil, errors.New("FormLedger ships a FormTxt template for invoice and statement only") + } + var buf bytes.Buffer + z := zip.NewWriter(&buf) + mt, err := z.CreateHeader(&zip.FileHeader{Name: "mimetype", Method: zip.Store, Modified: time.Unix(0, 0).UTC()}) + if err != nil { + return nil, err + } + if _, err = io.WriteString(mt, "application/x-formtxt"); err != nil { + return nil, err + } + doc, err := z.CreateHeader(&zip.FileHeader{Name: "document.json", Method: zip.Deflate, Modified: time.Unix(0, 0).UTC()}) + if err != nil { + return nil, err + } + if _, err = doc.Write(t.doc); err != nil { + return nil, err + } + if err = z.Close(); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +func TemplateCommand(args []string, stdout io.Writer) error { + kind, file := "invoice", "" + for i := 0; i < len(args); i++ { + switch a := args[i]; { + case a == "--out" && i+1 < len(args): + i++ + file = args[i] + case len(a) > 6 && a[:6] == "--out=": + file = a[6:] + case a == "invoice" || a == "statement": + kind = a + default: + return errors.New("usage: " + TemplateUsage) + } + } + if file == "" { + file = "formledger-" + kind + ".ftxt" + } + data, err := Template(kind) + if err != nil { + return err + } + if file == "-" { + _, err = stdout.Write(data) + return err + } + if err = os.WriteFile(file, data, 0o644); err != nil { + return err + } + abs, _ := filepath.Abs(file) + _, err = fmt.Fprintf(stdout, "wrote %s\nOpen it in FormTxt with File > Open or import file. FormLedger then finds the document named %q by itself.\n", abs, shipped[kind].title) + return err +} + +func findShipped(base, kind string) (string, error) { + t, ok := shipped[kind] + if !ok { + return "", ErrUnavailable + } + title := t.title + resp, err := (&http.Client{Timeout: 13 * time.Second}).Get(base + "/api/documents") + if err != nil { + return "", ErrUnavailable + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return "", ErrUnavailable + } + var list struct { + Documents []struct { + ID string `json:"id"` + Title string `json:"title"` + Modified float64 `json:"modified"` + } `json:"documents"` + } + if json.NewDecoder(io.LimitReader(resp.Body, 8<<20)).Decode(&list) != nil { + return "", ErrUnavailable + } + id, newest := "", -1.0 + for _, d := range list.Documents { + if d.Title == title && d.Modified > newest { + id, newest = d.ID, d.Modified + } + } + if id == "" { + return "", refused{"FormTxt holds no document named " + title + ", so FormLedger drew the plain page. Run ./formledger formtxt-template " + kind + ", open the file it writes in FormTxt with File > Open or import file, then print again."} + } + return id, nil +} diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index da1f62d..e648049 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1106,7 +1106,7 @@ dependencies = [ [[package]] name = "formledger-desktop" -version = "0.12.0" +version = "0.13.0" dependencies = [ "objc2", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index b49c1e8..25e7ec3 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formledger-desktop" -version = "0.12.0" +version = "0.13.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 8474f12..486ca32 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.12.0 +Current build version: v0.13.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 98e50a0..225141b 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.12.0", + "version": "0.13.0", "identifier": "ai.nodemode.formledger", "build": { "frontendDist": "splash" }, "app": { diff --git a/web/HASHOUT_LOG.md b/web/HASHOUT_LOG.md index 67cf141..0985c8a 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.12.0 +Current build version: v0.13.0 Last updated: 2026-11-26 (US Eastern) · account screens, and the fixes from the throttled browser check --- @@ -733,3 +733,10 @@ Measured side by side at 1400 by 900, dark, against a form.md build run from a c - logged: v0.12.0 · 2026-11-27 `writeSnapshot` posts to `/api/snapshot` and shows one toast (id `snapshot`) only when the answer comes: the absolute path, the table count and the row count; a 403 reads "Only the owner can write a snapshot." A waiting toast was tried first and dropped: it grew from one line to four when the answer replaced it and moved by 0.00108. A second call while one runs is ignored. The `file.snapshot` command in `app.ts` still shows the old command-line hint until its owner points it at `writeSnapshot(engine)`; the check ran on a private copy with that change. Palette rows were `1fr auto auto`, so the group label moved sideways whenever the row's text or key hint changed (0.0001 with input while typing); the columns are now `1fr 12ch 10ch` with the group placed in the trailing column and the key hint ending against it. Print shows Cmd or Ctrl+Alt+P because Cmd or Ctrl+P now opens Search, as in form.md. Checked under 4x CPU and the slowed network at 1400 by 900, palette open, "snapshot" typed, Enter: layout shift 0 without input and 0 with input. + +### src/ui/parts/linegrid.ts, src/ui/views/docform.ts, src/styles/views/docform.css, src/engine/format.ts, src/ui/parts/chart.ts · Template accounts and real minor units +- refers-to: src/ui/parts/linegrid.ts :: writeHint, LineGridOptions.accountFor; src/ui/views/docform.ts :: accountNames; src/styles/views/docform.css :: .grid__hint; src/engine/format.ts :: minorUnits; src/ui/parts/chart.ts :: setChartCurrency +- kind: rationale +- logged: v0.13.0 · 2026-11-27 + +Every description cell carries an empty `.grid__hint` from first paint, absolutely placed at the cell's end, so a form with no template is unchanged and a row stays at its height. When a template's lines arrive, `writeHint` writes the hint text ("4100 Sales") and the tooltip "Posts to 4100 Sales" once per free line. The hint follows the description, because the account still goes out keyed by that text: edit the description and the hint clears, which is the truth about what will be posted. An item line never shows one. The Post and Confirm label swap moved the action row by 0.00016 when a template set the kind to invoice; the primary label now keeps a minimum width of 8ch. `minorUnits` in engine/format is now the one list of zero-decimal currencies; the line grid reads it, and so does the chart's compact axis through `setChartCurrency`, which stays at two places until dashboards.ts calls it with the company currency. Checked under 4x CPU and the slowed network at 1400 by 900: sales and purchase templates opened by a hard reload read 0 shift; typing in two descriptions read 0 with input and 0 without. diff --git a/web/package-lock.json b/web/package-lock.json index 3b8c389..a3ea4d8 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "formledger", - "version": "0.12.0", + "version": "0.13.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formledger", - "version": "0.12.0", + "version": "0.13.0", "license": "Apache-2.0", "devDependencies": { "@types/node": "^22.20.5", diff --git a/web/package.json b/web/package.json index a5bb613..e884635 100644 --- a/web/package.json +++ b/web/package.json @@ -1,7 +1,7 @@ { "name": "formledger", "private": true, - "version": "0.12.0", + "version": "0.13.0", "license": "Apache-2.0", "type": "module", "scripts": { diff --git a/web/src/engine/format.ts b/web/src/engine/format.ts index 971563d..149d25a 100644 --- a/web/src/engine/format.ts +++ b/web/src/engine/format.ts @@ -1,4 +1,9 @@ const GROUP = /\B(?=(\d{3})+(?!\d))/g; +const ZERO_DECIMAL = new Set(["JPY", "KRW", "VND", "CLP", "ISK", "UGX", "XAF", "XOF"]); + +export function minorUnits(code: string): number { + return ZERO_DECIMAL.has(code.toUpperCase()) ? 0 : 2; +} export function money(minor: number, places = 2): string { const neg = minor < 0; diff --git a/web/src/styles/views/docform.css b/web/src/styles/views/docform.css index 6863c04..ffe8969 100644 --- a/web/src/styles/views/docform.css +++ b/web/src/styles/views/docform.css @@ -195,6 +195,12 @@ .df-actions .btn--primary { order: 5; + justify-content: center; +} + +.df-actions .btn--primary .df-btn__label { + min-inline-size: 8ch; + text-align: center; } .df-btn--cancel:not(:disabled):hover { @@ -251,3 +257,25 @@ flex: 1 1 auto; min-inline-size: 0; } + +.df .grid__c-desc { + position: relative; +} + +.df .grid__hint { + position: absolute; + inset-block-start: 50%; + inset-inline-end: var(--space-2); + transform: translateY(-50%); + max-inline-size: 45%; + overflow: hidden; + color: var(--text-muted); + font-size: var(--text-xs); + white-space: nowrap; + text-overflow: ellipsis; + pointer-events: none; +} + +.df .grid__c-desc.has-account .grid__input { + padding-inline-end: calc(45% + var(--space-2)); +} diff --git a/web/src/ui/parts/chart.ts b/web/src/ui/parts/chart.ts index 45160ea..a06970e 100644 --- a/web/src/ui/parts/chart.ts +++ b/web/src/ui/parts/chart.ts @@ -1,3 +1,4 @@ +import { minorUnits } from "../../engine/format"; import { h, setAttr, setText } from "../dom"; const NS = "http://www.w3.org/2000/svg"; @@ -59,8 +60,14 @@ export function monthName(period: string, withYear = false): string { const COMPACT = new Intl.NumberFormat("en-US", { notation: "compact", maximumFractionDigits: 1 }); +let axisPlaces = 2; + +export function setChartCurrency(code: string): void { + axisPlaces = minorUnits(code); +} + function axisLabel(minor: number): string { - return COMPACT.format(Math.round(minor / 100)); + return COMPACT.format(Math.round(minor / 10 ** axisPlaces)); } function scale(values: number[]): { lo: number; hi: number } { diff --git a/web/src/ui/parts/linegrid.ts b/web/src/ui/parts/linegrid.ts index 81be994..34911d4 100644 --- a/web/src/ui/parts/linegrid.ts +++ b/web/src/ui/parts/linegrid.ts @@ -1,4 +1,4 @@ -import { money, parseMoney, parseQty, qty } from "../../engine/format"; +import { minorUnits, money, parseMoney, parseQty, qty } from "../../engine/format"; import { h, setAttr, setText } from "../dom"; import type { ViewContext } from "../views"; import { mountPicker, type PickerHandle } from "./picker"; @@ -29,6 +29,7 @@ export interface LineGridOptions { currency: string; readOnly: boolean; onChange(lines: GridLine[]): void; + accountFor?(description: string): string; } export interface LineGridHandle { @@ -43,7 +44,6 @@ export interface LineGridHandle { flagMissing(): number[]; } -const ZERO_DECIMAL = new Set(["JPY", "KRW", "VND", "CLP", "ISK", "UGX", "XAF", "XOF"]); const SVG = "http://www.w3.org/2000/svg"; const COLS = ["item", "desc", "qty", "price", "tax"] as const; type Col = (typeof COLS)[number]; @@ -52,6 +52,7 @@ interface Row { el: HTMLElement; item: PickerHandle; desc: HTMLInputElement; + hint: HTMLElement; qty: HTMLInputElement; price: HTMLInputElement; tax: PickerHandle; @@ -89,7 +90,7 @@ function isBlank(l: GridLine): boolean { } export function mountLineGrid(host: HTMLElement, ctx: ViewContext, o: LineGridOptions): LineGridHandle { - const placesFor = (code: string) => (ZERO_DECIMAL.has(code.toUpperCase()) ? 0 : 2); + const placesFor = minorUnits; let currency = o.currency; let places = placesFor(currency); const fmt = (minor: number) => money(minor, places); @@ -169,11 +170,20 @@ export function mountLineGrid(host: HTMLElement, ctx: ViewContext, o: LineGridOp return out; } + function writeHint(r: Row): void { + const label = r.line.itemId || !o.accountFor ? "" : o.accountFor(r.line.description.trim()); + if (r.hint.textContent === label) return; + setText(r.hint, label); + setAttr(r.desc, "title", label ? `Posts to ${label}` : null); + r.hint.parentElement?.classList.toggle("has-account", Boolean(label)); + } + 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; + writeHint(r); const q = qty(l.qtyMilli); if (r.qty.value !== q) r.qty.value = q; const p = fmt(l.unitPrice); @@ -231,7 +241,8 @@ export function mountLineGrid(host: HTMLElement, ctx: ViewContext, o: LineGridOp const price = h("input", { class: "input grid__input grid__num", attrs: { type: "text", inputmode: "decimal", "aria-label": "Unit price", autocomplete: "off" } }); const remove = h("button", { class: "icon-btn grid__rm", attrs: { type: "button", "aria-label": "Remove line", title: "Remove line" } }); remove.append(removeIcon()); - cDesc.append(desc); + const hint = h("span", { class: "grid__hint", attrs: { "aria-hidden": "true" } }); + cDesc.append(desc, hint); cQty.append(qtyIn); cPrice.append(price); cRm.append(remove); @@ -265,6 +276,7 @@ export function mountLineGrid(host: HTMLElement, ctx: ViewContext, o: LineGridOp void r.tax.setById(rec.taxRateId); } } + writeHint(r); emit(); }, }); @@ -277,10 +289,11 @@ 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 }, touched: false }); + Object.assign(r, { el, item, desc, hint, qty: qtyIn, price, tax, sub, taxAmt, total, remove, error, line: { ...l }, touched: false }); desc.addEventListener("input", () => { r.line.description = desc.value; + writeHint(r); emit(); }); qtyIn.addEventListener("input", () => { diff --git a/web/src/ui/views/dashboards.ts b/web/src/ui/views/dashboards.ts index e483e45..32ca141 100644 --- a/web/src/ui/views/dashboards.ts +++ b/web/src/ui/views/dashboards.ts @@ -1,10 +1,11 @@ import { change, PERIODS, periodRange, series, top, type Metric, type MetricSeries, type PeriodKey, type TopRow } from "../../engine/dashboards"; -import { money, today } from "../../engine/format"; +import { minorUnits, money, today } from "../../engine/format"; import { h, setAttr, setText } from "../dom"; -import { hbarChart, sparkline, xyChart, type HBarChart, type XYChart } from "../parts/chart"; +import { hbarChart, setChartCurrency, sparkline, xyChart, type HBarChart, type XYChart } from "../parts/chart"; import type { ViewContext, ViewDef } from "../views"; const SVG = "http://www.w3.org/2000/svg"; +let places = 2; function arrow(): SVGSVGElement { const el = document.createElementNS(SVG, "svg"); @@ -40,7 +41,9 @@ function tile(title: string, target: string, ctx: () => ViewContext | null): Til return { el, fill(s, goodWhenUp) { - setText(figure, `${money(s.total)} ${s.currency}`); + places = minorUnits(s.currency); + setChartCurrency(s.currency); + setText(figure, `${money(s.total, places)} ${s.currency}`); setAttr(figure, "data-tone", s.metric === "profit" && s.total < 0 ? "danger" : null); spark.update(s.points.map((p) => p.value)); const c = change(s.total, s.previous.total); @@ -48,7 +51,7 @@ function tile(title: string, target: string, ctx: () => ViewContext | null): Til setAttr(badge, "data-tone", good === null ? "muted" : good ? "ok" : "bad"); setAttr(badge, "data-dir", c.dir); setText(changeText, c.pct === null ? "new" : Math.abs(c.pct) >= 1000 ? ">999%" : `${Math.abs(c.pct).toFixed(1)}%`); - setAttr(badge, "aria-label", `${c.dir === "flat" ? "No change" : c.dir === "up" ? "Up" : "Down"}${c.pct === null ? "" : ` ${Math.abs(c.pct).toFixed(1)} percent`} against ${s.previous.from} to ${s.previous.to}, which was ${money(s.previous.total)}`); + setAttr(badge, "aria-label", `${c.dir === "flat" ? "No change" : c.dir === "up" ? "Up" : "Down"}${c.pct === null ? "" : ` ${Math.abs(c.pct).toFixed(1)} percent`} against ${s.previous.from} to ${s.previous.to}, which was ${money(s.previous.total, places)}`); }, fail() { setText(figure, "Could not load"); @@ -61,7 +64,7 @@ function dashboardsView(): ViewDef { let period: PeriodKey = "last12"; let seq = 0; const getCtx = () => ctx; - const fmt = (n: number) => money(n); + const fmt = (n: number) => money(n, places); const tiles = { revenue: tile("Revenue", "profit-and-loss", getCtx), expenses: tile("Expenses", "profit-and-loss", getCtx), diff --git a/web/src/ui/views/docform.ts b/web/src/ui/views/docform.ts index 6478c34..686d2b7 100644 --- a/web/src/ui/views/docform.ts +++ b/web/src/ui/views/docform.ts @@ -84,6 +84,7 @@ function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext, headAc let newKind = firstKind; let loadSeq = 0; const accounts = new Map(); + const accountNames = new Map(); const root = h("div", { class: "df", attrs: { "data-family": spec.family } }); @@ -142,7 +143,7 @@ function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext, headAc const party = mountPicker(partyHost, ctx, { kind: spec.partyKind, label: spec.partyLabel, required: true, onPick: () => refresh() }); const warehouse: PickerHandle = mountPicker(warehouseHost, ctx, { kind: "warehouse", label: "Warehouse", onPick: () => refresh() }); - const grid: LineGridHandle = mountLineGrid(gridHost, ctx, { family: spec.family, currency: "", readOnly: false, onChange: () => undefined }); + const grid: LineGridHandle = mountLineGrid(gridHost, ctx, { family: spec.family, currency: "", readOnly: false, onChange: () => undefined, accountFor: (d) => accountNames.get(d) ?? "" }); const setError = (message: string) => setText(errorLine, message); @@ -227,6 +228,8 @@ function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext, headAc setValue(refInput, ""); setValue(memoInput, ""); party.set(null); + accounts.clear(); + accountNames.clear(); if (grid.getLines().length) grid.setLines([]); grid.setTotals(emptyTotals()); grid.setReadOnly(false); @@ -383,7 +386,12 @@ function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext, headAc const used = await useTemplate(ctx.api, id); if (seq !== loadSeq) return; reset(used.kind); - for (const l of used.lines) if (l.account && l.description.trim()) accounts.set(l.description.trim(), l.account); + for (const l of used.lines) { + const key = l.description.trim(); + if (!l.account || !key) continue; + accounts.set(key, l.account); + accountNames.set(key, l.accountName ? `${l.account} ${l.accountName}` : l.account); + } setValue(dateInput, used.date || today()); setValue(dueInput, used.dueDate ?? ""); setValue(memoInput, used.memo ?? "");