Component explorer / Application controls
Finance: invoices, accounts and a journal
Post an invoice and watch its journal entry appear and every account balance up the chart change, from one shared store.
A local simulation with sample data: nothing is sent anywhere. Changes last for this visit.
Code for this example
These excerpts come from the code running above, formatted for reading. They focus on the component behaviour; imports, fixtures and page setup are available in Full application source below.
Edit an invoice and its lines as one record
One RecordEdit per invoice holds the header model and the owned lines; it is kept while another invoice is shown, and saves as one deep update.
From apps/showcase/src/examples/finance/finance-invoices.js
// One edit per invoice, kept while another is shown, so a half-finished edit is still there on return.
const stopSelect = effect(() => {
const key = selection.key.value;
if (key === undefined)
return void (current.value = undefined);
let record = records.get(key);
if (!record) {
record = new RecordEdit(ctx, "Invoices", key, {
owned: {
lines: {
positionField: "position", defaults: () => ({
description: "", quantity: "1.00", rate: "0.00"
})
}
}
});
records.set(key, record);
}
note.value = "";
current.value = record;
});
Post an invoice: create the entry, then read the changed accounts
The entry's lines and its posted status are saved in one request. The service recomputes balances; the listener reads each reported account again so every view follows the store.
From apps/showcase/src/examples/finance/finance-service.js
// Balances are the service's to compute, so a write the client never made to an account still
// changes it. The service says which; each is read again into the store, and every view follows.
const reading = new Set();
const stop = mock.onChange(change => {
if (change.set !== "Accounts" || change.kind !== "update")
return;
const read = ctx.reload("Accounts", keyText([Number(change.key)]), "external").finally(() => reading.delete(read));
reading.add(read);
});
/** Resolves once the accounts a write changed have been read again. */
const settled = async () => { while (reading.size)
await Promise.allSettled([...reading]); };
Show the service's roll-up in a tree grid
The grid is configured with a parent field and a currency format. It never sums a child: balance is a server-computed field.
From apps/showcase/src/examples/finance/finance-accounts.js
const view = {
columns: [{
field: "code", width: 150
}, {
field: "name"
}, {
field: "type", width: 130
}, {
field: "balance", width: 170
}],
sort: [{
field: "code"
}],
filters: {},
frozen: 0,
};
const presentation = {
columns: {
balance: {
format: {
kind: "number", style: "currency", currency: "GBP"
}
}
},
rowClass: [{
when: {
field: "postable", op: "eq", value: false
}, class: "account-group"
}],
};
const tree = {
parentField: "parentId", autoOpen: 2
};
const toolbar = {
advanced: false, views: false, columns: false
};
Check debits against credits across the lines
An edit model's rule sees one record, so the entry's totals are computed from the list's rows and block posting.
From apps/showcase/src/examples/finance/finance-journal.js
/** Debits, credits and their difference over the lines as they are now, unsaved edits included. For display: the rule decides nothing here. */
export function entryFigures(record) {
const rows = record.owned.lines.rows.value.filter(row => !row.removing);
let debit = 0n;
let credit = 0n;
for (const row of rows) {
debit += amountOf(row.edit.values.value, "debit");
credit += amountOf(row.edit.values.value, "credit");
}
return {
count: rows.length, debit, credit, difference: debit - credit, balanced: debit === credit && debit > 0n
};
}
Full application source Application code & shared presentation
import "@getaster/elements";
import { effect, signal, untracked } from "@preact/signals-core";
import { html } from "lit-html";
import { mountAccounts } from "./finance-accounts.js";
import { mountInvoices } from "./finance-invoices.js";
import { mountJournal } from "./finance-journal.js";
import { connect } from "./finance-service.js";
const $ = selector => document.querySelector(selector);
const tabs = $("#screens");
try {
const finance = await connect();
const toaster = $("aster-toaster");
const toast = (message, action) => toaster.show(message, action);
const selected = signal("invoices");
const roots = {};
const stops = [];
let journal;
const mount = {
invoices: root => stops.push(mountInvoices(root, finance, { toast, showEntry })),
accounts: root => stops.push(mountAccounts(root, finance)),
journal: root => stops.push((journal = mountJournal(root, finance, { toast })).dispose),
};
// A screen is built the first time its tab shows, and kept: its drafts stay while another screen is open.
const screen = name => {
if (!roots[name]) {
roots[name] = Object.assign(document.createElement("div"), { className: "finance-screen" });
untracked(() => mount[name](roots[name]));
}
return roots[name];
};
function showEntry(key) {
selected.value = "journal";
screen("journal");
journal.show(key);
}
tabs.label = "Finance screens";
tabs.items = [{ value: "invoices", label: "Invoices" }, { value: "accounts", label: "Chart of accounts" }, { value: "journal", label: "Journal" }];
tabs.value = selected;
tabs.renderPanel = item => html`${screen(item.value)}`;
tabs.addEventListener("change", event => { if (event.target === tabs) selected.value = event.detail; });
$("#loading").remove();
// The same store the screens read, for the tests and for poking at from the console.
globalThis.finance = Object.defineProperty(finance, "journal", { get: () => journal });
const stop = effect(() => { document.documentElement.dataset.screen = selected.value; });
addEventListener("pagehide", event => {
if (event.persisted) return;
stop();
stops.forEach(dispose => dispose());
finance.dispose();
});
} catch (error) {
const failure = $("#loading");
failure.setAttribute("role", "alert");
failure.textContent = `The finance workspace could not load: ${error instanceof Error ? error.message : String(error)}. Reload to try again.`;
}
<!doctype html>
<html lang="en"><head><script type="importmap">{"imports":{"@getaster/data":"../lib/aster-ui.js","@getaster/elements":"../lib/aster-ui.js","@getaster/elements-preview":"../lib/aster-ui-preview.js","@getaster/elements-preview/rich-text":"../lib/aster-ui-rich-text.js","@getaster/data-navigator/model":"../lib/aster-data-navigator.js","@getaster/data-navigator":"../lib/aster-data-navigator.js","@getaster/mock":"../lib/aster-ui-mock.js","lit-html":"../lib/aster-ui.js","@preact/signals-core":"../lib/aster-ui.js"}}</script><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Finance workspace — Aster UI</title>
<link id="identity" rel="stylesheet" href="../lib/themes/lamplight.css"><link rel="stylesheet" href="../lib/aster-ui.css">
<link rel="stylesheet" href="./showcase.css"><link rel="stylesheet" href="./finance.css">
</head><body><main>
<header class="finance-intro finance-no-print">
<div>
<h1>Finance workspace</h1>
<p>Post an invoice and watch the ledger follow: its journal entry appears and every account balance up the chart changes. All three screens read one local dataset.</p>
</div>
<div class="finance-appearance"><div class="showcase-appearance"><span>Theme</span><aster-choice id="theme"></aster-choice></div><div class="showcase-appearance"><span>Scheme</span><aster-choice id="scheme"></aster-choice></div></div>
</header>
<p id="loading" role="status">Loading the ledger…</p>
<aster-tabs id="screens"></aster-tabs>
<aster-toaster></aster-toaster>
<script type="module" src="./showcase-nav.js"></script><script type="module" src="./finance.js"></script>
</main></body></html>
// The finance workspace's data: one mock service, one DataContext, and the writes that touch
// several records at once. Every view reads the same store, so a write is seen everywhere.
import { DataContext, RecordEdit, keyText } from "@getaster/data";
import { createMockService } from "@getaster/mock";
import { data, metadata } from "./finance-mock.js";
import { decimalText, percentOf, pence } from "./finance-amounts.js";
/** The accounts an invoice posts to. */
export const postingAccounts = { receivable: "1120", revenue: "4100", salesTax: "2120" };
const today = () => new Date().toISOString().slice(0, 10);
export async function connect() {
const mock = await createMockService({ metadata, data, wasm: new URL("../lib/odata_mock.wasm", import.meta.url) });
const ctx = await DataContext.connect(mock.transport);
// Balances are the service's to compute, so a write the client never made to an account still
// changes it. The service says which; each is read again into the store, and every view follows.
const reading = new Set();
const stop = mock.onChange(change => {
if (change.set !== "Accounts" || change.kind !== "update") return;
const read = ctx.reload("Accounts", keyText([Number(change.key)]), "external").finally(() => reading.delete(read));
reading.add(read);
});
/** Resolves once the accounts a write changed have been read again. */
const settled = async () => { while (reading.size) await Promise.allSettled([...reading]); };
const load = async options => {
const collection = ctx.collection(options);
await collection.loadAll();
return collection;
};
const accounts = await load({ set: "Accounts", orderBy: [{ field: "code" }] });
const customers = await load({ set: "Customers", orderBy: [{ field: "name" }] });
const invoices = await load({ set: "Invoices", orderBy: [{ field: "issueDate", descending: true }, { field: "id", descending: true }] });
const entries = await load({ set: "JournalEntries", orderBy: [{ field: "date", descending: true }, { field: "id", descending: true }] });
const accountByCode = code => accounts.items.value.find(account => account.code === code);
const entryLines = { defaults: () => ({ description: null, debit: "0.00", credit: "0.00" }) };
function nextReference() {
const used = entries.items.value.map(entry => Number(/(\d+)$/.exec(String(entry.reference))?.[1] ?? 0));
return `JE-${String(Math.max(0, ...used) + 1).padStart(4, "0")}`;
}
/** A draft entry with no lines. Resolves to its key. */
async function createEntry(values = {}) {
const saved = await ctx.create("JournalEntries", { reference: nextReference(), date: today(), memo: "New journal entry", status: "draft", invoiceId: null, ...values });
return saved.key;
}
/** The entry for an invoice: receivable for the total, revenue for the subtotal and sales tax for the tax. */
async function postInvoice(invoice) {
const saved = ctx.collection({ set: "InvoiceLines", filter: { op: "eq", field: "invoiceId", value: invoice.id } });
await saved.loadAll();
const subtotal = saved.items.value.reduce((sum, line) => sum + pence(String(line.amount)), 0n);
ctx.release(saved);
const tax = percentOf(subtotal, String(invoice.taxRate));
const key = await createEntry({ memo: `Invoice ${invoice.number}`, invoiceId: invoice.id });
const entry = new RecordEdit(ctx, "JournalEntries", key, { owned: { lines: entryLines } });
try {
await entry.ready;
const description = `Invoice ${invoice.number}`;
const add = (code, debit, credit) => entry.owned.lines.add({ accountId: accountByCode(code).id, description, debit: decimalText(debit), credit: decimalText(credit) });
add(postingAccounts.receivable, subtotal + tax, 0n);
add(postingAccounts.revenue, 0n, subtotal);
if (tax > 0n) add(postingAccounts.salesTax, 0n, tax);
entry.edit.set("status", "posted");
const result = await entry.save();
if (!result?.ok) throw new Error("The journal entry wasn't accepted.");
await ctx.update("Invoices", keyText([invoice.id]), { entryId: ctx.store.get("JournalEntries", key).entity.id });
} catch (error) {
await ctx.remove("JournalEntries", key).catch(() => {});
throw error;
} finally {
entry.dispose();
}
await settled();
return key;
}
/** Takes an invoice's entry back out of the ledger. */
async function unpostInvoice(invoice, entryKey) {
await ctx.update("Invoices", keyText([invoice.id]), { entryId: null });
await ctx.remove("JournalEntries", entryKey);
await settled();
}
/**
* Posts a draft entry whose lines are in `entry` (a RecordEdit) as one request. A refusal leaves the
* status set and the failure showing on the record, so the lines can be fixed and the post tried again.
*/
async function postEntry(entry) {
entry.edit.set("status", "posted");
const result = await entry.save();
await settled();
return result;
}
const setEntryStatus = async (key, status) => {
await ctx.update("JournalEntries", key, { status });
await settled();
};
return {
mock, ctx, accounts, customers, invoices, entries, entryLines, settled, accountByCode, createEntry, postInvoice, unpostInvoice, postEntry, setEntryStatus,
dispose: () => { stop(); [accounts, customers, invoices, entries].forEach(collection => ctx.release(collection)); },
};
}
// The invoice viewer: a list of invoices and, for the one chosen, its details as a form and the
// document itself. Editing the form or the lines updates the document as it is typed.
import { RecordEdit, Selection, keyText } from "@getaster/data";
import { formatDate, formatFigure } from "@getaster/elements";
import { computed, effect, signal } from "@preact/signals-core";
import { html, nothing, render } from "lit-html";
import { seller } from "./finance-mock.js";
import { GBP, lineAmount, pounds, percentOf, pence } from "./finance-amounts.js";
const STATUS = { paid: ["Paid", "positive"], pending: ["Pending", "caution"], overdue: ["Overdue", "negative"] };
export const statusView = status => {
const [label, tone] = STATUS[status] ?? [String(status ?? ""), undefined];
return html`<span class="aster-status" data-tone=${tone ?? nothing}>${label}</span>`;
};
export function mountInvoices(root, finance, { toast, showEntry }) {
const { ctx, invoices, customers } = finance;
const selection = new Selection(ctx.store, invoices);
const records = new Map();
const current = signal(undefined);
const busy = signal(false);
const note = signal("");
// One edit per invoice, kept while another is shown, so a half-finished edit is still there on return.
const stopSelect = effect(() => {
const key = selection.key.value;
if (key === undefined) return void (current.value = undefined);
let record = records.get(key);
if (!record) {
record = new RecordEdit(ctx, "Invoices", key, { owned: { lines: { positionField: "position", defaults: () => ({ description: "", quantity: "1.00", rate: "0.00" }) } } });
records.set(key, record);
}
note.value = "";
current.value = record;
});
const customerOf = id => customers.items.value.find(customer => customer.id === id);
const lineTotals = (record, values) => {
const rows = record.owned.lines.rows.value.filter(row => !row.removing);
const subtotal = rows.reduce((sum, row) => sum + lineAmount(String(row.edit.values.value.quantity ?? "0"), String(row.edit.values.value.rate ?? "0")), 0n);
const tax = percentOf(subtotal, String(values.taxRate ?? "0"));
return { count: rows.length, subtotal, tax, total: subtotal + tax };
};
// The line editor is made once; the record it edits changes.
const editor = document.createElement("aster-list-editor");
editor.editing = "row";
editor.addLabel = "Add line";
editor.empty = html`<p class="finance-empty">No lines yet. Add the first one.</p>`;
// One line of cells, so the editor stacks them on a narrow screen instead of dropping or scrolling any.
editor.layout = [[
{ field: "description", width: "minmax(10rem, 1fr)" },
{ field: "quantity", width: "5.5rem", format: { maximumFractionDigits: 2 } },
{ field: "rate", width: "7.5rem", format: GBP },
// The amount is the service's, but it is shown from the typed quantity and rate so it follows an edit before saving.
{ field: "amount", width: "8rem", format: GBP, display: row => pounds(lineAmount(String(row.edit.values.value.quantity ?? "0"), String(row.edit.values.value.rate ?? "0"))) },
]];
async function save(record) {
busy.value = true;
note.value = "";
try {
const result = await record.save();
if (result && !result.ok) note.value = "The invoice wasn't saved. Check the fields marked in the form.";
if (!result && !record.valid.value) {
record.problems();
note.value = "Some fields need attention before the invoice can be saved.";
}
} finally {
busy.value = false;
}
}
async function post(record) {
busy.value = true;
note.value = "";
try {
const invoice = ctx.store.get("Invoices", record.key).entity;
const entryKey = await finance.postInvoice(invoice);
const reference = ctx.store.get("JournalEntries", entryKey).entity.reference;
toast(`Posted ${invoice.number} as ${reference}`, { label: "Undo", run: () => void undo(invoice, entryKey) });
} catch (error) {
note.value = `The invoice wasn't posted: ${error instanceof Error ? error.message : String(error)}`;
} finally {
busy.value = false;
}
}
async function undo(invoice, entryKey) {
try {
await finance.unpostInvoice(invoice, entryKey);
toast(`${invoice.number} is back out of the ledger`);
} catch (error) {
note.value = `The posting wasn't undone: ${error instanceof Error ? error.message : String(error)}`;
}
}
const row = invoice => html`<span class="invoice-row">
<strong>${invoice.number}</strong><span class="invoice-row-who">${customerOf(invoice.customerId)?.name ?? ""}</span>
<span class="invoice-row-due">Due ${formatDate(String(invoice.dueDate))}</span><span class="invoice-row-status">${statusView(invoice.status)}</span></span>`;
// A posted invoice keeps its figures; only its payment status still changes.
const sections = [{
title: "Invoice details", columns: 3,
items: [
"number", { field: "customerId", options: customers }, "status",
"issueDate", "dueDate", "taxRate", { field: "reference", span: 3 },
],
}];
const postedSections = sections.map(section => ({
...section,
items: section.items.map(item => {
const field = typeof item === "string" ? { field: item } : item;
return { ...field, readOnly: field.field !== "status" };
}),
}));
const party = (heading, name, lines) => html`<section class="paper-party" aria-label=${heading}>
<h3>${heading}</h3><address><strong>${name}</strong>${lines.map(line => html`<span>${line}</span>`)}</address></section>`;
function document_(record) {
const values = record.edit.values.value;
const customer = customerOf(values.customerId);
const posted = values.entryId !== null && values.entryId !== undefined;
const totals = lineTotals(record, values);
const entry = posted ? ctx.store.get("JournalEntries", keyText([values.entryId]))?.entity : undefined;
const reason = posted ? `Already posted as ${entry?.reference ?? "a journal entry"}.`
: record.dirty.value ? "Save or revert your changes before posting."
: totals.count === 0 ? "Add at least one line before posting."
: !record.valid.value ? "Fix the fields marked in the form first."
: undefined;
editor.list = record.owned.lines;
editor.label = `Lines of ${values.number ?? "the invoice"}`;
editor.readOnlyReason = posted ? "Posted invoices can't be edited; their journal entry has booked these amounts." : undefined;
return html`<div class="invoice-document">
<aster-form class="finance-no-print" .model=${record.edit} .sections=${posted ? postedSections : sections} .headingLevel=${3}></aster-form>
<article class="paper" aria-labelledby="paper-title">
<header class="paper-head">
<div><p class="finance-eyebrow">Invoice</p><h2 id="paper-title">${values.number ?? ""}</h2></div>
${statusView(values.status)}
</header>
<div class="paper-parties">
${party("From", seller.name, [...seller.address, seller.email, `Tax no. ${seller.taxNumber}`])}
${party("Bill to", customer?.name ?? "No customer chosen", customer ? [...String(customer.address).split(", "), customer.email] : [])}
</div>
<dl class="paper-terms">
<div><dt>Issued</dt><dd>${values.issueDate ? formatDate(String(values.issueDate)) : "—"}</dd></div>
<div><dt>Due</dt><dd>${values.dueDate ? formatDate(String(values.dueDate)) : "—"}</dd></div>
<div><dt>Your reference</dt><dd>${values.reference || "—"}</dd></div>
</dl>
<div class="paper-lines">${editor}</div>
<dl class="paper-totals">
<div><dt>Subtotal</dt><dd class="finance-num">${pounds(totals.subtotal)}</dd></div>
<div><dt>Tax at ${formatFigure(String(values.taxRate ?? 0), { maximumFractionDigits: 2 })}%</dt><dd class="finance-num">${pounds(totals.tax)}</dd></div>
<div class="paper-total"><dt>Total due</dt><dd class="finance-num">${pounds(totals.total)}</dd></div>
</dl>
<footer class="paper-foot"><p>Pay by bank transfer: ${seller.payment}</p><p>Please quote ${values.number ?? "the invoice number"}.</p></footer>
</article>
<div class="finance-actions finance-no-print">
<aster-button .label=${"Save changes"} .variant=${"primary"} .busy=${busy.value} .reason=${record.dirty.value ? undefined : "No changes to save."} @click=${() => void save(record)}></aster-button>
<aster-button .label=${"Revert"} .reason=${record.dirty.value ? undefined : "No changes to revert."} @click=${() => record.revert()}></aster-button>
<aster-button .label=${"Post to ledger"} .busy=${busy.value} .reason=${reason} data-action="post-invoice" @click=${() => void post(record)}></aster-button>
<aster-button .label=${"Print"} @click=${() => window.print()}></aster-button>
${posted && entry ? html`<span class="finance-posted">Posted as <a href="#journal" @click=${event => { event.preventDefault(); showEntry(keyText([values.entryId])); }}>${entry.reference}</a></span>` : nothing}
<span class="finance-note" role="status">${note.value}</span>
</div>
</div>`;
}
const stopRender = effect(() => {
const record = current.value;
render(html`<div class="finance-split">
<aside class="finance-list finance-no-print" aria-label="Invoices">
<h2>Invoices</h2>
<aster-listbox .label=${"Invoices"} .selection=${selection} .renderRow=${row}></aster-listbox>
</aside>
<section class="finance-detail" aria-label="Invoice">${record ? document_(record) : nothing}</section>
</div>`, root);
});
return () => {
stopSelect();
stopRender();
records.forEach(record => record.dispose());
};
}
// The chart of accounts: a tree grid whose balances are the service's own roll-up of posted journal
// lines. Nothing here totals a child; a posting elsewhere changes the rows when the service says so.
import { effect } from "@preact/signals-core";
import { html, render } from "lit-html";
import { pounds, pence } from "./finance-amounts.js";
const view = {
columns: [{ field: "code", width: 150 }, { field: "name" }, { field: "type", width: 130 }, { field: "balance", width: 170 }],
sort: [{ field: "code" }],
filters: {},
frozen: 0,
};
const presentation = {
columns: { balance: { format: { kind: "number", style: "currency", currency: "GBP" } } },
rowClass: [{ when: { field: "postable", op: "eq", value: false }, class: "account-group" }],
};
const tree = { parentField: "parentId", autoOpen: 2 };
const toolbar = { advanced: false, views: false, columns: false };
export function mountAccounts(root, finance) {
const { ctx, accounts } = finance;
const total = type => accounts.items.value.filter(account => account.parentId === null && account.type === type).reduce((sum, account) => sum + pence(String(account.balance)), 0n);
const stop = effect(() => {
const figures = ["asset", "liability", "equity", "revenue", "expense"].map(type => [type, total(type)]);
const [assets, liabilities, equity, revenue, expenses] = figures.map(([, amount]) => amount);
const profit = revenue - expenses;
const balanced = assets === liabilities + equity + profit;
render(html`<div class="finance-accounts">
<dl class="aster-ledger finance-ledger">
${[["Assets", assets], ["Liabilities", liabilities], ["Equity", equity], ["Revenue", revenue], ["Expenses", expenses]].map(([title, amount]) => html`
<div class="aster-figure"><dt>${title}</dt><dd><span class="aster-big finance-figure" data-figure=${String(title).toLowerCase()}>${pounds(amount)}</span></dd></div>`)}
</dl>
<p class="finance-balance" data-state=${balanced ? "balanced" : "out"} role="status">
<span aria-hidden="true">${balanced ? "✓" : "!"}</span>
${balanced ? "The books balance: assets equal liabilities, equity and profit." : "The books are out of balance."}</p>
<aster-grid class="finance-grid" .ctx=${ctx} .set=${"Accounts"} .label=${"Chart of accounts"} .view=${view} .tree=${tree}
.presentation=${presentation} .toolbar=${toolbar}></aster-grid>
<p class="finance-hint">Each balance is computed by the service: the posted debits less credits on an account and everything under it, shown on its normal side. Drafts don't count.</p>
</div>`, root);
});
return stop;
}
// The journal: entries with their lines, a tree picker over the chart per line, running totals, and the entry's
// own rule: a posted entry has two lines and equal debits and credits. The service publishes that rule; the
// record judges it live over the lines being edited, and says why Post is unavailable.
import { RecordEdit, Selection } from "@getaster/data";
import { TreeChoices, formatDate } from "@getaster/elements";
import { effect, signal } from "@preact/signals-core";
import { html, nothing, render } from "lit-html";
import { GBP, pounds, pence } from "./finance-amounts.js";
// The summary takes focus when a save fails on the entry's rule, as it would for a field.
const formChrome = { autoFocus: true };
const sections = [{ title: "Entry", columns: 3, items: ["reference", "date", "memo"] }];
const readOnly = { readOnly: true };
const none = {};
const amountOf = (values, field) => pence(String(values[field] ?? "0"));
// A journal leaves the side a line does not use blank where it reads as text; the inputs keep their figure.
const blankZero = (values, field) => (amountOf(values, field) === 0n ? "" : pounds(amountOf(values, field)));
// What one line can say for itself. The totals below are across lines, so they aren't a rule.
const eitherSide = values => ({
credit: amountOf(values, "debit") > 0n && amountOf(values, "credit") > 0n ? "A line is a debit or a credit, not both." : undefined,
debit: amountOf(values, "debit") === 0n && amountOf(values, "credit") === 0n ? "Enter a debit or a credit." : undefined,
});
export const entryStatus = status => html`<span class="aster-status" data-tone=${status === "posted" ? "positive" : nothing}>${status === "posted" ? "Posted" : "Draft"}</span>`;
/** Debits, credits and their difference over the lines as they are now, unsaved edits included. For display: the rule decides nothing here. */
export function entryFigures(record) {
const rows = record.owned.lines.rows.value.filter(row => !row.removing);
let debit = 0n;
let credit = 0n;
for (const row of rows) {
debit += amountOf(row.edit.values.value, "debit");
credit += amountOf(row.edit.values.value, "credit");
}
return { count: rows.length, debit, credit, difference: debit - credit, balanced: debit === credit && debit > 0n };
}
export function mountJournal(root, finance, { toast }) {
const { ctx, entries } = finance;
const selection = new Selection(ctx.store, entries);
const records = new Map();
const current = signal(undefined);
const busy = signal(false);
const note = signal("");
// The chart as accountants read it, with only the accounts that take postings chosen; the groups stay open to browse.
const choices = new TreeChoices(ctx, {
set: "Accounts", parentField: "parentId", orderBy: [{ field: "code" }],
display: "label", searchFields: ["code", "name"], choosable: account => account.postable === true,
});
const stopSelect = effect(() => {
const key = selection.key.value;
if (key === undefined) return void (current.value = undefined);
let record = records.get(key);
if (!record) {
record = new RecordEdit(ctx, "JournalEntries", key, { owned: { lines: { ...finance.entryLines, rules: [eitherSide] } } });
records.set(key, record);
}
note.value = "";
current.value = record;
});
const editor = document.createElement("aster-list-editor");
editor.addLabel = "Add line";
editor.empty = html`<p class="finance-empty">No lines yet. Add a debit and a credit.</p>`;
editor.columns = [
{ field: "accountId", width: "minmax(11rem, 2fr)", options: choices },
{ field: "description", width: "minmax(8rem, 2fr)" },
{ field: "debit", width: "8.5rem", format: GBP, display: row => blankZero(row.edit.values.value, "debit") },
{ field: "credit", width: "8.5rem", format: GBP, display: row => blankZero(row.edit.values.value, "credit") },
];
// Why Post is unavailable: the entry is posted, a field or line is invalid, or the entry's rule would fail once posted.
function why(record, posted) {
if (posted) return "Already posted.";
if (!record.valid.value) return "Fix the lines marked first.";
return record.explain({ status: "posted" })[0]?.message;
}
async function save(record) {
busy.value = true;
note.value = "";
try {
// A draft is saved as a draft: a post that was refused left the status set.
record.edit.set("status", record.edit.baseline.value.status);
const result = await record.save();
if (!result) {
record.problems();
note.value = "Fix the fields marked before saving.";
} else if (!result.ok) note.value = "The entry wasn't saved.";
} finally {
busy.value = false;
}
}
async function post(record) {
busy.value = true;
note.value = "";
try {
const reference = record.edit.values.value.reference;
const key = record.key;
const result = await finance.postEntry(record);
if (!result?.ok) {
note.value = "The entry wasn't posted.";
return;
}
toast(`Posted ${reference}`, { label: "Undo", run: () => void finance.setEntryStatus(key, "draft").then(() => toast(`${reference} is a draft again`)) });
} catch (error) {
note.value = `The entry wasn't posted: ${error instanceof Error ? error.message : String(error)}`;
} finally {
busy.value = false;
}
}
async function create() {
busy.value = true;
try {
selection.select(await finance.createEntry());
} finally {
busy.value = false;
}
}
const row = entry => html`<span class="invoice-row">
<strong>${entry.reference}</strong><span class="invoice-row-who">${entry.memo}</span>
<span class="invoice-row-due">${formatDate(String(entry.date))}</span><span class="invoice-row-status">${entryStatus(entry.status)}</span></span>`;
function detail(record) {
const values = record.edit.values.value;
// Posted as saved: a post in flight (the status set, not yet accepted) leaves the lines open, so a refusal can be fixed.
const posted = record.edit.baseline.value.status === "posted";
const figures = entryFigures(record);
const reason = why(record, posted);
editor.list = record.owned.lines;
editor.label = `Lines of ${values.reference ?? "the entry"}`;
editor.readOnlyReason = posted ? "Posted entries can't be changed." : undefined;
const side = figures.difference > 0n ? "Debits exceed credits" : "Credits exceed debits";
const state = figures.count === 0 ? "empty" : figures.balanced ? "balanced" : "out";
return html`<div class="journal-entry">
<header class="journal-head"><h2>${values.reference ?? ""}</h2>${entryStatus(record.edit.baseline.value.status)}
${values.invoiceId ? html`<span class="finance-hint">Booked from an invoice</span>` : nothing}</header>
<aster-form class="finance-no-print" .model=${record.edit} .sections=${sections} .chrome=${formChrome} .headingLevel=${3} .policy=${posted ? readOnly : none}></aster-form>
<div class="journal-lines">${editor}</div>
<div class="journal-totals" role="group" aria-label="Totals">
<span class="journal-totals-label">Totals</span>
<span class="finance-num" data-total="debit"><span class="finance-sr">Debits </span>${pounds(figures.debit)}</span>
<span class="finance-num" data-total="credit"><span class="finance-sr">Credits </span>${pounds(figures.credit)}</span>
</div>
<p class="finance-balance" data-state=${state} role="status">
<span aria-hidden="true">${state === "balanced" ? "✓" : "!"}</span>
${state === "balanced" ? "Balanced: debits equal credits."
: state === "empty" ? "No lines yet."
: `Out of balance by ${pounds(figures.difference < 0n ? -figures.difference : figures.difference)}. ${side}.`}</p>
<div class="finance-actions finance-no-print">
<aster-button .label=${"Post entry"} .variant=${"primary"} .busy=${busy.value} .reason=${reason} data-action="post-entry" @click=${() => void post(record)}></aster-button>
<aster-button .label=${"Save draft"} .busy=${busy.value} .reason=${posted ? "Posted entries can't be changed." : record.dirty.value ? undefined : "No changes to save."} @click=${() => void save(record)}></aster-button>
<aster-button .label=${"Revert"} .reason=${record.dirty.value ? undefined : "No changes to revert."} @click=${() => record.revert()}></aster-button>
<span class="finance-note" role="status">${note.value}</span>
</div>
</div>`;
}
const stopRender = effect(() => {
const record = current.value;
render(html`<div class="finance-split">
<aside class="finance-list" aria-label="Journal entries">
<div class="finance-list-head"><h2>Entries</h2><aster-button .label=${"New entry"} .busy=${busy.value} @click=${() => void create()}></aster-button></div>
<aster-listbox .label=${"Journal entries"} .selection=${selection} .renderRow=${row}></aster-listbox>
</aside>
<section class="finance-detail" aria-label="Journal entry">${record ? detail(record) : nothing}</section>
</div>`, root);
});
return {
show: key => selection.select(key),
/** Runs the Post button's handler on the entry being edited; the button itself stays disabled while the rule would fail, so the tests use this to send a post the service refuses. */
post: () => (current.peek() ? post(current.peek()) : undefined),
dispose: () => {
stopSelect();
stopRender();
records.forEach(record => record.dispose());
},
};
}
// The finance service: its $metadata and a seed. Account balances and invoice line amounts are
// server-computed: the mock's Aster.Mock.V1 annotations stand in for the views a real service keeps.
const CORE = "Org.OData.Core.V1";
const Core = (term, value) => ({ [`@${CORE}.${term}`]: value });
const sums = (title, extra = {}) => ({ "@Org.OData.Core.V1.Description": title, ...extra });
const money = (title, extra = {}) => ({ $Type: "Edm.Decimal", $Precision: 14, $Scale: 2, ...sums(title), ...extra });
const choice = (title, values) => ({ ...sums(title), "@Org.OData.Validation.V1.AllowedValues": values.map(([Value, label]) => ({ Value, "@Org.OData.Core.V1.Description": label })) });
const key = { $Type: "Edm.Int32", ...Core("Computed", true) };
const include = (Namespace, Alias) => ({ $Include: [{ $Namespace: Namespace, $Alias: Alias }] });
// The totals of a column over an entry's lines, as the service publishes an aggregate.
const entryTotal = field => ({ $Apply: [{ $NavigationPropertyPath: "lines" }, { $PropertyPath: field }], $Function: "AsterData.Sum" });
export const metadata = {
$Version: "4.01",
$EntityContainer: "Finance.Container",
$Reference: {
"https://oasis-tcs.github.io/odata-vocabularies/vocabularies/Org.OData.Core.V1.json": include(CORE, "Core"),
"https://oasis-tcs.github.io/odata-vocabularies/vocabularies/Org.OData.Validation.V1.json": include("Org.OData.Validation.V1", "Validation"),
"https://aster.dev/vocabularies/Aster.Data.V1.json": include("Aster.Data.V1", "AsterData"),
},
Finance: {
Account: {
$Kind: "EntityType", $Key: ["id"], ...sums("Account", { "@AsterData.PluralTitle": "Accounts", "@AsterData.TitleField": "name" }),
id: key,
code: { $MaxLength: 10, ...sums("Code", { "@AsterData.MinLength": 1 }) },
name: { $MaxLength: 80, ...sums("Account", { "@AsterData.MinLength": 1 }) },
// Server-computed: how accountants name an account.
label: { $MaxLength: 100, ...sums("Account", { ...Core("Computed", true), "@Aster.Mock.V1.Concat": ["code", "name"] }) },
type: choice("Type", [["asset", "Asset"], ["liability", "Liability"], ["equity", "Equity"], ["revenue", "Revenue"], ["expense", "Expense"]]),
parentId: { $Type: "Edm.Int32", $Nullable: true, ...sums("Parent account") },
postable: { $Type: "Edm.Boolean", ...sums("Accepts postings") },
parent: { $Kind: "NavigationProperty", $Type: "Finance.Account", $Nullable: true, $ReferentialConstraint: { parentId: "id" }, "@AsterData.DisplayField": "name" },
// A server-computed field: the posted debits less credits of the account and every account under it,
// taken on the account's normal side.
balance: money("Balance", {
...Core("Computed", true),
"@Aster.Mock.V1.Rollup": {
Parent: "parentId", Lines: "JournalLines", Account: "accountId", Debit: "debit", Credit: "credit",
Entry: { Property: "entryId", Set: "JournalEntries", Status: "status", Value: "posted" },
Negate: { Property: "type", Values: ["liability", "equity", "revenue"] },
},
}),
},
JournalEntry: {
$Kind: "EntityType", $Key: ["id"], ...sums("Journal entry", { "@AsterData.PluralTitle": "Journal entries", "@AsterData.TitleField": "reference" }),
id: key,
reference: { $MaxLength: 20, ...sums("Reference", { "@AsterData.MinLength": 1 }) },
date: { $Type: "Edm.Date", ...sums("Date") },
memo: { $MaxLength: 200, ...sums("Memo", { "@AsterData.MinLength": 1 }) },
status: choice("Status", [["draft", "Draft"], ["posted", "Posted"]]),
invoiceId: { $Type: "Edm.Int32", $Nullable: true, ...sums("Invoice") },
lines: { $Kind: "NavigationProperty", $Type: "Finance.JournalLine", $Collection: true, $Partner: "entry", "@AsterData.Owned": true },
// A draft may be anything; a posted entry has two lines and equal debits and credits. The service judges
// it on the lines a write leaves; the client judges the same condition live over the lines being edited.
// status ne 'posted' or (lines/$count ge 2 and Sum(lines, debit) eq Sum(lines, credit))
"@Org.OData.Validation.V1.Constraint#EntryBalances": {
Condition: {
$Or: [
{ $Ne: [{ $Path: "status" }, "posted"] },
{ $And: [{ $Ge: [{ $Path: "lines/$count" }, 2] }, { $Eq: [entryTotal("debit"), entryTotal("credit")] }] },
],
},
FailureMessage: "An entry needs two lines and equal debits and credits to be posted.",
},
},
JournalLine: {
$Kind: "EntityType", $Key: ["id"], ...sums("Journal line", { "@AsterData.PluralTitle": "Journal lines", "@AsterData.TitleField": "description" }),
id: key,
entryId: { $Type: "Edm.Int32", ...sums("Entry") },
entry: { $Kind: "NavigationProperty", $Type: "Finance.JournalEntry", $Partner: "lines", $ReferentialConstraint: { entryId: "id" } },
accountId: { $Type: "Edm.Int32", ...sums("Account") },
account: { $Kind: "NavigationProperty", $Type: "Finance.Account", $ReferentialConstraint: { accountId: "id" }, "@AsterData.DisplayField": "name" },
description: { $Nullable: true, $MaxLength: 200, ...sums("Description", { "@AsterData.EmptyAsNull": true }) },
debit: money("Debit", { "@Org.OData.Validation.V1.Minimum": "0" }),
credit: money("Credit", { "@Org.OData.Validation.V1.Minimum": "0" }),
},
Customer: {
$Kind: "EntityType", $Key: ["id"], ...sums("Customer", { "@AsterData.PluralTitle": "Customers", "@AsterData.TitleField": "name" }),
id: key,
name: { $MaxLength: 80, ...sums("Customer", { "@AsterData.MinLength": 1 }) },
address: { $MaxLength: 200, ...sums("Address") },
email: { $MaxLength: 120, ...sums("Email") },
},
Invoice: {
$Kind: "EntityType", $Key: ["id"], ...sums("Invoice", { "@AsterData.PluralTitle": "Invoices", "@AsterData.TitleField": "number" }),
id: key,
number: { $MaxLength: 20, ...sums("Invoice number", { "@AsterData.MinLength": 1 }) },
customerId: { $Type: "Edm.Int32", ...sums("Bill to") },
customer: { $Kind: "NavigationProperty", $Type: "Finance.Customer", $ReferentialConstraint: { customerId: "id" }, "@AsterData.DisplayField": "name" },
issueDate: { $Type: "Edm.Date", ...sums("Issued") },
dueDate: { $Type: "Edm.Date", ...sums("Due") },
status: choice("Status", [["pending", "Pending"], ["paid", "Paid"], ["overdue", "Overdue"]]),
taxRate: { $Type: "Edm.Decimal", $Precision: 5, $Scale: 2, ...sums("Tax rate (%)", { "@Org.OData.Validation.V1.Minimum": "0", "@Org.OData.Validation.V1.Maximum": "100" }) },
reference: { $Nullable: true, $MaxLength: 60, ...sums("Customer reference", { "@AsterData.EmptyAsNull": true }) },
entryId: { $Type: "Edm.Int32", $Nullable: true, ...sums("Journal entry") },
lines: { $Kind: "NavigationProperty", $Type: "Finance.InvoiceLine", $Collection: true, $Partner: "invoice", "@AsterData.Owned": true },
},
InvoiceLine: {
$Kind: "EntityType", $Key: ["id"], ...sums("Invoice line", { "@AsterData.PluralTitle": "Invoice lines", "@AsterData.TitleField": "description" }),
id: key,
invoiceId: { $Type: "Edm.Int32", ...sums("Invoice") },
invoice: { $Kind: "NavigationProperty", $Type: "Finance.Invoice", $Partner: "lines", $ReferentialConstraint: { invoiceId: "id" } },
position: { $Type: "Edm.Int32", ...sums("Position") },
description: { $MaxLength: 200, ...sums("Description", { "@AsterData.MinLength": 1 }) },
quantity: { $Type: "Edm.Decimal", $Precision: 10, $Scale: 2, ...sums("Qty", { "@Org.OData.Validation.V1.Minimum": "0" }) },
rate: money("Rate", { "@Org.OData.Validation.V1.Minimum": "0" }),
amount: money("Amount", { ...Core("Computed", true), "@Aster.Mock.V1.Product": ["quantity", "rate"] }),
},
Container: {
$Kind: "EntityContainer",
Accounts: { $Collection: true, $Type: "Finance.Account", $NavigationPropertyBinding: { parent: "Accounts" } },
JournalEntries: { $Collection: true, $Type: "Finance.JournalEntry", $NavigationPropertyBinding: { lines: "JournalLines" } },
JournalLines: { $Collection: true, $Type: "Finance.JournalLine", $NavigationPropertyBinding: { entry: "JournalEntries", account: "Accounts" } },
Customers: { $Collection: true, $Type: "Finance.Customer" },
Invoices: { $Collection: true, $Type: "Finance.Invoice", $NavigationPropertyBinding: { customer: "Customers", lines: "InvoiceLines" } },
InvoiceLines: { $Collection: true, $Type: "Finance.InvoiceLine", $NavigationPropertyBinding: { invoice: "Invoices" } },
},
},
};
// [id, code, name, type, parent code]
const chart = [
[1, "1000", "Assets", "asset", null],
[2, "1100", "Current assets", "asset", "1000"],
[3, "1110", "Bank account", "asset", "1100"],
[4, "1120", "Accounts receivable", "asset", "1100"],
[5, "1500", "Fixed assets", "asset", "1000"],
[6, "1510", "Equipment", "asset", "1500"],
[7, "2000", "Liabilities", "liability", null],
[8, "2100", "Current liabilities", "liability", "2000"],
[9, "2110", "Accounts payable", "liability", "2100"],
[10, "2120", "Sales tax payable", "liability", "2100"],
[11, "2500", "Long-term loan", "liability", "2000"],
[12, "3000", "Equity", "equity", null],
[13, "3100", "Owner's capital", "equity", "3000"],
[14, "3200", "Retained earnings", "equity", "3000"],
[15, "4000", "Revenue", "revenue", null],
[16, "4100", "Consulting revenue", "revenue", "4000"],
[17, "4200", "Subscription revenue", "revenue", "4000"],
[18, "5000", "Expenses", "expense", null],
[19, "5100", "Operating expenses", "expense", "5000"],
[20, "5110", "Rent", "expense", "5100"],
[21, "5120", "Software", "expense", "5100"],
[22, "5130", "Salaries", "expense", "5100"],
[23, "5200", "Marketing", "expense", "5000"],
];
const accountId = Object.fromEntries(chart.map(([id, code]) => [code, id]));
// [id, reference, date, memo, status, invoiceId, [[account code, debit, credit]]]
const entries = [
[1, "JE-0001", "2026-01-02", "Opening capital", "posted", null, [["1110", "50000.00", "0.00"], ["3100", "0.00", "50000.00"]]],
[2, "JE-0002", "2026-01-15", "Laptops and monitors", "posted", null, [["1510", "4800.00", "0.00"], ["1110", "0.00", "4800.00"]]],
[3, "JE-0003", "2026-02-01", "February office rent", "posted", null, [["5110", "1200.00", "0.00"], ["1110", "0.00", "1200.00"]]],
[4, "JE-0004", "2026-02-03", "Design software licences", "posted", null, [["5120", "349.00", "0.00"], ["1110", "0.00", "349.00"]]],
[5, "JE-0005", "2026-09-15", "Invoice INV-1041", "posted", 1, [["1120", "7200.00", "0.00"], ["4100", "0.00", "6000.00"], ["2120", "0.00", "1200.00"]]],
[6, "JE-0006", "2026-10-12", "Payment received for INV-1041", "posted", null, [["1110", "7200.00", "0.00"], ["1120", "0.00", "7200.00"]]],
[7, "JE-0007", "2026-10-31", "October salaries", "posted", null, [["5130", "9500.00", "0.00"], ["1110", "0.00", "9500.00"]]],
[8, "JE-0008", "2026-11-16", "Month-end software accrual", "draft", null, [["5120", "120.00", "0.00"], ["2110", "0.00", "100.00"]]],
];
const customers = [
[1, "Northwind Traders", "12 Quay Street, Bristol BS1 4DJ", "accounts@northwind.example"],
[2, "Harbour & Vale Ltd", "Unit 4, Dockside Works, Cardiff CF10 4AH", "finance@harbourvale.example"],
[3, "Lumen Studio", "3 Lantern Row, Edinburgh EH3 9QG", "hello@lumenstudio.example"],
];
// [id, number, customer, issued, due, status, reference, entry, [[description, qty, rate]]]
const invoices = [
[1, "INV-1041", 1, "2026-09-15", "2026-10-15", "paid", "PO 7731", 5, [["Discovery workshop (2 days)", "2.00", "1500.00"], ["Prototype build", "1.00", "3000.00"]]],
[2, "INV-1042", 2, "2026-11-02", "2026-11-30", "pending", "HV-2026-118", null, [["Quarterly design retainer", "1.00", "3600.00"], ["Accessibility audit", "1.00", "1850.50"], ["Workshop travel", "3.00", "125.00"]]],
[3, "INV-1043", 3, "2026-09-28", "2026-10-28", "overdue", null, null, [["Brand identity refresh", "1.00", "2400.00"], ["Printed collateral (per set)", "12.00", "35.00"]]],
[4, "INV-1044", 1, "2026-11-10", "2026-12-10", "pending", "PO 7802", null, [["Support subscription, 25 seats", "25.00", "18.00"], ["Onboarding session", "2.00", "250.00"]]],
];
let lineId = 0;
let invoiceLineId = 0;
export const data = {
// Only a leaf account takes journal lines; the others total what is under them.
Accounts: chart.map(([id, code, name, type, parent]) => ({
id, code, name, type, parentId: parent ? accountId[parent] : null, postable: !chart.some(row => row[4] === code),
})),
JournalEntries: entries.map(([id, reference, date, memo, status, invoiceId]) => ({ id, reference, date, memo, status, invoiceId })),
JournalLines: entries.flatMap(([entryId, , , , , , lines]) => lines.map(([code, debit, credit]) => ({
id: ++lineId, entryId, accountId: accountId[code], description: null, debit, credit,
}))),
Customers: customers.map(([id, name, address, email]) => ({ id, name, address, email })),
Invoices: invoices.map(([id, number, customerId, issueDate, dueDate, status, reference, entryId]) => ({
id, number, customerId, issueDate, dueDate, status, taxRate: "20.00", reference, entryId,
})),
InvoiceLines: invoices.flatMap(([invoiceId, , , , , , , , lines]) => lines.map(([description, quantity, rate], i) => ({
id: ++invoiceLineId, invoiceId, position: i + 1, description, quantity, rate,
}))),
};
/** The company that issues the invoices. */
export const seller = {
name: "Fernbank Design Studio Ltd",
address: ["8 Mill Lane", "Leeds LS1 5AB"],
email: "billing@fernbank.example",
taxNumber: "GB 123 4567 89",
payment: "Sort code 40-12-76 · Account 1234 5678",
};
// Exact money arithmetic over the service's Decimal text. Amounts are whole pence (BigInt) so sums,
// products and tax never pass through floating point; the library formats them.
import { formatFigure } from "@getaster/elements";
const TEN = 10n;
/** "1234.5" -> { m: 123450n, s: 2 }; the scale is the number of fraction digits written. */
export function parse(text) {
const match = /^(-?)(\d*)(?:\.(\d*))?$/.exec(String(text ?? "").trim());
if (!match || (match[2] === "" && !match[3])) return { m: 0n, s: 0 };
const fraction = match[3] ?? "";
const m = BigInt(`${match[2] || "0"}${fraction}`);
return { m: match[1] ? -m : m, s: fraction.length };
}
/** `value` at `scale` places, halves away from zero. */
function at({ m, s }, scale) {
if (s <= scale) return m * TEN ** BigInt(scale - s);
const div = TEN ** BigInt(s - scale);
const q = m / div;
const twice = (m % div) * 2n;
const away = twice >= div || -twice >= div;
return away ? q + (m < 0n ? -1n : 1n) : q;
}
/** Whole pence of a Decimal text. */
export const pence = text => at(parse(text), 2);
/** quantity × rate, in pence, as the service's Product computes it. */
export function lineAmount(quantity, rate) {
const q = parse(quantity);
const r = parse(rate);
return at({ m: q.m * r.m, s: q.s + r.s }, 2);
}
/** `percent` per cent of `amount` pence, in pence. */
export function percentOf(amount, percent) {
const p = parse(percent);
return at({ m: amount * p.m, s: p.s + 2 }, 0);
}
/** Pence as the Decimal text the service stores: "1850.50". */
export function decimalText(amount) {
const sign = amount < 0n ? "-" : "";
const digits = (amount < 0n ? -amount : amount).toString().padStart(3, "0");
return `${sign}${digits.slice(0, -2)}.${digits.slice(-2)}`;
}
/** How a column of amounts reads; the field's scale gives its places. */
export const GBP = { style: "currency", currency: "GBP" };
const PENCE = { ...GBP, minimumFractionDigits: 2, maximumFractionDigits: 2 };
/** Pence as display text, "£1,850.50", for an amount that has no field. */
export const pounds = amount => formatFigure(decimalText(amount), PENCE);
/* Composition only: the controls, tokens and states come from the library. */
body { height: auto; min-height: 100dvh; padding: 24px; background: var(--aster-sunk); }
main { max-width: 1280px; margin: auto; min-width: 0; }
.finance-intro { display: flex; flex-wrap: wrap; align-items: flex-end; justify-content: space-between; gap: 16px 24px; margin-block: 8px 20px; }
.finance-intro h1 { margin: 0 0 6px; font-size: 2rem; letter-spacing: -.03em; }
.finance-intro p { margin: 0; max-width: 62ch; color: var(--aster-text-2); line-height: 1.55; }
.finance-appearance { display: flex; flex-wrap: wrap; gap: 8px 16px; }
.finance-eyebrow { margin: 0; font-size: .72rem; letter-spacing: .12em; text-transform: uppercase; color: var(--aster-text-3); }
.finance-hint, .finance-note { color: var(--aster-text-2); font-size: .85rem; }
.finance-empty { margin: 0; padding: 14px 0; color: var(--aster-text-2); }
.finance-sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
.finance-num { display: block; text-align: end; font-variant-numeric: tabular-nums lining-nums; white-space: nowrap; }
aster-tabs { display: block; min-width: 0; }
.finance-screen { min-width: 0; padding-block: 20px 8px; }
/* A list beside what it chooses */
.finance-split { display: grid; grid-template-columns: minmax(230px, 300px) minmax(0, 1fr); gap: 24px; align-items: start; }
.finance-list { min-width: 0; padding: 14px; border: 1px solid var(--aster-rule); border-radius: var(--aster-r-card); background: var(--aster-surface); }
.finance-list h2, .finance-list-head h2 { margin: 0 0 8px; font-size: 1rem; }
.finance-list-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 8px; }
.finance-list-head h2 { margin: 0; }
.invoice-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px 12px; width: 100%; padding: 4px 8px 4px 12px; box-sizing: border-box; }
.invoice-row > strong { font-variant-numeric: tabular-nums; }
.invoice-row-who, .invoice-row-due { grid-column: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--aster-text-2); font-size: .85rem; }
.invoice-row-status { grid-column: 2; grid-row: 1 / 3; align-self: center; }
.finance-detail { min-width: 0; display: grid; gap: 16px; }
.invoice-document, .journal-entry { display: grid; gap: 16px; min-width: 0; max-width: 860px; }
.finance-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 12px; }
.finance-posted { color: var(--aster-text-2); }
.finance-note:empty { display: none; }
/* The invoice, as a page */
.paper { max-width: 860px; padding: clamp(18px, 4vw, 40px); border: 1px solid var(--aster-rule); border-radius: var(--aster-r-card); background: var(--aster-surface); box-shadow: var(--aster-e1); display: grid; gap: 24px; min-width: 0; }
.paper-head { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: 12px; }
.paper-head h2 { margin: 2px 0 0; font-size: 2rem; letter-spacing: -.03em; font-variant-numeric: tabular-nums; }
.paper-parties { display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); gap: 20px 32px; }
.paper-party h3 { margin: 0 0 6px; font-size: .72rem; letter-spacing: .12em; text-transform: uppercase; color: var(--aster-text-3); font-weight: var(--aster-weight-label); }
.paper-party address { display: grid; gap: 2px; font-style: normal; line-height: 1.45; overflow-wrap: anywhere; }
.paper-terms { display: grid; grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr)); gap: 12px 24px; margin: 0; padding-block: 14px; border-block: 1px solid var(--aster-rule-2); }
.paper-terms dt, .paper-totals dt { color: var(--aster-text-3); font-size: .8rem; }
.paper-terms dd { margin: 2px 0 0; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
.paper-lines { min-width: 0; }
.journal-lines { min-width: 0; overflow-x: auto; }
.paper-totals { display: grid; gap: 6px; width: min(22rem, 100%); margin: 0 0 0 auto; }
.paper-totals > div { display: flex; justify-content: space-between; gap: 16px; }
.paper-totals dd { margin: 0; }
.paper-total { padding-top: 10px; border-top: 1px solid var(--aster-rule); font-weight: var(--aster-weight-strong); font-size: 1.15rem; }
.paper-total dt { color: var(--aster-text); font-size: inherit; }
.paper-foot { color: var(--aster-text-2); font-size: .85rem; border-top: 1px solid var(--aster-rule-2); padding-top: 12px; }
.paper-foot p { margin: 2px 0; }
/* Accounts */
.finance-accounts { display: grid; gap: 16px; min-width: 0; }
.finance-ledger { padding: 18px 22px; border: 1px solid var(--aster-rule); border-radius: var(--aster-r-card); background: var(--aster-surface); row-gap: 14px; grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr)); }
.finance-figure { white-space: nowrap; }
.finance-grid { height: min(64dvh, 640px); min-height: 360px; }
.account-group { font-weight: var(--aster-weight-strong); }
/* Journal */
.journal-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; }
.journal-head h2 { margin: 0; font-size: 1.5rem; letter-spacing: -.02em; font-variant-numeric: tabular-nums; }
.journal-totals { display: grid; grid-template-columns: minmax(0, 1fr) 8.5rem 8.5rem; gap: 0 8px; padding: 10px 62px 10px 0; border-block: 1px solid var(--aster-rule); font-weight: var(--aster-weight-strong); }
.journal-totals-label { color: var(--aster-text-2); font-weight: var(--aster-weight-label); }
.finance-balance { display: flex; align-items: center; gap: 10px; margin: 0; padding: 10px 14px; border: 1px solid var(--aster-rule); border-inline-start-width: 4px; border-radius: var(--aster-r-ctl); background: var(--aster-surface); }
.finance-balance > span { font-weight: var(--aster-weight-strong); }
.finance-balance[data-state="balanced"] { border-inline-start-color: var(--aster-positive); }
.finance-balance[data-state="balanced"] > span { color: var(--aster-positive); }
.finance-balance[data-state="out"] { border-inline-start-color: var(--aster-negative); }
.finance-balance[data-state="out"] > span { color: var(--aster-negative); }
@media (max-width: 860px) {
.finance-split { grid-template-columns: minmax(0, 1fr); }
}
@media (max-width: 600px) {
body { padding: 12px; }
.finance-intro h1 { font-size: 1.6rem; }
.paper { padding: 16px; }
}
@media print {
@page { margin: 16mm; }
html, body { background: none; }
body { padding: 0; min-height: 0; }
main { max-width: none; }
.finance-no-print, .finance-list, .showcase-nav { display: none !important; }
.finance-screen { padding: 0; }
.finance-split { display: block; }
.paper { max-width: none; padding: 0; border: 0; box-shadow: none; background: none; gap: 18px; }
.paper-totals, .paper-parties, .paper-terms, .paper-foot { break-inside: avoid; }
}
Download showcase-catalogue.ts
export const examples = [
{ id: "formatting", navigationLabel: "Named displays", title: "Display fields and related records", category: "Fields & layouts", file: "formatting.html", action: "Explore named displays", ref: "staticMethod:bindFieldPresentations", description: "Reuse named renderers for compact people and abbreviated commits in a grid and read-only form.", task: "Copy a complete commit from its abbreviated display." },
{ id: "data-navigator", navigationLabel: "Nested views", title: "Explore projects and their related records", category: "Nested data views", file: "data-navigator.html", action: "Explore nested views", ref: "class:NestedGrid", description: "Browse related collections in a nested grid or a custom form, with independent pages and shared selection.", task: "Expand tasks and their assignees, then switch to the form view." },
{ id: "query-calculations", navigationLabel: "Calculated columns", title: "Explore calculated line totals and elapsed hours", category: "Nested data views", file: "query-calculations.html", action: "Explore calculations", ref: "class:NestedGrid", description: "Filter and sort calculated values, with exact totals across every matching page.", task: "Open order lines, change their calculation, then switch to the form view." },
{ id: "foundations", navigationLabel: "Fields & layouts", title: "Fields and layouts for everyday work", category: "Fields & layouts", file: "foundations.html", action: "Explore fields and layouts", ref: "class:CompositeField",
description: "Group related editors, keep numeric values exact, resize nested panes and navigate retained settings and context.",
task: "Edit a budget, revert its group, then resize the workspace and open its settings." },
{ id: "mail", navigationLabel: "Mail workspace", title: "Mail that keeps your draft", category: "Authentication recovery", file: "mail.html", action: "Open the mail workspace", ref: "class:Authentication",
description: "Read messages, keep several drafts open and recover an expired session through a configurable sign-in flow. The entire example uses local mock data.",
task: "Start a draft, expire the session, then send it and complete simulated sign-in." },
{ id: "tiles", navigationLabel: "Tile grids", title: "Folders & device fleets", category: "Tile grids", file: "tiles.html", action: "Explore tile grids", ref: "class:TileGrid",
description: "Browse folders or a virtual fleet of 100,000 devices. Switch between tiles and a table while keeping your selection.",
task: "Try ordered selection, change the tile size, then switch views." },
{ id: "filters", navigationLabel: "Filtering", title: "Queries you can compose", category: "Advanced filtering", file: "filtering.html", action: "Build an expression", ref: "class:FilterBuilder",
description: "Combine nested All, Any and Not groups with typed fields, platform choices, related records and relative dates.",
task: "Open Advanced filter, choose Platform, then try “is one of”." },
{ id: "reports", navigationLabel: "Reporting", title: "From rows to answers", category: "Reporting & grouping", file: "reporting.html", action: "Explore grouped reports", ref: "class:Grid",
description: "Get exact totals across every matching record, expand multiple grouping levels and export the filtered result or ordered picks.",
task: "Group by Platform → Online → Site, then download a CSV." },
{ id: "charts", navigationLabel: "Charts", title: "Charts that work with your data", category: "Component integration", file: "components.html", action: "Connect charts and grids", ref: "class:ComponentHost",
description: "Optional ECharts components share filters and selection with a grid. HTML data views provide the same keyboard and touch actions.",
task: "Choose a platform in the chart, then select a device in either view." },
{ id: "windows", navigationLabel: "Windows", title: "A workspace that keeps your place", category: "Application windows", file: "windows.html", action: "Explore application windows", ref: "class:Window",
description: "Move between device details and editable notes. Minimize, maximize and restore without recreating content, with guarded close and saved layouts.",
task: "Write a note, minimize it, then restore it from the task list." },
{ id: "dashboard", navigationLabel: "Dashboard", title: "Build your own fleet workspace", category: "Dashboard composition", file: "dashboard.html", action: "Compose a dashboard", ref: "class:Dashboard",
description: "Arrange summaries, charts, device grids and notes. Widgets share live filters and selection, with saved layouts and protected edits.",
task: "Filter by platform, add a device, then move or maximize a widget." },
{ id: "dataview", navigationLabel: "DataView", title: "A directory made of custom cards", category: "DataView", file: "dataview.html", action: "Explore DataView", ref: "group:data-view",
description: "Browse a team directory with images, custom templates, live search and server-side sorting. Selection and updates follow the shared data layer.",
task: "Sort Z to A, try compact cards, then open and rename a colleague." },
{ id: "tabs", navigationLabel: "Tabs", title: "A place for every open device", category: "Tabs", file: "tabs.html", action: "Explore tabs", ref: "class:Tabs",
description: "Open data-driven tabs with lazy panels, retained drafts and optional close actions. A scrolling strip works on touch screens and narrow windows.",
task: "Write a note, switch tabs, then try closing your unsaved device." },
{ id: "finance", navigationLabel: "Finance workspace", title: "A ledger that follows every posting", category: "Finance workspace", file: "finance.html", action: "Open the finance workspace", ref: "class:Grid",
description: "Invoices, a chart of accounts and a journal over one dataset. Posting an invoice books its entry and the service recomputes every balance up the tree.",
task: "Post an invoice, then open the chart of accounts and the journal." },
{ id: "toasts", navigationLabel: "Toasts", title: "Messages that say what is happening", category: "Toasts", file: "toasts.html", action: "Explore toasts", ref: "class:Toaster",
description: "Success, warning and error toasts, a loading toast that updates in place with progress, and a small stack that waits while a dialog is open. Errors stay until dismissed.",
task: "Export the rows, then show five messages, open the dialog and press Escape." },
] as const;
export type ExampleId = typeof examples[number]["id"];
/** The standalone editor is also available from each component example. */
export const standaloneExamples: readonly (readonly [string, string])[] = [
...examples.slice(0, 2).map(example => [example.file, example.navigationLabel] as const),
["composition.html", "Composition"],
...examples.slice(2).map(example => [example.file, example.navigationLabel] as const),
];
// Shared navigation for the independent examples; no vendor code is loaded here.
import "@getaster/elements";
import { standaloneExamples } from "../../app/catalogue.ts";
for (const [id, label, values] of [["theme", "Theme", ["lamplight", "harbour"]], ["scheme", "Scheme", ["light", "dark"]]]) {
const choice = document.querySelector(`#${id}`);
choice.label = label;
choice.options = values.map(value => ({ value, label: value[0].toUpperCase() + value.slice(1) }));
choice.value = values[0];
}
const params = new URLSearchParams(location.search);
const themes = ["lamplight", "harbour"];
const schemes = ["light", "dark"];
const theme = params.get("theme");
const scheme = params.get("scheme");
if (themes.includes(theme)) {
document.querySelector("#theme").value = theme;
document.querySelector("#identity").href = `../lib/themes/${theme}.css`;
document.documentElement.dataset.identity = theme;
}
if (schemes.includes(scheme)) {
document.querySelector("#scheme").value = scheme;
document.documentElement.dataset.scheme = scheme;
document.documentElement.style.colorScheme = scheme;
}
const nav = document.createElement("nav");
nav.className = "showcase-nav";
nav.setAttribute("aria-label", "Component examples");
const back = document.createElement("a");
back.textContent = "← Component showcase";
const defaultApp = new URL(document.querySelector('meta[name="aster-site-layout"]') ? "../showcase/" : "../", document.baseURI);
let requestedApp = defaultApp;
try { requestedApp = new URL(params.get("app") ?? defaultApp.href, location.href); } catch { /* Malformed return URLs use the showcase root. */ }
const app = requestedApp.origin === location.origin ? requestedApp : defaultApp;
app.hash = "showcase";
back.href = app.href;
nav.append(back);
const links = document.createElement("div");
links.className = "showcase-nav-links";
nav.append(links);
for (const [file, label] of standaloneExamples) {
const link = document.createElement("a");
link.textContent = label;
link.href = file;
if (location.pathname.endsWith(`/${file}`)) link.setAttribute("aria-current", "page");
links.append(link);
}
function updateLinks() {
for (const link of nav.querySelectorAll("a")) {
const url = new URL(link.href);
if (link !== back) {
url.searchParams.set("theme", document.querySelector("#theme").value);
url.searchParams.set("scheme", document.querySelector("#scheme").value);
url.searchParams.set("showcase", "1");
url.searchParams.set("app", app.pathname);
} else {
url.searchParams.set("identity", document.querySelector("#theme").value);
url.searchParams.set("scheme", document.querySelector("#scheme").value);
}
link.href = url.href;
}
}
function applyAppearance() {
const theme = document.querySelector("#theme").value;
const scheme = document.querySelector("#scheme").value;
const stylesheet = document.querySelector("#identity");
const href = new URL(`../lib/themes/${theme}.css`, document.baseURI).href;
if (stylesheet.href !== href) stylesheet.href = href;
document.documentElement.dataset.identity = theme;
document.documentElement.dataset.scheme = scheme;
document.documentElement.style.colorScheme = scheme;
updateLinks();
}
for (const id of ["theme", "scheme"]) document.querySelector(`#${id}`).addEventListener("change", applyAppearance);
applyAppearance();
const embedded = params.get("embedded") === "1" && parent !== window;
if (!embedded) {
document.querySelector("main").prepend(nav);
requestAnimationFrame(() => {
const current = links.querySelector("[aria-current]");
if (!current || links.scrollWidth <= links.clientWidth) return;
const item = current.getBoundingClientRect();
const viewport = links.getBoundingClientRect();
links.scrollBy({ left: Math.min(0, item.left - viewport.left) + Math.max(0, item.right - viewport.right), behavior: "instant" });
});
const demo = location.pathname.split("/").pop().replace(".html", "");
for (const link of document.querySelectorAll("main a[href]")) {
if (link.hasAttribute("download")) continue;
const target = new URL(link.href);
if (target.origin !== location.origin) continue;
if (["composition", "mail"].includes(demo) && /\.(?:js|yaml|css)$/.test(target.pathname)) {
const viewer = new URL(`../examples/${demo}.html`, location.href);
viewer.searchParams.set("source", target.pathname.split("/").pop());
viewer.searchParams.set("theme", document.querySelector("#theme").value);
viewer.searchParams.set("scheme", document.querySelector("#scheme").value);
viewer.hash = "application-source";
link.href = viewer.href;
} else if (!/\/(?:guide|reference)\//.test(target.pathname)) continue;
link.target = "_blank";
link.rel = "noopener";
link.setAttribute("aria-label", `${link.textContent.trim()} (opens in a new tab)`);
}
}
else {
const demo = location.pathname.split("/").pop().replace(".html", "");
document.documentElement.dataset.embedded = "";
document.documentElement.dataset.demo = demo;
document.querySelector("main").setAttribute("aria-label", document.title);
const state = () => parent.postMessage({ type: "aster-demo-state", state: { theme: document.querySelector("#theme").value, scheme: document.querySelector("#scheme").value } }, location.origin);
const height = () => parent.postMessage({ type: "aster-demo-height", height: Math.ceil(document.body.getBoundingClientRect().height) }, location.origin);
new ResizeObserver(height).observe(document.body);
for (const id of ["theme", "scheme"]) document.querySelector(`#${id}`).addEventListener("change", state);
addEventListener("message", event => {
if (event.origin !== location.origin || event.source !== parent) return;
if (event.data?.type === "aster-example-appearance" && schemes.includes(event.data.scheme)) {
document.querySelector("#scheme").value = event.data.scheme;
if (themes.includes(event.data.theme)) document.querySelector("#theme").value = event.data.theme;
applyAppearance(); state();
}
if (event.data?.type === "aster-demo-request") { state(); height(); }
});
state(); height();
}
main a { color:var(--aster-accent); text-underline-offset:4px; }
.showcase-nav { display: grid; gap: 4px; padding-bottom: 12px; margin-bottom: 20px; border-bottom: 1px solid var(--aster-rule); min-width:0; }
.showcase-nav-links { display:flex; flex-wrap:wrap; gap:4px 16px; min-width:0; }
.showcase-nav a { display: inline-flex; align-items: center; min-height: 44px; color: var(--aster-accent); text-underline-offset: 4px; }
.showcase-nav > a:first-child { margin-right: auto; }
.showcase-nav [aria-current] { font-weight: var(--aster-weight-strong); text-decoration-thickness: 2px; }
.showcase-appearance { display: inline-flex; align-items: center; gap: 8px; }
.showcase-appearance > span { color: var(--aster-text-2); font-weight: var(--aster-weight-label); }
.showcase-appearance aster-choice { width: 9rem; }
.showcase-appearance #scheme { width: 7rem; }
.showcase-grouping aster-choice { width: min(17rem, 65vw); }
/* Match the canvas to the page, including browser rubber-band overscroll. */
html, body { background:var(--showcase-canvas, var(--aster-surface)); }
body { transition:color 300ms ease; }
html:has(.mail-intro) { --showcase-canvas:var(--aster-sunk); }
@media (max-width: 720px), (pointer: coarse) and (max-width: 1024px) {
.showcase-nav-links { flex-wrap:nowrap; overflow-x:auto; scrollbar-width:none; }
.showcase-nav-links::-webkit-scrollbar { display:none; }
.showcase-nav-links a { flex:none; white-space:nowrap; }
.showcase-nav [aria-current] { scroll-margin-inline:16px; }
}
html[data-embedded] body { height:auto; min-height:0!important; padding:20px; }
html[data-embedded] .showcase-appearance:has(#scheme) { display:none; }
html[data-embedded] main > p:last-child:has(a[href="./"]) { display:none; }
html[data-embedded][data-demo="windows"] body { min-height:820px!important; }
@media(max-width:600px) { html[data-embedded] body { padding:12px; } }
.bar select { min-height:var(--aster-ctl); max-width:100%; padding:6px 10px; border:1px solid var(--aster-rule); border-radius:var(--aster-r-ctl); background:var(--aster-sunk); color:var(--aster-text); }
@media(pointer:coarse) { .bar select { min-height:44px; } }
Try the workflow
- Open INV-1042 and post it to the ledger.
- Open the Journal tab: the entry is there, balanced, with three lines.
- Open Chart of accounts: the receivable and every parent above it changed.
- Choose Undo in the notice, or edit JE-0008 until its debits equal its credits and post it.
What the example owns
One mock service and data context serve all three screens. Parent balances are a server-computed field; the example reads again the accounts the service reports as changed. The balanced check for a journal entry is the example's own.