Pair Cash and Net Worth commands with their decoders #73

Merged
eleith merged 1 commits from refactor/pair-overview-report-commands into main 2026-11-22 23:47:27 +00:00
19 changed files with 289 additions and 243 deletions

No files matched your search

@@ -0,0 +1,5 @@
---
'@hledger-reports/worker': patch
---
Pair Cash and Net Worth’s hledger commands with their matching decoders. Report periods, values, and the saved format are unchanged.
+3 -3
View File
@@ -17,9 +17,9 @@ 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.
The saved `balance`, `incomestatement`, and `balancesheet` forms return their
arguments and matching decoder together. Report recipes 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
@@ -1,11 +1,18 @@
import { expect, it } from 'vitest';
import { formatQuantity, parseExactJson } from '../amounts.js';
import { parseBalanceSheet } from './balance-sheet.js';
import { historicalBalanceSheetCommand } from './balance-sheet.js';
const balanceSheet = historicalBalanceSheetCommand({
begin: '2026-04-01',
endExclusive: '2026-04-17',
depth: 1,
valuation: { date: '2026-04-16', commodity: 'USD' }
});
it('decodes exact native net quantities and retains unconsumed wire fields unchanged', () => {
const json =
'{"cbrDates":[],"cbrSubreports":[],"cbrTotals":{"prrAmounts":[[{"acommodity":"USD","aquantity":{"decimalMantissa":900719925474099301,"decimalPlaces":2},"acost":null}]],"prrAverage":[]},"nativeExtra":{"untouched":true}}';
const report = parseBalanceSheet(json);
const report = balanceSheet.decode(json);
expect(report).toEqual(parseExactJson(json));
expect(report.cbrTotals.prrAmounts[0][0].aquantity.decimalMantissa).toBe(900719925474099301n);
expect(formatQuantity(report.cbrTotals.prrAmounts[0][0].aquantity)).toBe('9007199254740993.01');
@@ -20,5 +27,5 @@ it.each([
'{"cbrDates":null,"cbrSubreports":[],"cbrTotals":{}}',
'{"cbrDates":[],"cbrSubreports":[]}'
])('rejects missing balance-sheet wire fields (case %#)', (text) => {
expect(() => parseBalanceSheet(text)).toThrow();
expect(() => balanceSheet.decode(text)).toThrow();
});
@@ -21,8 +21,8 @@ export function historicalBalanceSheetCommand({
endExclusive: string;
depth: number;
valuation: { date: string; commodity: string };
}): string[] {
return [
}) {
const args = [
'balancesheet',
'--historical',
'--flat',
@@ -37,9 +37,10 @@ export function historicalBalanceSheetCommand({
'-Ojson',
`not:date:${endExclusive}..`
];
return { args, decode: decodeBalanceSheet };
}
export function parseBalanceSheet(json: string): HledgerBalanceSheet {
function decodeBalanceSheet(json: string): HledgerBalanceSheet {
const report = parseExactJson(json);
if (
report === null ||
@@ -1,10 +1,18 @@
import { expect, it } from 'vitest';
import { formatQuantity } from '../amounts.js';
import { parseIncomeStatement } from './income-statement.js';
import { monthlyIncomeStatementCommand } from './income-statement.js';
const incomeStatement = monthlyIncomeStatementCommand({
begin: '2026-04-01',
calendarEndExclusive: '2026-05-01',
postingCutoffExclusive: '2026-04-17',
depth: 2,
excludeCapitalGains: true
});
it('parses exact mantissas in monthly and range totals', () => {
const json = `{"cbrDates":[],"cbrTotals":{"prrTotal":[]},"cbrSubreports":[["Revenues",{"prTotals":{"prrAmounts":[[{"acommodity":"USD","acost":null,"aquantity":{"decimalMantissa":900719925474099301,"decimalPlaces":2}}]],"prrTotal":[{"acommodity":"USD","aquantity":{"decimalMantissa":900719925474099301,"decimalPlaces":2}}]},"prRows":[]},true]]}`;
const report = parseIncomeStatement(json);
const report = incomeStatement.decode(json);
expect(report.cbrSubreports[0][1].prTotals.prrAmounts[0][0].aquantity.decimalMantissa).toBe(
900719925474099301n
);
@@ -23,5 +31,5 @@ it.each([
'SECRET invalid JSON',
'{"cbrDates":[],"cbrTotals":{"prrTotal":[]},"cbrSubreports":null}'
])('rejects malformed report shapes (case %#)', (text) => {
expect(() => parseIncomeStatement(text)).toThrow();
expect(() => incomeStatement.decode(text)).toThrow();
});
@@ -25,8 +25,8 @@ export function monthlyIncomeStatementCommand({
postingCutoffExclusive: string;
depth: number;
excludeCapitalGains: boolean;
}): string[] {
return [
}) {
const args = [
'incomestatement',
'--flat',
'--change',
@@ -42,11 +42,12 @@ export function monthlyIncomeStatementCommand({
// Monthly expansion can include postings beyond a mid-month cutoff.
`not:date:${postingCutoffExclusive}..`
];
return { args, decode: decodeIncomeStatement };
}
const failureMessage = 'Invalid native income statement.';
export function parseIncomeStatement(json: string): HledgerIncomeStatement {
function decodeIncomeStatement(json: string): HledgerIncomeStatement {
const report = parseExactJson(json);
if (
report === null ||
@@ -1,8 +1,7 @@
import { expect, it } from 'vitest';
import { planOverviewReports, readOverviewReports } from './plan.js';
import { cashAndNetWorthReports } from './native-reports.js';
import { journalMetadata } from '../../journal-stats.js';
import { ReportStreamReader } from '../../report-stream.js';
import { balanceReports, incomeReports } from '../../../test-fixtures.js';
import { balanceReports, incomeReports, reportReader } from '../../../test-fixtures.js';
const aprilJournal = journalMetadata(`Base currency : USD
Last txn : 2026-04-16
@@ -10,23 +9,13 @@ Txns : 12
Txns span : 2025-06-01 to 2026-04-17
`);
function readerFor(documents: string[]) {
return new ReportStreamReader(
(async function* () {
yield Buffer.from(documents.join('\n'));
})(),
() => {}
);
}
it('keeps the calendar column for Cash and values the last Net Worth point at the journal date', () => {
const plan = planOverviewReports(aprilJournal);
expect(plan.incomeRanges.map(({ months }) => months)).toEqual([1, 3, 6, 12]);
expect(plan.commands.map(([command]) => command)).toEqual([
const { commands } = cashAndNetWorthReports(aprilJournal);
expect(commands.map(([command]) => command)).toEqual([
...Array(4).fill('incomestatement'),
...Array(12).fill('balancesheet')
]);
const income = plan.commands[0];
const income = commands[0];
expect(income).toEqual(
expect.arrayContaining([
'--change',
@@ -42,7 +31,7 @@ it('keeps the calendar column for Cash and values the last Net Worth point at th
'-e',
'2026-05-01'
]);
const latest = plan.commands.at(-1);
const latest = commands.at(-1);
expect(latest).toEqual(
expect.arrayContaining([
'--historical',
@@ -57,36 +46,43 @@ it('keeps the calendar column for Cash and values the last Net Worth point at th
'-e',
'2026-04-17'
]);
expect(plan.snapshotPeriods.slice(-2)).toEqual([
{ begin: '2026-03-01', endExclusive: '2026-04-01', date: '2026-03-31' },
{ begin: '2026-04-01', endExclusive: '2026-04-17', date: '2026-04-16' }
]);
expect(commands.at(-2)).toContain('--value=2026-03-31,USD');
});
it('reads native JSON in plan order and attaches supplied counts and discovery coverage unchanged', async () => {
const plan = planOverviewReports(aprilJournal);
it('reads native JSON in command order and attaches counts to their primary transaction date windows', async () => {
const overview = cashAndNetWorthReports(aprilJournal);
const statements = incomeReports();
statements[0] = statements[0].replace(
'"prrTotal":[]',
'"prrTotal":[{"acommodity":"USD","aquantity":{"decimalMantissa":900719925474099306,"decimalPlaces":2}}]'
);
const reader = readerFor([...statements, ...balanceReports()]);
const reports = await readOverviewReports(reader, aprilJournal, plan, [1, 3, 6, 12]);
const reader = reportReader([...statements, ...balanceReports()]);
const countsByStart = new Map([
['2026-04-01', 2],
['2026-02-01', 7],
['2025-11-01', 11],
['2025-05-01', 19]
]);
const reports = await overview.read(reader, (begin, endExclusive) => {
expect(endExclusive).toBe('2026-04-17');
const count = countsByStart.get(begin);
if (count === undefined) throw new Error(`Unexpected count window: ${begin}`);
return count;
});
expect(reports.journalCoverage).toEqual(aprilJournal.journalCoverage);
expect(
reports.incomeStatements.map(({ months, transactionCount }) => [months, transactionCount])
).toEqual([
[1, 1],
[3, 3],
[6, 6],
[12, 12]
[1, 2],
[3, 7],
[6, 11],
[12, 19]
]);
expect(reports.incomeStatements[0].report.cbrTotals.prrTotal[0].aquantity.decimalMantissa).toBe(
900719925474099306n
);
expect(reports.snapshots.map(({ date }) => date)).toEqual(
plan.snapshotPeriods.map(({ date }) => date)
);
expect(reports.snapshots).toHaveLength(12);
expect(reports.snapshots.slice(-2).map(({ date }) => date)).toEqual(['2026-03-31', '2026-04-16']);
expect(reports.snapshots.at(-1)?.report.cbrDates[0][1].contents).toBe('2026-04-17');
await reader.eof();
});
@@ -97,26 +93,34 @@ it.each([
['0001-12-31', '0001-01-01', '0001-11-30', '0002-01-01']
])(
'derives twelve calendar months and the actual cutoff from %s',
(asOf, begin, previous, cutoff) => {
const plan = planOverviewReports({ asOf, baseCurrency: 'USD' });
const twelveMonthRange = plan.incomeRanges.find(({ months }) => months === 12);
expect(twelveMonthRange).toMatchObject({ begin, endExclusive: cutoff });
expect(plan.snapshotPeriods.slice(-2).map(({ date }) => date)).toEqual([previous, asOf]);
async (asOf, begin, previous, cutoff) => {
const overview = cashAndNetWorthReports({ ...aprilJournal, asOf });
const reader = reportReader([...incomeReports(asOf), ...balanceReports(asOf)]);
const reports = await overview.read(reader, () => 0);
expect(reports.incomeStatements.find(({ months }) => months === 12)).toMatchObject({
begin,
endExclusive: cutoff
});
expect(reports.snapshots.slice(-2).map(({ date }) => date)).toEqual([previous, asOf]);
await reader.eof();
}
);
it('rejects a twelve-month window outside supported dates', () => {
expect(() => planOverviewReports({ asOf: '0001-06-30', baseCurrency: 'USD' })).toThrow();
expect(() => cashAndNetWorthReports({ ...aprilJournal, asOf: '0001-06-30' })).toThrow();
});
it('omits all financial commands and reads for undated input', async () => {
const metadata = journalMetadata(
'Base currency : USD\nLast txn : none\nTxns : 0\nTxns span : to \n'
);
const plan = planOverviewReports(metadata);
expect(plan).toEqual({ commands: [], incomeRanges: [], snapshotPeriods: [] });
const reader = readerFor([]);
expect(await readOverviewReports(reader, metadata, plan, [])).toEqual({
const overview = cashAndNetWorthReports(metadata);
expect(overview.commands).toEqual([]);
const reader = reportReader([]);
const reports = await overview.read(reader, () => {
throw new Error('Undated journals have no count windows.');
});
expect(reports).toEqual({
...metadata,
incomeStatements: [],
snapshots: []
@@ -127,12 +131,6 @@ it('omits all financial commands and reads for undated input', async () => {
it.each([1, 7])('rejects a malformed native financial document at index %i', async (index) => {
const documents = [...incomeReports(), ...balanceReports()];
documents[index] = '{"cbrDates":[],"cbrTotals":{},"cbrSubreports":null}';
await expect(
readOverviewReports(
readerFor(documents),
aprilJournal,
planOverviewReports(aprilJournal),
[1, 3, 6, 12]
)
).rejects.toThrow();
const overview = cashAndNetWorthReports(aprilJournal);
await expect(overview.read(reportReader(documents), () => 0)).rejects.toThrow();
});
@@ -0,0 +1,104 @@
import {
historicalBalanceSheetCommand,
type HledgerBalanceSheet
} from '../../commands/balance-sheet.js';
import {
monthlyIncomeStatementCommand,
type HledgerIncomeStatement
} from '../../commands/income-statement.js';
import type { journalMetadata, JournalCoverage } from '../../journal-stats.js';
import type { ReportStreamReader } from '../../report-stream.js';
import { isoDate } from '../../report-date.js';
import { planIncomeRanges, type IncomeRangePlan, type Period } from './ranges.js';
type SnapshotPeriod = Period & { date: string };
export interface OverviewReports {
asOf: string | null;
baseCurrency: string;
journalCoverage: JournalCoverage;
incomeStatements: (IncomeRangePlan & {
transactionCount: number;
report: HledgerIncomeStatement;
})[];
snapshots: (SnapshotPeriod & { report: HledgerBalanceSheet })[];
}
export function cashAndNetWorthReports(metadata: ReturnType<typeof journalMetadata>) {
const { asOf, baseCurrency } = metadata;
const incomeRanges = asOf === null ? [] : planIncomeRanges(asOf);
const snapshotPeriods = asOf === null ? [] : netWorthSnapshotPeriods(incomeRanges, asOf);
const incomeStatements = incomeRanges.map((range) => ({
range,
command: monthlyIncomeStatementCommand({
begin: range.begin,
calendarEndExclusive: range.periods.at(-1)!.endExclusive,
postingCutoffExclusive: range.endExclusive,
depth: 2,
excludeCapitalGains: true
})
}));
const balanceSheets = snapshotPeriods.map((period) => ({
period,
command: historicalBalanceSheetCommand({
begin: period.begin,
endExclusive: period.endExclusive,
depth: 1,
valuation: { date: period.date, commodity: baseCurrency }
})
}));
return {
commands: [...incomeStatements, ...balanceSheets].map(({ command }) => command.args),
async read(
reader: ReportStreamReader,
countTransactionsByPrimaryDate: (
begin: string,
endExclusive: string
) => number | Promise<number>
): Promise<OverviewReports> {
// Finish the transaction lookups before consuming the native statements.
const countedStatements = [];
for (const { range, command } of incomeStatements) {
const transactionCount = await countTransactionsByPrimaryDate(
range.begin,
range.endExclusive
);
countedStatements.push({ range, command, transactionCount });
}
const statements: OverviewReports['incomeStatements'] = [];
for (const { range, command, transactionCount } of countedStatements) {
statements.push({
...range,
transactionCount,
report: command.decode(await reader.json())
});
}
const snapshots: OverviewReports['snapshots'] = [];
for (const { period, command } of balanceSheets) {
snapshots.push({ ...period, report: command.decode(await reader.json()) });
}
return { ...metadata, incomeStatements: statements, snapshots };
}
};
}
function netWorthSnapshotPeriods(
incomeRanges: readonly IncomeRangePlan[],
asOf: string
): SnapshotPeriod[] {
const twelveMonthRange = incomeRanges.find(({ months }) => months === 12);
if (!twelveMonthRange) throw new Error('Missing twelve-month overview range.');
const asOfMonth = twelveMonthRange.periods.at(-1)!;
const completedMonths = twelveMonthRange.periods.slice(0, -1);
const monthEndSnapshots = completedMonths.map((month) => {
const lastDay = new Date(`${month.endExclusive}T00:00:00Z`);
lastDay.setUTCDate(lastDay.getUTCDate() - 1);
return { ...month, date: isoDate(lastDay) };
});
const asOfSnapshot = {
begin: asOfMonth.begin,
endExclusive: twelveMonthRange.endExclusive,
date: asOf
};
return [...monthEndSnapshots, asOfSnapshot];
}
@@ -6,7 +6,7 @@ import { generateSavedReport, getHledgerVersion } from '../../index.js';
import { MemoryPreparationTransactions } from '../transactions.fixture.js';
import { balanceReports, decodeOverviewFixture, incomeReports } from '../../../test-fixtures.js';
import { planOverviewReports } from './plan.js';
import { cashAndNetWorthReports } from './native-reports.js';
import { journalMetadata } from '../../journal-stats.js';
const dates = [
'2025-05-31',
@@ -58,7 +58,7 @@ function documents(reports = sheets()) {
};
}
it('uses the exact native net bag, retaining mixed amounts, order and explicit zero entries', () => {
it('uses the exact native net bag, retaining mixed amounts, order and explicit zero entries', async () => {
const reports = sheets();
const report = reports[11];
// Deliberately unrelated numbers: no JS accounting or net reconstruction.
@@ -71,7 +71,7 @@ it('uses the exact native net bag, retaining mixed amounts, order and explicit z
report.cbrSubreports[1][1].prTotals.prrAmounts = [
[nativeAmount('unpriced', 0), nativeAmount('only-debt', 100)]
];
const data = decodeOverviewFixture(stats(), documents(reports));
const data = await decodeOverviewFixture(stats(), documents(reports));
expect(data.netWorth).toEqual({
currency: 'USD',
points: dates.map((date, index) => ({
@@ -95,10 +95,10 @@ it('uses the exact native net bag, retaining mixed amounts, order and explicit z
it.each(['', 'US,Dollar'])(
'preserves exact native base currency %j in projections and arguments',
(currency) => {
const data = decodeOverviewFixture(stats(currency), documents());
async (currency) => {
const data = await decodeOverviewFixture(stats(currency), documents());
expect(data.netWorth?.currency).toBe(currency);
const args = planOverviewReports(journalMetadata(stats(currency))).commands.flat();
const args = cashAndNetWorthReports(journalMetadata(stats(currency))).commands.flat();
expect(args.filter((arg) => arg.startsWith('--value='))).toEqual(
dates.map((date) => `--value=${date},${currency}`)
);
@@ -142,20 +142,23 @@ it.each([
'extra liabilities column',
(r: ReturnType<typeof sheets>[number]) => r.cbrSubreports[1][1].prTotals.prrAmounts.push([])
]
])('rejects %s in a middle balance sheet without publishing partial income', (_name, mutate) => {
const reports = sheets();
mutate(reports[3]);
expect(() => decodeOverviewFixture(stats(), documents(reports))).toThrow();
});
])(
'rejects %s in a middle balance sheet without publishing partial income',
async (_name, mutate) => {
const reports = sheets();
mutate(reports[3]);
await expect(decodeOverviewFixture(stats(), documents(reports))).rejects.toThrow();
}
);
it('rejects a malformed middle balance report', () => {
it('rejects a malformed middle balance report', async () => {
const reports = documents();
reports.snapshots[2] = '{"cbrDates":[],"cbrSubreports":null}';
expect(() => decodeOverviewFixture(stats(), reports)).toThrow();
await expect(decodeOverviewFixture(stats(), reports)).rejects.toThrow();
});
describe.each(['net', 'assets', 'liabilities'] as const)('malformed consumed %s bags', (side) => {
it('rejects a null bag without publishing partial reports', () => {
it('rejects a null bag without publishing partial reports', async () => {
const reports = sheets();
const report = reports[2];
let totals;
@@ -163,7 +166,7 @@ describe.each(['net', 'assets', 'liabilities'] as const)('malformed consumed %s
else if (side === 'assets') totals = report.cbrSubreports[0][1].prTotals;
else totals = report.cbrSubreports[1][1].prTotals;
Reflect.set(totals, 'prrAmounts', [null]);
expect(() => decodeOverviewFixture(stats(), documents(reports))).toThrow();
await expect(decodeOverviewFixture(stats(), documents(reports))).rejects.toThrow();
});
});
@@ -1,5 +1,5 @@
import { reportedAmounts, type Amount } from '../../amounts.js';
import type { OverviewReports } from './plan.js';
import type { OverviewReports } from './native-reports.js';
import type { NativeValue, OverviewData } from './report.js';
const failureMessage = 'Invalid hledger net-worth report.';
@@ -1,91 +0,0 @@
import {
historicalBalanceSheetCommand,
parseBalanceSheet,
type HledgerBalanceSheet
} from '../../commands/balance-sheet.js';
import {
monthlyIncomeStatementCommand,
parseIncomeStatement,
type HledgerIncomeStatement
} from '../../commands/income-statement.js';
import type { journalMetadata, JournalCoverage } from '../../journal-stats.js';
import type { ReportStreamReader } from '../../report-stream.js';
import { isoDate } from '../../report-date.js';
import { planIncomeRanges, type IncomeRangePlan, type Period } from './ranges.js';
type SnapshotPeriod = Period & { date: string };
export interface OverviewReports {
asOf: string | null;
baseCurrency: string;
journalCoverage: JournalCoverage;
incomeStatements: (IncomeRangePlan & {
transactionCount: number;
report: HledgerIncomeStatement;
})[];
snapshots: (SnapshotPeriod & { report: HledgerBalanceSheet })[];
}
export function planOverviewReports({
asOf,
baseCurrency
}: Pick<OverviewReports, 'asOf' | 'baseCurrency'>) {
if (asOf === null) return { commands: [], incomeRanges: [], snapshotPeriods: [] };
const incomeRanges = planIncomeRanges(asOf);
const twelveMonthRange = incomeRanges.find(({ months }) => months === 12);
if (!twelveMonthRange) throw new Error('Missing twelve-month overview range.');
const snapshotPeriods = planNetWorthSnapshots(twelveMonthRange, asOf);
const incomeStatements = incomeRanges.map((range) =>
monthlyIncomeStatementCommand({
begin: range.begin,
calendarEndExclusive: range.periods.at(-1)!.endExclusive,
postingCutoffExclusive: range.endExclusive,
depth: 2,
excludeCapitalGains: true
})
);
const balanceSheets = snapshotPeriods.map(({ begin, endExclusive, date }) =>
historicalBalanceSheetCommand({
begin,
endExclusive,
depth: 1,
valuation: { date, commodity: baseCurrency }
})
);
const commands = [...incomeStatements, ...balanceSheets];
return { commands, incomeRanges, snapshotPeriods };
}
function planNetWorthSnapshots(range: IncomeRangePlan, asOf: string): SnapshotPeriod[] {
const asOfMonth = range.periods.at(-1)!;
const completedMonths = range.periods.slice(0, -1);
const monthEndSnapshots = completedMonths.map((month) => {
const lastDay = new Date(`${month.endExclusive}T00:00:00Z`);
lastDay.setUTCDate(lastDay.getUTCDate() - 1);
return { ...month, date: isoDate(lastDay) };
});
const asOfSnapshot = { begin: asOfMonth.begin, endExclusive: range.endExclusive, date: asOf };
return [...monthEndSnapshots, asOfSnapshot];
}
export async function readOverviewReports(
reader: ReportStreamReader,
metadata: ReturnType<typeof journalMetadata>,
{ incomeRanges, snapshotPeriods }: ReturnType<typeof planOverviewReports>,
transactionCounts: readonly number[]
): Promise<OverviewReports> {
const incomeStatements: OverviewReports['incomeStatements'] = [];
for (const [index, range] of incomeRanges.entries()) {
incomeStatements.push({
...range,
transactionCount: transactionCounts[index],
report: parseIncomeStatement(await reader.json())
});
}
const snapshots: OverviewReports['snapshots'] = [];
for (const period of snapshotPeriods) {
snapshots.push({ ...period, report: parseBalanceSheet(await reader.json()) });
}
return { ...metadata, incomeStatements, snapshots };
}
@@ -4,7 +4,7 @@ import { join } from 'node:path';
import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { planIncomeRanges, organizeIncomeRange } from './ranges.js';
import {
parseIncomeStatement,
monthlyIncomeStatementCommand,
type HledgerIncomeStatement
} from '../../commands/income-statement.js';
import { incomeReports } from '../../../test-fixtures.js';
@@ -14,7 +14,14 @@ import { MemoryPreparationTransactions } from '../transactions.fixture.js';
const plan = planIncomeRanges('2026-04-16')[3];
function statement(range = plan): HledgerIncomeStatement {
return parseIncomeStatement(incomeReports()[([1, 3, 6, 12] as const).indexOf(range.months)]);
const command = monthlyIncomeStatementCommand({
begin: range.begin,
calendarEndExclusive: range.periods.at(-1)!.endExclusive,
postingCutoffExclusive: range.endExclusive,
depth: 2,
excludeCapitalGains: true
});
return command.decode(incomeReports()[([1, 3, 6, 12] as const).indexOf(range.months)]);
}
const amount = (commodity: string, mantissa: bigint): Amount => ({
acommodity: commodity,
@@ -152,7 +159,7 @@ describe('native hledger 1.99.5 finite overview ranges', () => {
posting('2026-04-10', 'Costs:Refund', 'Wallet', '-5.00') +
posting('2026-04-13', 'Wallet', 'Gains', '500.00') +
posting('2026-04-14', 'expenses:not-an-expense', 'Wallet', '999.00') +
posting('2026-04-16', 'Wallet', 'Reserve', '1.00') +
posting('2026-04-16', 'Costs:Food:Groceries', 'Wallet', '1.00') +
'\n2026-04-12 Later posting\n Costs:Food 700.00 USD ; date:2026-04-17\n Wallet\n' +
'\n~ monthly from 2025-05-01\n Costs:Food 900.00 USD\n Wallet\n';
await writeFile(journal, text);
@@ -162,10 +169,10 @@ describe('native hledger 1.99.5 finite overview ranges', () => {
});
expect(overview.asOf).toBe('2026-04-16');
for (const [months, begin, income, expenses, net, food] of [
[1, '2026-04-01', '400.00', '35.00', '365.00', '40.00'],
[3, '2026-02-01', '700.00', '65.00', '635.00', '40.00'],
[6, '2025-11-01', '900.00', '85.00', '815.00', '60.00'],
[12, '2025-05-01', '1000.00', '95.00', '905.00', '70.00']
[1, '2026-04-01', '400.00', '36.00', '364.00', '41.00'],
[3, '2026-02-01', '700.00', '66.00', '634.00', '41.00'],
[6, '2025-11-01', '900.00', '86.00', '814.00', '61.00'],
[12, '2025-05-01', '1000.00', '96.00', '904.00', '71.00']
] as const) {
const range = overview.ranges![months];
expect(range).toMatchObject({
@@ -195,7 +202,7 @@ describe('native hledger 1.99.5 finite overview ranges', () => {
begin: '2026-04-01',
endExclusive: '2026-05-01',
income: usd('400.00'),
expenses: usd('35.00')
expenses: usd('36.00')
});
expect(overview.incomeExpenses.months[1]).toMatchObject({ income: [], expenses: [] });
expect(await readFile(journal, 'utf8')).toBe(text);
@@ -14,8 +14,8 @@ afterEach(() => {
vi.useRealTimers();
});
it('publishes all four ranges, a shared twelve-month history and latest native sides', () => {
const data = decodeOverviewFixture(stats, reports());
it('publishes all four ranges, a shared twelve-month history and latest native sides', async () => {
const data = await decodeOverviewFixture(stats, reports());
expect(data).toMatchObject({
asOf: '2026-04-16',
journalCoverage: { transactionCount: 12, firstDate: '2025-05-01', lastDate: '2026-04-16' },
@@ -38,7 +38,7 @@ it('publishes all four ranges, a shared twelve-month history and latest native s
expect(JSON.parse(JSON.stringify(data))).toEqual(data);
});
it('publishes monthly history only from the twelve-month statement', () => {
it('publishes monthly history only from the twelve-month statement', async () => {
const amount = (mantissa: number) =>
JSON.stringify({
acommodity: 'USD',
@@ -53,14 +53,15 @@ it('publishes monthly history only from the twelve-month statement', () => {
'"prrAmounts":[[]',
`"prrAmounts":[[${amount(222)}]`
);
const data = decodeOverviewFixture(stats, native);
const data = await decodeOverviewFixture(stats, native);
expect(data.incomeExpenses.months[0].income).toEqual([{ commodity: 'USD', quantity: '2.22' }]);
expect(data.incomeExpenses.months[11].income).toEqual([]);
expect(data.ranges![12].income).toEqual([]);
});
it('projects undated input without invented ranges, sides, currency, dates or a timestamp', () => {
expect(decodeOverviewFixture(emptyStats, { incomeStatements: [], snapshots: [] }, [])).toEqual({
it('projects undated input without invented ranges, sides, currency, dates or a timestamp', async () => {
const data = await decodeOverviewFixture(emptyStats, { incomeStatements: [], snapshots: [] });
expect(data).toEqual({
asOf: null,
journalCoverage: { transactionCount: 0, firstDate: null, lastDate: null },
ranges: null,
@@ -70,7 +71,7 @@ it('projects undated input without invented ranges, sides, currency, dates or a
});
});
it('publishes no private metadata paths or unused native fields', () => {
it('publishes no private metadata paths or unused native fields', async () => {
const metadata = `Main file : /private/SECRET.journal\n${stats}`;
const native = reports();
native.incomeStatements = native.incomeStatements.map((json) =>
@@ -79,7 +80,7 @@ it('publishes no private metadata paths or unused native fields', () => {
native.snapshots = native.snapshots.map((json) =>
json.replace('"cbrTotals":', '"sourcePath":"SECRET","cbrTotals":')
);
const data = decodeOverviewFixture(metadata, native);
const data = await decodeOverviewFixture(metadata, native);
expect(data.journalCoverage).toEqual({
transactionCount: 12,
firstDate: '2025-05-01',
@@ -88,10 +89,10 @@ it('publishes no private metadata paths or unused native fields', () => {
expect(JSON.stringify(data)).not.toContain('SECRET');
});
it('does not consult the clock or assign the producer-owned completion timestamp', () => {
it('does not consult the clock or assign the producer-owned completion timestamp', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date('2099-12-31T12:34:56.789Z'));
const data = decodeOverviewFixture(stats, reports());
const data = await decodeOverviewFixture(stats, reports());
expect(data.asOf).toBe('2026-04-16');
expect(data).not.toHaveProperty('preparedAt');
expect(data).not.toHaveProperty('hledgerVersion');
@@ -1,5 +1,5 @@
import type { ReportedAmount } from '../../amounts.js';
import type { OverviewReports } from './plan.js';
import type { OverviewReports } from './native-reports.js';
import type { JournalCoverage } from '../../journal-stats.js';
import { organizeNetWorth } from './net-worth.js';
import { organizeIncomeRange, type OverviewMonths, type OverviewRange } from './ranges.js';
@@ -237,6 +237,23 @@ describe('preparation completion and failure', () => {
}
);
it('does not start another window count after cancellation between counts', async () => {
mockPreparationProcesses(accountFixture(1));
const controller = new AbortController();
const transactions = new MemoryPreparationTransactions();
const countInPeriod = vi.spyOn(transactions, 'countInPeriod').mockImplementationOnce(() => {
// Let the first count settle and its completion check run before aborting.
queueMicrotask(() => queueMicrotask(() => controller.abort()));
return Promise.resolve(1);
});
const writeRows = vi.fn(async () => {});
await expect(
generateSavedReport('/private', { transactions, writeRows, signal: controller.signal })
).rejects.toThrow();
expect(countInPeriod).toHaveBeenCalledOnce();
expect(writeRows).not.toHaveBeenCalled();
});
it('rejects a repeated register transaction even though shared storage permits rereads', async () => {
const { writeRows: writes } = await expectRejected({
output: `${datedExports}[${registerRow},${registerRow}]`,
+3 -3
View File
@@ -4,7 +4,7 @@ import type { OverviewData } from './cash-and-net-worth/report.js';
import { HledgerExecutionError, readHledger } from '../process.js';
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 { cashAndNetWorthReports } from './cash-and-net-worth/native-reports.js';
import {
investmentOverviewReports,
type PreparedInvestmentOverview
@@ -39,7 +39,7 @@ export async function generateSavedReport(
const inputFlags = ['--no-conf', '--lang=en', '--strict', '-f', journal];
const journalDiscovery = await discoverJournal(inputFlags, { signal: options.signal });
options.signal?.throwIfAborted();
const overviewPlan = planOverviewReports(journalDiscovery.journal);
const overviewReports = cashAndNetWorthReports(journalDiscovery.journal);
// Discover cash commodities for eligible investment accounts before the batch.
const investmentReports = await investmentOverviewReports({
configuredInvestmentAccounts: options.investmentAccounts ?? [],
@@ -51,7 +51,7 @@ export async function generateSavedReport(
});
const reportSequence = buildReportSequence({
journalDiscovery,
overviewPlan,
overviewReports,
investmentReports
});
const { overview, accounts, investmentOverview } = await runJsonCommands(
@@ -1,6 +1,6 @@
import { expect, it } from 'vitest';
import { journalMetadata } from '../journal-stats.js';
import { planOverviewReports } from './cash-and-net-worth/plan.js';
import { cashAndNetWorthReports } from './cash-and-net-worth/native-reports.js';
import { buildReportSequence } from './report-sequence.js';
it('plans one pair of journal exports and registers only for unambiguous accounts', () => {
@@ -8,7 +8,7 @@ it('plans one pair of journal exports and registers only for unambiguous account
'Base currency : USD\nLast txn : 2026-04-16\nTxns : 1\nTxns span : 2026-04-16 to 2026-04-17\n'
);
const { commands } = buildReportSequence({
overviewPlan: planOverviewReports(journal),
overviewReports: cashAndNetWorthReports(journal),
investmentReports: null,
journalDiscovery: {
journal,
+11 -22
View File
@@ -4,7 +4,7 @@ import {
type AccountBalanceReports,
type PreparedBalance
} from './accounts/balances.js';
import { planOverviewReports, readOverviewReports } from './cash-and-net-worth/plan.js';
import type { cashAndNetWorthReports } from './cash-and-net-worth/native-reports.js';
import { organizeOverviewData } from './cash-and-net-worth/report.js';
import type { ReportStreamReader } from '../report-stream.js';
import type { PreparationTransactions } from '../transactions/store.js';
@@ -19,11 +19,11 @@ export interface PreparedAccountSummary extends QualifiedAccount {
export function buildReportSequence({
journalDiscovery,
overviewPlan,
overviewReports,
investmentReports
}: {
journalDiscovery: JournalDiscovery;
overviewPlan: ReturnType<typeof planOverviewReports>;
overviewReports: ReturnType<typeof cashAndNetWorthReports>;
investmentReports: Awaited<ReturnType<typeof investmentOverviewReports>>;
}) {
const { journal: journalStats, accounts: journalAccounts, investment } = journalDiscovery;
@@ -36,7 +36,7 @@ export function buildReportSequence({
const commands = [
['print', '--round=none', '-Ojson'],
['print', '--round=none', '--value=transacted', '-Ojson'],
...overviewPlan.commands,
...overviewReports.commands,
...accountBalances.commands,
...accountRegisters.map(({ command }) => command),
...(investmentReports?.commands ?? [])
@@ -56,7 +56,13 @@ export function buildReportSequence({
}
) {
await importTransactionExports(reader, transactions, journalStats, check);
const overview = await readOverview(reader, overviewPlan, journalStats, transactions, check);
const nativeOverview = await overviewReports.read(reader, async (begin, endExclusive) => {
check();
const count = await transactions.countInPeriod(begin, endExclusive);
check();
return count;
});
const overview = organizeOverviewData(nativeOverview);
const balances = await accountBalances.read(reader);
const accounts = summarizeAccounts(journalAccounts, journalStats, balances);
for (const { index } of accountRegisters) {
@@ -102,23 +108,6 @@ async function importTransactionExports(
}
}
async function readOverview(
reader: ReportStreamReader,
plan: ReturnType<typeof planOverviewReports>,
journalStats: JournalDiscovery['journal'],
transactions: PreparationTransactions,
check: () => void
) {
const transactionCounts: number[] = [];
for (const { begin, endExclusive } of plan.incomeRanges) {
transactionCounts.push(await transactions.countInPeriod(begin, endExclusive));
check();
}
return organizeOverviewData(
await readOverviewReports(reader, journalStats, plan, transactionCounts)
);
}
function summarizeAccounts(
journalAccounts: readonly QualifiedAccount[],
{ asOf, baseCurrency }: JournalDiscovery['journal'],
+21 -25
View File
@@ -1,34 +1,30 @@
import { journalMetadata } from './src/journal-stats.js';
import {
planOverviewReports,
type OverviewReports
} from './src/reports/cash-and-net-worth/plan.js';
import { parseBalanceSheet } from './src/commands/balance-sheet.js';
import { parseIncomeStatement } from './src/commands/income-statement.js';
import { ReportStreamReader } from './src/report-stream.js';
import { cashAndNetWorthReports } from './src/reports/cash-and-net-worth/native-reports.js';
import { organizeOverviewData } from './src/reports/cash-and-net-worth/report.js';
import { planIncomeRanges } from './src/reports/cash-and-net-worth/ranges.js';
// Compose only pure production parsers/planners/organizers; never execute native jobs.
export function decodeOverviewFixture(
export function reportReader(documents: readonly string[]): ReportStreamReader {
return new ReportStreamReader(
(async function* () {
for (const document of documents) yield Buffer.from(`${document}\n`);
})(),
() => {}
);
}
// Read supplied native documents without running hledger.
export async function decodeOverviewFixture(
discoveryStats: string,
reports: { incomeStatements: string[]; snapshots: string[] },
transactionCounts: readonly number[] = [1, 3, 6, 12]
{ incomeStatements, snapshots }: { incomeStatements: string[]; snapshots: string[] }
) {
const metadata = journalMetadata(discoveryStats);
const plan = planOverviewReports(metadata);
const overview: OverviewReports = {
...metadata,
incomeStatements: plan.incomeRanges.map((range, index) => ({
...range,
transactionCount: transactionCounts[index],
report: parseIncomeStatement(reports.incomeStatements[index])
})),
snapshots: plan.snapshotPeriods.map((period, index) => ({
...period,
report: parseBalanceSheet(reports.snapshots[index])
}))
};
return organizeOverviewData(overview);
const reports = cashAndNetWorthReports(journalMetadata(discoveryStats));
const reader = reportReader([...incomeStatements, ...snapshots]);
const transactionCounts = [1, 3, 6, 12];
let nextCount = 0;
const native = await reports.read(reader, () => transactionCounts[nextCount++]);
await reader.eof();
return organizeOverviewData(native);
}
// Owned native JSON documents shared by the dashboard adapter tests only.