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 @@

Join FormLedger

Account +
@@ -81,7 +82,7 @@

Join FormLedger

-
+

Home

diff --git a/web/package-lock.json b/web/package-lock.json index 0396725..235227a 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -1,12 +1,12 @@ { "name": "formledger", - "version": "0.6.0", + "version": "0.7.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "formledger", - "version": "0.6.0", + "version": "0.7.0", "license": "Apache-2.0", "devDependencies": { "@types/node": "^22.20.5", diff --git a/web/package.json b/web/package.json index 6c27095..0a3e370 100644 --- a/web/package.json +++ b/web/package.json @@ -1,7 +1,7 @@ { "name": "formledger", "private": true, - "version": "0.6.0", + "version": "0.7.0", "license": "Apache-2.0", "type": "module", "scripts": { diff --git a/web/src/engine/docform.ts b/web/src/engine/docform.ts new file mode 100644 index 0000000..da91a94 --- /dev/null +++ b/web/src/engine/docform.ts @@ -0,0 +1,279 @@ +import type { Api } from "./index"; + +export type Family = "sales" | "purchase"; +export type DocStatus = "draft" | "posted" | "cancelled"; + +export interface DocLine { + id: string; + lineNo: number; + itemId: string; + item: string; + description: string; + quantityMilli: number; + unitPrice: number; + taxRateId: string; + taxRate: string; + rateBp: number; + lineSubtotal: number; + lineTax: number; + lineTotal: number; +} + +export interface Doc { + id: string; + kind: string; + number: string; + date: string; + dueDate: string; + partyId: string; + currency: string; + status: DocStatus; + sourceId: string; + amendsId: string; + warehouseId: string; + reference: string; + subtotal: number; + taxTotal: number; + total: number; + memo: string; + lines: DocLine[]; +} + +export interface DraftLine { + itemId: string; + description: string; + qtyMilli: number; + unitPrice: number; + taxRateId: string; +} + +export interface Draft { + kind: string; + date: string; + dueDate: string; + partyId: string; + warehouseId: string; + reference: string; + memo: string; + lines: DraftLine[]; +} + +export type MakeTarget = "sales-doc" | "purchase-doc" | "delivery-note" | "goods-receipt"; + +export interface MakeStep { + key: string; + label: string; + from: string; + path: string; + target: MakeTarget; + needsWarehouse: boolean; + action: string; +} + +export interface FamilySpec { + family: Family; + view: "sales-doc" | "purchase-doc"; + title: string; + base: string; + partyKind: "customer" | "supplier"; + partyLabel: string; + partyField: "customer" | "supplier"; + kinds: { id: string; label: string }[]; + hasReference: boolean; + draftAction: string; + postAction: string; + makes: MakeStep[]; +} + +export const SPECS: Record = { + sales: { + family: "sales", + view: "sales-doc", + title: "Sales document", + base: "/api/sales", + partyKind: "customer", + partyLabel: "Customer", + partyField: "customer", + kinds: [ + { id: "quote", label: "Quote" }, + { id: "order", label: "Sales order" }, + { id: "invoice", label: "Sales invoice" }, + ], + hasReference: false, + draftAction: "sales.draft", + postAction: "sales.post", + makes: [ + { key: "make-order", label: "Make order", from: "quote", path: "make-order", target: "sales-doc", needsWarehouse: false, action: "sales.draft" }, + { key: "make-invoice", label: "Make invoice", from: "order", path: "make-invoice", target: "sales-doc", needsWarehouse: false, action: "sales.draft" }, + { key: "make-delivery", label: "Make delivery note", from: "order", path: "make-delivery", target: "delivery-note", needsWarehouse: true, action: "stock.draft" }, + ], + }, + purchase: { + family: "purchase", + view: "purchase-doc", + title: "Purchase document", + base: "/api/purchase", + partyKind: "supplier", + partyLabel: "Supplier", + partyField: "supplier", + kinds: [ + { id: "order", label: "Purchase order" }, + { id: "invoice", label: "Purchase invoice" }, + ], + hasReference: true, + draftAction: "purchase.draft", + postAction: "purchase.post", + makes: [ + { key: "make-receipt", label: "Make goods receipt", from: "order", path: "make-receipt", target: "goods-receipt", needsWarehouse: true, action: "purchase.draft" }, + { key: "make-invoice", label: "Make invoice", from: "order", path: "make-invoice", target: "purchase-doc", needsWarehouse: false, action: "purchase.draft" }, + ], + }, +}; + +export function kindLabel(spec: FamilySpec, kind: string): string { + return spec.kinds.find((k) => k.id === kind)?.label ?? kind; +} + +export function statusLabel(kind: string, status: DocStatus): string { + if (status === "draft") return "Draft"; + if (status === "cancelled") return "Cancelled"; + return kind === "invoice" ? "Posted" : "Confirmed"; +} + +export function confirmLabel(kind: string): string { + return kind === "invoice" ? "Post" : "Confirm"; +} + +function str(v: unknown): string { + return typeof v === "string" ? v : ""; +} + +function num(v: unknown): number { + return typeof v === "number" && Number.isInteger(v) ? v : 0; +} + +export function readDoc(spec: FamilySpec, raw: Record): Doc { + const rawLines = Array.isArray(raw.lines) ? (raw.lines as Record[]) : []; + return { + id: str(raw.id), + kind: str(raw.kind), + number: str(raw.number), + date: str(raw.date), + dueDate: str(raw.dueDate), + partyId: str(spec.family === "sales" ? raw.customerId : raw.supplierId), + currency: str(raw.currency), + status: (str(raw.status) || "draft") as DocStatus, + sourceId: str(raw.sourceId), + amendsId: str(raw.amendsId), + warehouseId: str(raw.warehouseId), + reference: str(raw.supplierRef), + subtotal: num(raw.subtotal), + taxTotal: num(raw.taxTotal), + total: num(raw.total), + memo: str(raw.memo), + lines: rawLines.map((l) => ({ + id: str(l.id), + lineNo: num(l.lineNo), + itemId: str(l.itemId), + item: str(l.item), + description: str(l.description), + quantityMilli: num(l.quantityMilli), + unitPrice: num(l.unitPrice), + taxRateId: str(l.taxRateId), + taxRate: str(l.taxRate), + rateBp: num(l.rateBp), + lineSubtotal: num(l.lineSubtotal), + lineTax: num(l.lineTax), + lineTotal: num(l.lineTotal), + })), + }; +} + +export function isBlankLine(l: DraftLine): boolean { + return !l.itemId && !l.description.trim() && l.qtyMilli === 0 && l.unitPrice === 0; +} + +export function draftBody(spec: FamilySpec, d: Draft, create: boolean): Record { + const body: Record = { + date: d.date, + memo: d.memo, + [spec.partyField]: d.partyId, + lines: d.lines + .filter((l) => !isBlankLine(l)) + .map((l) => { + if (!l.itemId) return { description: l.description, quantityMilli: l.qtyMilli, unitPrice: l.unitPrice, taxRate: l.taxRateId }; + const out: Record = { item: l.itemId, quantityMilli: l.qtyMilli }; + if (l.description.trim()) out.description = l.description; + if (l.unitPrice > 0) out.unitPrice = l.unitPrice; + if (l.taxRateId) out.taxRate = l.taxRateId; + return out; + }), + }; + if (create) body.kind = d.kind; + if (d.dueDate) body.dueDate = d.dueDate; + if (spec.hasReference) body.supplierRef = d.reference; + if (spec.family === "purchase" && d.warehouseId) body.warehouse = d.warehouseId; + return body; +} + +const enc = encodeURIComponent; + +export async function loadDoc(api: Api, spec: FamilySpec, id: string): Promise { + return readDoc(spec, await api.call>("GET", `${spec.base}/docs/${enc(id)}`)); +} + +export async function saveDraft(api: Api, spec: FamilySpec, id: string | null, d: Draft): Promise { + const raw = id + ? await api.call>("PATCH", `${spec.base}/docs/${enc(id)}`, draftBody(spec, d, false)) + : await api.call>("POST", `${spec.base}/docs`, draftBody(spec, d, true)); + return readDoc(spec, raw); +} + +export async function confirmDoc(api: Api, spec: FamilySpec, doc: Doc): Promise { + const path = doc.kind === "invoice" ? `${spec.base}/invoices/${enc(doc.id)}/post` : `${spec.base}/docs/${enc(doc.id)}/confirm`; + await api.call("POST", path, {}); + return loadDoc(api, spec, doc.id); +} + +export async function cancelDoc(api: Api, spec: FamilySpec, doc: Doc): Promise { + const path = doc.kind === "invoice" ? `${spec.base}/invoices/${enc(doc.id)}/cancel` : `${spec.base}/docs/${enc(doc.id)}/cancel`; + await api.call("POST", path, {}); + return loadDoc(api, spec, doc.id); +} + +export async function amendDoc(api: Api, spec: FamilySpec, doc: Doc): Promise { + const out = await api.call>("POST", `${spec.base}/docs/${enc(doc.id)}/amend`, {}); + return str(out.id); +} + +export async function makeNext(api: Api, spec: FamilySpec, doc: Doc, step: MakeStep, warehouseId: string): Promise { + const body: Record = {}; + if (step.needsWarehouse) body.warehouse = warehouseId; + const out = await api.call>("POST", `${spec.base}/docs/${enc(doc.id)}/${step.path}`, body); + return str(out.id); +} + +export interface ActionState { + save: boolean; + confirm: boolean; + cancel: boolean; + amend: boolean; + makes: Record; +} + +export function actionState(spec: FamilySpec, doc: Doc | null, can: (a: string) => boolean, warehouseId: string, newKind = ""): ActionState { + const status = doc?.status ?? "draft"; + const kind = doc?.kind ?? newKind; + const draft = status === "draft"; + const posted = status === "posted"; + const postAction = kind === "invoice" ? spec.postAction : spec.draftAction; + const makes: Record = {}; + for (const m of spec.makes) makes[m.key] = !!doc && posted && kind === m.from && can(m.action) && (!m.needsWarehouse || !!warehouseId); + return { + save: draft && can(spec.draftAction), + confirm: draft && can(postAction) && can(spec.draftAction), + cancel: !!doc && posted && can(postAction), + amend: !!doc && status !== "draft" && can(spec.draftAction), + makes, + }; +} diff --git a/web/src/engine/doclists.ts b/web/src/engine/doclists.ts new file mode 100644 index 0000000..dc726c1 --- /dev/null +++ b/web/src/engine/doclists.ts @@ -0,0 +1,116 @@ +import type { Api } from "./session"; +import type { ViewGroup } from "../ui/views"; + +export type DocStatus = "draft" | "posted" | "cancelled"; + +export const STATUSES: readonly DocStatus[] = ["draft", "posted", "cancelled"]; + +export interface DocRow { + id: string; + number: string; + date: string; + party: string; + status: DocStatus; + total: number; + currency: string; +} + +export interface DocPage { + rows: DocRow[]; + next: string; +} + +export interface DocListSpec { + id: string; + title: string; + group: ViewGroup; + path: string; + kind: string; + key: "docs" | "notes"; + party: "customer" | "supplier"; + totalLabel: string; + paged: boolean; + form: string; + newAction: string | null; +} + +export const DOC_LISTS: readonly DocListSpec[] = [ + { id: "quotes", title: "Quotes", group: "Selling", path: "/api/sales/docs", kind: "quote", key: "docs", party: "customer", totalLabel: "Total", paged: true, form: "sales-doc", newAction: "sales.draft" }, + { id: "sales-orders", title: "Sales orders", group: "Selling", path: "/api/sales/docs", kind: "order", key: "docs", party: "customer", totalLabel: "Total", paged: true, form: "sales-doc", newAction: "sales.draft" }, + { id: "sales-invoices", title: "Sales invoices", group: "Selling", path: "/api/sales/docs", kind: "invoice", key: "docs", party: "customer", totalLabel: "Total", paged: true, form: "sales-doc", newAction: "sales.draft" }, + { id: "delivery-notes", title: "Delivery notes", group: "Stock", path: "/api/delivery/notes", kind: "", key: "notes", party: "customer", totalLabel: "Stock value", paged: false, form: "delivery-note", newAction: null }, + { id: "purchase-orders", title: "Purchase orders", group: "Buying", path: "/api/purchase/docs", kind: "order", key: "docs", party: "supplier", totalLabel: "Total", paged: true, form: "purchase-doc", newAction: "purchase.draft" }, + { id: "goods-receipts", title: "Goods receipts", group: "Buying", path: "/api/purchase/docs", kind: "receipt", key: "docs", party: "supplier", totalLabel: "Total", paged: true, form: "goods-receipt", newAction: null }, + { id: "purchase-invoices", title: "Purchase invoices", group: "Buying", path: "/api/purchase/docs", kind: "invoice", key: "docs", party: "supplier", totalLabel: "Total", paged: true, form: "purchase-doc", newAction: "purchase.draft" }, +]; + +export const PAGE_SIZE = 100; + +export function isStatus(value: string | null): value is DocStatus { + return value !== null && (STATUSES as readonly string[]).includes(value); +} + +interface RawDoc { + id: string; + number?: string | null; + date: string; + status: DocStatus; + total?: number; + value?: number; + currency?: string; + customerId?: string; + customerName?: string; + customer?: string; + supplierName?: string; + supplier?: string; +} + +let customerNames: Promise> | null = null; + +function customers(api: Api): Promise> { + customerNames ??= api + .call<{ customers: { id: string; code: string; name: string }[] }>("GET", "/api/customers?limit=500") + .then((out) => new Map((out.customers ?? []).map((c) => [c.id, c.name || c.code]))) + .catch(() => { + customerNames = null; + return new Map(); + }); + return customerNames; +} + +function partyOf(spec: DocListSpec, d: RawDoc, names: Map): string { + if (spec.party === "supplier") return d.supplierName || d.supplier || ""; + if (spec.key === "notes") return names.get(d.customerId ?? "") ?? d.customerId ?? ""; + return d.customerName || d.customer || ""; +} + +export async function loadPage(api: Api, spec: DocListSpec, status: DocStatus | null, cursor = ""): Promise { + const q = new URLSearchParams(); + if (spec.kind) q.set("kind", spec.kind); + if (status) q.set("status", status); + q.set("limit", String(PAGE_SIZE)); + if (cursor) q.set("cursor", cursor); + let [out, names] = await Promise.all([ + api.call>("GET", `${spec.path}?${q.toString()}`), + spec.key === "notes" ? customers(api) : Promise.resolve(new Map()), + ]); + const raw = (out[spec.key] as RawDoc[] | null) ?? []; + if (spec.key === "notes" && raw.some((d) => d.customerId && !names.has(d.customerId))) { + forgetParties(); + names = await customers(api); + } + const rows = raw.map((d) => ({ + id: d.id, + number: d.number ?? "", + date: d.date, + party: partyOf(spec, d, names), + status: d.status, + total: spec.key === "notes" ? (d.value ?? 0) : (d.total ?? 0), + currency: d.currency ?? "", + })); + return { rows, next: spec.paged ? String(out.nextCursor ?? "") : "" }; +} + +export function forgetParties(): void { + customerNames = null; +} diff --git a/web/src/engine/format.ts b/web/src/engine/format.ts new file mode 100644 index 0000000..971563d --- /dev/null +++ b/web/src/engine/format.ts @@ -0,0 +1,40 @@ +const GROUP = /\B(?=(\d{3})+(?!\d))/g; + +export function money(minor: number, places = 2): string { + const neg = minor < 0; + const abs = Math.abs(Math.trunc(minor)); + const scale = 10 ** places; + const whole = Math.trunc(abs / scale).toString().replace(GROUP, ","); + const frac = places ? `.${(abs % scale).toString().padStart(places, "0")}` : ""; + return `${neg ? "-" : ""}${whole}${frac}`; +} + +export function parseMoney(text: string, places = 2): number | null { + const m = /^(-?)(\d*)(?:\.(\d*))?$/.exec(text.replace(/[,\s]/g, "")); + if (!m || (!m[2] && !m[3])) return null; + const frac = (m[3] ?? "").padEnd(places, "0"); + if (frac.length > places) return null; + const value = Number(m[2] || "0") * 10 ** places + Number(frac || "0"); + return Number.isSafeInteger(value) ? (m[1] ? -value : value) : null; +} + +export function qty(milli: number): string { + const neg = milli < 0; + const abs = Math.abs(Math.trunc(milli)); + const frac = (abs % 1000).toString().padStart(3, "0").replace(/0+$/, ""); + const whole = Math.trunc(abs / 1000).toString().replace(GROUP, ","); + return `${neg ? "-" : ""}${whole}${frac ? `.${frac}` : ""}`; +} + +export function parseQty(text: string): number | null { + return parseMoney(text, 3); +} + +export function percent(basisPoints: number): string { + return `${money(basisPoints, 2)}%`; +} + +export function today(now: Date = new Date()): string { + const p = (n: number) => String(n).padStart(2, "0"); + return `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}`; +} diff --git a/web/src/engine/index.ts b/web/src/engine/index.ts index d18c071..429fa20 100644 --- a/web/src/engine/index.ts +++ b/web/src/engine/index.ts @@ -4,7 +4,7 @@ import { State } from "./state"; import { Api, ApiError, inviteTokenOf, INVITE_ROLES, type AuthState, type Created, type Invite, type InviteInfo, type Me, type Screen } from "./session"; -export type Route = "home" | "account"; +export type Route = string; export interface AppState { route: Route; @@ -28,6 +28,7 @@ export interface EngineOptions { export interface Engine { state: State; commands: Commands; + api: Api; start(): void; stop(): void; } @@ -225,6 +226,7 @@ export function createEngine(options: EngineOptions): Engine { return { state, commands, + api, start: () => { health.start(); void resolve(); @@ -233,7 +235,7 @@ export function createEngine(options: EngineOptions): Engine { }; } -export { ApiError, INVITE_ROLES } from "./session"; +export { Api, ApiError, INVITE_ROLES } from "./session"; export type { Me, Invite, InviteRole, Screen } from "./session"; export type { Health, HealthPhase } from "./health"; diff --git a/web/src/engine/ledger-screens.ts b/web/src/engine/ledger-screens.ts new file mode 100644 index 0000000..523f52c --- /dev/null +++ b/web/src/engine/ledger-screens.ts @@ -0,0 +1,140 @@ +import type { Api } from "./session"; +import { money, qty } from "./format"; + +export interface TrialRow { + accountId: string; + code: string; + name: string; + type: string; + isGroup: boolean; + debit: number; + credit: number; +} +export interface Trial { + asOf: string; + rows: TrialRow[]; + totalDebit: number; + totalCredit: number; + balanced: boolean; +} +export interface LedgerLine { + date: string; + number: string; + entryId: string; + lineNo: number; + memo: string; + debit: number; + credit: number; + balance: number; +} +export interface Ledger { + opening: number; + lines: LedgerLine[]; + closing: number; + totalLines: number; +} +export interface AccountOption { + code: string; + name: string; + isGroup: boolean; +} +export interface AgeingRow { + id: string; + code: string; + name: string; + currency: string; + current: number; + days1to30: number; + days31to60: number; + days61to90: number; + over90: number; + unallocated: number; + total: number; +} +export interface Ageing { + rows: AgeingRow[]; + totals: Omit[]; +} +export interface StockRow { + itemId: string; + code: string; + name: string; + qtyMilli: number; + averageCost: number; + value: number; + where: string; +} +export interface Stock { + rows: StockRow[]; + total: number; + ledgerTotal: number; + difference: number; + matched: boolean; +} + +const query = (params: Record) => { + const q = new URLSearchParams(); + for (const [k, v] of Object.entries(params)) if (v) q.set(k, v); + const s = q.toString(); + return s ? `?${s}` : ""; +}; + +export const amount = (n: number): string => money(n); + +export async function loadTrial(api: Api, asOf: string): Promise { + const out = await api.call("GET", `/api/reports/trial-balance${query({ asOf })}`); + return { ...out, rows: (out.rows ?? []).filter((r) => !r.isGroup) }; +} + +export async function loadAccounts(api: Api): Promise { + const out = await api.call<{ accounts: AccountOption[] }>("GET", "/api/accounts"); + return (out.accounts ?? []).filter((a) => !a.isGroup); +} + +export async function loadLedger(api: Api, account: string, from: string, to: string): Promise { + const out = await api.call("GET", `/api/reports/general-ledger${query({ account, from, to, limit: "1000" })}`); + return { ...out, lines: out.lines ?? [] }; +} + +export async function loadAgeing(api: Api, side: "receivables" | "payables", asOf: string, by: string): Promise { + const out = await api.call<{ rows: Record[]; totals: Ageing["totals"] }>("GET", `/api/${side}/ageing${query({ asOf, by })}`); + const idKey = side === "receivables" ? "customerId" : "supplierId"; + const rows = (out.rows ?? []).map((r) => ({ ...(r as unknown as AgeingRow), id: String(r[idKey] ?? r.code) })); + return { rows, totals: out.totals ?? [] }; +} + +export async function loadStock(api: Api, asOf: string): Promise { + const q = query({ asOf }); + const [val, bal, rec] = await Promise.all([ + api.call<{ items: { itemId: string; itemCode: string; itemName: string; qtyMilli: number; averageCost: number; value: number }[]; total: number }>("GET", `/api/stock/valuation${q}`), + api.call<{ balances: { itemId: string; warehouseCode: string; qtyMilli: number }[] }>("GET", `/api/stock/balances${q}`), + api.call<{ ledgerTotal: number; stockTotal: number; difference: number; matched: boolean }>("GET", `/api/stock/reconcile${q}`), + ]); + const where = new Map(); + for (const b of bal.balances ?? []) { + if (!b.qtyMilli) continue; + const list = where.get(b.itemId) ?? []; + list.push(`${b.warehouseCode} ${qty(b.qtyMilli)}`); + where.set(b.itemId, list); + } + const rows = (val.items ?? []).map((i) => ({ + itemId: i.itemId, + code: i.itemCode, + name: i.itemName, + qtyMilli: i.qtyMilli, + averageCost: i.averageCost, + value: i.value, + where: (where.get(i.itemId) ?? []).join(", "), + })); + return { rows, total: val.total ?? 0, ledgerTotal: rec.ledgerTotal, difference: rec.difference, matched: rec.matched }; +} + +export function balanceLine(t: { balanced: boolean; totalDebit: number; totalCredit: number }): string { + return t.balanced ? "The trial balance balances." : `The trial balance does not balance: difference ${amount(t.totalDebit - t.totalCredit)}.`; +} + +export function tieLine(s: Stock): string { + return s.matched + ? `Stock value ${amount(s.total)} agrees with the inventory accounts in the ledger (${amount(s.ledgerTotal)}).` + : `Stock value ${amount(s.total)} differs from the ledger ${amount(s.ledgerTotal)} by ${amount(s.difference)}.`; +} diff --git a/web/src/engine/lookups.ts b/web/src/engine/lookups.ts new file mode 100644 index 0000000..12185bb --- /dev/null +++ b/web/src/engine/lookups.ts @@ -0,0 +1,108 @@ +import type { Api } from "./session"; + +export type LookupKind = "customer" | "supplier" | "item" | "tax-rate" | "account" | "warehouse"; + +export interface LookupEntry { + id: string; + code: string; + name: string; + active: boolean; + record: Record; +} + +interface Source { + path: string; + key: string; + paged: boolean; +} + +const SOURCES: Record = { + customer: { path: "/api/customers", key: "customers", paged: true }, + supplier: { path: "/api/suppliers", key: "suppliers", paged: true }, + item: { path: "/api/items", key: "items", paged: true }, + "tax-rate": { path: "/api/tax-rates", key: "taxRates", paged: false }, + account: { path: "/api/accounts", key: "accounts", paged: false }, + warehouse: { path: "/api/warehouses", key: "warehouses", paged: false }, +}; + +const MAX_PAGES = 50; + +const cache = new Map>(); + +function toEntry(r: Record): LookupEntry { + return { + id: String(r.id ?? ""), + code: String(r.code ?? ""), + name: String(r.name ?? ""), + active: r.active === undefined ? true : Boolean(r.active), + record: r, + }; +} + +async function fetchAll(api: Api, kind: LookupKind): Promise { + const src = SOURCES[kind]; + const out: LookupEntry[] = []; + let cursor = ""; + for (let page = 0; page < MAX_PAGES; page++) { + const query = src.paged ? `?limit=200${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}` : ""; + const body = await api.call>("GET", `${src.path}${query}`); + const rows = body[src.key]; + if (Array.isArray(rows)) for (const r of rows) out.push(toEntry(r as Record)); + const next = body.nextCursor ?? body.next ?? ""; + if (!src.paged || typeof next !== "string" || !next) break; + cursor = next; + } + return out; +} + +export function lookup(api: Api, kind: LookupKind): Promise { + let hit = cache.get(kind); + if (!hit) { + hit = fetchAll(api, kind); + cache.set(kind, hit); + hit.catch(() => { + if (cache.get(kind) === hit) cache.delete(kind); + }); + } + return hit; +} + +export function forget(kind?: LookupKind): void { + if (kind) cache.delete(kind); + else cache.clear(); +} + +export async function findById(api: Api, kind: LookupKind, id: string): Promise { + const list = await lookup(api, kind); + return list.find((e) => e.id === id) ?? null; +} + +export function filterEntries(list: LookupEntry[], text: string, limit: number): LookupEntry[] { + const q = text.trim().toLowerCase(); + const out: LookupEntry[] = []; + if (!q) { + for (const e of list) { + if (!e.active) continue; + out.push(e); + if (out.length >= limit) break; + } + return out; + } + const starts: LookupEntry[] = []; + const contains: LookupEntry[] = []; + for (const e of list) { + if (!e.active) continue; + const code = e.code.toLowerCase(); + const name = e.name.toLowerCase(); + if (code.startsWith(q) || name.startsWith(q)) starts.push(e); + else if (code.includes(q) || name.includes(q)) contains.push(e); + if (starts.length >= limit) break; + } + for (const e of starts) if (out.length < limit) out.push(e); + for (const e of contains) if (out.length < limit) out.push(e); + return out; +} + +export function label(e: { code: string; name: string }): string { + return e.code ? `${e.code} · ${e.name}` : e.name; +} diff --git a/web/src/engine/masters.ts b/web/src/engine/masters.ts new file mode 100644 index 0000000..a4a8985 --- /dev/null +++ b/web/src/engine/masters.ts @@ -0,0 +1,266 @@ +import type { Api } from "./index"; +import { money, parseMoney, percent } from "./format"; + +export type Row = Record; +export type Kind = "text" | "money" | "int" | "bp" | "select" | "bool"; + +export interface Field { + key: string; + label: string; + kind: Kind; + from?: string; + required?: boolean; + createOnly?: boolean; + options?: string[]; + fallback?: string; +} + +export interface Column { + key: string; + label: string; + width: string; + end?: boolean; +} + +export interface Master { + id: string; + title: string; + singular: string; + path: string; + listKey: string; + paged: boolean; + columns: Column[]; + fields: Field[]; +} + +const CURRENCY: Field = { key: "currency", label: "Currency", kind: "text", createOnly: true, fallback: "USD" }; +const ACTIVE: Field = { key: "active", label: "Active", kind: "bool" }; + +export const MASTERS: Master[] = [ + { + id: "customers", + title: "Customers", + singular: "customer", + path: "/api/customers", + listKey: "customers", + paged: true, + columns: [ + { key: "code", label: "Code", width: "9ch" }, + { key: "name", label: "Name", width: "auto" }, + { key: "email", label: "Email", width: "22ch" }, + { key: "paymentTermsDays", label: "Terms", width: "8ch", end: true }, + { key: "active", label: "Active", width: "8ch" }, + ], + fields: [ + { key: "code", label: "Code", kind: "text", required: true, createOnly: true }, + { key: "name", label: "Name", kind: "text", required: true }, + { key: "email", label: "Email", kind: "text" }, + { key: "phone", label: "Phone", kind: "text" }, + { key: "address", label: "Address", kind: "text" }, + { key: "taxId", label: "Tax id", kind: "text" }, + CURRENCY, + { key: "receivableAccount", label: "Receivable account code", kind: "text", createOnly: true }, + { key: "paymentTermsDays", label: "Payment terms (days)", kind: "int", fallback: "30" }, + ACTIVE, + ], + }, + { + id: "suppliers", + title: "Suppliers", + singular: "supplier", + path: "/api/suppliers", + listKey: "suppliers", + paged: true, + columns: [ + { key: "code", label: "Code", width: "9ch" }, + { key: "name", label: "Name", width: "auto" }, + { key: "email", label: "Email", width: "22ch" }, + { key: "paymentTermsDays", label: "Terms", width: "8ch", end: true }, + { key: "active", label: "Active", width: "8ch" }, + ], + fields: [ + { key: "code", label: "Code", kind: "text", required: true, createOnly: true }, + { key: "name", label: "Name", kind: "text", required: true }, + { key: "email", label: "Email", kind: "text" }, + { key: "phone", label: "Phone", kind: "text" }, + { key: "address", label: "Address", kind: "text" }, + { key: "taxId", label: "Tax id", kind: "text" }, + CURRENCY, + { key: "payableAccount", label: "Payable account code", kind: "text", createOnly: true }, + { key: "paymentTermsDays", label: "Payment terms (days)", kind: "int", fallback: "30" }, + ACTIVE, + ], + }, + { + id: "items", + title: "Items", + singular: "item", + path: "/api/items", + listKey: "items", + paged: true, + columns: [ + { key: "code", label: "Code", width: "10ch" }, + { key: "name", label: "Name", width: "auto" }, + { key: "unit", label: "Unit", width: "8ch" }, + { key: "salePrice", label: "Price", width: "12ch", end: true }, + { key: "taxRate", label: "Tax", width: "8ch" }, + { key: "active", label: "Active", width: "8ch" }, + ], + fields: [ + { key: "code", label: "Code", kind: "text", required: true, createOnly: true }, + { key: "name", label: "Name", kind: "text", required: true }, + { key: "description", label: "Description", kind: "text" }, + { key: "unit", label: "Unit", kind: "text", fallback: "each" }, + { key: "salePrice", label: "Sale price", kind: "money" }, + CURRENCY, + { key: "incomeAccount", label: "Income account code", kind: "text" }, + { key: "taxRate", label: "Tax rate code", kind: "text" }, + ACTIVE, + ], + }, + { + id: "tax-rates", + title: "Tax rates", + singular: "tax rate", + path: "/api/tax-rates", + listKey: "taxRates", + paged: false, + columns: [ + { key: "code", label: "Code", width: "10ch" }, + { key: "name", label: "Name", width: "auto" }, + { key: "rateBp", label: "Rate", width: "10ch", end: true }, + { key: "payableAccount", label: "Payable", width: "10ch" }, + { key: "active", label: "Active", width: "8ch" }, + ], + fields: [ + { key: "code", label: "Code", kind: "text", required: true, createOnly: true }, + { key: "name", label: "Name", kind: "text", required: true }, + { key: "rateBp", label: "Rate (basis points)", kind: "bp", required: true }, + { key: "payableAccount", label: "Payable account code", kind: "text", required: true, createOnly: true }, + ACTIVE, + ], + }, + { + id: "warehouses", + title: "Warehouses", + singular: "warehouse", + path: "/api/warehouses", + listKey: "warehouses", + paged: false, + columns: [ + { key: "code", label: "Code", width: "12ch" }, + { key: "name", label: "Name", width: "auto" }, + { key: "active", label: "Active", width: "8ch" }, + ], + fields: [ + { key: "code", label: "Code", kind: "text", required: true, createOnly: true }, + { key: "name", label: "Name", kind: "text", required: true }, + ACTIVE, + ], + }, + { + id: "accounts", + title: "Chart of accounts", + singular: "account", + path: "/api/accounts", + listKey: "accounts", + paged: false, + columns: [ + { key: "code", label: "Code", width: "9ch" }, + { key: "name", label: "Name", width: "auto" }, + { key: "type", label: "Type", width: "11ch" }, + { key: "parentCode", label: "Parent", width: "9ch" }, + { key: "active", label: "Active", width: "8ch" }, + ], + fields: [ + { key: "code", label: "Code", kind: "text", required: true, createOnly: true }, + { key: "name", label: "Name", kind: "text", required: true }, + { key: "type", label: "Type", kind: "select", options: ["asset", "liability", "equity", "income", "expense"], required: true, createOnly: true }, + { key: "parent", label: "Parent account code", kind: "text", from: "parentCode", createOnly: true }, + CURRENCY, + { key: "isGroup", label: "Group account", kind: "bool", createOnly: true }, + ACTIVE, + ], + }, +]; + +export function cell(row: Row, key: string): string { + const v = row[key]; + if (key === "active") return v ? "yes" : "no"; + if (key === "salePrice" && typeof v === "number") return money(v); + if (key === "rateBp" && typeof v === "number") return percent(v); + return v === undefined || v === null ? "" : String(v); +} + +export function fieldText(f: Field, row: Row | null): string { + if (!row) return f.fallback ?? (f.kind === "money" ? "0.00" : ""); + const v = row[f.from ?? f.key]; + if (f.kind === "money") return typeof v === "number" ? money(v) : "0.00"; + if (v === undefined || v === null) return ""; + return String(v); +} + +export function boolValue(f: Field, row: Row | null): boolean { + if (!row) return f.key === "active"; + return Boolean(row[f.key]); +} + +export type Raw = Record; + +function convert(f: Field, text: string): { ok: true; value: unknown } | { ok: false; error: string } { + if (f.kind === "money") { + const n = parseMoney(text); + return n === null || n < 0 ? { ok: false, error: `${f.label} must be an amount such as 12.50.` } : { ok: true, value: n }; + } + if (f.kind === "int" || f.kind === "bp") { + if (!/^\d+$/.test(text)) return { ok: false, error: `${f.label} must be a whole number.` }; + return { ok: true, value: Number(text) }; + } + return { ok: true, value: text }; +} + +export function buildBody(m: Master, raw: Raw, current: Row | null): { body: Row } | { error: string } { + const body: Row = {}; + for (const f of m.fields) { + if (current && f.createOnly) continue; + if (f.key === "active" && !current) continue; + if (f.kind === "bool") { + const next = Boolean(raw[f.key]); + if (!current || next !== Boolean(current[f.key])) body[f.key] = next; + continue; + } + const text = String(raw[f.key] ?? "").trim(); + if (!text) { + if (f.required) return { error: `${f.label} is required.` }; + if (current && fieldText(f, current) !== "") body[f.key] = ""; + continue; + } + const out = convert(f, text); + if (!out.ok) return { error: out.error }; + if (current && fieldText(f, current) === text) continue; + body[f.key] = out.value; + } + if (current && Object.keys(body).length === 0) return { error: "Nothing has changed." }; + return { body }; +} + +export async function listAll(api: Api, m: Master): Promise { + const out: Row[] = []; + let cursor = ""; + for (let page = 0; page < 50; page++) { + const query = m.paged ? `?limit=200${cursor ? `&cursor=${encodeURIComponent(cursor)}` : ""}` : ""; + const res = await api.call("GET", `${m.path}${query}`); + out.push(...((res[m.listKey] as Row[] | undefined) ?? [])); + cursor = String(res.next ?? res.nextCursor ?? ""); + if (!m.paged || !cursor) break; + } + return out; +} + +export function create(api: Api, m: Master, body: Row): Promise { + return api.call("POST", m.path, body); +} + +export function update(api: Api, m: Master, id: string, body: Row): Promise { + return api.call("PATCH", `${m.path}/${id}`, body); +} diff --git a/web/src/engine/payments.ts b/web/src/engine/payments.ts new file mode 100644 index 0000000..71dedde --- /dev/null +++ b/web/src/engine/payments.ts @@ -0,0 +1,297 @@ +import type { Api } from "./index"; + +export type PayDir = "in" | "out"; + +export interface Allocation { + id: string; + invoiceId: string; + invoiceNumber: string | null; + amount: number; +} + +export interface Payment { + id: string; + number: string | null; + date: string; + party: string; + partyId: string; + currency: string; + amount: number; + account: string; + status: string; + memo: string; + allocated: number; + unallocated: number; + allocations: Allocation[]; +} + +export interface OpenInvoice { + id: string; + number: string; + date: string; + dueDate: string; + total: number; + outstanding: number; +} + +export interface Party { + id: string; + code: string; + name: string; + currency: string; +} + +export interface Account { + id: string; + code: string; + name: string; + type: string; + isGroup: boolean; + active: boolean; +} + +export interface PaymentDraft { + party: string; + date: string; + amount: number; + account: string; + memo: string; +} + +export interface AllocationInput { + invoice: string; + amount: number; +} + +export interface PayFamily { + dir: PayDir; + base: string; + partyKey: "customer" | "supplier"; + accountKey: "deposit" | "paidFrom"; + partyList: string; + position: string; + draftPerm: string; + postPerm: string; +} + +export const FAMILIES: Record = { + in: { + dir: "in", + base: "/api/sales/payments", + partyKey: "customer", + accountKey: "deposit", + partyList: "/api/customers", + position: "/api/receivables/customers/", + draftPerm: "sales.draft", + postPerm: "sales.post", + }, + out: { + dir: "out", + base: "/api/purchase/payments", + partyKey: "supplier", + accountKey: "paidFrom", + partyList: "/api/suppliers", + position: "/api/payables/suppliers/", + draftPerm: "purchase.draft", + postPerm: "purchase.post", + }, +}; + +type Raw = Record; + +const s = (v: unknown): string => (typeof v === "string" ? v : ""); +const n = (v: unknown): number => (typeof v === "number" && Number.isInteger(v) ? v : 0); + +function toPayment(f: PayFamily, r: Raw): Payment { + const allocs = Array.isArray(r.allocations) ? (r.allocations as Raw[]) : []; + return { + id: s(r.id), + number: typeof r.number === "string" ? r.number : null, + date: s(r.date), + party: s(r[f.partyKey]), + partyId: s(r[`${f.partyKey}Id`]), + currency: s(r.currency), + amount: n(r.amount), + account: s(r[f.accountKey]), + status: s(r.status), + memo: s(r.memo), + allocated: n(r.allocated), + unallocated: n(r.unallocated), + allocations: allocs.map((a) => ({ + id: s(a.id), + invoiceId: s(a.invoiceId), + invoiceNumber: typeof a.invoiceNumber === "string" ? a.invoiceNumber : null, + amount: n(a.amount), + })), + }; +} + +const enc = encodeURIComponent; + +export async function listPayments(api: Api, f: PayFamily, status = ""): Promise { + const q = new URLSearchParams({ limit: "200" }); + if (status) q.set("status", status); + const out = await api.call<{ payments: Raw[] | null }>("GET", `${f.base}?${q}`); + return (out.payments ?? []).map((r) => toPayment(f, r)); +} + +export async function getPayment(api: Api, f: PayFamily, id: string): Promise { + return toPayment(f, await api.call("GET", `${f.base}/${enc(id)}`)); +} + +function body(f: PayFamily, d: PaymentDraft): Raw { + const out: Raw = { [f.partyKey]: d.party, date: d.date, amount: d.amount, memo: d.memo }; + if (d.account) out[f.accountKey] = d.account; + return out; +} + +export async function createPayment(api: Api, f: PayFamily, d: PaymentDraft): Promise { + return toPayment(f, await api.call("POST", f.base, body(f, d))); +} + +export async function updatePayment(api: Api, f: PayFamily, id: string, d: PaymentDraft): Promise { + return toPayment(f, await api.call("PATCH", `${f.base}/${enc(id)}`, body(f, d))); +} + +export async function postPayment(api: Api, f: PayFamily, id: string, allocations: AllocationInput[]): Promise { + await api.call("POST", `${f.base}/${enc(id)}/post`, allocations.length ? { allocations } : {}); +} + +export async function allocatePayment(api: Api, f: PayFamily, id: string, allocations: AllocationInput[]): Promise { + await api.call("POST", `${f.base}/${enc(id)}/allocate`, { allocations }); +} + +export async function cancelPayment(api: Api, f: PayFamily, id: string): Promise { + await api.call("POST", `${f.base}/${enc(id)}/cancel`, {}); +} + +export async function listParties(api: Api, f: PayFamily): Promise { + const key = f.partyKey === "customer" ? "customers" : "suppliers"; + const out = await api.call>("GET", `${f.partyList}?limit=200`); + return (out[key] ?? []).map((r) => ({ id: s(r.id), code: s(r.code), name: s(r.name), currency: s(r.currency) })); +} + +export async function listAssetAccounts(api: Api): Promise { + const out = await api.call<{ accounts: Raw[] | null }>("GET", "/api/accounts"); + return (out.accounts ?? []) + .map((r) => ({ id: s(r.id), code: s(r.code), name: s(r.name), type: s(r.type), isGroup: r.isGroup === true, active: r.active !== false })) + .filter((a) => a.type === "asset" && !a.isGroup && a.active); +} + +export async function openInvoices(api: Api, f: PayFamily, partyId: string): Promise { + const out = await api.call<{ invoices: Raw[] | null }>("GET", `${f.position}${enc(partyId)}`); + return (out.invoices ?? []).map((r) => ({ + id: s(r.id), + number: s(r.number), + date: s(r.date), + dueDate: s(r.dueDate), + total: n(r.total), + outstanding: n(r.outstanding), + })); +} + +export type StockKind = "delivery" | "receipt"; + +export interface StockLine { + id: string; + lineNo: number; + item: string; + description: string; + quantityMilli: number; + amount: number; +} + +export interface StockDoc { + id: string; + number: string; + date: string; + party: string; + warehouse: string; + status: string; + memo: string; + total: number; + lines: StockLine[]; +} + +let warehouseNames: Promise> | null = null; + +function warehouses(api: Api): Promise> { + warehouseNames ??= api + .call<{ warehouses: Raw[] | null }>("GET", "/api/warehouses") + .then((out) => new Map((out.warehouses ?? []).map((w) => [s(w.id), `${s(w.code)} ${s(w.name)}`.trim()]))) + .catch(() => { + warehouseNames = null; + return new Map(); + }); + return warehouseNames; +} + +let itemCodeMap: Promise> | null = null; + +function itemCodes(api: Api): Promise> { + itemCodeMap ??= api + .call<{ items: Raw[] | null }>("GET", "/api/items?limit=500") + .then((out) => new Map((out.items ?? []).map((i) => [s(i.id), s(i.code)]))) + .catch(() => { + itemCodeMap = null; + return new Map(); + }); + return itemCodeMap; +} + +export async function getStockDoc(api: Api, kind: StockKind, id: string): Promise { + if (kind === "receipt") { + const r = await api.call("GET", `/api/purchase/docs/${enc(id)}`); + const lines = Array.isArray(r.lines) ? (r.lines as Raw[]) : []; + return { + id: s(r.id), + number: s(r.number), + date: s(r.date), + party: `${s(r.supplier)} ${s(r.supplierName)}`.trim(), + warehouse: s(r.warehouse), + status: s(r.status), + memo: s(r.memo), + total: n(r.total), + lines: lines.map((l) => ({ + id: s(l.id), + lineNo: n(l.lineNo), + item: s(l.item), + description: s(l.description), + quantityMilli: n(l.quantityMilli), + amount: n(l.lineSubtotal), + })), + }; + } + const [r, names, codes] = await Promise.all([api.call("GET", `/api/delivery/notes/${enc(id)}`), warehouses(api), itemCodes(api)]); + const lines = Array.isArray(r.lines) ? (r.lines as Raw[]) : []; + const who = await api.call("GET", `/api/customers/${enc(s(r.customerId))}`).catch(() => ({}) as Raw); + return { + id: s(r.id), + number: s(r.number), + date: s(r.date), + party: `${s(who.code)} ${s(who.name)}`.trim() || s(r.customerId), + warehouse: names.get(s(r.warehouseId)) ?? s(r.warehouseId), + status: s(r.status), + memo: s(r.memo), + total: n(r.value), + lines: lines.map((l) => ({ + id: s(l.id), + lineNo: n(l.lineNo), + item: codes.get(s(l.itemId)) ?? s(l.itemId), + description: s(l.description), + quantityMilli: n(l.quantityMilli), + amount: n(l.value), + })), + }; +} + +export async function stockAction(api: Api, kind: StockKind, id: string, action: "post" | "cancel"): Promise { + const base = kind === "receipt" ? "/api/purchase/receipts/" : "/api/delivery/notes/"; + await api.call("POST", `${base}${enc(id)}/${action}`, {}); +} + +export function remainder(amount: number, already: number, entered: Iterable): number { + let left = amount - already; + for (const v of entered) left -= v; + return left; +} diff --git a/web/src/engine/statements.ts b/web/src/engine/statements.ts new file mode 100644 index 0000000..a77b8ac --- /dev/null +++ b/web/src/engine/statements.ts @@ -0,0 +1,53 @@ +import type { Api } from "./session"; + +export interface StatementLine { + accountId: string; + code: string; + name: string; + currency: string; + amount: number; +} + +export interface StatementSection { + type: string; + title: string; + lines: StatementLine[]; + total: number; +} + +export interface ProfitAndLoss { + from: string; + to: string; + income: StatementSection; + expenses: StatementSection; + netProfit: number; +} + +export interface BalanceSheet { + asOf: string; + assets: StatementSection; + liabilities: StatementSection; + equity: StatementSection; + unclosedResult: number; + totalEquity: number; + totalLiabilitiesAndEquity: number; + balanced: boolean; +} + +export function yearStart(day: string): string { + return `${day.slice(0, 4)}-01-01`; +} + +export function profitAndLoss(api: Api, from: string, to: string): Promise { + const q = new URLSearchParams({ from, to }); + return api.call("GET", `/api/reports/profit-and-loss?${q}`); +} + +export function balanceSheet(api: Api, asOf: string): Promise { + const q = new URLSearchParams({ as_of: asOf }); + return api.call("GET", `/api/reports/balance-sheet?${q}`); +} + +export function resultLabel(net: number): string { + return net < 0 ? "Net loss" : "Net profit"; +} diff --git a/web/src/styles/main.css b/web/src/styles/main.css index d8c4393..04bbf96 100644 --- a/web/src/styles/main.css +++ b/web/src/styles/main.css @@ -4,3 +4,11 @@ @import "./shell.css"; @import "./overlays.css"; @import "./account.css"; +@import "./parts.css"; +@import "./views/grid.css"; +@import "./views/masters.css"; +@import "./views/doclists.css"; +@import "./views/docform.css"; +@import "./views/payments.css"; +@import "./views/ledger-screens.css"; +@import "./views/statements.css"; diff --git a/web/src/styles/parts.css b/web/src/styles/parts.css new file mode 100644 index 0000000..3b7de7b --- /dev/null +++ b/web/src/styles/parts.css @@ -0,0 +1,137 @@ +.view--page[data-active] { + display: block; +} + +.sb-views { + display: grid; + align-content: start; + row-gap: var(--space-1); +} + +.sb-group { + margin: 0; + padding: var(--space-3) var(--space-2) var(--space-1); + font-size: var(--text-2xs); + font-weight: var(--weight-semibold); + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--text-faint); + user-select: none; +} + +.page { + display: grid; + align-content: start; + row-gap: var(--space-4); + padding: var(--space-6); + min-inline-size: 0; +} + +.page__title { + margin: 0; + font-size: var(--text-lg); + font-weight: var(--weight-semibold); +} + +.page__body { + display: grid; + align-content: start; + row-gap: var(--space-4); + min-inline-size: 0; +} + +.tbl { + position: relative; + min-block-size: calc(var(--row) * 4); + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); + overflow: auto hidden; +} + +.tbl__table { + inline-size: 100%; + table-layout: fixed; + border-collapse: collapse; + font-size: var(--text-sm); + font-variant-numeric: tabular-nums; +} + +.tbl__table th, +.tbl__table td { + block-size: var(--row); + padding: 0 var(--space-3); + text-align: start; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + border-block-end: 1px solid var(--border); +} + +.tbl__table th { + font-size: var(--text-xs); + font-weight: var(--weight-medium); + color: var(--text-muted); + background: var(--surface-2); +} + +.tbl__table [data-align="end"] { + text-align: end; +} + +.tbl__table tbody tr:last-child td { + border-block-end: 0; +} + +.tbl__table tfoot td { + font-weight: var(--weight-semibold); + border-block-start: 1px solid var(--border-strong); + border-block-end: 0; +} + +.tbl[data-open] tbody tr { + cursor: pointer; +} + +.tbl[data-open] tbody tr:hover, +.tbl[data-open] tbody tr:focus-visible { + background: var(--hover); + outline: 0; +} + +.tbl__table td[data-tone="muted"] { + color: var(--text-muted); +} + +.tbl__table td[data-tone="danger"] { + color: var(--danger); +} + +.tbl__empty, +.tbl__error { + position: absolute; + inset-inline: 0; + inset-block-start: calc(var(--row) * 1.5); + margin: 0; + text-align: center; + font-size: var(--text-sm); + color: var(--text-muted); + pointer-events: none; +} + +.tbl__empty { + visibility: hidden; +} + +.tbl[data-empty] .tbl__empty { + visibility: visible; +} + +.tbl__error { + inset-block-start: calc(var(--row) * 2.5); + color: var(--danger); +} + +.tbl[data-busy] .tbl__table tbody { + opacity: 0.55; +} diff --git a/web/src/styles/views/docform.css b/web/src/styles/views/docform.css new file mode 100644 index 0000000..615a860 --- /dev/null +++ b/web/src/styles/views/docform.css @@ -0,0 +1,121 @@ +.df { + --df-head-h: 32px; + --df-number-w: 200px; + --df-status-w: 300px; + --df-busy-w: 72px; + --df-kind-w: 168px; + --df-field-min: 160px; + --df-party-w: 280px; + --df-error-h: calc(var(--text-sm) * var(--leading) * 2); + --df-actions-h: calc(var(--control) + var(--space-4)); + display: grid; + row-gap: var(--space-4); + min-inline-size: 0; +} + +.df-head { + display: grid; + grid-template-columns: var(--df-kind-w) var(--df-number-w) var(--df-status-w) var(--df-busy-w); + align-items: center; + column-gap: var(--space-3); + block-size: var(--df-head-h); +} + +.df-number, +.df-status, +.df-busy { + overflow: hidden; + font-size: var(--text-sm); + white-space: nowrap; + text-overflow: ellipsis; +} + +.df-number { + font-variant-numeric: tabular-nums; + font-weight: var(--weight-medium); +} + +.df-status { + color: var(--text-muted); + font-variant-numeric: tabular-nums; +} + +.df-status[data-status="posted"] { + color: var(--success); +} + +.df-status[data-status="cancelled"] { + color: var(--danger); +} + +.df-busy { + color: var(--text-muted); + visibility: hidden; +} + +.df-busy.is-on { + visibility: visible; +} + +.df-fields { + display: grid; + grid-template-columns: var(--df-party-w) repeat(auto-fill, minmax(var(--df-field-min), 1fr)); + align-items: end; + gap: var(--space-3); +} + +.df-field { + min-inline-size: 0; +} + +.df-field--notes { + grid-column: 1 / -1; +} + +.df-lines { + min-inline-size: 0; +} + +.df-error { + overflow: hidden; + block-size: var(--df-error-h); + margin: 0; + font-size: var(--text-sm); + line-height: var(--leading); + color: var(--danger); +} + +.df-actions { + display: flex; + flex-wrap: nowrap; + align-items: center; + column-gap: var(--space-2); + block-size: var(--df-actions-h); + padding: var(--space-2) 0; + overflow-x: auto; + border-block-start: 1px solid var(--border); +} + +.df-actions__gap { + flex: 1 1 auto; +} + +.df-btn { + display: inline-flex; + flex: none; + align-items: center; + column-gap: var(--space-1); +} + +.df-btn:disabled { + cursor: default; + opacity: 0.45; +} + +.df-btn.is-denied { + visibility: hidden; +} + +.df[aria-busy="true"] .df-actions { + pointer-events: none; +} diff --git a/web/src/styles/views/doclists.css b/web/src/styles/views/doclists.css new file mode 100644 index 0000000..8d0b8e9 --- /dev/null +++ b/web/src/styles/views/doclists.css @@ -0,0 +1,49 @@ +.dl { + --dl-bar-height: 36px; + --dl-col-number: 160px; + --dl-col-date: 112px; + --dl-col-status: 112px; + --dl-col-total: 168px; + --dl-filter-width: 160px; + display: flex; + flex-direction: column; + gap: var(--space-3); +} + +.dl__bar { + display: flex; + align-items: center; + gap: var(--space-2); + block-size: var(--dl-bar-height); +} + +.dl__filter { + inline-size: var(--dl-filter-width); +} + +.dl__gap { + flex: 1; +} + +.dl__new { + display: inline-flex; + align-items: center; + gap: var(--space-1); +} + +.dl__count { + font-variant-numeric: tabular-nums; +} + +.dl .tbl__table td[data-tone="muted"], +.dl .tbl__table td[data-tone="cancelled"] { + opacity: 0.6; +} + +.dl .tbl__table td[data-tone="posted"] { + font-weight: 600; +} + +.dl .tbl__table td[data-align="end"] { + font-variant-numeric: tabular-nums; +} diff --git a/web/src/styles/views/grid.css b/web/src/styles/views/grid.css new file mode 100644 index 0000000..4e8da2e --- /dev/null +++ b/web/src/styles/views/grid.css @@ -0,0 +1,200 @@ +.picker-layer { + --picker-row: 32px; + position: fixed; + inset: 0; + z-index: var(--z-popover); + pointer-events: none; +} + +.picker__list { + position: fixed; + max-block-size: calc(var(--picker-row) * 9); + overflow: hidden; + padding: var(--space-1) 0; + background: var(--surface, Canvas); + border: 1px solid var(--border, GrayText); + border-radius: var(--radius-sm, 4px); + box-shadow: var(--shadow-md, 0 4px 16px rgb(0 0 0 / 0.2)); + pointer-events: auto; +} + +.picker__list[hidden], +.picker__row[hidden], +.picker__empty[hidden] { + display: none; +} + +.picker__row, +.picker__empty { + display: flex; + gap: var(--space-2); + align-items: center; + block-size: var(--picker-row); + padding: 0 var(--space-3); + white-space: nowrap; + overflow: hidden; +} + +.picker__row { + cursor: pointer; +} + +.picker__row.is-active, +.picker__row:hover { + background: var(--hover, Highlight); +} + +.picker__code { + flex: none; + min-inline-size: 6ch; + color: var(--text-muted, GrayText); + font-variant-numeric: tabular-nums; +} + +.picker__name { + overflow: hidden; + text-overflow: ellipsis; +} + +.picker__empty { + color: var(--text-muted, GrayText); +} + +.picker--bare .picker__input { + inline-size: 100%; +} + +.grid { + --grid-row: 40px; + --grid-err: 18px; + --grid-c-item: 200px; + --grid-c-desc: 240px; + --grid-c-qty: 96px; + --grid-c-price: 112px; + --grid-c-tax: 120px; + --grid-c-num: 112px; + --grid-c-rm: 40px; + --grid-totals-w: 280px; + display: flex; + flex-direction: column; + gap: var(--space-3); + min-inline-size: 0; +} + +.grid__scroll { + overflow-x: auto; + overflow-y: hidden; +} + +.grid__table { + inline-size: max-content; +} + +.grid__row { + display: grid; + grid-template-columns: + var(--grid-c-item) var(--grid-c-desc) var(--grid-c-qty) var(--grid-c-price) var(--grid-c-tax) + var(--grid-c-num) var(--grid-c-num) var(--grid-c-num) var(--grid-c-rm); + column-gap: var(--space-1); + align-items: center; +} + +.grid__head { + block-size: var(--grid-row); + border-block-end: 1px solid var(--border, GrayText); +} + +.grid__th { + padding: 0 var(--space-2); + color: var(--text-muted, GrayText); + font-size: 0.85em; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.grid__th:nth-child(n + 3):nth-child(-n + 4), +.grid__th:nth-child(n + 6):nth-child(-n + 8) { + text-align: end; +} + +.grid__line { + grid-template-rows: var(--grid-row) var(--grid-err); + border-block-end: 1px solid var(--border-subtle, transparent); +} + +.grid__td { + min-inline-size: 0; + overflow: hidden; +} + +.grid__input { + inline-size: 100%; +} + +.grid__num { + text-align: end; + font-variant-numeric: tabular-nums; +} + +.grid__input.is-invalid { + outline: 1px solid var(--danger, red); +} + +.grid__c-num { + padding: 0 var(--space-2); + text-align: end; + white-space: nowrap; + font-variant-numeric: tabular-nums; +} + +.grid__c-total { + font-weight: 600; +} + +.grid__c-rm { + display: grid; + place-items: center; +} + +.grid__err { + grid-column: 1 / -1; + block-size: var(--grid-err); + padding: 0 var(--space-2); + overflow: hidden; + color: var(--danger, red); + font-size: 0.8em; + line-height: var(--grid-err); + white-space: nowrap; + text-overflow: ellipsis; +} + +.grid__foot { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: var(--space-4); +} + +.grid__totals { + display: grid; + grid-template-columns: 1fr auto; + column-gap: var(--space-4); + row-gap: var(--space-1); + inline-size: var(--grid-totals-w); + margin: 0; +} + +.grid__totals dt { + color: var(--text-muted, GrayText); +} + +.grid__totals dd { + margin: 0; + text-align: end; + font-variant-numeric: tabular-nums; +} + +.grid__sum-value--total { + font-weight: 600; +} diff --git a/web/src/styles/views/ledger-screens.css b/web/src/styles/views/ledger-screens.css new file mode 100644 index 0000000..0bd8072 --- /dev/null +++ b/web/src/styles/views/ledger-screens.css @@ -0,0 +1,44 @@ +.ls { + --ls-field: 36px; + --ls-label: 20px; + --ls-status: 24px; + display: flex; + flex-direction: column; + row-gap: var(--space-3); +} + +.ls__bar { + display: flex; + flex-wrap: wrap; + align-items: end; + gap: var(--space-3); + block-size: calc(var(--ls-field) + var(--ls-label) + var(--space-1)); + overflow: hidden; +} + +.ls__field { + display: flex; + flex-direction: column; + row-gap: var(--space-1); +} + +.ls__label { + block-size: var(--ls-label); + font-size: var(--text-sm); + color: var(--text-muted); +} + +.ls__input { + inline-size: 220px; + block-size: var(--ls-field); +} + +.ls__status { + margin: 0; + block-size: var(--ls-status); + line-height: var(--ls-status); + font-size: var(--text-sm); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} diff --git a/web/src/styles/views/masters.css b/web/src/styles/views/masters.css new file mode 100644 index 0000000..c622645 --- /dev/null +++ b/web/src/styles/views/masters.css @@ -0,0 +1,67 @@ +.masters { + --masters-panel-w: 340px; + --masters-table-h: 62dvh; + --masters-form-h: 62dvh; + display: grid; + grid-template-columns: minmax(0, 1fr) var(--masters-panel-w); + column-gap: var(--space-4); + align-items: start; +} + +.masters__list { + block-size: var(--masters-table-h); + min-inline-size: 0; + overflow: auto; +} + +.masters__form { + block-size: var(--masters-form-h); + grid-template-rows: auto minmax(0, 1fr) auto auto; + overflow: hidden; +} + +.masters__fields { + align-content: start; + row-gap: var(--space-2); + min-block-size: 0; + overflow: auto; + display: grid; +} + +.masters__field { + row-gap: var(--space-1); + display: grid; +} + +.masters__field--bool { + grid-template-columns: auto minmax(0, 1fr); + column-gap: var(--space-2); + align-items: center; + min-block-size: var(--control); +} + +.masters__field .input { + inline-size: 100%; +} + +.masters__actions { + column-gap: var(--space-2); + grid-template-columns: minmax(0, 1fr) auto; + display: grid; +} + +.masters__mode { + font-size: var(--text-sm); + color: var(--text-muted); +} + +.masters .tbl__table tr[data-selected] td { + background: var(--active); +} + +@media (max-width: 900px) { + .masters { + grid-template-columns: minmax(0, 1fr); + row-gap: var(--space-4); + } +} diff --git a/web/src/styles/views/payments.css b/web/src/styles/views/payments.css new file mode 100644 index 0000000..bab05bf --- /dev/null +++ b/web/src/styles/views/payments.css @@ -0,0 +1,139 @@ +.pay { + --pay-col-number: 10rem; + --pay-col-date: 7.5rem; + --pay-col-status: 6.5rem; + --pay-col-money: 8.5rem; + --pay-col-input: 9.5rem; + --pay-col-line: 3rem; + --pay-field-h: 3.75rem; + --pay-head-h: 2rem; + --pay-error-h: 1.5rem; + display: flex; + flex-direction: column; + gap: var(--space-4); +} + +.pay__bar { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-3); + block-size: var(--row); +} + +.pay__status { + inline-size: 10rem; +} + +.pay__head { + display: flex; + align-items: center; + gap: var(--space-3); + block-size: var(--pay-head-h); +} + +.pay__number { + min-inline-size: var(--pay-col-number); + font-size: var(--text-lg); + font-weight: var(--weight-medium); + font-variant-numeric: tabular-nums; +} + +.pay__badge { + min-inline-size: 6rem; + padding: 0 var(--space-2); + font-size: var(--text-xs); + color: var(--text-muted); + text-transform: capitalize; +} + +.pay[data-status="posted"] .pay__badge { + color: var(--success); +} + +.pay[data-status="cancelled"] .pay__badge { + color: var(--danger); +} + +.pay__grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr)); + gap: var(--space-3) var(--space-4); +} + +.pay__field { + block-size: var(--pay-field-h); + min-inline-size: 0; +} + +.pay__value { + display: block; + block-size: var(--row); + line-height: var(--row); + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.pay__sub { + margin: 0; +} + +.pay__num { + inline-size: 100%; + text-align: end; + font-variant-numeric: tabular-nums; +} + +.pay__alloc td .pay__num { + block-size: calc(var(--row) - var(--space-2)); +} + +.pay__num[aria-invalid="true"] { + border-color: var(--danger); +} + +.pay__remain { + display: flex; + justify-content: flex-end; + gap: var(--space-4); + block-size: var(--row); + align-items: center; + padding: 0 var(--space-3); + border-block-start: 1px solid var(--border-strong); + font-variant-numeric: tabular-nums; +} + +.pay__remain-label { + color: var(--text-muted); + font-size: var(--text-sm); +} + +.pay__remain-value { + min-inline-size: var(--pay-col-input); + text-align: end; + font-weight: var(--weight-medium); +} + +.pay__remain[data-tone="bad"] .pay__remain-value { + color: var(--danger); +} + +.pay__error { + block-size: var(--pay-error-h); + margin: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.pay__actions { + display: flex; + gap: var(--space-2); + block-size: var(--row); +} + +.pay[data-busy] .pay__actions, +.pay[data-busy] .pay__alloc-box { + opacity: 0.6; +} diff --git a/web/src/styles/views/statements.css b/web/src/styles/views/statements.css new file mode 100644 index 0000000..1bd4ea0 --- /dev/null +++ b/web/src/styles/views/statements.css @@ -0,0 +1,107 @@ +.st { + --st-field: 36px; + --st-label: 20px; + --st-status: 24px; + --st-code: 6rem; + --st-amount: 10rem; + --st-rows: 9; + --st-date: 11rem; + display: flex; + flex-direction: column; + row-gap: var(--space-3); +} + +.st__bar { + display: flex; + align-items: end; + gap: var(--space-3); + block-size: calc(var(--st-field) + var(--st-label) + var(--space-1)); + overflow: hidden; +} + +.st__field { + display: flex; + flex-direction: column; + row-gap: var(--space-1); +} + +.st__label { + block-size: var(--st-label); + font-size: var(--text-sm); + color: var(--text-muted); +} + +.st__date { + inline-size: var(--st-date); + block-size: var(--st-field); +} + +.st__run { + display: inline-flex; + align-items: center; + column-gap: var(--space-2); + block-size: var(--st-field); +} + +.st__status { + block-size: var(--st-status); + line-height: var(--st-status); + margin: 0; + font-size: var(--text-sm); + color: var(--text-muted); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.st__status[data-tone="danger"] { + color: var(--danger); +} + +.st__sections { + display: flex; + flex-direction: column; + row-gap: var(--space-4); +} + +.st__heading { + block-size: var(--st-label); + margin: 0 0 var(--space-2); + font-size: var(--text-sm); + font-weight: var(--weight-semibold); +} + +.st .tbl { + block-size: calc(var(--row) * var(--st-rows)); + min-block-size: calc(var(--row) * var(--st-rows)); + overflow: auto; +} + +.st__summary { + display: flex; + flex-direction: column; + row-gap: var(--space-1); + padding: var(--space-3); + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface-2); +} + +.st__sum { + display: flex; + justify-content: space-between; + block-size: var(--row); + line-height: var(--row); + margin: 0; + font-weight: var(--weight-semibold); + font-variant-numeric: tabular-nums; +} + +.st__sum-value { + inline-size: var(--st-amount); + text-align: end; +} + +.st__sum-value[data-tone="danger"] { + color: var(--danger); +} diff --git a/web/src/ui/account.ts b/web/src/ui/account.ts index d5cb8ad..e54f3c3 100644 --- a/web/src/ui/account.ts +++ b/web/src/ui/account.ts @@ -100,7 +100,7 @@ function bindFrame(engine: Engine): void { engine.state.watch( "route", (route) => { - setText(title, route === "account" ? "Account" : "Home"); + if (route === "home" || route === "account") setText(title, route === "account" ? "Account" : "Home"); setAttr(navAccount, "aria-current", route === "account" ? "page" : null); }, { immediate: true }, diff --git a/web/src/ui/app.ts b/web/src/ui/app.ts index dc761b4..1022aae 100644 --- a/web/src/ui/app.ts +++ b/web/src/ui/app.ts @@ -2,6 +2,7 @@ import type { Engine, Health } from "../engine"; import { delayedIndicator, ref, setAttr, setText } from "./dom"; import { dismissToast, toast } from "./toast"; import { mountAccount } from "./account"; +import { mountViews } from "./views"; const SERVER_TOAST = "server-health"; @@ -72,4 +73,5 @@ export function mountApp(engine: Engine): void { bindNav(engine); bindStatus(engine); mountAccount(engine); + mountViews(engine); } diff --git a/web/src/ui/parts/linegrid.ts b/web/src/ui/parts/linegrid.ts new file mode 100644 index 0000000..0e81a9a --- /dev/null +++ b/web/src/ui/parts/linegrid.ts @@ -0,0 +1,384 @@ +import { money, parseMoney, parseQty, qty } from "../../engine/format"; +import { h, setAttr, setText } from "../dom"; +import type { ViewContext } from "../views"; +import { mountPicker, type PickerHandle } from "./picker"; + +export interface GridLine { + itemId: string; + description: string; + qtyMilli: number; + unitPrice: number; + taxRateId: string; +} + +export interface GridLineTotals { + subtotal: number; + tax: number; + total: number; +} + +export interface GridTotals { + lines: GridLineTotals[]; + subtotal: number; + tax: number; + total: number; +} + +export interface LineGridOptions { + family: "sales" | "purchase"; + currency: string; + readOnly: boolean; + onChange(lines: GridLine[]): void; +} + +export interface LineGridHandle { + root: HTMLElement; + getLines(): GridLine[]; + setLines(lines: GridLine[]): void; + setTotals(totals: GridTotals): void; + setReadOnly(readOnly: boolean): void; + setLineError(index: number, message: string): void; + focusFirst(): void; + setCurrency(code: string): void; +} + +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]; + +interface Row { + el: HTMLElement; + item: PickerHandle; + desc: HTMLInputElement; + qty: HTMLInputElement; + price: HTMLInputElement; + tax: PickerHandle; + sub: HTMLElement; + taxAmt: HTMLElement; + total: HTMLElement; + remove: HTMLButtonElement; + error: HTMLElement; + line: GridLine; +} + +function removeIcon(): SVGSVGElement { + const svg = document.createElementNS(SVG, "svg"); + svg.setAttribute("viewBox", "0 0 24 24"); + svg.setAttribute("width", "16"); + svg.setAttribute("height", "16"); + svg.setAttribute("fill", "none"); + svg.setAttribute("stroke", "currentColor"); + svg.setAttribute("stroke-width", "1.75"); + svg.setAttribute("stroke-linecap", "round"); + svg.setAttribute("aria-hidden", "true"); + const path = document.createElementNS(SVG, "path"); + path.setAttribute("d", "M6 6l12 12M18 6L6 18"); + svg.append(path); + return svg; +} + +function blank(): GridLine { + return { itemId: "", description: "", qtyMilli: 1000, unitPrice: 0, taxRateId: "" }; +} + +function isBlank(l: GridLine): boolean { + return !l.itemId && !l.description.trim(); +} + +export function mountLineGrid(host: HTMLElement, ctx: ViewContext, o: LineGridOptions): LineGridHandle { + const placesFor = (code: string) => (ZERO_DECIMAL.has(code.toUpperCase()) ? 0 : 2); + let currency = o.currency; + let places = placesFor(currency); + const fmt = (minor: number) => money(minor, places); + let readOnly = o.readOnly; + const rows: Row[] = []; + let emitted: Row[] = []; + + const head = h( + "div", + { class: "grid__row grid__head", attrs: { role: "row" } }, + ...["Item", "Description", "Quantity", "Unit price", "Tax", "Subtotal", "Tax amount", "Total", ""].map((t) => h("div", { class: "grid__th", attrs: { role: "columnheader" }, text: t })), + ); + const body = h("div", { class: "grid__body", attrs: { role: "rowgroup" } }); + const addBtn = h("button", { class: "btn grid__add", attrs: { type: "button" }, text: "Add line" }); + const sumSub = h("span", { class: "grid__sum-value", text: fmt(0) }); + const sumTax = h("span", { class: "grid__sum-value", text: fmt(0) }); + const sumTotal = h("span", { class: "grid__sum-value grid__sum-value--total", text: fmt(0) }); + const totalLabel = h("dt", { text: currency ? `Total ${currency}` : "Total" }); + const totals = h( + "dl", + { class: "grid__totals" }, + h("dt", { text: "Subtotal" }), + h("dd", {}, sumSub), + h("dt", { text: "Tax" }), + h("dd", {}, sumTax), + totalLabel, + h("dd", {}, sumTotal), + ); + const root = h( + "div", + { class: "grid", attrs: { "data-family": o.family } }, + h("div", { class: "grid__scroll" }, h("div", { class: "grid__table", attrs: { role: "table", "aria-label": "Lines" } }, head, body)), + h("div", { class: "grid__foot" }, addBtn, totals), + ); + host.append(root); + + function emit(): void { + o.onChange(collect()); + } + + function collect(): GridLine[] { + emitted = rows.filter((r) => !isBlank(r.line)); + return emitted.map((r) => ({ ...r.line })); + } + + function writeLine(r: Row, l: GridLine): void { + r.line = { ...l }; + if (r.desc.value !== l.description) r.desc.value = l.description; + const q = qty(l.qtyMilli); + if (r.qty.value !== q) r.qty.value = q; + const p = fmt(l.unitPrice); + if (r.price.value !== p) r.price.value = p; + r.qty.classList.remove("is-invalid"); + r.price.classList.remove("is-invalid"); + void r.item.setById(l.itemId); + void r.tax.setById(l.taxRateId); + } + + function clearTotals(r: Row): void { + setText(r.sub, ""); + setText(r.taxAmt, ""); + setText(r.total, ""); + } + + function applyReadOnly(r: Row): void { + r.item.setDisabled(readOnly); + r.tax.setDisabled(readOnly); + r.desc.readOnly = readOnly; + r.qty.readOnly = readOnly; + r.price.readOnly = readOnly; + r.remove.disabled = readOnly; + } + + function focusCell(r: Row | undefined, col: Col): void { + if (!r) return; + if (col === "item") r.item.focus(); + else if (col === "tax") r.tax.focus(); + else r[col].focus(); + } + + function colOf(r: Row, target: EventTarget | null): Col | null { + if (target === r.item.input) return "item"; + if (target === r.desc) return "desc"; + if (target === r.qty) return "qty"; + if (target === r.price) return "price"; + if (target === r.tax.input) return "tax"; + return null; + } + + function addRow(l: GridLine): Row { + const cell = (cls: string) => h("div", { class: `grid__td ${cls}`, attrs: { role: "cell" } }); + const cItem = cell("grid__c-item"); + const cDesc = cell("grid__c-desc"); + const cQty = cell("grid__c-qty"); + const cPrice = cell("grid__c-price"); + const cTax = cell("grid__c-tax"); + const sub = cell("grid__c-num"); + const taxAmt = cell("grid__c-num"); + const total = cell("grid__c-num grid__c-total"); + const cRm = cell("grid__c-rm"); + const desc = h("input", { class: "input grid__input", attrs: { type: "text", "aria-label": "Description", autocomplete: "off" } }); + const qtyIn = h("input", { class: "input grid__input grid__num", attrs: { type: "text", inputmode: "decimal", "aria-label": "Quantity", autocomplete: "off" } }); + 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); + cQty.append(qtyIn); + cPrice.append(price); + cRm.append(remove); + const error = h("div", { class: "grid__err", attrs: { role: "status" } }); + const el = h("div", { class: "grid__row grid__line", attrs: { role: "row" } }, cItem, cDesc, cQty, cPrice, cTax, sub, taxAmt, total, cRm, error); + + const r = {} as Row; + const item = mountPicker(cItem, ctx, { + kind: "item", + label: "Item", + bare: true, + onPick: (picked) => { + r.line.itemId = picked?.id ?? ""; + if (picked) { + const rec = picked.record; + if (!r.line.description.trim()) { + r.line.description = String(rec.description || rec.name || ""); + desc.value = r.line.description; + } + if (o.family === "sales" && typeof rec.salePrice === "number") { + r.line.unitPrice = rec.salePrice; + price.value = fmt(rec.salePrice); + price.classList.remove("is-invalid"); + } + if (typeof rec.taxRateId === "string" && rec.taxRateId) { + r.line.taxRateId = rec.taxRateId; + void r.tax.setById(rec.taxRateId); + } + } + emit(); + }, + }); + const tax = mountPicker(cTax, ctx, { + kind: "tax-rate", + label: "Tax rate", + bare: true, + onPick: (picked) => { + r.line.taxRateId = picked?.id ?? ""; + emit(); + }, + }); + Object.assign(r, { el, item, desc, qty: qtyIn, price, tax, sub, taxAmt, total, remove, error, line: { ...l } }); + + desc.addEventListener("input", () => { + r.line.description = desc.value; + emit(); + }); + qtyIn.addEventListener("input", () => { + const v = parseQty(qtyIn.value); + const ok = v !== null && v > 0; + qtyIn.classList.toggle("is-invalid", !ok); + if (ok && v !== r.line.qtyMilli) { + r.line.qtyMilli = v; + emit(); + } + }); + qtyIn.addEventListener("blur", () => { + if (!qtyIn.classList.contains("is-invalid")) qtyIn.value = qty(r.line.qtyMilli); + }); + price.addEventListener("input", () => { + const v = parseMoney(price.value, places); + const ok = v !== null && v >= 0; + price.classList.toggle("is-invalid", !ok); + if (ok && v !== r.line.unitPrice) { + r.line.unitPrice = v; + emit(); + } + }); + price.addEventListener("blur", () => { + if (!price.classList.contains("is-invalid")) price.value = fmt(r.line.unitPrice); + }); + remove.addEventListener("click", () => { + if (readOnly) return; + dropRow(r); + emit(); + }); + el.addEventListener("keydown", (ev) => { + if (readOnly) return; + const col = colOf(r, ev.target); + if (!col) return; + const i = rows.indexOf(r); + const picker = col === "item" || col === "tax"; + if (ev.key === "Enter" && !ev.shiftKey) { + ev.preventDefault(); + if (i === rows.length - 1) { + const next = addRow(blank()); + focusCell(next, "item"); + } else focusCell(rows[i + 1], col); + } else if (!picker && ev.key === "ArrowDown") { + ev.preventDefault(); + focusCell(rows[i + 1], col); + } else if (!picker && ev.key === "ArrowUp") { + ev.preventDefault(); + focusCell(rows[i - 1], col); + } else if (ev.key === "Delete" && ev.ctrlKey) { + ev.preventDefault(); + const target = rows[i + 1] ?? rows[i - 1]; + dropRow(r); + emit(); + focusCell(target, col); + } + }); + + writeLine(r, l); + applyReadOnly(r); + rows.push(r); + body.append(el); + return r; + } + + function dropRow(r: Row): void { + const i = rows.indexOf(r); + if (i < 0) return; + if (rows.length === 1) { + writeLine(r, blank()); + clearTotals(r); + setText(r.error, ""); + return; + } + rows.splice(i, 1); + r.el.remove(); + } + + addBtn.addEventListener("click", () => { + if (readOnly) return; + focusCell(addRow(blank()), "item"); + }); + + addRow(blank()); + addBtn.disabled = readOnly; + + return { + root, + getLines: () => collect(), + setLines: (next) => { + const want = Math.max(next.length, 1); + while (rows.length > want) { + const r = rows.pop(); + r?.el.remove(); + } + rows.forEach((r, i) => { + writeLine(r, next[i] ?? blank()); + clearTotals(r); + setText(r.error, ""); + }); + for (let i = rows.length; i < want; i++) addRow(next[i] ?? blank()); + collect(); + }, + setTotals: (t) => { + const targets = emitted.length ? emitted : rows.filter((r) => !isBlank(r.line)); + for (const r of rows) { + const k = targets.indexOf(r); + const lt = k >= 0 ? t.lines[k] : undefined; + if (lt) { + setText(r.sub, fmt(lt.subtotal)); + setText(r.taxAmt, fmt(lt.tax)); + setText(r.total, fmt(lt.total)); + } else clearTotals(r); + } + setText(sumSub, fmt(t.subtotal)); + setText(sumTax, fmt(t.tax)); + setText(sumTotal, fmt(t.total)); + }, + setReadOnly: (value) => { + readOnly = value; + addBtn.disabled = value; + setAttr(root, "data-readonly", value ? "" : null); + for (const r of rows) applyReadOnly(r); + }, + setLineError: (index, message) => { + const r = emitted[index] ?? rows[index]; + if (!r) return; + setText(r.error, message); + r.el.classList.toggle("has-error", Boolean(message)); + }, + focusFirst: () => focusCell(rows[0], "item"), + setCurrency: (code) => { + if (code === currency) return; + currency = code; + places = placesFor(code); + setText(totalLabel, code ? `Total ${code}` : "Total"); + for (const r of rows) { + const p = fmt(r.line.unitPrice); + if (r.price.value !== p) r.price.value = p; + } + }, + }; +} diff --git a/web/src/ui/parts/picker.ts b/web/src/ui/parts/picker.ts new file mode 100644 index 0000000..52d5dc7 --- /dev/null +++ b/web/src/ui/parts/picker.ts @@ -0,0 +1,265 @@ +import { filterEntries, findById, label, lookup, type LookupEntry } from "../../engine/lookups"; +import { h, setAttr, setText } from "../dom"; +import type { ViewContext } from "../views"; + +export type PickKind = "customer" | "supplier" | "item" | "tax-rate" | "account" | "warehouse"; + +export interface Picked { + id: string; + code: string; + name: string; + record: Record; +} + +export interface PickerOptions { + kind: PickKind; + label: string; + value?: Picked | null; + required?: boolean; + bare?: boolean; + accept?(candidate: Picked): boolean; + onPick(picked: Picked | null): void; +} + +export interface PickerHandle { + root: HTMLElement; + input: HTMLInputElement; + get(): Picked | null; + set(picked: Picked | null): void; + setById(id: string): Promise; + setDisabled(disabled: boolean): void; + focus(): void; +} + +const ROWS = 8; +let seq = 0; +let layer: HTMLElement | null = null; + +function overlayLayer(): HTMLElement { + if (layer && layer.isConnected) return layer; + layer = h("div", { class: "picker-layer" }); + document.body.append(layer); + return layer; +} + +function toPicked(e: LookupEntry): Picked { + return { id: e.id, code: e.code, name: e.name, record: e.record }; +} + +export function mountPicker(host: HTMLElement, ctx: ViewContext, o: PickerOptions): PickerHandle { + const id = `picker-${++seq}`; + const input = h("input", { + class: "input picker__input", + attrs: { + type: "text", + role: "combobox", + autocomplete: "off", + spellcheck: "false", + "aria-label": o.label, + "aria-autocomplete": "list", + "aria-expanded": "false", + "aria-controls": `${id}-list`, + }, + }); + if (o.required) input.required = true; + const root = o.bare + ? h("div", { class: "picker picker--bare", attrs: { "data-kind": o.kind } }, input) + : h("label", { class: "field picker", attrs: { "data-kind": o.kind } }, h("span", { class: "field__label", text: o.label }), input); + host.append(root); + + let list: HTMLElement | null = null; + const rows: HTMLElement[] = []; + const empty = h("div", { class: "picker__empty", text: "" }); + let shown: LookupEntry[] = []; + let shownFor = ""; + let active = -1; + let open = false; + let value: Picked | null = o.value ?? null; + let token = 0; + + function ensureList(): HTMLElement { + if (list) return list; + list = h("div", { class: "picker__list", attrs: { id: `${id}-list`, role: "listbox", hidden: "" } }); + for (let i = 0; i < ROWS; i++) { + const row = h("div", { class: "picker__row", attrs: { role: "option", id: `${id}-o${i}`, hidden: "" } }, h("span", { class: "picker__code" }), h("span", { class: "picker__name" })); + row.addEventListener("mousedown", (ev) => { + ev.preventDefault(); + choose(i); + }); + rows.push(row); + list.append(row); + } + list.append(empty); + overlayLayer().append(list); + return list; + } + + function place(): void { + if (!list) return; + const r = input.getBoundingClientRect(); + list.style.left = `${Math.round(r.left)}px`; + const room = list.offsetHeight || 9 * 32; + const below = r.bottom + room <= window.innerHeight || r.top < room; + list.style.top = `${Math.round(below ? r.bottom : r.top - room)}px`; + list.style.width = `${Math.max(Math.round(r.width), 240)}px`; + } + + function mark(i: number): void { + rows[active]?.classList.remove("is-active"); + active = i; + const row = rows[active]; + if (row) { + row.classList.add("is-active"); + setAttr(input, "aria-activedescendant", row.id); + } else setAttr(input, "aria-activedescendant", null); + } + + function paint(entries: LookupEntry[], note: string): void { + shown = entries; + shownFor = input.value; + rows.forEach((row, i) => { + const e = entries[i]; + const [code, name] = [row.children[0], row.children[1]]; + if (e && code && name) { + setText(code, e.code); + setText(name, e.name); + setAttr(row, "hidden", null); + } else setAttr(row, "hidden", ""); + }); + setText(empty, note); + setAttr(empty, "hidden", note ? null : ""); + mark(entries.length ? 0 : -1); + } + + async function refresh(): Promise { + const mine = ++token; + try { + const all = await lookup(ctx.api, o.kind); + if (mine !== token || !open) return; + const accept = o.accept; + const pool = accept ? all.filter((e) => accept(toPicked(e))) : all; + const hits = filterEntries(pool, input.value, ROWS); + paint(hits, hits.length ? "" : "No match"); + place(); + } catch (err) { + if (mine !== token || !open) return; + paint([], err instanceof Error ? err.message : "Could not load the list"); + } + } + + function show(): void { + if (input.disabled) return; + const el = ensureList(); + place(); + if (!open) { + open = true; + setAttr(el, "hidden", null); + setAttr(input, "aria-expanded", "true"); + window.addEventListener("scroll", place, true); + window.addEventListener("resize", place); + } + void refresh(); + } + + function close(): void { + if (!open) return; + open = false; + token++; + window.removeEventListener("scroll", place, true); + window.removeEventListener("resize", place); + if (list) setAttr(list, "hidden", ""); + setAttr(input, "aria-expanded", "false"); + mark(-1); + } + + function write(picked: Picked | null): void { + value = picked; + const text = picked ? label(picked) : ""; + if (input.value !== text) input.value = text; + } + + async function commitTyped(text: string, at: number): Promise { + if (!text) return; + const all = await lookup(ctx.api, o.kind).catch(() => [] as LookupEntry[]); + const accept = o.accept; + const pool = accept ? all.filter((e) => accept(toPicked(e))) : all; + const q = text.toLowerCase(); + const exact = pool.find((e) => e.active && (e.code.toLowerCase() === q || label(e).toLowerCase() === q)); + const hit = exact ?? (at >= 0 ? shown[at] : undefined) ?? filterEntries(pool, text, 1)[0]; + if (!hit) return; + const picked = toPicked(hit); + write(picked); + close(); + o.onPick(picked); + } + + function choose(i: number): void { + const e = shown[i]; + if (!e) return; + const picked = toPicked(e); + write(picked); + close(); + o.onPick(picked); + } + + input.addEventListener("focus", () => input.select()); + input.addEventListener("input", show); + input.addEventListener("keydown", (ev) => { + if (ev.key === "ArrowDown" || ev.key === "ArrowUp") { + ev.preventDefault(); + if (!open) { + show(); + return; + } + if (!shown.length) return; + const n = Math.min(shown.length, ROWS); + mark(ev.key === "ArrowDown" ? (active + 1) % n : (active - 1 + n) % n); + } else if (ev.key === "Enter") { + const text = input.value.trim(); + if (open || (text && (!value || text !== label(value)))) { + ev.preventDefault(); + ev.stopPropagation(); + void commitTyped(text, open && shownFor === input.value ? active : -1); + } + } else if (ev.key === "Escape") { + if (open) { + ev.preventDefault(); + ev.stopPropagation(); + close(); + write(value); + } + } + }); + input.addEventListener("blur", () => { + close(); + if (!input.value.trim()) { + if (value) { + value = null; + o.onPick(null); + } + } else write(value); + }); + + write(value); + + return { + root, + input, + get: () => value, + set: (picked) => write(picked), + setById: async (pid) => { + if (!pid) { + write(null); + return; + } + if (value && value.id === pid) return; + const e = await findById(ctx.api, o.kind, pid); + write(e ? toPicked(e) : null); + }, + setDisabled: (disabled) => { + input.disabled = disabled; + if (disabled) close(); + }, + focus: () => input.focus(), + }; +} diff --git a/web/src/ui/parts/table.ts b/web/src/ui/parts/table.ts new file mode 100644 index 0000000..2d94b8f --- /dev/null +++ b/web/src/ui/parts/table.ts @@ -0,0 +1,154 @@ +import { delayedIndicator, h, setAttr, setText } from "../dom"; + +export interface Column { + key: string; + label: string; + width: string; + align?: "start" | "end"; + text(row: T): string; + tone?(row: T): string; +} + +export interface TableOptions { + label: string; + columns: Column[]; + rowKey(row: T): string; + empty: string; + foot?: boolean; + onOpen?(row: T): void; +} + +export interface TableHandle { + root: HTMLElement; + setRows(rows: T[]): void; + patchRow(row: T): void; + removeRow(key: string): void; + setFoot(cells: Record): void; + setBusy(busy: boolean): void; + setError(message: string): void; +} + +export function mountTable(host: HTMLElement, o: TableOptions): TableHandle { + const align = (c: Column) => ({ "data-align": c.align ?? "start" }); + const body = h("tbody"); + const footCells = new Map(); + const empty = h("p", { class: "tbl__empty", text: o.empty }); + const error = h("p", { class: "tbl__error", attrs: { role: "alert" } }); + const table = h( + "table", + { class: "tbl__table", attrs: { "aria-label": o.label } }, + h("colgroup", {}, ...o.columns.map((c) => h("col", { attrs: { style: `inline-size:${c.width}` } }))), + h("thead", {}, h("tr", {}, ...o.columns.map((c) => h("th", { attrs: { scope: "col", ...align(c) }, text: c.label })))), + body, + ); + if (o.foot) { + const row = h("tr"); + for (const c of o.columns) { + const cell = h("td", { attrs: align(c) }); + footCells.set(c.key, cell); + row.append(cell); + } + table.append(h("tfoot", {}, row)); + } + const root = h("div", { class: "tbl", attrs: { "data-empty": "true" } }, table, empty, error); + host.append(root); + + const rows = new Map(); + + const fill = (el: HTMLTableRowElement, row: T) => { + o.columns.forEach((c, i) => { + const cell = el.cells[i]; + if (!cell) return; + setText(cell, c.text(row)); + setAttr(cell, "data-tone", c.tone?.(row) || null); + }); + }; + + const make = (key: string, row: T): HTMLTableRowElement => { + const el = h("tr", { attrs: o.onOpen ? { "data-key": key, tabindex: "0" } : { "data-key": key } }); + for (const c of o.columns) el.append(h("td", { attrs: align(c) })); + fill(el, row); + return el; + }; + + const open = (target: EventTarget | null) => { + const el = target instanceof Element ? target.closest("tr[data-key]") : null; + const hit = el ? rows.get(el.dataset.key ?? "") : undefined; + if (hit) o.onOpen?.(hit.row); + }; + if (o.onOpen) { + setAttr(root, "data-open", "true"); + body.addEventListener("click", (e) => open(e.target)); + body.addEventListener("keydown", (e) => { + if (e.key === "Enter") open(e.target); + }); + } + + const mark = () => setAttr(root, "data-empty", rows.size ? null : "true"); + let endBusy: (() => void) | null = null; + + return { + root, + setRows(next) { + const seen = new Set(); + let at: ChildNode | null = body.firstChild; + for (const row of next) { + const key = o.rowKey(row); + seen.add(key); + let hit = rows.get(key); + if (hit) { + hit.row = row; + fill(hit.el, row); + } else { + hit = { el: make(key, row), row }; + rows.set(key, hit); + } + if (hit.el === at) at = at.nextSibling; + else body.insertBefore(hit.el, at); + } + for (const [key, hit] of rows) { + if (seen.has(key)) continue; + hit.el.remove(); + rows.delete(key); + } + mark(); + }, + patchRow(row) { + const key = o.rowKey(row); + const hit = rows.get(key); + if (hit) { + hit.row = row; + fill(hit.el, row); + return; + } + const el = make(key, row); + rows.set(key, { el, row }); + body.append(el); + mark(); + }, + removeRow(key) { + const hit = rows.get(key); + if (!hit) return; + hit.el.remove(); + rows.delete(key); + mark(); + }, + setFoot(cells) { + for (const [key, cell] of footCells) setText(cell, cells[key] ?? ""); + }, + setBusy(busy) { + if (busy && !endBusy) { + endBusy = delayedIndicator( + () => setAttr(root, "data-busy", "true"), + () => setAttr(root, "data-busy", null), + ); + } else if (!busy && endBusy) { + endBusy(); + endBusy = null; + } + }, + setError(message) { + setText(error, message); + }, + }; +} diff --git a/web/src/ui/views.ts b/web/src/ui/views.ts new file mode 100644 index 0000000..2a0d5da --- /dev/null +++ b/web/src/ui/views.ts @@ -0,0 +1,125 @@ +import type { Api, Engine } from "../engine"; +import { h, ref, setAttr, setText } from "./dom"; +import { iconNode, type IconName } from "./icons"; +import { ALL_VIEWS } from "./views/index"; + +export type ViewGroup = "Selling" | "Buying" | "Stock" | "Ledger" | "Setup"; + +export const VIEW_GROUPS: readonly ViewGroup[] = ["Selling", "Buying", "Stock", "Ledger", "Setup"]; + +export interface ViewContext { + engine: Engine; + api: Api; + can(action: string): boolean; + go(id: string, params?: Record): void; +} + +export interface ViewDef { + id: string; + title: string; + group: ViewGroup; + nav: boolean; + icon?: IconName; + mount(host: HTMLElement, ctx: ViewContext): void; + show?(params: URLSearchParams): void; + hide?(): void; +} + +interface Mounted { + def: ViewDef; + section: HTMLElement; + body: HTMLElement; + link: HTMLAnchorElement | null; + ready: boolean; +} + +function parse(hash: string): { id: string; params: URLSearchParams } { + const raw = hash.replace(/^#\/?/, ""); + const cut = raw.indexOf("?"); + return { id: cut < 0 ? raw : raw.slice(0, cut), params: new URLSearchParams(cut < 0 ? "" : raw.slice(cut + 1)) }; +} + +export function hashFor(id: string, params: Record = {}): string { + const query = new URLSearchParams(params).toString(); + return `#/${id}${query ? `?${query}` : ""}`; +} + +export function mountViews(engine: Engine): void { + const scroller = ref("views"); + const nav = ref("nav-views"); + const title = ref("topbar-title"); + const views = new Map(); + let active: Mounted | null = null; + + const ctx: ViewContext = { + engine, + api: engine.api, + can: (action) => engine.state.get("me")?.can.includes(action) ?? false, + go: (id, params) => { + location.hash = hashFor(id, params); + }, + }; + + for (const group of VIEW_GROUPS) { + const defs = ALL_VIEWS.filter((d) => d.group === group); + if (!defs.length) continue; + if (defs.some((d) => d.nav)) nav.append(h("p", { class: "sb-group", text: group })); + for (const def of defs) { + const body = h("div", { class: "page__body" }); + const section = h( + "section", + { class: "view view--page", attrs: { "data-view": def.id, "aria-label": def.title } }, + h("div", { class: "page" }, h("h1", { class: "page__title", text: def.title }), body), + ); + scroller.append(section); + let link: HTMLAnchorElement | null = null; + if (def.nav) { + const mark = h("span", { class: "sb-icon" }); + if (def.icon) mark.append(iconNode(def.icon)); + link = h("a", { class: "sb-item", attrs: { href: hashFor(def.id) } }, mark, h("span", { class: "sb-label", text: def.title })); + nav.append(link); + } + views.set(def.id, { def, section, body, link, ready: false }); + } + } + + const leave = () => { + if (!active) return; + setAttr(active.section, "data-active", null); + if (active.link) setAttr(active.link, "aria-current", null); + active.def.hide?.(); + active = null; + }; + + const apply = () => { + if (engine.state.get("screen") !== "app") return; + const { id, params } = parse(location.hash); + const next = views.get(id); + if (!next) { + if (id) history.replaceState(null, "", location.pathname + location.search); + return; + } + if (!next.ready) { + next.def.mount(next.body, ctx); + next.ready = true; + } + if (active !== next) { + leave(); + active = next; + engine.state.set("route", id); + setAttr(next.section, "data-active", "true"); + if (next.link) setAttr(next.link, "aria-current", "page"); + setText(title, next.def.title); + } + next.def.show?.(params); + }; + + engine.state.watch("route", (route) => { + if (route !== "home" && route !== "account") return; + leave(); + if (location.hash) history.replaceState(null, "", location.pathname + location.search); + }); + engine.state.watch("screen", () => apply()); + window.addEventListener("hashchange", apply); + apply(); +} diff --git a/web/src/ui/views/docform.ts b/web/src/ui/views/docform.ts new file mode 100644 index 0000000..8e2d994 --- /dev/null +++ b/web/src/ui/views/docform.ts @@ -0,0 +1,319 @@ +import { + SPECS, + actionState, + amendDoc, + cancelDoc, + confirmDoc, + confirmLabel, + kindLabel, + loadDoc, + makeNext, + saveDraft, + statusLabel, + type Doc, + type Draft, + type Family, + type FamilySpec, +} from "../../engine/docform"; +import { money, today } from "../../engine/format"; +import { delayedIndicator, h, setAttr, setText } from "../dom"; +import { mountLineGrid, type GridLine, type GridTotals, type LineGridHandle } from "../parts/linegrid"; +import { mountPicker, type PickerHandle } from "../parts/picker"; +import type { ViewContext, ViewDef } from "../views"; + +const SVG = "http://www.w3.org/2000/svg"; + +function glyph(d: string): SVGSVGElement { + const svg = document.createElementNS(SVG, "svg"); + svg.setAttribute("viewBox", "0 0 16 16"); + svg.setAttribute("width", "16"); + svg.setAttribute("height", "16"); + svg.setAttribute("fill", "none"); + svg.setAttribute("stroke", "currentColor"); + svg.setAttribute("stroke-width", "1.5"); + svg.setAttribute("stroke-linecap", "round"); + svg.setAttribute("stroke-linejoin", "round"); + svg.setAttribute("aria-hidden", "true"); + const path = document.createElementNS(SVG, "path"); + path.setAttribute("d", d); + svg.append(path); + return svg; +} + +const GLYPHS = { + save: "M3 2.5h8l2.5 2.5v8.5h-10.5z M5.5 2.5v3.5h5v-3.5 M5 13.5v-4h6v4", + confirm: "M3 8.5l3 3 7-7", + cancel: "M4 4l8 8 M12 4l-8 8", + amend: "M10.5 2.5l3 3-8 8h-3v-3z", + make: "M3 8h9 M9 4.5l3.5 3.5-3.5 3.5", +}; + +function button(label: string, d: string, primary = false): HTMLButtonElement { + const b = h("button", { class: primary ? "btn btn--primary df-btn" : "btn df-btn", attrs: { type: "button" } }); + b.append(glyph(d), h("span", { class: "df-btn__label", text: label })); + b.disabled = true; + return b; +} + +function field(label: string, control: HTMLElement): HTMLElement { + return h("label", { class: "field df-field" }, h("span", { class: "field__label", text: label }), control); +} + +function sameLines(a: GridLine[], b: GridLine[]): boolean { + if (a.length !== b.length) return false; + return a.every((l, i) => { + const o = b[i]; + if (!o) return false; + return l.itemId === o.itemId && l.description === o.description && l.qtyMilli === o.qtyMilli && l.unitPrice === o.unitPrice && l.taxRateId === o.taxRateId; + }); +} + +function emptyTotals(): GridTotals { + return { lines: [], subtotal: 0, tax: 0, total: 0 }; +} + +function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext): (params: URLSearchParams) => void { + const firstKind = spec.kinds[0]?.id ?? "order"; + let doc: Doc | null = null; + let newKind = firstKind; + let loadSeq = 0; + + const root = h("div", { class: "df", attrs: { "data-family": spec.family } }); + + const kindSelect = h("select", { class: "input df-kind", attrs: { "aria-label": "Kind" } }); + for (const k of spec.kinds) kindSelect.append(h("option", { attrs: { value: k.id }, text: k.label })); + const numberText = h("span", { class: "df-number", text: "New draft" }); + const statusText = h("span", { class: "df-status", attrs: { "data-status": "draft" }, text: "Draft" }); + const busyText = h("span", { class: "df-busy", attrs: { "aria-live": "polite" }, text: "Working" }); + const head = h("div", { class: "df-head" }, kindSelect, numberText, statusText, busyText); + + const partyHost = h("div", { class: "df-picker" }); + const dateInput = h("input", { class: "input", attrs: { type: "date", required: "" } }); + const dueInput = h("input", { class: "input", attrs: { type: "date" } }); + const refInput = h("input", { class: "input", attrs: { type: "text", maxlength: "120", autocomplete: "off" } }); + const warehouseHost = h("div", { class: "df-picker" }); + const memoInput = h("input", { class: "input", attrs: { type: "text", maxlength: "500", autocomplete: "off" } }); + const fields = h( + "div", + { class: "df-fields" }, + h("div", { class: "field df-field df-field--party" }, partyHost), + field("Date", dateInput), + field("Due date", dueInput), + ...(spec.hasReference ? [field("Supplier reference", refInput)] : []), + h("div", { class: "field df-field" }, warehouseHost), + h("label", { class: "field df-field df-field--notes" }, h("span", { class: "field__label", text: "Notes" }), memoInput), + ); + + const gridHost = h("div", { class: "df-lines" }); + const errorLine = h("p", { class: "df-error", attrs: { role: "alert" } }); + + const saveBtn = button("Save draft", GLYPHS.save); + const confirmBtn = button("Confirm", GLYPHS.confirm, true); + const cancelBtn = button("Cancel", GLYPHS.cancel); + const amendBtn = button("Amend", GLYPHS.amend); + const makeBtns = new Map(spec.makes.map((m) => [m.key, button(m.label, GLYPHS.make)])); + const actions = h("div", { class: "df-actions" }, saveBtn, confirmBtn, cancelBtn, amendBtn, h("span", { class: "df-actions__gap" }), ...makeBtns.values()); + + root.append(head, fields, gridHost, errorLine, actions); + host.append(root); + + 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 setError = (message: string) => setText(errorLine, message); + + const setValue = (input: HTMLInputElement | HTMLSelectElement, value: string) => { + if (input.value !== value) input.value = value; + }; + + const setDenied = (b: HTMLButtonElement, denied: boolean) => { + b.classList.toggle("is-denied", denied); + setAttr(b, "aria-hidden", denied ? "true" : null); + }; + + const refresh = () => { + const state = actionState(spec, doc, ctx.can, warehouse.get()?.id ?? "", newKind); + const kind = doc?.kind ?? newKind; + const postAction = kind === "invoice" ? spec.postAction : spec.draftAction; + saveBtn.disabled = !state.save; + confirmBtn.disabled = !state.confirm; + cancelBtn.disabled = !state.cancel; + amendBtn.disabled = !state.amend; + setDenied(saveBtn, !ctx.can(spec.draftAction)); + setDenied(amendBtn, !ctx.can(spec.draftAction)); + setDenied(confirmBtn, !ctx.can(postAction)); + setDenied(cancelBtn, !ctx.can(postAction)); + setText(confirmBtn.querySelector(".df-btn__label") as HTMLElement, confirmLabel(kind)); + for (const m of spec.makes) { + const b = makeBtns.get(m.key) as HTMLButtonElement; + b.disabled = !state.makes[m.key]; + setDenied(b, !ctx.can(m.action) || !spec.kinds.some((k) => k.id === m.from)); + } + const editable = !doc || doc.status === "draft"; + kindSelect.disabled = !!doc; + for (const input of [dateInput, dueInput, refInput, memoInput]) input.readOnly = !editable; + party.setDisabled(!editable); + warehouse.setDisabled(!editable && spec.family === "purchase"); + setText(numberText, doc ? doc.number || "Draft, not numbered" : "New draft"); + const status = doc?.status ?? "draft"; + setAttr(statusText, "data-status", status); + setText(statusText, `${kindLabel(spec, kind)} · ${statusLabel(kind, status)}${doc ? ` · ${doc.currency} ${money(doc.total)}` : ""}`); + }; + + const writeTotals = (d: Doc) => { + grid.setTotals({ + lines: d.lines.map((l) => ({ subtotal: l.lineSubtotal, tax: l.lineTax, total: l.lineTotal })), + subtotal: d.subtotal, + tax: d.taxTotal, + total: d.total, + }); + }; + + const fill = async (d: Doc) => { + doc = d; + setValue(kindSelect, d.kind); + setValue(dateInput, d.date); + setValue(dueInput, d.dueDate); + setValue(refInput, d.reference); + setValue(memoInput, d.memo); + const lines: GridLine[] = d.lines.map((l) => ({ itemId: l.itemId, description: l.description, qtyMilli: l.quantityMilli, unitPrice: l.unitPrice, taxRateId: l.taxRateId })); + if (!sameLines(grid.getLines(), lines)) grid.setLines(lines); + writeTotals(d); + grid.setReadOnly(d.status !== "draft"); + refresh(); + await Promise.all([ + party.get()?.id === d.partyId ? Promise.resolve() : party.setById(d.partyId), + !d.warehouseId || warehouse.get()?.id === d.warehouseId ? Promise.resolve() : warehouse.setById(d.warehouseId), + ]); + refresh(); + }; + + const reset = (kind: string) => { + doc = null; + newKind = spec.kinds.some((k) => k.id === kind) ? kind : firstKind; + setValue(kindSelect, newKind); + setValue(dateInput, today()); + setValue(dueInput, ""); + setValue(refInput, ""); + setValue(memoInput, ""); + party.set(null); + if (grid.getLines().length) grid.setLines([]); + grid.setTotals(emptyTotals()); + grid.setReadOnly(false); + setError(""); + refresh(); + }; + + const draft = (): Draft => ({ + kind: doc?.kind ?? newKind, + date: dateInput.value, + dueDate: dueInput.value, + partyId: party.get()?.id ?? "", + warehouseId: warehouse.get()?.id ?? "", + reference: refInput.value, + memo: memoInput.value, + lines: grid.getLines(), + }); + + let running = false; + const run = async (work: () => Promise) => { + if (running) return; + running = true; + setError(""); + root.setAttribute("aria-busy", "true"); + const done = delayedIndicator( + () => busyText.classList.add("is-on"), + () => busyText.classList.remove("is-on"), + ); + try { + await work(); + } catch (e) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + done(); + root.removeAttribute("aria-busy"); + running = false; + } + }; + + const save = async (): Promise => { + const wasNew = !doc; + const saved = await saveDraft(ctx.api, spec, doc?.id ?? null, draft()); + await fill(saved); + if (wasNew) ctx.go(spec.view, { id: saved.id }); + return saved; + }; + + saveBtn.addEventListener("click", () => run(async () => void (await save()))); + confirmBtn.addEventListener("click", () => + run(async () => { + const saved = await save(); + await fill(await confirmDoc(ctx.api, spec, saved)); + }), + ); + cancelBtn.addEventListener("click", () => + run(async () => { + if (doc) await fill(await cancelDoc(ctx.api, spec, doc)); + }), + ); + amendBtn.addEventListener("click", () => + run(async () => { + if (doc) ctx.go(spec.view, { id: await amendDoc(ctx.api, spec, doc) }); + }), + ); + for (const m of spec.makes) { + (makeBtns.get(m.key) as HTMLButtonElement).addEventListener("click", () => + run(async () => { + if (doc) ctx.go(m.target, { id: await makeNext(ctx.api, spec, doc, m, warehouse.get()?.id ?? "") }); + }), + ); + } + kindSelect.addEventListener("change", () => { + if (doc) return; + newKind = kindSelect.value; + refresh(); + }); + root.addEventListener("keydown", (e) => { + if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "s") { + e.preventDefault(); + if (!saveBtn.disabled) saveBtn.click(); + } + }); + + reset(newKind); + + return (params) => { + const id = params.get("id"); + if (!id) { + const kind = params.get("kind") ?? firstKind; + if (doc || kind !== newKind) reset(kind); + return; + } + if (doc?.id === id) return; + const seq = ++loadSeq; + void run(async () => { + const d = await loadDoc(ctx.api, spec, id); + if (seq === loadSeq) await fill(d); + }); + }; +} + +function formView(family: Family): ViewDef { + const spec = SPECS[family]; + let show: ((params: URLSearchParams) => void) | null = null; + return { + id: spec.view, + title: spec.title, + group: family === "sales" ? "Selling" : "Buying", + nav: false, + mount(host, ctx) { + show = mountForm(spec, host, ctx); + }, + show(params) { + show?.(params); + }, + }; +} + +export const views: ViewDef[] = [formView("sales"), formView("purchase")]; diff --git a/web/src/ui/views/doclists.ts b/web/src/ui/views/doclists.ts new file mode 100644 index 0000000..fdf00a0 --- /dev/null +++ b/web/src/ui/views/doclists.ts @@ -0,0 +1,109 @@ +import { DOC_LISTS, STATUSES, isStatus, loadPage, type DocListSpec, type DocRow, type DocStatus } from "../../engine/doclists"; +import { money } from "../../engine/format"; +import { h, setAttr, setText } from "../dom"; +import { mountTable, type TableHandle } from "../parts/table"; +import type { ViewContext, ViewDef } from "../views"; + +const SVG = "http://www.w3.org/2000/svg"; + +function plusIcon(): SVGSVGElement { + const svg = document.createElementNS(SVG, "svg"); + for (const [k, v] of Object.entries({ class: "icon", viewBox: "0 0 24 24", width: "16", height: "16", fill: "none", stroke: "currentColor", "stroke-width": "1.75", "stroke-linecap": "round", "aria-hidden": "true", focusable: "false" })) svg.setAttribute(k, v); + const path = document.createElementNS(SVG, "path"); + path.setAttribute("d", "M12 5.5v13M5.5 12h13"); + svg.append(path); + return svg; +} + +const STATUS_LABEL: Record = { draft: "Draft", posted: "Posted", cancelled: "Cancelled" }; + +function countText(shown: number, more: boolean): string { + if (!shown) return ""; + return `${shown} shown${more ? ", more to load" : ""}`; +} + +function listView(spec: DocListSpec): ViewDef { + let ctx: ViewContext; + let table: TableHandle; + let filter: HTMLSelectElement; + let more: HTMLButtonElement; + let count: HTMLElement; + let status: DocStatus | null = null; + let cursor = ""; + let shown = 0; + let seq = 0; + + const run = async (append: boolean) => { + const mine = ++seq; + table.setBusy(true); + setAttr(more, "disabled", ""); + try { + const page = await loadPage(ctx.api, spec, status, append ? cursor : ""); + if (mine !== seq) return; + if (append) for (const row of page.rows) table.patchRow(row); + else table.setRows(page.rows); + shown = append ? shown + page.rows.length : page.rows.length; + cursor = page.next; + table.setError(""); + } catch (e) { + if (mine !== seq) return; + table.setError(e instanceof Error ? e.message : "The list could not be read."); + } finally { + if (mine === seq) { + table.setBusy(false); + setAttr(more, "disabled", cursor ? null : ""); + setText(count, countText(shown, cursor !== "")); + } + } + }; + + return { + id: spec.id, + title: spec.title, + group: spec.group, + nav: true, + mount(host, c) { + ctx = c; + const root = h("div", { class: "dl" }); + filter = h("select", { class: "input dl__filter", attrs: { id: `dl-status-${spec.id}` } },h("option", { attrs: { value: "" }, text: "All statuses" }), ...STATUSES.map((s) => h("option", { attrs: { value: s }, text: STATUS_LABEL[s] }))); + filter.addEventListener("change", () => ctx.go(spec.id, filter.value ? { status: filter.value } : {})); + const bar = h("div", { class: "dl__bar" }, h("label", { class: "dl__label", attrs: { for: `dl-status-${spec.id}` }, text: "Status" }), filter, h("span", { class: "dl__gap" })); + if (spec.newAction && ctx.can(spec.newAction)) { + const add = h("button", { class: "btn btn--primary dl__new", attrs: { type: "button" } }, plusIcon(), h("span", { text: "New" })); + add.addEventListener("click", () => ctx.go(spec.form, { kind: spec.kind })); + bar.append(add); + } + root.append(bar); + const tableHost = h("div", { class: "dl__table" }); + root.append(tableHost); + table = mountTable(tableHost, { + label: spec.title, + rowKey: (r) => r.id, + empty: `No ${spec.title.toLowerCase()} yet.`, + onOpen: (r) => ctx.go(spec.form, { id: r.id }), + columns: [ + { key: "number", label: "Number", width: "var(--dl-col-number)", text: (r) => r.number || "Draft", tone: (r) => (r.number ? "" : "muted") }, + { key: "date", label: "Date", width: "var(--dl-col-date)", text: (r) => r.date }, + { key: "party", label: spec.party === "customer" ? "Customer" : "Supplier", width: "auto", text: (r) => r.party }, + { key: "status", label: "Status", width: "var(--dl-col-status)", text: (r) => STATUS_LABEL[r.status] ?? r.status, tone: (r) => r.status }, + { key: "total", label: spec.totalLabel, width: "var(--dl-col-total)", align: "end", text: (r) => (r.currency ? `${money(r.total)} ${r.currency}` : money(r.total)) }, + ], + }); + count = h("span", { class: "dl__count", attrs: { "aria-live": "polite" } }); + more = h("button", { class: "btn btn--quiet dl__more", attrs: { type: "button", disabled: "" }, text: "Load more" }); + more.addEventListener("click", () => void run(true)); + bar.insertBefore(count, bar.querySelector(".dl__gap")); + if (spec.paged) bar.insertBefore(more, bar.querySelector(".dl__gap")); + host.append(root); + }, + show(params) { + const raw = params.get("status"); + const next = isStatus(raw) ? raw : null; + if (filter.value !== (next ?? "")) filter.value = next ?? ""; + status = next; + void run(false); + }, + }; +} + +export const views: ViewDef[] = DOC_LISTS.map(listView); diff --git a/web/src/ui/views/index.ts b/web/src/ui/views/index.ts new file mode 100644 index 0000000..a835803 --- /dev/null +++ b/web/src/ui/views/index.ts @@ -0,0 +1,9 @@ +import type { ViewDef } from "../views"; +import { views as docForms } from "./docform"; +import { views as docLists } from "./doclists"; +import { views as ledgerScreens } from "./ledger-screens"; +import { views as masters } from "./masters"; +import { views as payments } from "./payments"; +import { views as statements } from "./statements"; + +export const ALL_VIEWS: ViewDef[] = [...docLists, ...docForms, ...payments, ...ledgerScreens, ...statements, ...masters]; diff --git a/web/src/ui/views/ledger-screens.ts b/web/src/ui/views/ledger-screens.ts new file mode 100644 index 0000000..1939204 --- /dev/null +++ b/web/src/ui/views/ledger-screens.ts @@ -0,0 +1,252 @@ +import { ApiError } from "../../engine/session"; +import { amount, balanceLine, loadAccounts, loadAgeing, loadLedger, loadStock, loadTrial, tieLine, type AgeingRow, type LedgerLine, type StockRow, type TrialRow } from "../../engine/ledger-screens"; +import { qty, today } from "../../engine/format"; +import { h, setText } from "../dom"; +import type { ViewContext, ViewDef, ViewGroup } from "../views"; +import { mountTable, type Column, type TableHandle } from "../parts/table"; + +interface Control { + el: HTMLInputElement | HTMLSelectElement; + read(): string; +} + +interface Screen { + id: string; + title: string; + group: ViewGroup; + controls: (ctx: ViewContext) => { label: string; control: Control }[]; +} + +const date = (value: string): Control => { + const el = h("input", { class: "input ls__input", attrs: { type: "date", value } }); + return { el, read: () => el.value }; +}; + +const choose = (options: [string, string][]): Control => { + const el = h("select", { class: "input ls__input" }); + for (const [value, label] of options) el.append(h("option", { text: label, attrs: { value } })); + return { el, read: () => el.value }; +}; + +const dash = (n: number) => (n ? amount(n) : ""); + +function shell(host: HTMLElement, controls: { label: string; control: Control }[], onChange: () => void) { + const bar = h("div", { class: "ls__bar" }); + for (const { label, control } of controls) { + const field = h("label", { class: "ls__field" }, h("span", { class: "ls__label", text: label }), control.el); + control.el.addEventListener("change", onChange); + bar.append(field); + } + const status = h("p", { class: "ls__status", attrs: { role: "status" } }); + const tableHost = h("div", { class: "ls__table" }); + host.classList.add("ls"); + host.append(bar, status, tableHost); + return { status, tableHost }; +} + +function guard(table: TableHandle, status: HTMLElement) { + let serial = 0; + return async (run: () => Promise) => { + const mine = ++serial; + table.setBusy(true); + try { + const text = await run(); + if (mine !== serial) return; + table.setError(""); + setText(status, text); + } catch (e) { + if (mine !== serial) return; + table.setError(e instanceof ApiError ? e.message : "The figures could not be read."); + setText(status, ""); + } finally { + if (mine === serial) table.setBusy(false); + } + }; +} + +const num = (key: string, label: string, pick: (r: T) => number, width = "110px", blank = false): Column => ({ + key, + label, + width, + align: "end", + text: (r) => (blank ? dash(pick(r)) : amount(pick(r))), +}); + +function trialScreen(): ViewDef { + let reload = () => {}; + return { + id: "trial-balance", + title: "Trial balance", + group: "Ledger", + nav: true, + mount(host, ctx) { + const asOf = date(today()); + const { status, tableHost } = shell(host, [{ label: "As of", control: asOf }], () => reload()); + const cols: Column[] = [ + { key: "code", label: "Code", width: "110px", text: (r) => r.code }, + { key: "name", label: "Account", width: "auto", text: (r) => r.name }, + { key: "type", label: "Type", width: "110px", text: (r) => r.type, tone: () => "muted" }, + num("debit", "Debit", (r) => r.debit, "130px", true), + num("credit", "Credit", (r) => r.credit, "130px", true), + ]; + const table = mountTable(tableHost, { label: "Trial balance", columns: cols, rowKey: (r) => r.accountId, empty: "No ledger lines yet.", foot: true }); + const run = guard(table as TableHandle, status); + reload = () => + void run(async () => { + const t = await loadTrial(ctx.api, asOf.read()); + table.setRows(t.rows); + table.setFoot({ name: "Total", debit: amount(t.totalDebit), credit: amount(t.totalCredit) }); + return balanceLine(t); + }); + }, + show() { + reload(); + }, + }; +} + +function ledgerScreen(): ViewDef { + let reload = () => {}; + return { + id: "general-ledger", + title: "General ledger", + group: "Ledger", + nav: true, + mount(host, ctx) { + const account = choose([["", "Choose an account"]]); + const from = date(""); + const to = date(today()); + const { status, tableHost } = shell( + host, + [ + { label: "Account", control: account }, + { label: "From", control: from }, + { label: "To", control: to }, + ], + () => reload(), + ); + const cols: Column[] = [ + { key: "date", label: "Date", width: "110px", text: (r) => r.date }, + { key: "number", label: "Entry", width: "150px", text: (r) => r.number }, + { key: "memo", label: "Memo", width: "auto", text: (r) => r.memo }, + num("debit", "Debit", (r) => r.debit, "120px", true), + num("credit", "Credit", (r) => r.credit, "120px", true), + num("balance", "Balance", (r) => r.balance, "130px"), + ]; + const table = mountTable(tableHost, { label: "General ledger", columns: cols, rowKey: (r) => `${r.entryId}:${r.lineNo}`, empty: "No lines in this range.", foot: true }); + const run = guard(table as TableHandle, status); + reload = () => { + if (!account.read()) return; + void run(async () => { + const l = await loadLedger(ctx.api, account.read(), from.read(), to.read()); + table.setRows(l.lines); + table.setFoot({ memo: "Opening", balance: amount(l.opening) }); + return `Opening ${amount(l.opening)}, closing ${amount(l.closing)}, ${l.totalLines} lines${l.totalLines > l.lines.length ? ` (first ${l.lines.length} shown)` : ""}.`; + }); + }; + void loadAccounts(ctx.api) + .then((list) => { + for (const a of list) account.el.append(h("option", { text: `${a.code} ${a.name}`, attrs: { value: a.code } })); + }) + .catch((e) => table.setError(e instanceof ApiError ? e.message : "The accounts could not be read.")); + }, + show() { + reload(); + }, + }; +} + +function ageingScreen(id: string, title: string, group: ViewGroup, side: "receivables" | "payables", party: string): ViewDef { + let reload = () => {}; + return { + id, + title, + group, + nav: true, + mount(host, ctx) { + const asOf = date(today()); + const by = choose([ + ["due", "Due date"], + ["date", "Invoice date"], + ]); + const { status, tableHost } = shell( + host, + [ + { label: "As of", control: asOf }, + { label: "Counted from", control: by }, + ], + () => reload(), + ); + const cols: Column[] = [ + { key: "name", label: party, width: "auto", text: (r) => `${r.code} ${r.name}` }, + { key: "cur", label: "Cur", width: "56px", text: (r) => r.currency, tone: () => "muted" }, + num("current", "Current", (r) => r.current, "104px", true), + num("d30", "1 to 30", (r) => r.days1to30, "104px", true), + num("d60", "31 to 60", (r) => r.days31to60, "104px", true), + num("d90", "61 to 90", (r) => r.days61to90, "104px", true), + num("over", "Over 90", (r) => r.over90, "104px", true), + num("un", "Unallocated", (r) => r.unallocated, "112px", true), + num("total", "Total", (r) => r.total, "120px"), + ]; + const table = mountTable(tableHost, { label: title, columns: cols, rowKey: (r) => r.id, empty: "Nothing outstanding.", foot: true }); + const run = guard(table as TableHandle, status); + reload = () => + void run(async () => { + const a = await loadAgeing(ctx.api, side, asOf.read(), by.read()); + table.setRows(a.rows); + const one = a.totals.length === 1 ? a.totals[0] : null; + table.setFoot( + one + ? { name: "Total", cur: one.currency, current: dash(one.current), d30: dash(one.days1to30), d60: dash(one.days31to60), d90: dash(one.days61to90), over: dash(one.over90), un: dash(one.unallocated), total: amount(one.total) } + : { name: a.totals.length ? "Several currencies, see the line above" : "Total" }, + ); + return a.totals.length > 1 ? a.totals.map((t) => `${t.currency} ${amount(t.total)}`).join(" · ") : `${a.rows.length} ${party.toLowerCase()}s with a balance.`; + }); + }, + show() { + reload(); + }, + }; +} + +function stockScreen(): ViewDef { + let reload = () => {}; + return { + id: "stock-balance", + title: "Stock balance and valuation", + group: "Stock", + nav: true, + mount(host, ctx) { + const asOf = date(today()); + const { status, tableHost } = shell(host, [{ label: "As of", control: asOf }], () => reload()); + const cols: Column[] = [ + { key: "code", label: "Item", width: "120px", text: (r) => r.code }, + { key: "name", label: "Name", width: "auto", text: (r) => r.name }, + { key: "where", label: "Warehouses", width: "220px", text: (r) => r.where, tone: () => "muted" }, + { key: "qty", label: "Quantity", width: "110px", align: "end", text: (r) => qty(r.qtyMilli) }, + num("avg", "Average cost", (r) => r.averageCost, "130px"), + num("value", "Value", (r) => r.value, "130px"), + ]; + const table = mountTable(tableHost, { label: "Stock valuation", columns: cols, rowKey: (r) => r.itemId, empty: "No stock movements yet.", foot: true }); + const run = guard(table as TableHandle, status); + reload = () => + void run(async () => { + const s = await loadStock(ctx.api, asOf.read()); + table.setRows(s.rows); + table.setFoot({ name: "Total", value: amount(s.total) }); + return tieLine(s); + }); + }, + show() { + reload(); + }, + }; +} + +export const views: ViewDef[] = [ + trialScreen(), + ledgerScreen(), + ageingScreen("receivables-ageing", "Receivables ageing", "Selling", "receivables", "Customer"), + ageingScreen("payables-ageing", "Payables ageing", "Buying", "payables", "Supplier"), + stockScreen(), +]; diff --git a/web/src/ui/views/masters.ts b/web/src/ui/views/masters.ts new file mode 100644 index 0000000..3d072c8 --- /dev/null +++ b/web/src/ui/views/masters.ts @@ -0,0 +1,158 @@ +import { boolValue, buildBody, cell, create, fieldText, listAll, MASTERS, update, type Field, type Master, type Raw, type Row } from "../../engine/masters"; +import { ApiError } from "../../engine/session"; +import { h, setAttr, setText } from "../dom"; +import type { IconName } from "../icons"; +import { mountTable, type TableHandle } from "../parts/table"; +import type { ViewContext, ViewDef } from "../views"; + +const ICONS: Record = { customers: "user", suppliers: "user" }; + +function mountMaster(m: Master, host: HTMLElement, ctx: ViewContext): { show(): void } { + const root = h("div", { class: "masters" }); + const listHost = h("div", { class: "masters__list" }); + root.append(listHost); + host.append(root); + + const table: TableHandle = mountTable(listHost, { + label: m.title, + columns: m.columns.map((c) => ({ key: c.key, label: c.label, width: c.width, align: c.end ? "end" : "start", text: (r: Row) => cell(r, c.key) })), + rowKey: (r) => String(r.id), + empty: `No ${m.title.toLowerCase()} yet.`, + onOpen: (r) => fill(r), + }); + + const mode = h("p", { class: "masters__mode" }); + const fieldsBox = h("div", { class: "masters__fields" }); + const error = h("p", { class: "form__error", attrs: { role: "alert" } }); + const save = h("button", { class: "btn btn--primary", text: "Save", attrs: { type: "button" } }); + const fresh = h("button", { class: "btn", text: "New", attrs: { type: "button" } }); + const panel = h( + "div", + { class: "panel masters__form" }, + mode, + fieldsBox, + error, + h("div", { class: "masters__actions" }, h("span"), h("span", {}, fresh, " ", save)), + ); + root.append(panel); + + const inputs = new Map(); + for (const f of m.fields) { + const boolean = f.kind === "bool"; + let input: HTMLInputElement | HTMLSelectElement; + if (f.kind === "select") { + input = h("select", { class: "input", attrs: { id: `${m.id}-${f.key}` } }); + for (const o of f.options ?? []) input.append(h("option", { text: o, attrs: { value: o } })); + } else { + input = h("input", { class: boolean ? "" : "input", attrs: { id: `${m.id}-${f.key}`, type: boolean ? "checkbox" : "text", autocomplete: "off" } }); + } + const label = h("label", { class: "field__label", text: f.label, attrs: { for: `${m.id}-${f.key}` } }); + const wrap = h("div", { class: boolean ? "masters__field masters__field--bool" : "masters__field" }, ...(boolean ? [input, label] : [label, input])); + inputs.set(f.key, { field: f, input, wrap }); + fieldsBox.append(wrap); + } + + let current: Row | null = null; + const fill = (row: Row | null) => { + current = row; + for (const { field, input } of inputs.values()) { + if (input instanceof HTMLInputElement && input.type === "checkbox") { + const on = boolValue(field, row); + if (input.checked !== on) input.checked = on; + } else if (input.value !== fieldText(field, row)) { + input.value = fieldText(field, row); + } + const locked = Boolean(row) && field.createOnly === true; + if (input.disabled !== locked) input.disabled = locked; + } + setText(mode, row ? `Editing ${String(row.code ?? row.name ?? "")}` : `New ${m.singular}`); + setText(error, ""); + for (const tr of listHost.querySelectorAll("tr[data-selected]")) setAttr(tr, "data-selected", null); + if (row) { + const tr = listHost.querySelector(`tr[data-key="${CSS.escape(String(row.id))}"]`); + if (tr) setAttr(tr, "data-selected", "true"); + } + }; + fresh.addEventListener("click", () => fill(null)); + fill(null); + + const WRITE: Record = { customers: "sales.draft", suppliers: "purchase.draft", items: "sales.post", "tax-rates": "sales.post", warehouses: "stock.post", accounts: "ledger.post" }; + const allowed = () => ctx.can(WRITE[m.id] ?? ""); + const gate = () => { + const ok = allowed(); + if (save.disabled === ok) save.disabled = !ok; + if (fresh.disabled === ok) fresh.disabled = !ok; + }; + + let saving = false; + const submit = async () => { + if (saving || !allowed()) return; + const raw: Raw = {}; + for (const { field, input } of inputs.values()) { + raw[field.key] = input instanceof HTMLInputElement && input.type === "checkbox" ? input.checked : input.value; + } + const built = buildBody(m, raw, current); + if ("error" in built) { + setText(error, built.error); + return; + } + saving = true; + save.disabled = true; + setText(error, ""); + try { + const row = current ? await update(ctx.api, m, String(current.id), built.body) : await create(ctx.api, m, built.body); + table.patchRow(row); + fill(row); + } catch (e) { + setText(error, e instanceof ApiError ? e.message : "The change could not be saved."); + } finally { + saving = false; + gate(); + } + }; + save.addEventListener("click", () => void submit()); + fieldsBox.addEventListener("keydown", (e) => { + if (e.key === "Enter" && e.target instanceof HTMLInputElement && e.target.type === "text") { + e.preventDefault(); + void submit(); + } + }); + + let loaded = false; + const load = async () => { + table.setBusy(true); + try { + table.setRows(await listAll(ctx.api, m)); + table.setError(""); + loaded = true; + } catch (e) { + table.setError(e instanceof ApiError ? e.message : "The list could not be read."); + } finally { + table.setBusy(false); + } + }; + + return { + show() { + gate(); + if (!loaded) void load(); + }, + }; +} + +export const views: ViewDef[] = MASTERS.map((m) => { + let mounted: { show(): void } | null = null; + return { + id: m.id, + title: m.title, + group: "Setup", + nav: true, + icon: ICONS[m.id] ?? "logo", + mount(host, ctx) { + mounted = mountMaster(m, host, ctx); + }, + show() { + mounted?.show(); + }, + }; +}); diff --git a/web/src/ui/views/payments.ts b/web/src/ui/views/payments.ts new file mode 100644 index 0000000..a1e2a5e --- /dev/null +++ b/web/src/ui/views/payments.ts @@ -0,0 +1,563 @@ +import { money, parseMoney, qty, today } from "../../engine/format"; +import { ApiError } from "../../engine/index"; +import { + allocatePayment, + cancelPayment, + createPayment, + FAMILIES, + getPayment, + getStockDoc, + listAssetAccounts, + listParties, + listPayments, + openInvoices, + postPayment, + remainder, + stockAction, + updatePayment, + type StockDoc, + type StockKind, + type StockLine, + type AllocationInput, + type OpenInvoice, + type Party, + type PayDir, + type PayFamily, + type Payment, + type PaymentDraft, +} from "../../engine/payments"; +import { delayedIndicator, h, setAttr, setText } from "../dom"; +import { mountTable } from "../parts/table"; +import type { ViewContext, ViewDef } from "../views"; + +const STATUSES = ["", "draft", "posted", "cancelled"]; + +function mountList(dir: PayDir, host: HTMLElement, ctx: ViewContext): (params: URLSearchParams) => void { + const f: PayFamily = FAMILIES[dir]; + const root = h("div", { class: "pay pay--list" }); + const status = h("select", { class: "input pay__status", attrs: { "aria-label": "Status" } }); + for (const v of STATUSES) status.append(h("option", { attrs: { value: v }, text: v ? v.charAt(0).toUpperCase() + v.slice(1) : "All" })); + const add = h("button", { class: "btn btn--primary", attrs: { type: "button" }, text: "New payment" }); + if (!ctx.can(f.draftPerm)) add.hidden = true; + const bar = h("div", { class: "pay__bar" }, status, add); + const tableHost = h("div", { class: "pay__table" }); + root.append(bar, tableHost); + host.append(root); + const form = dir === "in" ? "payment-in" : "payment-out"; + const table = mountTable(tableHost, { + label: dir === "in" ? "Payments received" : "Payments made", + columns: [ + { key: "number", label: "Number", width: "var(--pay-col-number)", text: (p) => p.number ?? "Draft" }, + { key: "date", label: "Date", width: "var(--pay-col-date)", text: (p) => p.date }, + { key: "party", label: dir === "in" ? "Customer" : "Supplier", width: "auto", text: (p) => p.party }, + { key: "status", label: "Status", width: "var(--pay-col-status)", text: (p) => p.status, tone: (p) => p.status }, + { key: "unallocated", label: "Unallocated", width: "var(--pay-col-money)", align: "end", text: (p) => money(p.unallocated) }, + { key: "amount", label: "Amount", width: "var(--pay-col-money)", align: "end", text: (p) => money(p.amount) }, + ], + rowKey: (p) => p.id, + empty: "No payments yet.", + foot: true, + onOpen: (p) => ctx.go(form, { id: p.id }), + }); + let seq = 0; + const load = async () => { + const mine = ++seq; + table.setBusy(true); + try { + const rows = await listPayments(ctx.api, f, status.value); + if (mine !== seq) return; + table.setRows(rows); + table.setError(""); + const total = rows.filter((p) => p.status !== "cancelled").reduce((a, p) => a + p.amount, 0); + table.setFoot({ number: `${rows.length} shown`, amount: money(total) }); + } catch (e) { + if (mine === seq) table.setError(e instanceof Error ? e.message : String(e)); + } finally { + if (mine === seq) table.setBusy(false); + } + }; + status.addEventListener("change", () => { + ctx.go(dir === "in" ? "payments-in" : "payments-out", status.value ? { status: status.value } : {}); + }); + add.addEventListener("click", () => ctx.go(form, { new: "1" })); + return (params) => { + const want = params.get("status") ?? ""; + if (status.value !== want) status.value = STATUSES.includes(want) ? want : ""; + void load(); + }; +} + +function listView(dir: PayDir): ViewDef { + let show: ((p: URLSearchParams) => void) | null = null; + return { + id: dir === "in" ? "payments-in" : "payments-out", + title: dir === "in" ? "Payments received" : "Payments made", + group: dir === "in" ? "Selling" : "Buying", + nav: true, + mount(host, ctx) { + show = mountList(dir, host, ctx); + }, + show(params) { + show?.(params); + }, + }; +} + +interface AllocRow { + el: HTMLTableRowElement; + number: HTMLElement; + date: HTMLElement; + due: HTMLElement; + outstanding: HTMLElement; + done: HTMLElement; + input: HTMLInputElement; +} + +function field(label: string, control: HTMLElement): HTMLElement { + return h("label", { class: "field pay__field" }, h("span", { class: "field__label", text: label }), control); +} + +function mountForm(dir: PayDir, host: HTMLElement, ctx: ViewContext): (params: URLSearchParams) => void { + const f: PayFamily = FAMILIES[dir]; + const formId = dir === "in" ? "payment-in" : "payment-out"; + const party = h("select", { class: "input" }); + party.append(h("option", { attrs: { value: "" }, text: "Choose" })); + const date = h("input", { class: "input", attrs: { type: "date" } }); + const amount = h("input", { class: "input pay__num", attrs: { inputmode: "decimal", autocomplete: "off" } }); + const account = h("select", { class: "input" }); + account.append(h("option", { attrs: { value: "" }, text: dir === "in" ? "Default (1120)" : "Default" })); + const memo = h("input", { class: "input", attrs: { autocomplete: "off" } }); + const number = h("span", { class: "pay__number" }); + const status = h("span", { class: "pay__badge" }); + const head = h("div", { class: "pay__head" }, number, status); + const grid = h( + "div", + { class: "pay__grid" }, + field(dir === "in" ? "Customer" : "Supplier", party), + field("Date", date), + field("Amount", amount), + field(dir === "in" ? "Deposit to" : "Paid from", account), + field("Memo", memo), + ); + const body = h("tbody"); + const table = h( + "table", + { class: "tbl__table pay__alloc", attrs: { "aria-label": "Allocations" } }, + h( + "colgroup", + {}, + h("col", { attrs: { style: "inline-size:var(--pay-col-number)" } }), + h("col", { attrs: { style: "inline-size:var(--pay-col-date)" } }), + h("col", { attrs: { style: "inline-size:var(--pay-col-date)" } }), + h("col", { attrs: { style: "inline-size:var(--pay-col-money)" } }), + h("col", { attrs: { style: "inline-size:var(--pay-col-money)" } }), + h("col", { attrs: { style: "inline-size:var(--pay-col-input)" } }), + ), + h( + "thead", + {}, + h( + "tr", + {}, + h("th", { attrs: { scope: "col" }, text: "Invoice" }), + h("th", { attrs: { scope: "col" }, text: "Date" }), + h("th", { attrs: { scope: "col" }, text: "Due" }), + h("th", { attrs: { scope: "col", "data-align": "end" }, text: "Outstanding" }), + h("th", { attrs: { scope: "col", "data-align": "end" }, text: "Allocated" }), + h("th", { attrs: { scope: "col", "data-align": "end" }, text: "Allocate now" }), + ), + ), + body, + ); + const allocEmpty = h("p", { class: "tbl__empty pay__empty" }); + const remainLabel = h("span", { class: "pay__remain-label", text: "Unallocated" }); + const remainValue = h("span", { class: "pay__remain-value" }); + const remain = h("div", { class: "pay__remain", attrs: { "aria-live": "polite" } }, remainLabel, remainValue); + const allocBox = h("div", { class: "tbl pay__alloc-box" }, table, allocEmpty, remain); + const save = h("button", { class: "btn", attrs: { type: "button" }, text: "Save draft" }); + const post = h("button", { class: "btn btn--primary", attrs: { type: "button" }, text: "Post" }); + const allocate = h("button", { class: "btn", attrs: { type: "button" }, text: "Allocate" }); + const cancel = h("button", { class: "btn btn--quiet", attrs: { type: "button" }, text: "Cancel payment" }); + const actions = h("div", { class: "pay__actions" }, save, post, allocate, cancel); + const error = h("p", { class: "form__error pay__error", attrs: { role: "alert" } }); + const root = h("div", { class: "pay pay--form panel", attrs: { "data-status": "new" } }, head, grid, h("h2", { class: "panel__title pay__sub", text: "Allocation" }), allocBox, error, actions); + host.append(root); + + const rows = new Map(); + const parties = new Map(); + let current: Payment | null = null; + let seq = 0; + let endBusy: (() => void) | null = null; + + const busy = (on: boolean) => { + if (on && !endBusy) endBusy = delayedIndicator(() => setAttr(root, "data-busy", "true"), () => setAttr(root, "data-busy", null)); + else if (!on && endBusy) { + endBusy(); + endBusy = null; + } + }; + + const fail = (e: unknown) => setText(error, e instanceof ApiError || e instanceof Error ? e.message : String(e)); + + const entered = (): Map => { + const out = new Map(); + for (const [id, r] of rows) { + const raw = r.input.value.trim(); + if (!raw) continue; + const v = parseMoney(raw); + setAttr(r.input, "aria-invalid", v === null || v < 0 ? "true" : null); + if (v !== null && v > 0) out.set(id, v); + } + return out; + }; + + const writeRemainder = () => { + const amt = current && current.status !== "draft" ? current.amount : (parseMoney(amount.value.trim()) ?? 0); + const already = current && current.status !== "draft" ? current.allocated : 0; + const left = remainder(amt, already, entered().values()); + setText(remainValue, money(left)); + setAttr(remain, "data-tone", left < 0 ? "bad" : null); + }; + + const makeRow = (id: string): AllocRow => { + const cell = (align?: string) => h("td", align ? { attrs: { "data-align": align } } : {}); + const r: AllocRow = { + el: h("tr", { attrs: { "data-key": id } }), + number: cell(), + date: cell(), + due: cell(), + outstanding: cell("end"), + done: cell("end"), + input: h("input", { class: "input pay__num", attrs: { inputmode: "decimal", autocomplete: "off", "aria-label": "Amount to allocate" } }), + }; + const inputCell = cell("end"); + inputCell.append(r.input); + r.el.append(r.number, r.date, r.due, r.outstanding, r.done, inputCell); + r.input.addEventListener("input", writeRemainder); + return r; + }; + + const setAllocRows = (invoices: OpenInvoice[], p: Payment | null) => { + const done = new Map(); + const names = new Map(); + for (const a of p?.allocations ?? []) { + done.set(a.invoiceId, (done.get(a.invoiceId) ?? 0) + a.amount); + names.set(a.invoiceId, a.invoiceNumber ?? a.invoiceId); + } + const list: OpenInvoice[] = [...invoices]; + for (const [id, amt] of done) { + if (!invoices.some((i) => i.id === id)) list.push({ id, number: names.get(id) ?? id, date: "", dueDate: "", total: amt, outstanding: 0 }); + } + list.sort((a, b) => a.number.localeCompare(b.number)); + const seen = new Set(); + let at: ChildNode | null = body.firstChild; + const editable = !p || p.status === "draft" || (p.status === "posted" && p.unallocated > 0); + for (const inv of list) { + seen.add(inv.id); + let r = rows.get(inv.id); + if (!r) { + r = makeRow(inv.id); + rows.set(inv.id, r); + } + setText(r.number, inv.number); + setText(r.date, inv.date); + setText(r.due, inv.dueDate); + setText(r.outstanding, money(inv.outstanding)); + setText(r.done, done.has(inv.id) ? money(done.get(inv.id) ?? 0) : ""); + r.input.disabled = !editable || inv.outstanding <= 0; + if (r.input.disabled && r.input.value) r.input.value = ""; + if (r.el === at) at = at.nextSibling; + else body.insertBefore(r.el, at); + } + for (const [id, r] of rows) { + if (seen.has(id)) continue; + r.el.remove(); + rows.delete(id); + } + setText(allocEmpty, list.length ? "" : party.value ? "No open invoices for this party." : "Choose a party to see open invoices."); + setAttr(allocBox, "data-empty", list.length ? null : "true"); + writeRemainder(); + }; + + const loadInvoices = async (p: Payment | null) => { + const who = parties.get(party.value); + if (!who) { + setAllocRows([], p); + return; + } + const mine = seq; + try { + const inv = await openInvoices(ctx.api, f, who.id); + if (mine === seq) setAllocRows(inv, p); + } catch (e) { + if (mine === seq) fail(e); + } + }; + + const setButtons = () => { + const st = current?.status ?? "new"; + setAttr(root, "data-status", st); + const draft = st === "new" || st === "draft"; + const canDraft = ctx.can(f.draftPerm); + const canPost = ctx.can(f.postPerm); + save.disabled = !draft || !canDraft; + post.disabled = !draft || !canPost; + allocate.disabled = st !== "posted" || !canPost || (current?.unallocated ?? 0) <= 0; + cancel.disabled = st !== "posted" || !canPost; + save.hidden = !canDraft; + post.hidden = allocate.hidden = cancel.hidden = !canPost; + for (const c of [party, date, amount, account, memo]) c.disabled = !draft || !canDraft; + setText(number, current?.number ?? (current ? "Draft" : "New payment")); + setText(status, st === "new" ? "" : st); + }; + + const fill = (p: Payment | null) => { + current = p; + party.value = p ? (parties.has(p.party) ? p.party : "") : ""; + date.value = p?.date ?? today(); + amount.value = p ? money(p.amount) : ""; + account.value = p?.account ?? ""; + memo.value = p?.memo ?? ""; + for (const r of rows.values()) r.input.value = ""; + setText(error, ""); + setButtons(); + }; + + const draftBody = (): PaymentDraft | null => { + const amt = parseMoney(amount.value.trim()); + if (amt === null || amt <= 0) { + setText(error, "Enter an amount greater than zero."); + return null; + } + return { party: party.value, date: date.value, amount: amt, account: account.value, memo: memo.value.trim() }; + }; + + const allocList = (): AllocationInput[] => [...entered()].map(([invoice, amt]) => ({ invoice, amount: amt })); + + const run = async (step: () => Promise) => { + setText(error, ""); + busy(true); + for (const b of [save, post, allocate, cancel]) b.disabled = true; + try { + const id = await step(); + if (id) { + if (current?.id === id) await open(id); + else ctx.go(formId, { id }); + } + } catch (e) { + fail(e); + setButtons(); + } finally { + busy(false); + } + }; + + const saveDraft = async (): Promise => { + const d = draftBody(); + if (!d) return null; + const p = current ? await updatePayment(ctx.api, f, current.id, d) : await createPayment(ctx.api, f, d); + return p.id; + }; + + save.addEventListener("click", () => void run(saveDraft)); + post.addEventListener("click", () => + void run(async () => { + const allocs = allocList(); + const id = await saveDraft(); + if (!id) return null; + await postPayment(ctx.api, f, id, allocs); + return id; + }), + ); + allocate.addEventListener("click", () => + void run(async () => { + if (!current) return null; + const allocs = allocList(); + if (!allocs.length) { + setText(error, "Enter an amount against at least one invoice."); + return null; + } + await allocatePayment(ctx.api, f, current.id, allocs); + return current.id; + }), + ); + cancel.addEventListener("click", () => + void run(async () => { + if (!current) return null; + await cancelPayment(ctx.api, f, current.id); + return current.id; + }), + ); + amount.addEventListener("input", writeRemainder); + party.addEventListener("change", () => { + seq++; + for (const r of rows.values()) r.input.value = ""; + void loadInvoices(current); + }); + + const ready = (async () => { + const [ps, accts] = await Promise.all([listParties(ctx.api, f), listAssetAccounts(ctx.api)]); + for (const p of ps) { + parties.set(p.code, p); + party.append(h("option", { attrs: { value: p.code }, text: `${p.code} ${p.name}` })); + } + for (const a of accts) account.append(h("option", { attrs: { value: a.code }, text: `${a.code} ${a.name}` })); + })().catch(fail); + + const open = async (id: string | null) => { + const mine = ++seq; + busy(true); + try { + await ready; + const p = id ? await getPayment(ctx.api, f, id) : null; + if (mine !== seq) return; + fill(p); + await loadInvoices(p); + } catch (e) { + if (mine === seq) fail(e); + } finally { + if (mine === seq) busy(false); + } + }; + + return (params) => void open(params.get("id")); +} + +function formView(dir: PayDir): ViewDef { + let show: ((p: URLSearchParams) => void) | null = null; + return { + id: dir === "in" ? "payment-in" : "payment-out", + title: dir === "in" ? "Payment received" : "Payment made", + group: dir === "in" ? "Selling" : "Buying", + nav: false, + mount(host, ctx) { + show = mountForm(dir, host, ctx); + }, + show(params) { + show?.(params); + }, + }; +} + +function mountStock(kind: StockKind, host: HTMLElement, ctx: ViewContext): (params: URLSearchParams) => void { + const perm = "stock.post"; + const number = h("span", { class: "pay__number" }); + const status = h("span", { class: "pay__badge" }); + const value = (label: string) => { + const v = h("span", { class: "pay__value" }); + return { v, el: h("div", { class: "field pay__field" }, h("span", { class: "field__label", text: label }), v) }; + }; + const party = value(kind === "receipt" ? "Supplier" : "Customer"); + const date = value("Date"); + const warehouse = value("Warehouse"); + const memo = value("Memo"); + const root = h("div", { class: "pay pay--stock panel", attrs: { "data-status": "new" } }); + const tableHost = h("div", { class: "pay__table" }); + const post = h("button", { class: "btn btn--primary", attrs: { type: "button" }, text: "Post" }); + const cancel = h("button", { class: "btn btn--quiet", attrs: { type: "button" }, text: "Cancel" }); + const back = h("button", { class: "btn", attrs: { type: "button" }, text: kind === "receipt" ? "All receipts" : "All delivery notes" }); + const error = h("p", { class: "form__error pay__error", attrs: { role: "alert" } }); + root.append( + h("div", { class: "pay__head" }, number, status), + h("div", { class: "pay__grid" }, party.el, date.el, warehouse.el, memo.el), + tableHost, + error, + h("div", { class: "pay__actions" }, post, cancel, back), + ); + host.append(root); + const table = mountTable(tableHost, { + label: "Lines", + columns: [ + { key: "line", label: "#", width: "var(--pay-col-line)", align: "end", text: (l) => String(l.lineNo) }, + { key: "item", label: "Item", width: "var(--pay-col-number)", text: (l) => l.item }, + { key: "description", label: "Description", width: "auto", text: (l) => l.description }, + { key: "qty", label: "Quantity", width: "var(--pay-col-money)", align: "end", text: (l) => qty(l.quantityMilli) }, + { key: "amount", label: kind === "receipt" ? "Amount" : "Value", width: "var(--pay-col-money)", align: "end", text: (l) => money(l.amount) }, + ], + rowKey: (l) => l.id, + empty: "No lines.", + foot: true, + }); + const canPost = ctx.can(perm); + post.hidden = cancel.hidden = !canPost; + let current: StockDoc | null = null; + let seq = 0; + const setButtons = () => { + const st = current?.status ?? ""; + setAttr(root, "data-status", st || "new"); + post.disabled = st !== "draft" || !canPost; + cancel.disabled = st !== "posted" || !canPost; + setText(number, current ? current.number || "Draft" : ""); + setText(status, st); + }; + const open = async (id: string | null) => { + const mine = ++seq; + setText(error, ""); + if (!id) { + current = null; + table.setRows([]); + setButtons(); + setText(error, "No document named in the address."); + return; + } + table.setBusy(true); + try { + const d = await getStockDoc(ctx.api, kind, id); + if (mine !== seq) return; + current = d; + setText(party.v, d.party); + setText(date.v, d.date); + setText(warehouse.v, d.warehouse); + setText(memo.v, d.memo); + table.setRows(d.lines); + table.setFoot({ description: `${d.lines.length} lines`, amount: money(d.total) }); + setButtons(); + } catch (e) { + if (mine === seq) setText(error, e instanceof Error ? e.message : String(e)); + } finally { + if (mine === seq) table.setBusy(false); + } + }; + const act = (action: "post" | "cancel") => async () => { + if (!current) return; + const id = current.id; + post.disabled = cancel.disabled = true; + setText(error, ""); + try { + await stockAction(ctx.api, kind, id, action); + await open(id); + } catch (e) { + setText(error, e instanceof Error ? e.message : String(e)); + setButtons(); + } + }; + post.addEventListener("click", () => void act("post")()); + cancel.addEventListener("click", () => void act("cancel")()); + back.addEventListener("click", () => ctx.go(kind === "receipt" ? "goods-receipts" : "delivery-notes")); + return (params) => void open(params.get("id")); +} + +function stockView(kind: StockKind): ViewDef { + let show: ((p: URLSearchParams) => void) | null = null; + return { + id: kind === "receipt" ? "goods-receipt" : "delivery-note", + title: kind === "receipt" ? "Goods receipt" : "Delivery note", + group: kind === "receipt" ? "Buying" : "Stock", + nav: false, + mount(host, ctx) { + show = mountStock(kind, host, ctx); + }, + show(params) { + show?.(params); + }, + }; +} + +export const views: ViewDef[] = [ + listView("in"), + listView("out"), + formView("in"), + formView("out"), + stockView("delivery"), + stockView("receipt"), +]; diff --git a/web/src/ui/views/statements.ts b/web/src/ui/views/statements.ts new file mode 100644 index 0000000..e435fb9 --- /dev/null +++ b/web/src/ui/views/statements.ts @@ -0,0 +1,220 @@ +import { ApiError } from "../../engine"; +import { money, today } from "../../engine/format"; +import { + balanceSheet, + profitAndLoss, + resultLabel, + yearStart, + type StatementLine, + type StatementSection, +} from "../../engine/statements"; +import { delayedIndicator, h, setAttr, setText } from "../dom"; +import { mountTable, type TableHandle } from "../parts/table"; +import { hashFor, type ViewContext, type ViewDef } from "../views"; + +function goOrRefresh(ctx: ViewContext | null, id: string, params: Record, refresh: () => void): void { + if (location.hash === hashFor(id, params)) refresh(); + else ctx?.go(id, params); +} + +const SVG = "http://www.w3.org/2000/svg"; + +function runIcon(): SVGSVGElement { + const svg = document.createElementNS(SVG, "svg"); + svg.setAttribute("viewBox", "0 0 24 24"); + svg.setAttribute("width", "16"); + svg.setAttribute("height", "16"); + svg.setAttribute("aria-hidden", "true"); + svg.setAttribute("fill", "none"); + svg.setAttribute("stroke", "currentColor"); + svg.setAttribute("stroke-width", "1.75"); + svg.setAttribute("stroke-linecap", "round"); + svg.setAttribute("stroke-linejoin", "round"); + const path = document.createElementNS(SVG, "path"); + path.setAttribute("d", "M4 12a8 8 0 1 0 2.3-5.6M4 4v4h4"); + svg.append(path); + return svg; +} + +interface Section { + table: TableHandle; + title: string; +} + +function mountSection(host: HTMLElement, title: string, span = "in this range"): Section { + const wrap = h("div", { class: "st__section" }, h("h2", { class: "st__heading", text: title })); + host.append(wrap); + const table = mountTable(wrap, { + label: title, + columns: [ + { key: "code", label: "Code", width: "var(--st-code)", text: (r) => r.code }, + { key: "name", label: "Account", width: "auto", text: (r) => r.name }, + { key: "amount", label: "Amount", width: "var(--st-amount)", align: "end", text: (r) => money(r.amount), tone: (r) => (r.amount < 0 ? "danger" : "") }, + ], + rowKey: (r) => r.accountId, + empty: `No ${title.toLowerCase()} ${span}.`, + foot: true, + }); + table.setFoot({ name: `Total ${title.toLowerCase()}`, amount: money(0) }); + return { table, title }; +} + +function fillSection(s: Section, data: StatementSection): void { + s.table.setRows(data.lines); + s.table.setFoot({ name: `Total ${s.title.toLowerCase()}`, amount: money(data.total) }); +} + +interface Shell { + root: HTMLElement; + bar: HTMLFormElement; + status: HTMLElement; + summary: HTMLElement; + sections: HTMLElement; + run: HTMLButtonElement; +} + +function dateField(label: string, input: HTMLInputElement): HTMLElement { + return h("label", { class: "st__field" }, h("span", { class: "st__label", text: label }), input); +} + +function dateInput(name: string): HTMLInputElement { + return h("input", { class: "input st__date", attrs: { type: "date", name, required: "" } }); +} + +function mountShell(host: HTMLElement, fields: HTMLElement[]): Shell { + const run = h("button", { class: "btn btn--primary st__run", attrs: { type: "submit" } }, runIcon(), h("span", { text: "Show" })); + const bar = h("form", { class: "st__bar", attrs: { role: "search" } }, ...fields, run); + const status = h("p", { class: "st__status", attrs: { role: "status", "aria-live": "polite" } }); + const sections = h("div", { class: "st__sections" }); + const summary = h("div", { class: "st__summary" }); + const root = h("div", { class: "st" }, bar, status, sections, summary); + host.append(root); + return { root, bar, status, summary, sections, run }; +} + +function summaryLine(host: HTMLElement, label: string): { label: HTMLElement; value: HTMLElement } { + const l = h("span", { class: "st__sum-label", text: label }); + const v = h("span", { class: "st__sum-value", text: money(0) }); + host.append(h("p", { class: "st__sum" }, l, v)); + return { label: l, value: v }; +} + +function failText(err: unknown): string { + return err instanceof ApiError || err instanceof Error ? err.message : "The statement could not be loaded."; +} + +function runner(shell: Shell, sections: Section[], load: () => Promise): () => void { + let seq = 0; + return () => { + const mine = ++seq; + const stop = delayedIndicator( + () => { + setAttr(shell.root, "aria-busy", "true"); + for (const s of sections) s.table.setBusy(true); + }, + () => { + setAttr(shell.root, "aria-busy", null); + for (const s of sections) s.table.setBusy(false); + }, + ); + load() + .then((line) => { + if (mine !== seq) return; + for (const s of sections) s.table.setError(""); + setText(shell.status, line); + setAttr(shell.status, "data-tone", null); + }) + .catch((err) => { + if (mine !== seq) return; + setText(shell.status, failText(err)); + setAttr(shell.status, "data-tone", "danger"); + }) + .finally(stop); + }; +} + +function profitAndLossView(): ViewDef { + let ctx: ViewContext | null = null; + let refresh: () => void = () => undefined; + const from = dateInput("from"); + const to = dateInput("to"); + return { + id: "profit-and-loss", + title: "Profit and loss", + group: "Ledger", + nav: true, + mount(host, c) { + ctx = c; + const shell = mountShell(host, [dateField("From", from), dateField("To", to)]); + const income = mountSection(shell.sections, "Income"); + const expenses = mountSection(shell.sections, "Expenses"); + const net = summaryLine(shell.summary, "Net profit"); + refresh = runner(shell, [income, expenses], async () => { + if (!ctx) return ""; + const p = await profitAndLoss(ctx.api, from.value, to.value); + fillSection(income, p.income); + fillSection(expenses, p.expenses); + setText(net.label, resultLabel(p.netProfit)); + setText(net.value, money(p.netProfit)); + setAttr(net.value, "data-tone", p.netProfit < 0 ? "danger" : null); + return `From ${p.from} to ${p.to}, posted entries and the reversals of cancelled ones.`; + }); + shell.bar.addEventListener("submit", (e) => { + e.preventDefault(); + goOrRefresh(ctx, "profit-and-loss", { from: from.value, to: to.value }, refresh); + }); + }, + show(params) { + const day = params.get("to") || today(); + to.value = day; + from.value = params.get("from") || yearStart(day); + refresh(); + }, + }; +} + +function balanceSheetView(): ViewDef { + let ctx: ViewContext | null = null; + let refresh: () => void = () => undefined; + const asOf = dateInput("asOf"); + return { + id: "balance-sheet", + title: "Balance sheet", + group: "Ledger", + nav: true, + mount(host, c) { + ctx = c; + const shell = mountShell(host, [dateField("As of", asOf)]); + const assets = mountSection(shell.sections, "Assets", "on this day"); + const liabilities = mountSection(shell.sections, "Liabilities", "on this day"); + const equity = mountSection(shell.sections, "Equity", "on this day"); + const result = summaryLine(shell.summary, "Unclosed result in equity"); + const totalEquity = summaryLine(shell.summary, "Total equity"); + const both = summaryLine(shell.summary, "Total liabilities and equity"); + refresh = runner(shell, [assets, liabilities, equity], async () => { + if (!ctx) return ""; + const b = await balanceSheet(ctx.api, asOf.value); + fillSection(assets, b.assets); + fillSection(liabilities, b.liabilities); + fillSection(equity, b.equity); + setText(result.value, money(b.unclosedResult)); + setText(totalEquity.value, money(b.totalEquity)); + setText(both.value, money(b.totalLiabilitiesAndEquity)); + setAttr(both.value, "data-tone", b.balanced ? null : "danger"); + return b.balanced + ? `As of ${b.asOf}: assets equal liabilities plus equity.` + : `As of ${b.asOf}: assets and liabilities plus equity differ by ${money(b.assets.total - b.totalLiabilitiesAndEquity)}.`; + }); + shell.bar.addEventListener("submit", (e) => { + e.preventDefault(); + goOrRefresh(ctx, "balance-sheet", { asOf: asOf.value }, refresh); + }); + }, + show(params) { + asOf.value = params.get("asOf") || today(); + refresh(); + }, + }; +} + +export const views: ViewDef[] = [profitAndLossView(), balanceSheetView()]; diff --git a/web/vite.config.ts b/web/vite.config.ts index 5cb9e3d..e05ec21 100644 --- a/web/vite.config.ts +++ b/web/vite.config.ts @@ -3,8 +3,8 @@ import { writeFileSync } from "node:fs"; import { resolve } from "node:path"; import { iconSvg, isIconName } from "./src/ui/icons.ts"; -const FRONTEND_PORT = 5340; -const BACKEND = "http://127.0.0.1:8340"; +const FRONTEND_PORT = Number(process.env.FORMLEDGER_UI_PORT ?? 5340); +const BACKEND = `http://127.0.0.1:${Number(process.env.FORMLEDGER_SERVER_PORT ?? 8340)}`; const toBackend = { target: BACKEND,