Clarify saved balances and Investment Overview displays #72

Merged
eleith merged 1 commits from refactor/hledger-balance-command into main 2026-11-22 17:02:14 +00:00
21 changed files with 499 additions and 303 deletions

No files matched your search

@@ -0,0 +1,5 @@
---
'@hledger-reports/worker': patch
---
Pair hledger `balance` arguments with their matching decoder, and organize Investment Overview by the values it shows. Report values, saved format, and preparation behavior are unchanged.
+7 -1
View File
@@ -17,9 +17,15 @@ exports already in hand, without running hledger.
and decoded. `commands/run.ts` wraps `hledger run`: give it an ordered list of
commands and read each result in that order. For JSON commands, it streams
documents or individual rows and checks that all output was consumed.
Each saved `balance` form in `commands/balance.ts` returns its arguments and
matching decoder together. Saved account summaries and Investment Overview
choose the scope, dates, and valuation; they don't select a JSON decoder.
- **Execution:** `src/process.ts` owns the child process and cancellation.
It doesn't know which reports are being prepared.
- **Saved reports:** Start at `src/reports/generate.ts`. It discovers the journal's
dates, accounts, and lot commodities, then runs and reads the commands listed
in `reports/report-sequence.ts`. The `cash-and-net-worth`, `accounts`, and
`investment-overview` folders define their parts of the saved report.
`investment-overview` folders define their parts of the saved report. For
Investment Overview, start at `investment-overview/prepare.ts`. It checks
scope, gathers shared balances and holdings through `native-reports.ts`,
and assembles the values from `displays/`.
@@ -0,0 +1,24 @@
import { expect, it } from 'vitest';
import { monthlyHistoricalBalanceCommand } from './balance.js';
it('decodes monthly balances only for the exact periods requested by the command', () => {
const april = { begin: '2026-04-01', endExclusive: '2026-05-01' };
const query = ['acct:^Assets:Brokerage$'];
const aprilBalance = monthlyHistoricalBalanceCommand([april], query, 'USD');
const aprilOutput = `{
"prDates":[[{"tag":"Exact","contents":"2026-04-01"},{"tag":"Exact","contents":"2026-05-01"}]],
"prRows":[],
"prTotals":{"prrAmounts":[[{"acommodity":"USD","aquantity":{"decimalMantissa":900719925474099301,"decimalPlaces":2}}]]}
}`;
const decoded = aprilBalance.decode(aprilOutput);
expect(decoded.months).toEqual([april]);
expect(decoded.totals).toEqual([[{ commodity: 'USD', quantity: '9007199254740993.01' }]]);
decoded.months[0].begin = '2026-04-02';
expect(aprilBalance.decode(aprilOutput).months).toEqual([april]);
for (const output of [
aprilOutput.replace(april.begin, '2026-04-02'),
aprilOutput.replace(april.endExclusive, '2026-04-30')
]) {
expect(() => aprilBalance.decode(output)).toThrow();
}
});
+155
View File
@@ -0,0 +1,155 @@
import { parseExactJson, reportedAmounts, type Amount, type ReportedAmount } from '../amounts.js';
export type BalanceValuation = { date: string; commodity: string };
type BalancePeriod = { begin: string; endExclusive: string };
export interface BalanceReport {
rows: Map<string, ReportedAmount[]>;
total: ReportedAmount[];
}
const invalidBalance = 'Invalid hledger account balance report.';
function valueFlag({ date, commodity }: BalanceValuation): string {
// Preserve the literal commodity as one argument, including empty/spaces/commas.
return `--value=${date},${commodity}`;
}
export function declaredTreeBalanceCommand(endExclusive: string, valuation?: BalanceValuation) {
return {
args: [
'balance',
'--tree',
'--no-elide',
'--declared',
'--historical',
'--empty',
'-e',
endExclusive,
'-Ojson',
`not:date:${endExclusive}..`,
...(valuation ? [valueFlag(valuation)] : [])
],
decode: decodeBalanceReport
};
}
export function flatHistoricalBalanceCommand(
endExclusive: string,
queryTerms: readonly string[],
valuation?: BalanceValuation
) {
return {
args: flatHistoricalBalanceArgs(endExclusive, queryTerms, valuation),
decode: decodeBalanceReport
};
}
function flatHistoricalBalanceArgs(
endExclusive: string,
queryTerms: readonly string[],
valuation?: BalanceValuation
): string[] {
return [
'balance',
'--flat',
'--historical',
'--empty',
'-Ojson',
'-e',
endExclusive,
`not:date:${endExclusive}..`,
...queryTerms,
...(valuation ? [valueFlag(valuation)] : [])
];
}
export function monthlyHistoricalBalanceCommand(
months: readonly BalancePeriod[],
queryTerms: readonly string[],
commodity: string
) {
const expectedMonths = months.map(({ begin, endExclusive }) => ({ begin, endExclusive }));
const first = expectedMonths[0];
const last = expectedMonths.at(-1);
if (!first || !last) throw new Error('Monthly balances need at least one expected month.');
return {
args: [
...flatHistoricalBalanceArgs(last.endExclusive, queryTerms),
'--monthly',
'-b',
first.begin,
valueFlag({ date: 'end', commodity })
],
decode: (text: string) => decodeMonthlyBalanceReport(text, expectedMonths)
};
}
function decodeBalanceReport(text: string): BalanceReport {
const report = parseExactJson(text);
if (!Array.isArray(report) || report.length !== 2 || !Array.isArray(report[0])) {
throw new Error(invalidBalance);
}
const total = reportedAmounts(report[1] as Amount[]);
const rows = new Map<string, ReportedAmount[]>();
for (const row of report[0]) {
if (
!Array.isArray(row) ||
row.length !== 4 ||
typeof row[0] !== 'string' ||
!row[0] ||
typeof row[1] !== 'string' ||
!Number.isInteger(row[2]) ||
row[2] < 0 ||
rows.has(row[0])
) {
throw new Error(invalidBalance);
}
// Index the exact full name, not the shortened tree display label.
rows.set(row[0], reportedAmounts(row[3] as Amount[]));
}
return { rows, total };
}
type NativeBoundary = { tag: string; contents: string };
interface NativeMonthlyBalance {
prDates: [NativeBoundary, NativeBoundary][];
prRows: { prrName: string; prrAmounts: Amount[][] }[];
prTotals: { prrAmounts: Amount[][] };
}
function decodeMonthlyBalanceReport(text: string, expectedMonths: readonly BalancePeriod[]) {
const report = parseExactJson(text) as Partial<NativeMonthlyBalance> | null;
const failure = () => new Error('Invalid native monthly investment balances.');
if (
!Array.isArray(report?.prDates) ||
report.prDates.length !== expectedMonths.length ||
!Array.isArray(report.prRows)
)
throw failure();
for (const [index, { begin, endExclusive }] of expectedMonths.entries()) {
const period = report.prDates[index];
if (
period?.length !== 2 ||
period[0]?.tag !== 'Exact' ||
period[0].contents !== begin ||
period[1]?.tag !== 'Exact' ||
period[1].contents !== endExclusive
)
throw failure();
}
function amounts(columns: Amount[][] | undefined) {
if (!Array.isArray(columns) || columns.length !== expectedMonths.length) throw failure();
return columns.map(reportedAmounts);
}
const rows = new Map<string, ReturnType<typeof amounts>>();
for (const row of report.prRows) {
if (!row || typeof row.prrName !== 'string' || rows.has(row.prrName)) throw failure();
rows.set(row.prrName, amounts(row.prrAmounts));
}
return {
months: expectedMonths.map((month) => ({ ...month })),
rows,
totals: amounts(report.prTotals?.prrAmounts)
};
}
+1 -1
View File
@@ -22,7 +22,7 @@ export type { PreparedInvestmentOverview } from './reports/investment-overview/p
export {
largestHoldingLimit,
type PreparedPortfolioValues
} from './reports/investment-overview/portfolio-values.js';
} from './reports/investment-overview/displays/portfolio-values.js';
export type { PreparedBalance } from './reports/accounts/balances.js';
export type { PreparedAccountRow } from './transactions/account-rows.js';
export type {
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
import { ReportStreamReader } from '../../report-stream.js';
import { organizeAccountBalance, planAccountBalances, readAccountBalances } from './balances.js';
import { accountBalanceReports, organizeAccountBalance } from './balances.js';
const asOf = '2026-04-02';
const empty = '[[],[]]';
@@ -16,8 +16,8 @@ function reportReader(...documents: string[]): ReportStreamReader {
}
describe('finite account balance reports', () => {
it('plans two all-account native tree commands with the exact cutoff and literal target', () => {
const commands = planAccountBalances({ asOf, baseCurrency: 'US D,quoted' });
it('builds two all-account native tree commands with the exact cutoff and literal target', () => {
const { commands } = accountBalanceReports({ asOf, baseCurrency: 'US D,quoted' });
const balance = [
'balance',
'--tree',
@@ -31,11 +31,10 @@ describe('finite account balance reports', () => {
'not:date:2026-04-03..'
];
expect(commands).toEqual([balance, [...balance, '--value=2026-04-02,US D,quoted']]);
expect(planAccountBalances({ asOf, baseCurrency: '' })).toEqual([
expect(accountBalanceReports({ asOf, baseCurrency: '' }).commands).toEqual([
balance,
[...balance, '--value=2026-04-02,']
]);
expect(planAccountBalances({ asOf: null, baseCurrency: '' })).toEqual([]);
});
it('reads two native JSON documents losslessly, preserving bags and exact full names', async () => {
@@ -48,7 +47,7 @@ describe('finite account balance reports', () => {
]]],[]]`;
const reader = reportReader(raw, valued);
const json = vi.spyOn(reader, 'json');
const decoded = await readAccountBalances(reader, asOf);
const decoded = await accountBalanceReports({ asOf, baseCurrency: 'USD' }).read(reader);
expect(json).toHaveBeenCalledTimes(2);
expect(decoded.balances.get('Assets:Parent')).toEqual([
amount('ABC', '9007199254740993.01'),
@@ -66,15 +65,16 @@ describe('finite account balance reports', () => {
});
it('rejects duplicate or blank full names and invalid native amount bags', async () => {
const accountBalances = accountBalanceReports({ asOf, baseCurrency: 'USD' });
for (const raw of [
'[[["a","a",0,[]],["a","a",0,[]]],[]]',
'[[["","a",0,[]]],[]]',
'[[["a","a",0,null]],[]]'
]) {
await expect(readAccountBalances(reportReader(raw, empty), asOf)).rejects.toThrow();
await expect(accountBalances.read(reportReader(raw, empty))).rejects.toThrow();
}
await expect(
readAccountBalances(reportReader(empty, '[[["a","a",0,[]]],null]'), asOf)
accountBalances.read(reportReader(empty, '[[["a","a",0,[]]],null]'))
).rejects.toThrow();
});
@@ -100,7 +100,9 @@ describe('finite account balance reports', () => {
it('keeps qualification and dates authoritative without reading undated reports', async () => {
const reader = reportReader();
const json = vi.spyOn(reader, 'json');
const reports = await readAccountBalances(reader, null);
const accountBalances = accountBalanceReports({ asOf: null, baseCurrency: '' });
expect(accountBalances.commands).toEqual([]);
const reports = await accountBalances.read(reader);
expect(json).not.toHaveBeenCalled();
expect(reports).toEqual({ balances: new Map(), valuations: new Map() });
expect(organizeAccountBalance('a', 'ambiguous', null, 'USD', reports)).toEqual({
@@ -1,9 +1,5 @@
import {
parseExactJson,
reportedAmounts,
type Amount,
type ReportedAmount
} from '../../amounts.js';
import type { ReportedAmount } from '../../amounts.js';
import { declaredTreeBalanceCommand } from '../../commands/balance.js';
import type { NativeValue } from '../cash-and-net-worth/report.js';
import { isoDate } from '../../report-date.js';
import type { ReportStreamReader } from '../../report-stream.js';
@@ -20,74 +16,36 @@ export interface AccountBalanceReports {
const failureMessage = 'Invalid hledger account balance report.';
/** Plan two finite native reports against the cached journal. */
export function planAccountBalances({
/** Pair the native and market-valued balance commands with their ordered reader. */
export function accountBalanceReports({
asOf,
baseCurrency
}: {
asOf: string | null;
baseCurrency: string;
}): string[][] {
if (asOf === null) return [];
}): {
commands: string[][];
read: (reader: ReportStreamReader) => Promise<AccountBalanceReports>;
} {
if (asOf === null) {
return {
commands: [],
read: async () => ({ balances: new Map(), valuations: new Map() })
};
}
const end = new Date(`${asOf}T00:00:00Z`);
end.setUTCDate(end.getUTCDate() + 1);
const endExclusive = isoDate(end);
const balance = [
'balance',
'--tree',
'--no-elide',
'--declared',
'--historical',
'--empty',
'-e',
endExclusive,
'-Ojson',
`not:date:${endExclusive}..`
];
return [
balance,
[
...balance,
// The inferred commodity ID is literal, even when empty or containing spaces/commas.
`--value=${asOf},${baseCurrency}`
]
];
}
export function decodeBalanceReport(text: string) {
const report = parseExactJson(text);
if (!Array.isArray(report) || report.length !== 2 || !Array.isArray(report[0])) {
throw new Error(failureMessage);
}
const total = reportedAmounts(report[1] as Amount[]);
const rows = new Map<string, ReportedAmount[]>();
for (const row of report[0]) {
if (
!Array.isArray(row) ||
row.length !== 4 ||
typeof row[0] !== 'string' ||
!row[0] ||
typeof row[1] !== 'string' ||
!Number.isInteger(row[2]) ||
row[2] < 0 ||
rows.has(row[0])
) {
throw new Error(failureMessage);
const unvalued = declaredTreeBalanceCommand(endExclusive);
const valued = declaredTreeBalanceCommand(endExclusive, { date: asOf, commodity: baseCurrency });
return {
commands: [unvalued.args, valued.args],
async read(reader) {
const { rows: balances } = unvalued.decode(await reader.json());
const { rows: valuations } = valued.decode(await reader.json());
return { balances, valuations };
}
// Index the exact full name, not the shortened tree display label.
rows.set(row[0], reportedAmounts(row[3] as Amount[]));
}
return { rows, total };
}
export async function readAccountBalances(
reader: ReportStreamReader,
asOf: string | null
): Promise<AccountBalanceReports> {
if (asOf === null) return { balances: new Map(), valuations: new Map() };
const { rows: balances } = decodeBalanceReport(await reader.json());
const { rows: valuations } = decodeBalanceReport(await reader.json());
return { balances, valuations };
};
}
/** Qualification belongs to the existing native account directory, not row presence. */
@@ -124,7 +124,7 @@ include detail.journal
});
expect(after.overview.netWorth).not.toEqual(reports.overview.netWorth);
expect(after.investmentOverview?.portfolioValue?.quantity).toBe('2.00');
});
}, 15_000);
it('withholds both accounts when native selection resolves their identities to the same account', async () => {
const journal = await createJournal(`commodity USD
+7 -3
View File
@@ -6,7 +6,7 @@ import type { PreparationTransactions } from '../transactions/store.js';
import type { AccountRowWriter } from './accounts/register-rows.js';
import { planOverviewReports } from './cash-and-net-worth/plan.js';
import {
planInvestmentOverview,
investmentOverviewReports,
type PreparedInvestmentOverview
} from './investment-overview/prepare.js';
import { discoverJournal } from './discover-journal.js';
@@ -41,7 +41,7 @@ export async function generateSavedReport(
options.signal?.throwIfAborted();
const overviewPlan = planOverviewReports(journalDiscovery.journal);
// Discover cash commodities for eligible investment accounts before the batch.
const investmentPlan = await planInvestmentOverview({
const investmentReports = await investmentOverviewReports({
configuredInvestmentAccounts: options.investmentAccounts ?? [],
journalStats: journalDiscovery.journal,
journalAccounts: journalDiscovery.accounts,
@@ -49,7 +49,11 @@ export async function generateSavedReport(
readPreflight: (command) =>
readHledger([...inputFlags, ...command], { signal: options.signal })
});
const reportSequence = buildReportSequence({ journalDiscovery, overviewPlan, investmentPlan });
const reportSequence = buildReportSequence({
journalDiscovery,
overviewPlan,
investmentReports
});
const { overview, accounts, investmentOverview } = await runJsonCommands(
inputFlags,
reportSequence.commands,
@@ -1,5 +1,5 @@
import type { decodeBalanceReport } from '../accounts/balances.js';
import type { ReportedAmount } from '../../amounts.js';
import type { BalanceReport } from '../../commands/balance.js';
import {
isUnitlessZero,
mayHaveBalance,
@@ -7,7 +7,6 @@ import {
reportedTotalInCurrency
} from './balances.js';
type BalanceReport = ReturnType<typeof decodeBalanceReport>;
type AccountBalances = ReadonlyMap<string, ReportedAmount[]>;
type CashBalanceReports = { selected: BalanceReport; valued: BalanceReport };
@@ -0,0 +1,11 @@
import type { ReportedAmount } from '../../../amounts.js';
import type { BalanceReport } from '../../../commands/balance.js';
import { reportedTotalInCurrency } from '../balances.js';
export function portfolioValue(
marketBalances: BalanceReport,
currency: string | null
): ReportedAmount | null {
if (currency === null) return null;
return reportedTotalInCurrency(marketBalances.total, marketBalances.rows.values(), currency);
}
@@ -1,4 +1,4 @@
import { formatQuantity } from '../../amounts.js';
import { formatQuantity } from '../../../amounts.js';
export interface PreparedPortfolioValues {
commodity: string;
@@ -9,6 +9,26 @@ export interface PreparedPortfolioValues {
cash: 'ranked' | 'zero' | 'unavailable';
}
export function portfolioValueBreakdown(
coveredHoldings: readonly { security: string; quantity: string | null }[] | null,
currency: string,
cashQuantity: string | null
): PreparedPortfolioValues {
return preparePortfolioValues(pricedSecurities(coveredHoldings), currency, cashQuantity);
}
function pricedSecurities(
holdings: readonly { security: string; quantity: string | null }[] | null
) {
if (holdings === null) return null;
const prices = [];
for (const { security, quantity } of holdings) {
if (!security || quantity === null) return null;
prices.push({ security, quantity });
}
return prices;
}
export const largestHoldingLimit = 5;
function decimalQuantity(quantity: string) {
@@ -0,0 +1,6 @@
export function countPortfolioSecurities(
holdings: readonly { security: string }[] | null
): number | null {
// Native open-lot rows count even when their units would round to zero in JSON.
return holdings === null ? null : new Set(holdings.map(({ security }) => security)).size;
}
@@ -0,0 +1,33 @@
import { isoDate } from '../../../report-date.js';
import type { Period } from '../../cash-and-net-worth/ranges.js';
import { reportedTotalInCurrency } from '../balances.js';
import type { InvestmentReports } from '../native-reports.js';
export function priorInvestmentMonths(asOf: string): Period[] {
const date = new Date(`${asOf}T00:00:00Z`);
date.setUTCDate(1);
date.setUTCMonth(date.getUTCMonth() - 5);
return Array.from({ length: 5 }, () => {
const begin = isoDate(date);
date.setUTCMonth(date.getUTCMonth() + 1);
return { begin, endExclusive: isoDate(date) };
});
}
export function portfolioHistory(
{ months, rows, totals }: InvestmentReports['monthlyBalances'],
firstDate: string | null,
currency: string | null
) {
return months.map(({ endExclusive }, column) => {
const lastDay = new Date(`${endExclusive}T00:00:00Z`);
lastDay.setUTCDate(lastDay.getUTCDate() - 1);
const date = isoDate(lastDay);
if (currency === null || firstDate === null || date < firstDate) return { date, total: null };
const accountBalances = [...rows.values()].map((amounts) => amounts[column]);
return {
date,
total: reportedTotalInCurrency(totals[column], accountBalances, currency)
};
});
}
@@ -0,0 +1,33 @@
import { mayHaveBalance } from './balances.js';
import type { InvestmentReports } from './native-reports.js';
/** Open holdings are usable only if the native reports cover all in-scope securities. */
export function coveredOpenHoldings(
{
openHoldings,
allHoldings,
investmentBalances,
virtualBalances
}: Pick<
InvestmentReports,
'openHoldings' | 'allHoldings' | 'investmentBalances' | 'virtualBalances'
>,
cashCommodities: ReadonlySet<string>
): InvestmentReports['openHoldings'] | null {
// Holdings doesn't account for virtual securities, even if a real lot in the
// same account and commodity appears in the coverage report.
for (const amounts of virtualBalances.rows.values()) {
if (amounts.some((amount) => mayHaveBalance(amount) && !cashCommodities.has(amount.commodity)))
return null;
}
const holdingPairs = new Set(
allHoldings.map(({ account, security }) => JSON.stringify([account, security]))
);
for (const [account, amounts] of investmentBalances.rows) {
for (const amount of amounts) {
if (!mayHaveBalance(amount) || cashCommodities.has(amount.commodity)) continue;
if (!holdingPairs.has(JSON.stringify([account, amount.commodity]))) return null;
}
}
return openHoldings;
}
@@ -0,0 +1,64 @@
import { expect, it } from 'vitest';
import { ReportStreamReader } from '../../report-stream.js';
import { nativeInvestmentReports } from './native-reports.js';
const account = 'Assets:Brokerage';
const april = { begin: '2026-04-01', endExclusive: '2026-05-01' };
const balance = (accountName: string, commodity: string, quantity: number) => {
const amounts = [
{ acommodity: commodity, aquantity: { decimalMantissa: quantity, decimalPlaces: 0 } }
];
return [[[accountName, accountName, 0, amounts]], amounts];
};
it('uses cash preflight to select the query but reads fresh cash evidence in batch order', async () => {
const reports = await nativeInvestmentReports({
investmentAccountNames: [account],
asOf: '2026-05-12',
baseCurrency: 'USD',
priorMonths: [april],
lotCommodities: new Set(),
async readPreflight(command) {
expect(command).toContain('type:C');
return JSON.stringify(balance('Assets:Bank', 'EUR', 5));
}
});
expect(reports.commands.filter((command) => command.includes('cur:^(EUR)$'))).toHaveLength(2);
const reader = new ReportStreamReader(
(async function* () {
for (const document of [
balance(account, 'EUR', 3),
balance(account, 'USD', 6),
balance('Assets:Bank', 'GBP', 9),
balance(account, 'EUR', 3),
balance(account, 'USD', 6),
[[], []],
[],
[],
{
prDates: [
[
{ tag: 'Exact', contents: april.begin },
{ tag: 'Exact', contents: april.endExclusive }
]
],
prRows: [],
prTotals: { prrAmounts: [[]] }
}
])
yield Buffer.from(`${JSON.stringify(document)}\n`);
})(),
() => {}
);
const { cashAccountBalances, cashSubtotalReports } = await reports.read(reader);
expect(cashAccountBalances.rows.get('Assets:Bank')).toEqual([
{ commodity: 'GBP', quantity: '9' }
]);
expect(cashSubtotalReports?.selected.rows.get(account)).toEqual([
{ commodity: 'EUR', quantity: '3' }
]);
expect(cashSubtotalReports?.valued.rows.get(account)).toEqual([
{ commodity: 'USD', quantity: '6' }
]);
await reader.eof();
});
@@ -1,11 +1,15 @@
import { decodeBalanceReport } from '../accounts/balances.js';
import { parseExactJson, reportedAmounts, type Amount } from '../../amounts.js';
import { parseExactJson } from '../../amounts.js';
import {
flatHistoricalBalanceCommand,
monthlyHistoricalBalanceCommand,
type BalanceValuation
} from '../../commands/balance.js';
import type { Period } from '../cash-and-net-worth/ranges.js';
import { isoDate } from '../../report-date.js';
import type { ReportStreamReader } from '../../report-stream.js';
import { identifyCashCommodities } from './cash.js';
export async function planInvestmentReports({
export async function nativeInvestmentReports({
investmentAccountNames,
asOf,
baseCurrency,
@@ -22,30 +26,31 @@ export async function planInvestmentReports({
}) {
const end = dayAfter(asOf);
const scope = accountQuery(investmentAccountNames);
const cashAccountCommand = [...balanceCommand(end), 'type:C'];
const cashAccountCommand = flatHistoricalBalanceCommand(end, ['type:C']);
const valuation = { date: asOf, commodity: baseCurrency };
const holdingsCurrency =
!lotCommodities.has(baseCurrency) && canValueHoldingsIn(baseCurrency) ? baseCurrency : null;
const cashSubtotalReports = await planCashReports({
const cashSubtotalReports = await cashSubtotalReportsForScope({
cashAccountCommand,
end,
scope,
marketValue: holdingsCurrency === null ? null : valueAt(asOf, holdingsCurrency),
valuation: holdingsCurrency === null ? null : valuation,
lotCommodities,
readPreflight
});
// This is the wire order for both the hledger batch and the stream reader.
const reports = {
investmentBalances: balanceReport(end, scope),
marketBalances: balanceReport(end, scope, valueAt(asOf, baseCurrency)),
cashAccountBalances: jsonReport(cashAccountCommand, decodeBalanceReport),
investmentBalances: jsonReport(flatHistoricalBalanceCommand(end, [scope])),
marketBalances: jsonReport(flatHistoricalBalanceCommand(end, [scope], valuation)),
cashAccountBalances: jsonReport(cashAccountCommand),
cashSubtotalReports,
virtualBalances: balanceReport(end, scope, 'real:0'),
virtualBalances: jsonReport(flatHistoricalBalanceCommand(end, [scope, 'real:0'])),
openHoldings: openHoldingsReport(asOf, end, scope, holdingsCurrency),
// Closed lots can leave cost entries in balance JSON. They establish coverage,
// but only open lots count towards the securities held.
allHoldings: allHoldingsReport(asOf, end, scope),
monthlyBalances: monthlyBalanceReport(scope, priorMonths, baseCurrency)
monthlyBalances: jsonReport(monthlyHistoricalBalanceCommand(priorMonths, [scope], baseCurrency))
};
return {
@@ -55,16 +60,22 @@ export async function planInvestmentReports({
};
}
type InvestmentReportPlan = Awaited<ReturnType<typeof planInvestmentReports>>;
export type InvestmentReports = Awaited<ReturnType<InvestmentReportPlan['read']>>;
type NativeReportSet = Awaited<ReturnType<typeof nativeInvestmentReports>>;
export type InvestmentReports = Awaited<ReturnType<NativeReportSet['read']>>;
type Report<Result> = {
commands: string[][];
read: (reader: ReportStreamReader) => Promise<Result>;
};
function jsonReport<Result>(command: string[], decode: (json: string) => Result): Report<Result> {
return { commands: [command], read: async (reader) => decode(await reader.json()) };
function jsonReport<Result>({
args,
decode
}: {
args: string[];
decode: (json: string) => Result;
}): Report<Result> {
return { commands: [args], read: async (reader) => decode(await reader.json()) };
}
async function readReports<Results extends object>(
@@ -91,44 +102,29 @@ function escapeQueryLiteral(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
function valueAt(date: string, commodity: string): string {
return `--value=${date},${commodity}`;
}
function balanceCommand(end: string): string[] {
return ['balance', '--flat', '--historical', '--empty', '-Ojson', '-e', end, `not:date:${end}..`];
}
function balanceReport(
end: string,
...args: string[]
): Report<ReturnType<typeof decodeBalanceReport>> {
return jsonReport([...balanceCommand(end), ...args], decodeBalanceReport);
}
async function planCashReports({
async function cashSubtotalReportsForScope({
cashAccountCommand,
end,
scope,
marketValue,
valuation,
lotCommodities,
readPreflight
}: {
cashAccountCommand: string[];
cashAccountCommand: ReturnType<typeof flatHistoricalBalanceCommand>;
end: string;
scope: string;
marketValue: string | null;
valuation: BalanceValuation | null;
lotCommodities: ReadonlySet<string>;
readPreflight: (command: readonly string[]) => Promise<string>;
}) {
if (marketValue === null) return { commands: [], read: async () => null };
if (valuation === null) return { commands: [], read: async () => null };
// Cash account balances supply commodity names, not the subtotal for these investments.
const { rows } = decodeBalanceReport(await readPreflight(cashAccountCommand));
const { rows } = cashAccountCommand.decode(await readPreflight(cashAccountCommand.args));
const selector = cashCommodityQuery(identifyCashCommodities(rows, lotCommodities));
if (!selector) return { commands: [], read: async () => null };
const selected = balanceReport(end, scope, selector);
const valued = balanceReport(end, scope, selector, marketValue);
const selected = jsonReport(flatHistoricalBalanceCommand(end, [scope, selector]));
const valued = jsonReport(flatHistoricalBalanceCommand(end, [scope, selector], valuation));
return {
commands: [...selected.commands, ...valued.commands],
async read(reader: ReportStreamReader) {
@@ -161,20 +157,27 @@ function holdingsCommand(asOf: string, end: string, scope: string): string[] {
function openHoldingsReport(asOf: string, end: string, scope: string, commodity: string | null) {
const command = holdingsCommand(asOf, end, scope);
if (commodity !== null) {
command.push(valueAt(asOf, commodity), '--round=none', `--commodity-style="${commodity}" 1.00`);
command.push(
`--value=${asOf},${commodity}`,
'--round=none',
`--commodity-style="${commodity}" 1.00`
);
}
return jsonReport(command, (text) =>
decodeHoldings(text, (identity, value) => ({
...identity,
quantity: decodeHoldingQuantity(value, commodity)
}))
);
return jsonReport({
args: command,
decode: (text) =>
decodeHoldings(text, (identity, value) => ({
...identity,
quantity: decodeHoldingQuantity(value, commodity)
}))
});
}
function allHoldingsReport(asOf: string, end: string, scope: string) {
return jsonReport([...holdingsCommand(asOf, end, scope), '--empty'], (text) =>
decodeHoldings(text, (identity) => identity)
);
return jsonReport({
args: [...holdingsCommand(asOf, end, scope), '--empty'],
decode: (text) => decodeHoldings(text, (identity) => identity)
});
}
type HoldingIdentity = { account: string; security: string };
@@ -204,54 +207,3 @@ function decodeHoldingQuantity(value: unknown, commodity: string | null): string
const quantity = value.slice(prefix.length);
return /^-?\d+(?:\.\d{1,255})?(?![\s\S])/.test(quantity) ? quantity : null;
}
function monthlyBalanceReport(scope: string, months: readonly Period[], commodity: string) {
const command = [
...balanceCommand(months.at(-1)!.endExclusive),
scope,
'--monthly',
'-b',
months[0].begin,
valueAt('end', commodity)
];
return jsonReport(command, (text) => decodeMonthlyBalances(text, months));
}
type NativeBoundary = { tag: string; contents: string };
interface NativeMonthlyBalance {
prDates: [NativeBoundary, NativeBoundary][];
prRows: { prrName: string; prrAmounts: Amount[][] }[];
prTotals: { prrAmounts: Amount[][] };
}
function decodeMonthlyBalances(text: string, months: readonly Period[]) {
const report = parseExactJson(text) as Partial<NativeMonthlyBalance> | null;
const failure = () => new Error('Invalid native monthly investment balances.');
if (
!Array.isArray(report?.prDates) ||
report.prDates.length !== months.length ||
!Array.isArray(report.prRows)
)
throw failure();
for (const [index, { begin, endExclusive }] of months.entries()) {
const period = report.prDates[index];
if (
period?.length !== 2 ||
period[0]?.tag !== 'Exact' ||
period[0].contents !== begin ||
period[1]?.tag !== 'Exact' ||
period[1].contents !== endExclusive
)
throw failure();
}
function amounts(columns: Amount[][] | undefined) {
if (!Array.isArray(columns) || columns.length !== months.length) throw failure();
return columns.map(reportedAmounts);
}
const rows = new Map<string, ReturnType<typeof amounts>>();
for (const row of report.prRows) {
if (!row || typeof row.prrName !== 'string' || rows.has(row.prrName)) throw failure();
rows.set(row.prrName, amounts(row.prrAmounts));
}
return { rows, totals: amounts(report.prTotals?.prrAmounts) };
}
@@ -1,13 +1,17 @@
import type { ReportedAmount } from '../../amounts.js';
import type { Period } from '../cash-and-net-worth/ranges.js';
import { isoDate } from '../../report-date.js';
import type { ReportStreamReader } from '../../report-stream.js';
import type { journalMetadata } from '../../journal-stats.js';
import type { QualifiedAccount } from '../discover-journal.js';
import { mayHaveBalance, reportedTotalInCurrency } from './balances.js';
import { identifyCashCommodities, investmentCashValue } from './cash.js';
import { planInvestmentReports, type InvestmentReports } from './hledger-reports.js';
import { preparePortfolioValues, type PreparedPortfolioValues } from './portfolio-values.js';
import { coveredOpenHoldings } from './holdings-coverage.js';
import { nativeInvestmentReports, type InvestmentReports } from './native-reports.js';
import { portfolioValue } from './displays/portfolio-value.js';
import {
portfolioValueBreakdown,
type PreparedPortfolioValues
} from './displays/portfolio-values.js';
import { countPortfolioSecurities } from './displays/securities-held.js';
import { portfolioHistory, priorInvestmentMonths } from './displays/value-history.js';
export interface PreparedInvestmentOverview {
investmentAccountNames: string[];
@@ -19,7 +23,7 @@ export interface PreparedInvestmentOverview {
history?: { date: string; total: ReportedAmount | null }[];
}
export async function planInvestmentOverview({
export async function investmentOverviewReports({
configuredInvestmentAccounts,
journalStats,
journalAccounts,
@@ -54,7 +58,7 @@ export async function planInvestmentOverview({
}
const priorMonths = priorInvestmentMonths(asOf);
const reports = await planInvestmentReports({
const reports = await nativeInvestmentReports({
investmentAccountNames,
asOf,
baseCurrency,
@@ -68,7 +72,6 @@ export async function planInvestmentOverview({
async read(reader: ReportStreamReader): Promise<PreparedInvestmentOverview> {
const evidence = await reports.read(reader);
return assembleOverview(overview, evidence, {
priorMonths,
firstDate: journalCoverage.firstDate,
balanceCurrency,
holdingsCurrency: reports.holdingsCurrency,
@@ -86,13 +89,11 @@ function assembleOverview(
overview: PreparedInvestmentOverview,
reports: InvestmentReports,
{
priorMonths,
firstDate,
balanceCurrency,
holdingsCurrency,
lotCommodities
}: {
priorMonths: readonly Period[];
firstDate: string | null;
balanceCurrency: string | null;
holdingsCurrency: string | null;
@@ -104,42 +105,27 @@ function assembleOverview(
return { ...overview, state: 'scope-unavailable' };
}
const {
investmentBalances,
marketBalances,
cashAccountBalances,
cashSubtotalReports,
openHoldings,
monthlyBalances
} = reports;
const cashCommodities = identifyCashCommodities(cashAccountBalances.rows, lotCommodities);
const securityCount = countPortfolioSecurities(reports, cashCommodities);
let portfolioValues = null;
if (holdingsCurrency !== null) {
const cash = investmentCashValue({
investmentBalances: investmentBalances.rows,
cashReports: cashSubtotalReports,
cashCommodities,
currency: holdingsCurrency,
investmentAccountNames
});
const securities = securityCount === null ? null : pricedSecurities(openHoldings);
portfolioValues = preparePortfolioValues(securities, holdingsCurrency, cash?.quantity ?? null);
}
const cashCommodities = identifyCashCommodities(reports.cashAccountBalances.rows, lotCommodities);
const holdings = coveredOpenHoldings(reports, cashCommodities);
const verifiedCash =
holdingsCurrency === null
? null
: investmentCashValue({
investmentBalances: reports.investmentBalances.rows,
cashReports: reports.cashSubtotalReports,
cashCommodities,
currency: holdingsCurrency,
investmentAccountNames
});
return {
...overview,
securityCount,
portfolioValues,
portfolioValue:
balanceCurrency === null
securityCount: countPortfolioSecurities(holdings),
portfolioValues:
holdingsCurrency === null
? null
: reportedTotalInCurrency(
marketBalances.total,
marketBalances.rows.values(),
balanceCurrency
),
history: portfolioHistory(monthlyBalances, priorMonths, firstDate, balanceCurrency)
: portfolioValueBreakdown(holdings, holdingsCurrency, verifiedCash?.quantity ?? null),
portfolioValue: portfolioValue(reports.marketBalances, balanceCurrency),
history: portfolioHistory(reports.monthlyBalances, firstDate, balanceCurrency)
};
}
@@ -165,65 +151,3 @@ function hasOnlyConfiguredInvestmentAccounts(
];
return reportedAccounts.every((account) => investmentAccountNames.has(account));
}
function countPortfolioSecurities(
{ openHoldings, allHoldings, investmentBalances, virtualBalances }: InvestmentReports,
cashCommodities: ReadonlySet<string>
): number | null {
// Holdings doesn't account for virtual securities, even if a real lot in the
// same account and commodity appears in the coverage report.
for (const amounts of virtualBalances.rows.values()) {
if (amounts.some((amount) => mayHaveBalance(amount) && !cashCommodities.has(amount.commodity)))
return null;
}
const holdingPairs = new Set(
allHoldings.map(({ account, security }) => JSON.stringify([account, security]))
);
for (const [account, amounts] of investmentBalances.rows) {
for (const amount of amounts) {
if (!mayHaveBalance(amount) || cashCommodities.has(amount.commodity)) continue;
if (!holdingPairs.has(JSON.stringify([account, amount.commodity]))) return null;
}
}
// Native open-lot rows count even when their units would round to zero in JSON.
return new Set(openHoldings.map(({ security }) => security)).size;
}
function pricedSecurities(holdings: InvestmentReports['openHoldings']) {
const prices = [];
for (const { security, quantity } of holdings) {
if (!security || quantity === null) return null;
prices.push({ security, quantity });
}
return prices;
}
function priorInvestmentMonths(asOf: string): Period[] {
const date = new Date(`${asOf}T00:00:00Z`);
date.setUTCDate(1);
date.setUTCMonth(date.getUTCMonth() - 5);
return Array.from({ length: 5 }, () => {
const begin = isoDate(date);
date.setUTCMonth(date.getUTCMonth() + 1);
return { begin, endExclusive: isoDate(date) };
});
}
function portfolioHistory(
balances: InvestmentReports['monthlyBalances'],
months: readonly Period[],
firstDate: string | null,
currency: string | null
) {
return months.map(({ endExclusive }, column) => {
const lastDay = new Date(`${endExclusive}T00:00:00Z`);
lastDay.setUTCDate(lastDay.getUTCDate() - 1);
const date = isoDate(lastDay);
if (currency === null || firstDate === null || date < firstDate) return { date, total: null };
const accountBalances = [...balances.rows.values()].map((amounts) => amounts[column]);
return {
date,
total: reportedTotalInCurrency(balances.totals[column], accountBalances, currency)
};
});
}
@@ -9,7 +9,7 @@ it('plans one pair of journal exports and registers only for unambiguous account
);
const { commands } = buildReportSequence({
overviewPlan: planOverviewReports(journal),
investmentPlan: null,
investmentReports: null,
journalDiscovery: {
journal,
accounts: [
+15 -15
View File
@@ -1,7 +1,7 @@
import {
accountBalanceReports,
organizeAccountBalance,
planAccountBalances,
readAccountBalances,
type AccountBalanceReports,
type PreparedBalance
} from './accounts/balances.js';
import { planOverviewReports, readOverviewReports } from './cash-and-net-worth/plan.js';
@@ -9,7 +9,7 @@ import { organizeOverviewData } from './cash-and-net-worth/report.js';
import type { ReportStreamReader } from '../report-stream.js';
import type { PreparationTransactions } from '../transactions/store.js';
import { writePreparedAccountRows, type AccountRowWriter } from './accounts/register-rows.js';
import type { planInvestmentOverview } from './investment-overview/prepare.js';
import type { investmentOverviewReports } from './investment-overview/prepare.js';
import type { JournalDiscovery, QualifiedAccount } from './discover-journal.js';
export interface PreparedAccountSummary extends QualifiedAccount {
@@ -20,14 +20,14 @@ export interface PreparedAccountSummary extends QualifiedAccount {
export function buildReportSequence({
journalDiscovery,
overviewPlan,
investmentPlan
investmentReports
}: {
journalDiscovery: JournalDiscovery;
overviewPlan: ReturnType<typeof planOverviewReports>;
investmentPlan: Awaited<ReturnType<typeof planInvestmentOverview>>;
investmentReports: Awaited<ReturnType<typeof investmentOverviewReports>>;
}) {
const { journal: journalStats, accounts: journalAccounts, investment } = journalDiscovery;
const accountBalanceCommands = planAccountBalances(journalStats);
const accountBalances = accountBalanceReports(journalStats);
const accountRegisters = journalAccounts.flatMap(({ name, access }, index) =>
access === 'ready' ? [{ index, command: accountRegisterCommand(name) }] : []
);
@@ -37,9 +37,9 @@ export function buildReportSequence({
['print', '--round=none', '-Ojson'],
['print', '--round=none', '--value=transacted', '-Ojson'],
...overviewPlan.commands,
...accountBalanceCommands,
...accountBalances.commands,
...accountRegisters.map(({ command }) => command),
...(investmentPlan?.commands ?? [])
...(investmentReports?.commands ?? [])
];
return {
commands,
@@ -57,7 +57,8 @@ export function buildReportSequence({
) {
await importTransactionExports(reader, transactions, journalStats, check);
const overview = await readOverview(reader, overviewPlan, journalStats, transactions, check);
const accounts = await readAccountSummaries(reader, journalAccounts, journalStats);
const balances = await accountBalances.read(reader);
const accounts = summarizeAccounts(journalAccounts, journalStats, balances);
for (const { index } of accountRegisters) {
await writePreparedAccountRows(
reader,
@@ -68,7 +69,7 @@ export function buildReportSequence({
check
);
}
const investmentOverview = await investmentPlan?.read(reader);
const investmentOverview = await investmentReports?.read(reader);
return { overview, accounts, investmentOverview };
}
};
@@ -118,12 +119,11 @@ async function readOverview(
);
}
async function readAccountSummaries(
reader: ReportStreamReader,
function summarizeAccounts(
journalAccounts: readonly QualifiedAccount[],
{ asOf, baseCurrency }: JournalDiscovery['journal']
): Promise<PreparedAccountSummary[]> {
const balances = await readAccountBalances(reader, asOf);
{ asOf, baseCurrency }: JournalDiscovery['journal'],
balances: AccountBalanceReports
): PreparedAccountSummary[] {
return journalAccounts.map(({ name, access }) => ({
name,
access,