diff --git a/.claude/skills/formledger-harness/SKILL.md b/.claude/skills/formledger-harness/SKILL.md index 1fa43d3..7870221 100644 --- a/.claude/skills/formledger-harness/SKILL.md +++ b/.claude/skills/formledger-harness/SKILL.md @@ -10,7 +10,7 @@ metadata: # formledger-harness -FormLedger is a local-first business app that is the system of record for a small company. Apache-2.0, Copyright 2026 NodeAgentc, Inc. Repository `nodemode-dev/formledger`. Status: accounts, roles, the audit trail and the ledger core exist (chart of accounts, fiscal periods, journal, posting, reports, a command line) and the selling chain (customers, items, tax rates, quotes, orders, invoices, payments, receivables), the buying chain (suppliers, purchase orders, goods receipts, purchase invoices, payments made, payables) and stock (warehouses, an append-only stock ledger at moving average cost, delivery notes), with no screens for any of it yet; read the current version number from the binary's `version` command, not from this pack. +FormLedger is a local-first business app that is the system of record for a small company. Apache-2.0, Copyright 2026 NodeAgentc, Inc. Repository `nodemode-dev/formledger`. Status: accounts, roles, the audit trail and the ledger core exist (chart of accounts, fiscal periods, journal, posting, reports, a command line) and the selling chain (customers, items, tax rates, quotes, orders, invoices, payments, receivables), the buying chain (suppliers, purchase orders, goods receipts, purchase invoices, payments made, payables) and stock (warehouses, an append-only stock ledger at moving average cost, delivery notes), and a web client with a first set of screens for all of it (`web/src/ui/views.ts` is the registry a view joins; `web/src/ui/parts/` holds the table, picker and line grid; logic sits in `web/src/engine/`, never in a view); read the current version number from the binary's `version` command, not from this pack. This pack is for agents who change the repository. It is not about using the app. `docs/BEHAVIOURS.md` is the specification: every phase's exit criterion traces to a behaviour there, and nothing outside the repo is a source of behaviour. Outside reference products are never opened or copied. diff --git a/CHANGELOG.md b/CHANGELOG.md index a1d5d1f..e93323c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,33 @@ # Changelog +## 0.7.0 + +The web client gets its first screens. Until now everything was done from the command line or the server's routes. This is a first pass: it has been run in a browser in parts, not yet as a whole. + +### New +- A sidebar of screens grouped as Selling, Buying, Stock, Ledger and Setup. The address names the screen, so a reload comes back to the same place. +- A list for every kind of document, narrowed by status, with more rows loaded on request. +- One form for quotes, orders and invoices on both the selling and the buying side: pick the party and each item by typing, enter lines in a grid, save, confirm or post, cancel, amend, and make the next document in the chain. +- Payments received and made: enter the amount, spread it across the party's open invoices, and see what is left over as you type. +- Goods receipts and delivery notes, shown with their lines, with Post and Cancel. +- Setup lists for customers, suppliers, items, tax rates, warehouses and the chart of accounts, each with a small form to add or edit. +- Trial balance, general ledger, receivables and payables ageing, and stock balance with its value. +- Profit and loss over a range of dates and a balance sheet as of a day, as screens, as server routes, and as `./formledger cli statement pl` and `bs`. + +### Known issues +- Entering a twenty-line invoice in the form has not been completed in a check: one run posted an invoice with nine of twenty lines, and the cause has not been confirmed. +- Small movements on screen were measured in several places and are not all traced. The largest known one: a list's totals row sits under its rows and moves once when they arrive. +- There is no year-end closing step, so the balance sheet shows the result so far as "Unclosed result" inside equity. +- Profit and loss starts on January 1 of the end date's year unless you give a start date. +- Amounts are shown with two decimal places for every currency. +- Payments use a plain list to choose the party, and the setup forms take account and tax codes as typed text. +- No icons in the sidebar, no printing, no search across documents. +- The desktop app has still not been compiled, and data is still not encrypted on disk. + +### Under the hood +- `docs/window/README.md` describes the screens; `docs/ledger/statements.md` describes the two statements and names its source. +- The dev server's ports can be set with `FORMLEDGER_UI_PORT` and `FORMLEDGER_SERVER_PORT`. + ## 0.6.0 Buying and stock arrive. You can order from a supplier, receive the goods into a warehouse, record the supplier's invoice, pay it, and deliver what you sold, with stock counted and valued along the way. Still from the command line and the server's routes only. diff --git a/Makefile b/Makefile index edc4663..5cb32c7 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -VERSION := v0.6.0 +VERSION := v0.7.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 1a9def4..92b59d5 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ A local-first business app from the FormAI family of apps: every sale, purchase, payment and stock movement is a numbered document that posts to shared ledgers for money and stock. -**Status:** early. People can sign in with a role, the owner can invite others, and an audit trail records who did what ([`docs/ROLES.md`](docs/ROLES.md)). The ledger core works from the command line and over the server's routes: a chart of accounts, fiscal periods, journal entries that post and cancel, and a trial balance ([`docs/ledger/`](docs/ledger/)). So does the selling chain: customers, items and tax rates, then a quote, an order, an invoice that posts to the ledger, payments with part payment, and receivables ageing ([`docs/selling/`](docs/selling/README.md)). And the buying chain and stock: suppliers, purchase orders, goods receipts into a warehouse, purchase invoices, payments made, payables ageing, a stock ledger valued at moving average cost, and delivery notes that take stock out and post its cost ([`docs/buying/`](docs/buying/documents.md), [`docs/stock/`](docs/stock/README.md)). The web client has no ledger, selling, buying or stock screens, and the desktop app in `src-tauri/` has not been compiled. [`docs/BEHAVIOURS.md`](docs/BEHAVIOURS.md) lists what the app commits to do. +**Status:** early. People can sign in with a role, the owner can invite others, and an audit trail records who did what ([`docs/ROLES.md`](docs/ROLES.md)). The ledger core works from the command line and over the server's routes: a chart of accounts, fiscal periods, journal entries that post and cancel, and a trial balance ([`docs/ledger/`](docs/ledger/)). So does the selling chain: customers, items and tax rates, then a quote, an order, an invoice that posts to the ledger, payments with part payment, and receivables ageing ([`docs/selling/`](docs/selling/README.md)). And the buying chain and stock: suppliers, purchase orders, goods receipts into a warehouse, purchase invoices, payments made, payables ageing, a stock ledger valued at moving average cost, and delivery notes that take stock out and post its cost ([`docs/buying/`](docs/buying/documents.md), [`docs/stock/`](docs/stock/README.md)). The web client now has screens for this: a list for every document type, one form for sales and purchase documents with a line grid, payments with allocation, the setup lists, and trial balance, general ledger, profit and loss, balance sheet, ageing and stock ([`docs/window/`](docs/window/README.md)). They are new and only partly checked in a browser; the desktop app in `src-tauri/` has not been compiled. [`docs/BEHAVIOURS.md`](docs/BEHAVIOURS.md) lists what the app commits to do. ## Run it from source diff --git a/cmd/HASHOUT_LOG.md b/cmd/HASHOUT_LOG.md index 7fd5c46..1ecb871 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.6.0 +Current build version: v0.7.0 Last updated: 2026-11-26 (US Eastern) · skeleton port from form.md --- diff --git a/docs/ledger/statements.md b/docs/ledger/statements.md new file mode 100644 index 0000000..c02c75a --- /dev/null +++ b/docs/ledger/statements.md @@ -0,0 +1,42 @@ +# Profit and loss and the balance sheet + +Two statements built from the same journal lines as the trial balance: every line of an entry whose status is `posted` or `cancelled` (a cancelled entry stays counted because its reversal, also posted, cancels it out). Drafts are never counted. Both routes need the right `reports.read`. + +## Profit and loss + +`GET /api/reports/profit-and-loss?from=YYYY-MM-DD&to=YYYY-MM-DD` + +- `to` defaults to today in US Eastern time; `from` defaults to the first of January of the year of `to`. A `from` later than `to` is refused with 400 `bad_range`. +- Lines dated from `from` to `to`, both included, on accounts of type `income` and `expense`, summed per account. An account whose movement in the range nets to zero is left out. +- Income amounts are credit minus debit; expense amounts are debit minus credit, so both are positive in the usual case. +- Answer: `{from, to, income: {type, title, lines: [{accountId, code, name, currency, amount}], total}, expenses: {...}, netProfit}` where `netProfit` is income total minus expenses total. All amounts are integers in minor units. + +## Balance sheet + +`GET /api/reports/balance-sheet?as_of=YYYY-MM-DD` + +- `as_of` defaults to today in US Eastern time. All lines dated on or before `as_of`. +- Sections `assets` (debit minus credit), `liabilities` and `equity` (credit minus debit), in the same section shape as above. +- `unclosedResult` is income minus expenses over every line up to `as_of`, the same sum the profit and loss gives from the first entry to `as_of`. `totalEquity` is the equity section total plus `unclosedResult`, and `totalLiabilitiesAndEquity` is liabilities plus `totalEquity`. `balanced` is true when assets equal that sum. + +### How the year's result reaches the balance sheet + +FormLedger has no year-end closing entry yet: income and expense accounts are never moved to retained earnings by a posting. So the balance sheet carries the result itself. Every income and expense line ever posted up to `as_of` is summed into one line, "Unclosed result", shown inside equity. Since every posted entry balances, assets always equal liabilities plus equity plus that result. When a closing step is added later, the closing entry moves the result into retained earnings (`3200` in the starter chart) and this line falls to the result of the years not yet closed. Nothing in this route has to change for that. + +## Accounting source for the layout + +The split into a statement of financial position at the end of the period and a statement of profit or loss for the period follows IAS 1 Presentation of Financial Statements, as described on the IFRS Foundation's page for the standard (https://www.ifrs.org/issued-standards/list-of-standards/ias-1-presentation-of-financial-statements/, fetched 2026-11-27). That page lists the two statements as part of a complete set and says profit or loss may be shown alone or with other comprehensive income. It does not list the line items, and FormLedger does not yet split current from non-current items or show other comprehensive income: sections follow the five account types of the chart. + +## Command line + +- `./formledger cli statement pl [--from D] [--to D] [--currency XXX]` +- `./formledger cli statement bs [--as-of D] [--currency XXX]` + +## In the window + +Two views in the Ledger group, "Profit and loss" (a From and To date) and "Balance sheet" (an As of date). Each section is a table of fixed height with its totals row; the summary underneath shows the net profit or loss, or the unclosed result, total equity and total liabilities and equity. The dates are kept in the address, so a reload shows the same statement. + +## Defaults to confirm + +- One currency: amounts of accounts in different currencies are added together as they are. Every account in the starter chart is in `USD`. +- The profit and loss starts on the first of January of the end date's year by default, not the start of the fiscal year. diff --git a/docs/window/README.md b/docs/window/README.md new file mode 100644 index 0000000..0c573b1 --- /dev/null +++ b/docs/window/README.md @@ -0,0 +1,45 @@ +# The window + +The web client is the same app as the command line and the server's routes, shown as screens. Everything it does goes through the routes described in `docs/selling/`, `docs/buying/`, `docs/stock/` and `docs/ledger/`; it keeps no numbers of its own. This page says what is on each screen as of v0.7.0 and what is not there yet. + +## Getting around + +The sidebar groups the screens: Selling, Buying, Stock, Ledger and Setup. The address in the browser names the screen, for example `#/quotes?status=posted`, so a reload or a bookmark comes back to the same place. A screen shows only the actions your role allows. + +## Lists + +There is one list for each kind of document: quotes, sales orders, sales invoices, delivery notes, payments received, purchase orders, goods receipts, purchase invoices and payments made. Each shows the number, date, party, status and total, can be narrowed by status, and loads more rows on request. A draft that has no number yet reads "Draft". Open a row with a click or with Enter. + +## The document form + +Quotes, sales orders, sales invoices, purchase orders and purchase invoices share one form: who it is for, the dates, and a grid of lines. A line is an item, a description, a quantity, a unit price and a tax rate. Pick the party and each item by typing part of its code or name. + +The server works out every amount. Line totals and the document total appear after a save, in space that was already there for them. + +The buttons along the bottom are always the same ones; a button that does not apply right now is greyed, not removed. From there a document is saved as a draft, confirmed or posted, cancelled or amended, and the next document in the chain is made: an order from a quote, an invoice from an order, a delivery note or a goods receipt. + +When the server refuses something, for example a locked period, its own sentence is shown under the grid. + +## Payments + +A payment names the party, the date, the amount and the account, and lists that party's open invoices. Type an amount against each invoice the payment covers; what is left over is shown as you type and stays on account. + +## Goods receipts and delivery notes + +These are made from an order and shown read-only, with Post and Cancel. + +## Setup + +Customers, suppliers, items, tax rates, warehouses and the chart of accounts each have a list and a small form to add one or edit the opened row. Linked accounts and tax rates are typed as codes for now. + +## Ledger and position screens + +Trial balance (as of a day, and whether it balances), general ledger (one account over a range, with a running balance), profit and loss (over a range), balance sheet (as of a day), receivables and payables ageing, and stock balance with its value and the check against the books. `docs/ledger/statements.md` describes how profit and loss and the balance sheet are built. + +## Not there yet + +- Amounts are shown with two decimal places for every currency. +- Receipts and delivery notes cannot be edited before posting. +- There are no icons in the sidebar, no search across documents, and no printing. +- The setup lists have no delete, because the server has none. +- A list's totals row sits under its rows and moves once when the rows arrive. diff --git a/internal/HASHOUT_LOG.md b/internal/HASHOUT_LOG.md index 92c324b..7a27d72 100644 --- a/internal/HASHOUT_LOG.md +++ b/internal/HASHOUT_LOG.md @@ -2,8 +2,8 @@ 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.6.0 -Last updated: 2026-11-27 (US Eastern) · the buying chain and stock: suppliers, purchase documents, receipts, purchase invoices, payments made, payables, the stock ledger and delivery notes +Current build version: v0.7.0 +Last updated: 2026-11-27 (US Eastern) · profit and loss and the balance sheet --- @@ -1770,3 +1770,17 @@ An item line's expense account is the code in the setting `purchase.expense_acco - logged: v0.6.0 · 2026-11-27 Copied from internal/cli/sales.go. It reuses salesLineIn, parseSalesLine, parseQuantity and milliText from sales.go rather than declaring them twice; `purchase new` adds `--warehouse` and `--ref`. + +### internal/reports/statements.go · buildBalanceSheet +- refers-to: internal/reports/statements.go :: buildBalanceSheet, movements, statementSQL +- kind: rationale +- logged: v0.7.0 · 2026-11-27 + +There is no closing entry yet, so the balance sheet adds income minus expenses of every counted line up to `as_of` as `unclosedResult` inside equity; with balanced entries that makes assets equal liabilities plus equity by construction. The query takes the same `counted` filter as the trial balance, so a cancelled entry and its reversal both count and net to zero. The type list is spliced into the SQL as `?` placeholders, never as values. Accounts netting to zero in the range are dropped by `HAVING`. `beginning` (`0000-01-01`) stands for "from the first entry". + +### internal/reports/statements_routes.go · profitAndLossRoute +- refers-to: internal/reports/statements_routes.go :: profitAndLossRoute, balanceSheetRoute; internal/reports/reports.go :: Mount (the mountStatements line) +- kind: explainer +- 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`. diff --git a/internal/app/version.go b/internal/app/version.go index e1a3fb2..1c572ca 100644 --- a/internal/app/version.go +++ b/internal/app/version.go @@ -1,5 +1,5 @@ package app -var Version = "v0.6.0" +var Version = "v0.7.0" const Product = "FormLedger" diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 7c5ccb2..7f3f8d8 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -49,6 +49,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()}, + {"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/cli/statements.go b/internal/cli/statements.go new file mode 100644 index 0000000..6a99217 --- /dev/null +++ b/internal/cli/statements.go @@ -0,0 +1,85 @@ +package cli + +import ( + "encoding/json" + "net/url" + + "github.com/nodemode-ai/formledger/internal/money" +) + +func statementVerbs() []verb { + return []verb{ + {"pl", "[--from D] [--to D] [--currency XXX]", "profit and loss of posted and cancelled entries between two dates", statementPL}, + {"bs", "[--as-of D] [--currency XXX]", "balance sheet as of a day, with the unclosed result inside equity", statementBS}, + } +} + +func sectionRows(sec map[string]any, cur string) [][]string { + var rows [][]string + lines, _ := sec["lines"].([]any) + for _, x := range lines { + if l, ok := x.(map[string]any); ok { + rows = append(rows, []string{str(l, "code"), str(l, "name"), money.Format(minor(l, "amount"), cur)}) + } + } + return append(rows, []string{"", "Total " + str(sec, "title"), money.Format(minor(sec, "total"), cur)}) +} + +func statementPL(e *env, args []string) error { + fs := e.flags("statement pl") + from := fs.String("from", "", "first date, YYYY-MM-DD (default: the first of January of --to)") + to := fs.String("to", "", "last date, YYYY-MM-DD (default: today on the server)") + cur := fs.String("currency", money.DefaultCurrency, "currency used to show amounts in a table") + if _, err := e.parse(fs, args, 0, 0); err != nil { + return err + } + q := url.Values{} + if *from != "" { + q.Set("from", *from) + } + if *to != "" { + q.Set("to", *to) + } + return e.call("GET", "/api/reports/profit-and-loss", q, nil, func(raw json.RawMessage) error { + var m map[string]any + if err := decode(raw, &m); err != nil { + return err + } + inc, _ := m["income"].(map[string]any) + exp, _ := m["expenses"].(map[string]any) + rows := append(sectionRows(inc, *cur), sectionRows(exp, *cur)...) + rows = append(rows, []string{"", "Net profit", money.Format(minor(m, "netProfit"), *cur)}) + e.out.Write([]byte("Profit and loss from " + str(m, "from") + " to " + str(m, "to") + "\n")) + return printTable(e.out, []string{"CODE", "NAME", "AMOUNT"}, rows) + }) +} + +func statementBS(e *env, args []string) error { + fs := e.flags("statement bs") + asOf := fs.String("as-of", "", "date, YYYY-MM-DD (default: today on the server)") + cur := fs.String("currency", money.DefaultCurrency, "currency used to show amounts in a table") + if _, err := e.parse(fs, args, 0, 0); err != nil { + return err + } + q := url.Values{} + if *asOf != "" { + q.Set("as_of", *asOf) + } + return e.call("GET", "/api/reports/balance-sheet", q, nil, func(raw json.RawMessage) error { + var m map[string]any + if err := decode(raw, &m); err != nil { + return err + } + var rows [][]string + for _, k := range []string{"assets", "liabilities", "equity"} { + sec, _ := m[k].(map[string]any) + rows = append(rows, sectionRows(sec, *cur)...) + } + rows = append(rows, + []string{"", "Unclosed result", money.Format(minor(m, "unclosedResult"), *cur)}, + []string{"", "Total liabilities and equity", money.Format(minor(m, "totalLiabilitiesAndEquity"), *cur)}, + []string{"", "Balanced", str(m, "balanced")}) + e.out.Write([]byte("Balance sheet as of " + str(m, "asOf") + "\n")) + return printTable(e.out, []string{"CODE", "NAME", "AMOUNT"}, rows) + }) +} diff --git a/internal/reports/reports.go b/internal/reports/reports.go index 80181b0..d80420f 100644 --- a/internal/reports/reports.go +++ b/internal/reports/reports.go @@ -48,6 +48,7 @@ func (m module) Mount(rt *httpx.Router, d *app.Deps) error { m.route(rt, db, "GET /api/reports/balances", balances) m.route(rt, db, "GET /api/reports/period-activity", activity) m.route(rt, db, "GET /api/reports/verify", verify) + m.mountStatements(rt, db) return nil } diff --git a/internal/reports/statements.go b/internal/reports/statements.go new file mode 100644 index 0000000..263ab93 --- /dev/null +++ b/internal/reports/statements.go @@ -0,0 +1,138 @@ +package reports + +import ( + "context" + "database/sql" + "strings" +) + +type statementLine struct { + AccountID string `json:"accountId"` + Code string `json:"code"` + Name string `json:"name"` + Currency string `json:"currency"` + Amount int64 `json:"amount"` +} + +type statementSection struct { + Type string `json:"type"` + Title string `json:"title"` + Lines []statementLine `json:"lines"` + Total int64 `json:"total"` +} + +type profitAndLoss struct { + From string `json:"from"` + To string `json:"to"` + Income statementSection `json:"income"` + Expenses statementSection `json:"expenses"` + NetProfit int64 `json:"netProfit"` +} + +type balanceSheet struct { + AsOf string `json:"asOf"` + Assets statementSection `json:"assets"` + Liabilities statementSection `json:"liabilities"` + Equity statementSection `json:"equity"` + UnclosedResult int64 `json:"unclosedResult"` + TotalEquity int64 `json:"totalEquity"` + TotalLiabilitiesEquity int64 `json:"totalLiabilitiesAndEquity"` + Balanced bool `json:"balanced"` +} + +const statementSQL = ` +SELECT a.id, a.code, a.name, a.type, a.currency, SUM(l.debit) - SUM(l.credit) +FROM journal_lines l +JOIN journal_entries e ON e.id = l.entry_id +JOIN accounts a ON a.id = l.account_id +WHERE ` + counted + ` AND e.entry_date >= ? AND e.entry_date <= ? AND a.type IN (%s) +GROUP BY a.id +HAVING SUM(l.debit) - SUM(l.credit) <> 0 +ORDER BY a.code` + +var sectionTitles = map[string]string{ + "income": "Income", + "expense": "Expenses", + "asset": "Assets", + "liability": "Liabilities", + "equity": "Equity", +} + +func newSection(kind string) statementSection { + return statementSection{Type: kind, Title: sectionTitles[kind], Lines: []statementLine{}} +} + +func creditNormal(kind string) bool { + return kind == "income" || kind == "liability" || kind == "equity" +} + +func movements(ctx context.Context, db *sql.DB, from, to string, kinds []string, sections map[string]*statementSection) error { + q, args := statementQuery(from, to, kinds) + rows, err := db.QueryContext(ctx, q, args...) + if err != nil { + return err + } + defer rows.Close() + for rows.Next() { + var l statementLine + var kind string + var net int64 + if err := rows.Scan(&l.AccountID, &l.Code, &l.Name, &kind, &l.Currency, &net); err != nil { + return err + } + s := sections[kind] + if s == nil { + continue + } + l.Amount = net + if creditNormal(kind) { + l.Amount = -net + } + s.Lines = append(s.Lines, l) + s.Total += l.Amount + } + return rows.Err() +} + +func statementQuery(from, to string, kinds []string) (string, []any) { + marks := "" + args := []any{from, to} + for i, k := range kinds { + if i > 0 { + marks += ", " + } + marks += "?" + args = append(args, k) + } + return strings.Replace(statementSQL, "%s", marks, 1), args +} + +func buildProfitAndLoss(ctx context.Context, db *sql.DB, from, to string) (*profitAndLoss, error) { + p := &profitAndLoss{From: from, To: to, Income: newSection("income"), Expenses: newSection("expense")} + err := movements(ctx, db, from, to, []string{"income", "expense"}, map[string]*statementSection{"income": &p.Income, "expense": &p.Expenses}) + if err != nil { + return nil, err + } + p.NetProfit = p.Income.Total - p.Expenses.Total + return p, nil +} + +const beginning = "0000-01-01" + +func buildBalanceSheet(ctx context.Context, db *sql.DB, asOf string) (*balanceSheet, error) { + b := &balanceSheet{AsOf: asOf, Assets: newSection("asset"), Liabilities: newSection("liability"), Equity: newSection("equity")} + err := movements(ctx, db, beginning, asOf, []string{"asset", "liability", "equity"}, + map[string]*statementSection{"asset": &b.Assets, "liability": &b.Liabilities, "equity": &b.Equity}) + if err != nil { + return nil, err + } + pl, err := buildProfitAndLoss(ctx, db, beginning, asOf) + if err != nil { + return nil, err + } + b.UnclosedResult = pl.NetProfit + b.TotalEquity = b.Equity.Total + b.UnclosedResult + b.TotalLiabilitiesEquity = b.Liabilities.Total + b.TotalEquity + b.Balanced = b.Assets.Total == b.TotalLiabilitiesEquity + return b, nil +} diff --git a/internal/reports/statements_routes.go b/internal/reports/statements_routes.go new file mode 100644 index 0000000..41fc23b --- /dev/null +++ b/internal/reports/statements_routes.go @@ -0,0 +1,37 @@ +package reports + +import ( + "context" + "database/sql" + "net/http" + + "github.com/nodemode-ai/formledger/internal/httpx" +) + +func (m module) mountStatements(rt *httpx.Router, db *sql.DB) { + m.route(rt, db, "GET /api/reports/profit-and-loss", profitAndLossRoute) + m.route(rt, db, "GET /api/reports/balance-sheet", balanceSheetRoute) +} + +func profitAndLossRoute(ctx context.Context, db *sql.DB, r *http.Request) (any, error) { + to, err := date(r, "to", today()) + if err != nil { + return nil, err + } + from, err := date(r, "from", to[:4]+"-01-01") + if err != nil { + return nil, err + } + if from > to { + return nil, httpx.Fail(http.StatusBadRequest, "bad_range", "from must not be later than to") + } + return buildProfitAndLoss(ctx, db, from, to) +} + +func balanceSheetRoute(ctx context.Context, db *sql.DB, r *http.Request) (any, error) { + asOf, err := date(r, "as_of", today()) + if err != nil { + return nil, err + } + return buildBalanceSheet(ctx, db, asOf) +} diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 82777cb..c0b071e 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -1106,7 +1106,7 @@ dependencies = [ [[package]] name = "formledger-desktop" -version = "0.6.0" +version = "0.7.0" dependencies = [ "objc2", "objc2-app-kit", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 7ed4a2d..cf49af7 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "formledger-desktop" -version = "0.6.0" +version = "0.7.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 36ca7a9..f1c9852 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.6.0 +Current build version: v0.7.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 e330b10..8ae8070 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.6.0", + "version": "0.7.0", "identifier": "ai.nodemode.formledger", "build": { "frontendDist": "splash" }, "app": { diff --git a/web/HASHOUT_LOG.md b/web/HASHOUT_LOG.md index 9d596f5..3a5f10f 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.6.0 +Current build version: v0.7.0 Last updated: 2026-11-26 (US Eastern) · account screens, and the fixes from the throttled browser check --- @@ -492,3 +492,88 @@ Calls `mountAccount` after the nav and status bindings. - logged: v0.3.0 · 2026-11-26 The dev server also proxies `/desktop` so `/desktop/enter?key=KEY` reaches the server and its redirect lands on the dev client. + +### src/engine/doclists.ts · DOC_LISTS +- refers-to: src/engine/doclists.ts :: DOC_LISTS, loadPage +- kind: explainer +- logged: v0.7.0 · 2026-11-27 + +One spec per document list: route, `kind` query, the list key in the answer (`docs` or `notes`), party side, the form view a row opens and the right needed for "New" (`null` where a document is only made from another: delivery notes and goods receipts). Delivery notes answer only `customerId` and a stock `value`, no total or currency, so the party name comes from one cached `GET /api/customers?limit=500` (read again once when a note names an id not in the cache) and the amount column is labelled "Stock value". Only the paged routes (`/api/sales/docs`, `/api/purchase/docs`) give `nextCursor`; delivery notes show the first 100. + +### src/ui/views/doclists.ts · listView +- refers-to: src/ui/views/doclists.ts :: listView +- kind: rationale +- logged: v0.7.0 · 2026-11-27 + +Built once on mount on `mountTable`. The status filter writes the address (`?status=`) and `show` reads it back, so the filter survives a reload; every `show` re-reads the first page and `setRows` patches by id. "Load more" appends with `patchRow`. A sequence number drops answers that arrive after a newer request. A draft has no number and shows "Draft" in the number cell. "New" goes to the form view with `{kind}` and is left out at mount when `ctx.can` refuses. + +### src/ui/views/ledger-screens.ts · screens +- refers-to: src/ui/views/ledger-screens.ts :: shell +- kind: rationale +- logged: v0.7.0 · 2026-11-27 + +Five read-only views share one shell: a filter bar and a status line of fixed height above a `mountTable`, so growing rows push nothing. A filter change re-reads and `setRows` patches by key. A serial number drops an answer that arrives after a newer one. The status line carries the facts that are not table rows: whether the trial balance balances, opening and closing of an account, the tie of stock value to the ledger, and per-currency ageing totals when there is more than one currency (the foot row shows a total only for one). + +### src/engine/ledger-screens.ts · money places +- refers-to: src/engine/ledger-screens.ts :: amount +- kind: rationale +- logged: v0.7.0 · 2026-11-27 + +Amounts are shown with two places for every currency, because `format.money` takes the places as an argument and the engine does not hand the client a currency exponent. A currency with another exponent would be shown wrongly until that is added. The stock screen builds one row per item from the valuation and writes the warehouses and their quantities into one cell from the balances. + +### src/ui/views/statements.ts · profitAndLossView +- refers-to: src/ui/views/statements.ts :: profitAndLossView, balanceSheetView, runner, goOrRefresh +- kind: rationale +- logged: v0.7.0 · 2026-11-27 + +Each view builds its filter bar, status line, one `mountTable` per section and the summary block once on mount; every table is a fixed `--st-rows` rows high and scrolls inside, so a long section never pushes the next one down. The dates live in the address; Show navigates, or re-runs when the address would not change (no `hashchange` fires then). A sequence number drops answers older than the latest request, and the busy mark comes through `delayedIndicator`. The run icon is drawn here rather than in the shared `icons.ts`. + +### src/engine/lookups.ts · lookup +- refers-to: src/engine/lookups.ts :: lookup, filterEntries, findById, forget +- kind: rationale +- logged: v0.7.0 · 2026-11-27 + +One promise per kind, kept for the life of the page and dropped if it fails, so every picker of a kind shares one fetch. Paged routes are followed by `nextCursor` (items) or `next` (customers, suppliers) at 200 a page, up to 50 pages. Filtering puts code or name prefix matches before substring matches and skips inactive records. `forget(kind)` is there for a view that has just created a record. + +### src/ui/parts/picker.ts · mountPicker +- refers-to: src/ui/parts/picker.ts :: mountPicker, overlayLayer +- kind: rationale +- logged: v0.7.0 · 2026-11-27 + +The scaffold has no overlay root besides the toast root, so the picker makes one fixed layer on `body` at `--z-popover` and puts each list there, built on first open with eight rows that are rewritten in place and hidden when unused. The list is placed from the input's rectangle, follows it on scroll and resize while open, and opens upward when there is no room below. Enter on an open list is consumed so the grid does not also act on it. Blur with an empty input clears the value; otherwise the label of the current value is put back. `bare` drops the field label for use inside a grid cell; `input` is exposed for keyboard routing. + +### src/ui/parts/linegrid.ts · mountLineGrid +- refers-to: src/ui/parts/linegrid.ts :: mountLineGrid +- kind: rationale +- logged: v0.7.0 · 2026-11-27 + +Rows are CSS grid rows with fixed column widths and a reserved error strip; the totals block under the grid is a fixed width. Typing writes only the line model and calls `onChange`; subtotal, tax and total cells are written only by `setTotals`, which maps its `lines` to the rows `getLines` last returned (blank rows are left out of `getLines`). Picking an item fills an empty description, the sale price (sales family only, as items carry no purchase price) and the item's tax rate. Enter moves down a row in the same column and adds a row on the last; arrow keys move between rows outside the pickers; Ctrl+Delete or the button removes a row, and the last row is cleared rather than removed. Places come from a short list of zero-decimal currencies, else two, because the client has no exponent table; `setCurrency` was added for a form that learns the currency after mount. + +### src/engine/payments.ts · FAMILIES +- refers-to: src/engine/payments.ts :: FAMILIES, getStockDoc, remainder +- kind: rationale +- logged: v0.7.0 · 2026-11-27 + +One family record per direction carries the route base, the party and account field names (`customer`/`deposit`, `supplier`/`paidFrom`), the position route that lists open invoices, and the permissions, so the list and form code is shared. A delivery note answers only ids for its customer, warehouse and item, so the customer is read once per note and the warehouse and item lists once per page (cached, dropped on failure). A goods receipt is a purchase document of kind `receipt`; its post and cancel go to `/api/purchase/receipts/{id}`. Amounts are read and shown with two places. + +### src/ui/views/payments.ts · mountForm +- refers-to: src/ui/views/payments.ts :: mountList, mountForm, mountStock +- kind: rationale +- logged: v0.7.0 · 2026-11-27 + +The form is built once per direction. The party is a plain select filled once from the party list, not the shared picker. The allocation table is keyed by invoice id: the party's open invoices plus the invoices this payment already allocates to, ordered by number, rewritten cell by cell; typing an amount writes only the remainder. The remainder is the amount less the amounts typed for a draft, and the payment's own unallocated amount less those typed for a posted one. Post saves the draft first, then posts with the typed allocations; Allocate is for a posted payment with money left. Buttons are always present and only enabled or disabled; those the person may not use are hidden from mount. A refusal shows the server's sentence in the reserved error line. + +### src/ui/views/docform.ts · mountForm +- refers-to: src/ui/views/docform.ts :: mountForm, formView; src/engine/docform.ts :: SPECS, draftBody, actionState +- kind: rationale +- logged: v0.7.0 · 2026-11-27 + +One form per family (`sales-doc`, `purchase-doc`) is built on first show from `SPECS`; loading another document writes values in place, and the grid's lines are replaced only when they differ from what the server answered. A line naming an item sends only the fields the person filled, so the server fills description, price and tax from the item. Confirm or Post saves the draft first and then posts; every action re-reads the document so status, number and totals come from the server. Make steps for a delivery note or goods receipt need the warehouse picked in the header. Buttons stay in place: disabled when the status does not allow them, `visibility: hidden` when the person may not use them. Sales documents have no reference column, so the reference field is built only for purchase documents. + +## masters setup lists + +- refers-to: src/ui/views/masters.ts :: mountMaster, src/engine/masters.ts :: MASTERS, buildBody +- kind: rationale +- logged: v0.7.0 · 2026-11-27 + +Six setup views come from one table of specs. Each view builds its table and a fixed-size form once; opening a row rewrites the field values and locks the fields the server refuses to change after create (code, type, currency, linked account codes). Edit sends only the fields that changed. Account, tax rate and item links are typed as codes, not picked, because the picker slice may not land; the server's own sentence shows when a code is unknown. Accounts have no cursor, so the whole chart is read once. diff --git a/web/index.html b/web/index.html index bfeee1e..471e1ea 100644 --- a/web/index.html +++ b/web/index.html @@ -72,6 +72,7 @@