Track investments as broker facts with a position leg
An account now has a kind, and an investment account holds positions as well as
cash. A broker row is not a new entity: it is a bank fact with an optional
position leg, so deduplication, the journal, fact immutability, the DuckDB
projection and the transactions view carry it unchanged. Facts.Amount stays the
cash leg and is zero on the rows that move only a position.
Scalable Capital exports are recognized locally as a fourth format, read by
their own parser because a column mapping cannot describe them: the amount
column is settled cash on a cash row, a gross to be netted on a trade, and a
position valuation that must never touch cash on a corporate action or a depot
transfer. A cash amount is already net of the tax the broker withheld or
refunded, so that tax is recorded on the fact and never subtracted a second
time; treating a corporate action's valuation as money conjures cash, and a
depot switch would do it once per instrument. The share column is signed only
for those two types, so buys and sells take their direction from the type. Every
security row is checked against shares times price at 128-bit width, because a
lost decimal separator survives every other check. An unknown status, type or
assetType, a foreign currency, a missing ISIN, or one failed check rejects the
whole file with the record number.
Instruments live in instruments.finance, keyed by ISIN with an ID derived from
it, so re-importing never registers a security twice. One ISIN appears under
several broker descriptions over the years and sometimes under the ISIN itself:
the most recent real description names it, and an import never renames one that
already exists. A broker also reuses a single reference across every leg of one
event, so transaction identity includes the event and its instrument.
domain.Fallback returns kind "investment" for any fact carrying a position leg,
so no broker row reaches the sign-based branch. That single rule is what stops
an unmatched deposit from counting as income and a broker fee from counting as
household spending; the monthly PRIME fee and its matching credit now cancel in
clearing:investments with no configuration at all. Investment rows are excluded
from spending analytics, from bulk reclassification and from the model, exactly
as transfers are.
Equal competing transfers are paired instead of skipped. Every connected
component of the candidate graph is a complete bipartite graph between two fixed
accounts at one amount and currency, so every pairing produces the same
accounts, kinds and postings and only the displayed counterpart differs.
Refusing to choose was the expensive option: both legs fell through to the
sign-based fallback and appeared as spending and income that never happened.
Pairing follows the nearest booking date, then the transaction ID, so iteration
order decides nothing. POST /api/transactions/{id}/transfer rewrites the old and
the new pair in one commit, because reciprocity is validated and a half-applied
link is an invalid dataset, and the matcher now skips any record classified
manually so a hand-made link or unlink outlives the next import.
Wealth reports each account's cash and positions from the journal rather than
the index, with named checks - row arithmetic, cash never negative, holdings
never negative - because it exists to be compared against the figures a broker
shows on its own screen. A negative holding means the imported history is
partial. Share counts are exact to eight places; a reinvested distribution
quoted to six is rounded to money's four and the residue is reported rather than
hidden. Market prices, market value, net worth over time, FIFO lot accounting,
realised gains and currency conversion are deliberately absent.
This commit is contained in:
@@ -0,0 +1,309 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
AlertTriangle,
|
||||
CandlestickChart,
|
||||
CheckCircle2,
|
||||
Landmark,
|
||||
PiggyBank,
|
||||
} from "lucide-react";
|
||||
import type { Wealth, WealthAccount } from "./api";
|
||||
import { money, request } from "./api";
|
||||
import { Empty, ErrorMessage } from "./ui";
|
||||
|
||||
// The report is recomputed from the journal, so it is keyed on the revision and
|
||||
// never cached: it exists to be compared with a bank or broker's own screen.
|
||||
// Renaming a security lives in the Instruments registry, beside every other
|
||||
// registry entity, rather than being a second editor here.
|
||||
export default function WealthPage({ revision }: { revision: string }) {
|
||||
const [wealth, setWealth] = useState<Wealth | null>(null);
|
||||
const [error, setError] = useState("");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [retry, setRetry] = useState(0);
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError("");
|
||||
request<Wealth>("/api/wealth", undefined, controller.signal)
|
||||
.then((value) => {
|
||||
for (const key of ["accounts", "totals"] as const) {
|
||||
if (!(key in value))
|
||||
throw new Error(`Wealth response is missing ${key}.`);
|
||||
if (value[key] === null) Object.assign(value, { [key]: [] });
|
||||
}
|
||||
for (const account of value.accounts) {
|
||||
account.holdings ??= [];
|
||||
account.checks ??= [];
|
||||
}
|
||||
setWealth(value);
|
||||
})
|
||||
.catch((err) => {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(err instanceof Error ? err.message : String(err));
|
||||
setWealth(null);
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (!controller.signal.aborted) setLoading(false);
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [revision, retry]);
|
||||
const failures =
|
||||
wealth?.accounts.reduce(
|
||||
(total, account) => total + account.checks.filter((c) => c.failed).length,
|
||||
0,
|
||||
) || 0;
|
||||
const failingAccounts =
|
||||
wealth?.accounts.filter((account) => account.checks.some((c) => c.failed))
|
||||
.length || 0;
|
||||
return (
|
||||
<>
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<h2>Wealth</h2>
|
||||
<p>
|
||||
Cash and positions recomputed from your journal, with the checks
|
||||
that decide whether the figures can be trusted.
|
||||
</p>
|
||||
</div>
|
||||
<button
|
||||
className="button secondary"
|
||||
onClick={() => setRetry(retry + 1)}
|
||||
disabled={loading}
|
||||
>
|
||||
Recheck figures
|
||||
</button>
|
||||
</div>
|
||||
<ErrorMessage error={error} />
|
||||
{loading ? (
|
||||
<div className="loading-block" role="status">
|
||||
<span className="spinner" />
|
||||
Recomputing cash and positions…
|
||||
</div>
|
||||
) : (
|
||||
wealth && (
|
||||
<>
|
||||
{failures > 0 && (
|
||||
<div className="alert error" role="alert">
|
||||
<AlertTriangle size={19} />
|
||||
<div>
|
||||
<strong>
|
||||
{failures} check{failures === 1 ? "" : "s"} failed across{" "}
|
||||
{failingAccounts} account
|
||||
{failingAccounts === 1 ? "" : "s"}.
|
||||
</strong>
|
||||
<p>
|
||||
A failed check means the journal disagrees with itself, so
|
||||
the balance below will not match your bank or broker. The
|
||||
details sit with the account that failed.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{wealth.totals.length > 0 && (
|
||||
<section className="panel">
|
||||
<div className="panel-heading">
|
||||
<div>
|
||||
<h3>
|
||||
<PiggyBank size={17} />
|
||||
Total cash
|
||||
</h3>
|
||||
<p>
|
||||
Every recorded movement summed per currency, across all{" "}
|
||||
{wealth.accounts.length} account
|
||||
{wealth.accounts.length === 1 ? "" : "s"}.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="registry">
|
||||
<div className="preview-summary">
|
||||
{wealth.totals.map((total) => (
|
||||
<span key={total.currency}>
|
||||
<strong className="money">
|
||||
{money(total.cash, total.currency)}
|
||||
</strong>{" "}
|
||||
in cash
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
{wealth.accounts.length === 0 ? (
|
||||
<section className="panel">
|
||||
<Empty title="No accounts to report on yet">
|
||||
Add an account and import a statement or broker export to see
|
||||
its cash balance, positions and checks here.
|
||||
</Empty>
|
||||
</section>
|
||||
) : (
|
||||
wealth.accounts.map((account) => (
|
||||
<AccountReport key={account.account_id} account={account} />
|
||||
))
|
||||
)}
|
||||
<section className="panel">
|
||||
<div className="panel-heading">
|
||||
<div>
|
||||
<h3>Reading these figures</h3>
|
||||
<p>
|
||||
The three rules that decide what a broker export does and
|
||||
does not move.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="registry">
|
||||
<dl className="facts">
|
||||
<div>
|
||||
<dt>Tax on broker cash</dt>
|
||||
<dd>
|
||||
A broker cash amount is already net of tax. The tax is
|
||||
recorded on the transaction and deliberately not
|
||||
subtracted a second time.
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Position-only events</dt>
|
||||
<dd>
|
||||
Corporate actions and position transfers move a position
|
||||
and settle zero cash, so they change a holding without
|
||||
touching the balance.
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Investment transactions</dt>
|
||||
<dd>
|
||||
Transactions classified as investment are excluded from
|
||||
every spending and income figure, exactly like transfers.
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Completeness</dt>
|
||||
<dd>
|
||||
Cash equals the real balance only when the journal holds
|
||||
that account's full history: a broker export does, a
|
||||
date-windowed bank statement does not.
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
)
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
function AccountReport({ account }: { account: WealthAccount }) {
|
||||
const range =
|
||||
account.first_booking && account.last_booking
|
||||
? `${account.first_booking} – ${account.last_booking}`
|
||||
: account.first_booking || account.last_booking || "";
|
||||
const failed = account.checks.filter((check) => check.failed);
|
||||
const notes = account.checks.filter((check) => !check.failed);
|
||||
const investing = account.kind === "investment";
|
||||
return (
|
||||
<section className="panel">
|
||||
<div className="panel-heading">
|
||||
<div>
|
||||
<h3>
|
||||
{investing ? (
|
||||
<CandlestickChart size={17} />
|
||||
) : (
|
||||
<Landmark size={17} />
|
||||
)}
|
||||
{account.display_name}
|
||||
</h3>
|
||||
<p>
|
||||
{account.institution} · {investing ? "Investment" : "Cash"} account
|
||||
· {account.records} record{account.records === 1 ? "" : "s"}
|
||||
{range ? ` · ${range}` : " · no bookings"}
|
||||
{!account.active && " · archived"}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<span className="eyebrow">Cash balance</span>
|
||||
<span className="large-money money">
|
||||
{money(account.cash, account.currency)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{account.holdings.length > 0 && (
|
||||
<div className="table-scroll">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Instrument</th>
|
||||
<th>ISIN</th>
|
||||
<th className="numeric">Quantity</th>
|
||||
<th className="numeric">Invested</th>
|
||||
<th className="numeric">Received</th>
|
||||
<th className="numeric">Records</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{account.holdings.map((holding) => {
|
||||
// A quantity is an exact decimal string and stays one: the sign
|
||||
// is its first character and a digit above zero is what makes
|
||||
// the position non-empty, with no number parsing in between.
|
||||
// A negative holding means more units left the account than
|
||||
// entered it, which is always worth seeing.
|
||||
const negative = holding.quantity.startsWith("-");
|
||||
const empty = !/[1-9]/.test(holding.quantity);
|
||||
return (
|
||||
<tr key={holding.instrument_id}>
|
||||
<td>{holding.name}</td>
|
||||
<td className="nowrap muted">{holding.isin}</td>
|
||||
<td
|
||||
className={`numeric money ${negative ? "text-danger" : empty ? "muted" : "positive"}`}
|
||||
>
|
||||
{holding.quantity}
|
||||
{negative && (
|
||||
<small className="text-danger">
|
||||
more units left than entered
|
||||
</small>
|
||||
)}
|
||||
</td>
|
||||
<td className="numeric money">
|
||||
{money(holding.invested, account.currency)}
|
||||
</td>
|
||||
<td className="numeric money">
|
||||
{money(holding.received, account.currency)}
|
||||
</td>
|
||||
<td className="numeric">{holding.records}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
{failed.length > 0 && (
|
||||
<div className="registry">
|
||||
{failed.map((check) => (
|
||||
<div className="alert error" role="alert" key={check.name}>
|
||||
<AlertTriangle size={19} />
|
||||
<div>
|
||||
<strong>{check.name}</strong>
|
||||
<p>{check.detail}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{notes.length > 0 && (
|
||||
<div className="health-grid">
|
||||
{notes.map((check) => (
|
||||
<div className="health" key={check.name}>
|
||||
<span className="positive">
|
||||
<CheckCircle2 size={18} />
|
||||
</span>
|
||||
<div>
|
||||
<strong>{check.name}</strong>
|
||||
<p>{check.detail}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user