Clarify saved report generation #71

Merged
eleith merged 1 commits from refactor/saved-report-preparation-plan into main 2026-11-22 14:10:57 +00:00
42 changed files with 508 additions and 405 deletions

No files matched your search

@@ -0,0 +1,5 @@
---
'@hledger-reports/worker': patch
---
Group saved-report generation by report and keep the hledger commands beside their read order. Report values and behavior are unchanged.
+3 -3
View File
@@ -5,7 +5,7 @@ import {
getHledgerVersion,
runCostBalance,
runHoldings,
prepareReports
generateSavedReport
} from '@hledger-reports/hledger';
import { createReportStage } from '@hledger-reports/snapshots';
import { openJobsClient, type JobsClient } from '@hledger-reports/jobs';
@@ -44,7 +44,7 @@ vi.mock('@hledger-reports/hledger', async (original) => ({
getHledgerVersion: vi.fn(),
runCostBalance: vi.fn(),
runHoldings: vi.fn(),
prepareReports: vi.fn()
generateSavedReport: vi.fn()
}));
vi.mock('@hledger-reports/snapshots', () => ({ createReportStage: vi.fn() }));
vi.mock('@hledger-reports/jobs', async (original) => ({
@@ -148,7 +148,7 @@ it('loads config and version before registering work, fixes concurrency at one,
worker.start.mock.invocationCallOrder[0]!
);
expect(prepare).not.toHaveBeenCalled();
expect(prepareReports).not.toHaveBeenCalled();
expect(generateSavedReport).not.toHaveBeenCalled();
expect(createReportStage).not.toHaveBeenCalled();
expect(runCostBalance).not.toHaveBeenCalled();
expect(runHoldings).not.toHaveBeenCalled();
+5 -5
View File
@@ -1,5 +1,5 @@
import { beforeEach, expect, it, vi } from 'vitest';
import { runCostBalance, runHoldings, prepareReports } from '@hledger-reports/hledger';
import { runCostBalance, runHoldings, generateSavedReport } from '@hledger-reports/hledger';
import { createReportStage } from '@hledger-reports/snapshots';
import {
retiredBalanceQuerySpec,
@@ -32,7 +32,7 @@ vi.mock('@hledger-reports/hledger', async (original) => ({
...(await original<typeof import('@hledger-reports/hledger')>()),
runCostBalance: vi.fn(),
runHoldings: vi.fn(),
prepareReports: vi.fn()
generateSavedReport: vi.fn()
}));
vi.mock('@hledger-reports/snapshots', () => ({ createReportStage: vi.fn() }));
type Handler = (context: {
@@ -90,7 +90,7 @@ it('registers all six identities explicitly, including one-attempt holdings', as
expect(await registration![1]({ input: request })).toBe(report);
expect(runHoldings).toHaveBeenCalledExactlyOnceWith('/configured/live.journal', request);
expect(createReportStage).not.toHaveBeenCalled();
expect(prepareReports).not.toHaveBeenCalled();
expect(generateSavedReport).not.toHaveBeenCalled();
});
it('registers SDK retention and returns only a deleted count', async () => {
@@ -122,7 +122,7 @@ it('registers the configured preparation handler directly', () => {
'/deployment/data/snapshots',
investmentAccounts
);
expect(prepareReports).not.toHaveBeenCalled();
expect(generateSavedReport).not.toHaveBeenCalled();
expect(createReportStage).not.toHaveBeenCalled();
});
@@ -135,7 +135,7 @@ it('retires queued income previews without interpreting their old input or execu
expect(() => registration![1]({ input: { arbitrary: 'old preview' } })).toThrow(
'Income preparation previews are retired. Refresh the dashboard.'
);
expect(prepareReports).not.toHaveBeenCalled();
expect(generateSavedReport).not.toHaveBeenCalled();
expect(createReportStage).not.toHaveBeenCalled();
});
@@ -3,7 +3,7 @@ import {
checkJournal,
JournalCheckError,
ReportCommandExitedNonzero,
prepareReports,
generateSavedReport,
type OverviewData,
type PreparedInvestmentOverview
} from '@hledger-reports/hledger';
@@ -20,7 +20,7 @@ import { createPrepareReports } from './run.js';
vi.mock('@hledger-reports/hledger', async (original) => ({
...(await original<typeof import('@hledger-reports/hledger')>()),
checkJournal: vi.fn(),
prepareReports: vi.fn()
generateSavedReport: vi.fn()
}));
vi.mock('@hledger-reports/snapshots', () => ({
createReportStage: vi.fn(),
@@ -81,7 +81,7 @@ beforeEach(() => {
vi.mocked(writeValidation).mockResolvedValue(undefined);
vi.mocked(readReportPublication).mockResolvedValue(previous);
vi.mocked(createReportStage).mockResolvedValue(stage);
vi.mocked(prepareReports).mockImplementation(async (_journal, options) => {
vi.mocked(generateSavedReport).mockImplementation(async (_journal, options) => {
await options.writeRows('assets:cash', []);
return { overview, accounts };
});
@@ -98,7 +98,7 @@ it('records a completed nonzero check and stops before touching financial report
expect(writeReportPreparationFailure).toHaveBeenCalledExactlyOnceWith(directory, run, journal);
expect(readReportPublication).not.toHaveBeenCalled();
expect(createReportStage).not.toHaveBeenCalled();
expect(prepareReports).not.toHaveBeenCalled();
expect(generateSavedReport).not.toHaveBeenCalled();
});
it.each([new JournalCheckError('not-completed'), new Error('unexpected check failure')])(
@@ -109,7 +109,7 @@ it.each([new JournalCheckError('not-completed'), new Error('unexpected check fai
expect(writeValidation).not.toHaveBeenCalled();
expect(writeReportPreparationFailure).not.toHaveBeenCalled();
expect(createReportStage).not.toHaveBeenCalled();
expect(prepareReports).not.toHaveBeenCalled();
expect(generateSavedReport).not.toHaveBeenCalled();
}
);
@@ -120,7 +120,7 @@ it('does not start financial work when evidence cannot be saved', async () => {
expect(checkJournal).toHaveBeenCalledOnce();
expect(readReportPublication).not.toHaveBeenCalled();
expect(createReportStage).not.toHaveBeenCalled();
expect(prepareReports).not.toHaveBeenCalled();
expect(generateSavedReport).not.toHaveBeenCalled();
});
it('awaits durable evidence before financial staging', async () => {
@@ -130,7 +130,7 @@ it('awaits durable evidence before financial staging', async () => {
try {
await vi.waitFor(() => expect(writeValidation).toHaveBeenCalledOnce());
expect(createReportStage).not.toHaveBeenCalled();
expect(prepareReports).not.toHaveBeenCalled();
expect(generateSavedReport).not.toHaveBeenCalled();
} finally {
release();
}
@@ -160,7 +160,7 @@ it.each([true, false])(
expect(vi.mocked(writeValidation).mock.invocationCallOrder[0]).toBeLessThan(
vi.mocked(createReportStage).mock.invocationCallOrder[0]!
);
expect(prepareReports).toHaveBeenCalledExactlyOnceWith(journal, {
expect(generateSavedReport).toHaveBeenCalledExactlyOnceWith(journal, {
transactions: stage.transactions,
writeRows: stage.writeRows,
investmentAccounts: []
@@ -198,9 +198,9 @@ it.each(['ready', 'undated', 'scope-unavailable'] as const)(
portfolioValue: null,
securityCount: state === 'ready' ? 1 : null
};
vi.mocked(prepareReports).mockResolvedValue({ overview, accounts, investmentOverview });
vi.mocked(generateSavedReport).mockResolvedValue({ overview, accounts, investmentOverview });
expect(await prepareInvestmentReports(context)).toBe(overview);
expect(prepareReports).toHaveBeenCalledExactlyOnceWith(journal, {
expect(generateSavedReport).toHaveBeenCalledExactlyOnceWith(journal, {
transactions: stage.transactions,
writeRows: stage.writeRows,
investmentAccounts
@@ -220,7 +220,7 @@ it.each(['producer', 'native nonzero', 'publish'] as const)(
const error =
kind === 'native nonzero' ? new ReportCommandExitedNonzero() : new Error('failed');
if (kind !== 'publish') {
vi.mocked(prepareReports).mockImplementation(async (_journal, options) => {
vi.mocked(generateSavedReport).mockImplementation(async (_journal, options) => {
await options.writeRows('assets:cash', []);
throw error;
});
@@ -2,7 +2,7 @@ import {
checkJournal,
JournalCheckError,
ReportCommandExitedNonzero,
prepareReports
generateSavedReport
} from '@hledger-reports/hledger';
import {
createReportStage,
@@ -49,7 +49,7 @@ export function createPrepareReports(
throw error;
});
try {
const { overview, accounts, investmentOverview } = await prepareReports(journal, {
const { overview, accounts, investmentOverview } = await generateSavedReport(journal, {
transactions: stage.transactions,
writeRows: stage.writeRows,
investmentAccounts
+10 -9
View File
@@ -8,17 +8,18 @@ it does not run hledger.
## Entry points and layout
Import `prepareReports` for saved reporting, `runHoldings` or `runCostBalance`
Import `generateSavedReport` for saved reporting, `runHoldings` or `runCostBalance`
for a live report, and `checkJournal` for validation from `@hledger-reports/hledger`.
Use `@hledger-reports/hledger/transactions` to decode or interpret transaction
exports already in hand, without running hledger.
- **Commands:** `src/commands/` is the starting point for how a command is called
and decoded. It currently contains the monthly income statement and historical
balance sheet commands used by the overview.
- **Execution:** `src/process.ts` owns the child process. `src/report-stream.ts`
separates JSON documents on its output stream. Neither chooses report dates.
- **Report recipes:** `src/overview/plan.ts` chooses which Cash and Net Worth
reports to request and for which dates. `src/overview/report.ts` shapes the
decoded results. `src/prepare-reports/run.ts` coordinates saved-report
preparation. Callers don't need to know the command flags or batch order.
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.
- **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.
@@ -0,0 +1,30 @@
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { expect, it } from 'vitest';
import { runJsonCommands } from './run.js';
it('reads JSON results in command order and rejects an unconsumed result', async () => {
const directory = await mkdtemp(join(tmpdir(), 'hledger-run-'));
try {
const journal = join(directory, 'empty.journal');
await writeFile(journal, 'commodity 1.00 USD\n');
const inputFlags = ['--no-conf', '--strict', '-f', journal];
const commands = [
['print', '-Ojson'],
['balance', '-Ojson']
];
const results = await runJsonCommands(inputFlags, commands, {}, async (reader) => [
JSON.parse(await reader.json()),
JSON.parse(await reader.json())
]);
expect(results).toEqual([[], [[], []]]);
await expect(
runJsonCommands(inputFlags, commands, {}, (reader) => reader.json())
).rejects.toMatchObject({ kind: 'not-completed' });
} finally {
await rm(directory, { recursive: true, force: true });
}
});
+24
View File
@@ -0,0 +1,24 @@
import { consumeHledger, type ProcessOptions } from '../process.js';
import { ReportStreamReader } from '../report-stream.js';
export function hledgerRunArgs(
inputFlags: readonly string[],
commands: readonly (readonly string[])[]
): string[] {
return [...inputFlags, 'run', ...commands.flatMap((command) => ['--', ...command])];
}
/** Run JSON-producing commands together and read their output in command order. */
export function runJsonCommands<Result>(
inputFlags: readonly string[],
commands: readonly (readonly string[])[],
options: ProcessOptions,
read: (output: ReportStreamReader, check: () => void) => Promise<Result>
): Promise<Result> {
return consumeHledger(hledgerRunArgs(inputFlags, commands), options, async (output, check) => {
const reader = new ReportStreamReader(output, check);
const result = await read(reader, check);
await reader.eof();
return result;
});
}
+14 -27
View File
@@ -1,5 +1,6 @@
import { randomUUID } from 'node:crypto';
import { formatQuantity, parseExactJson, type ReportedAmount } from '../amounts.js';
import { hledgerRunArgs } from '../commands/run.js';
import { readHledger, type CommandRunner } from '../process.js';
export interface HoldingPosition {
@@ -225,9 +226,8 @@ export async function runHoldings(
const markers = ['ASSETS', 'CASH', 'LOTS'].map(
(name) => `\n__HLEDGER_HOLDINGS_${id}_${name}__\n`
);
const echo = (marker: string) => ['--', 'echo', marker.slice(0, -1)];
const echo = (marker: string) => ['echo', marker.slice(0, -1)];
const balance = (type: string) => [
'--',
'balance',
'--flat',
'--historical',
@@ -237,31 +237,18 @@ export async function runHoldings(
'-Ojson',
`type:${type}`
];
const args = [
'--no-conf',
'--lang=en',
'--strict',
'-f',
journal,
'--today',
asOf,
'run',
...balance('A'),
...echo(markers[0]),
...balance('C'),
...echo(markers[1]),
'--',
'commodities',
'tag:lots',
...echo(markers[2]),
'--',
'holdings',
'--flat',
'--round=none',
'-e',
end,
'-Ocsv'
];
const args = hledgerRunArgs(
['--no-conf', '--lang=en', '--strict', '-f', journal, '--today', asOf],
[
balance('A'),
echo(markers[0]),
balance('C'),
echo(markers[1]),
['commodities', 'tag:lots'],
echo(markers[2]),
['holdings', '--flat', '--round=none', '-e', end, '-Ocsv']
]
);
let text = options.run
? await options.run(args)
: await readHledger(args, { signal: options.signal });
+6 -6
View File
@@ -9,21 +9,21 @@ export type {
OverviewMonths,
OverviewRange,
NativeValue
} from './overview/report.js';
} from './reports/cash-and-net-worth/report.js';
export { runCostBalance } from './queries/cost-balance.js';
export type { CostBalanceReport } from './queries/cost-balance.js';
export type { ReportedAmount } from './amounts.js';
export { runHoldings } from './holdings/report.js';
export type { HoldingPosition, HoldingsAccount, HoldingsReport } from './holdings/report.js';
export { ReportCommandExitedNonzero, prepareReports } from './prepare-reports/run.js';
export { ReportCommandExitedNonzero, generateSavedReport } from './reports/generate.js';
export type { PreparationTransactions } from './transactions/store.js';
export type { PreparedAccountSummary } from './prepare-reports/batch.js';
export type { PreparedInvestmentOverview } from './prepare-reports/investment-overview/prepare.js';
export type { PreparedAccountSummary } from './reports/report-sequence.js';
export type { PreparedInvestmentOverview } from './reports/investment-overview/prepare.js';
export {
largestHoldingLimit,
type PreparedPortfolioValues
} from './prepare-reports/investment-overview/portfolio-values.js';
export type { PreparedBalance } from './accounts/balances.js';
} from './reports/investment-overview/portfolio-values.js';
export type { PreparedBalance } from './reports/accounts/balances.js';
export type { PreparedAccountRow } from './transactions/account-rows.js';
export type {
PreparedInvestmentData,
@@ -1,41 +0,0 @@
import { expect, it } from 'vitest';
import { journalMetadata } from '../journal-stats.js';
import { planPreparedReportCommands } from './batch.js';
it('exports the whole journal once regardless of account count or ambiguous selections', () => {
const { args } = planPreparedReportCommands([], {
journal: journalMetadata(
'Base currency : USD\nLast txn : 2026-04-16\nTxns : 1\nTxns span : 2026-04-16 to 2026-04-17\n'
),
accounts: [
{ name: 'assets:cash', access: 'ready' },
{ name: 'assets:cash:daily', access: 'ready' },
{ name: 'assets:Case', access: 'ambiguous' }
],
investment: {
assets: new Set(),
cash: new Set(),
liabilities: new Set(),
income: new Set(),
expenses: new Set(),
gains: new Set(),
lotCommodities: new Set()
}
});
expect(args.filter((argument) => argument === 'print')).toHaveLength(2);
expect(args.slice(args.indexOf('print'), args.indexOf('incomestatement'))).toEqual([
'print',
'--round=none',
'-Ojson',
'--',
'print',
'--round=none',
'--value=transacted',
'-Ojson',
'--'
]);
expect(args.filter((argument) => argument === 'aregister')).toHaveLength(2);
expect(args).not.toContain('^assets:Case$');
expect(args).not.toContain('echo');
expect(args).not.toContain('stats');
});
@@ -1,63 +0,0 @@
import { readOverviewReports, planOverviewReports } from '../overview/plan.js';
import { organizeOverviewData } from '../overview/report.js';
import {
planAccountBalances,
readAccountBalances,
organizeAccountBalance,
type PreparedBalance
} from '../accounts/balances.js';
import type { ReportStreamReader } from '../report-stream.js';
import type { PreparationMetadata, QualifiedAccount } from './metadata.js';
export interface PreparedAccountSummary extends QualifiedAccount {
rowCount: number | null;
summary: PreparedBalance;
}
function escapeAccountName(name: string): string {
return name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
export function planPreparedReportCommands(
inputFlags: readonly string[],
metadata: PreparationMetadata
) {
const overviewPlan = planOverviewReports(metadata.journal);
const commands = [
['print', '--round=none', '-Ojson'],
['print', '--round=none', '--value=transacted', '-Ojson'],
...overviewPlan.commands,
...planAccountBalances(metadata.journal)
];
for (const { name, access } of metadata.accounts) {
if (access === 'ambiguous') continue;
const exactAccountPattern = `^${escapeAccountName(name)}$`;
commands.push(['aregister', '--historical', '--empty', '-Ojson', exactAccountPattern]);
}
const args = [...inputFlags, 'run', ...commands.flatMap((command) => ['--', ...command])];
return { args, overviewPlan };
}
export async function readPreparedReports(
reader: ReportStreamReader,
metadata: PreparationMetadata,
overviewPlan: ReturnType<typeof planOverviewReports>,
transactionCounts: readonly number[]
) {
const overview = organizeOverviewData(
await readOverviewReports(reader, metadata.journal, overviewPlan, transactionCounts)
);
const accountReports = await readAccountBalances(reader, metadata.journal.asOf);
const accounts: PreparedAccountSummary[] = metadata.accounts.map(({ name, access }) => {
const rowCount = access === 'ambiguous' ? null : 0;
const summary = organizeAccountBalance(
name,
access,
metadata.journal.asOf,
metadata.journal.baseCurrency,
accountReports
);
return { name, access, rowCount, summary };
});
return { overview, accounts };
}
-124
View File
@@ -1,124 +0,0 @@
import { getHledgerVersion, supportedHledgerVersion } from '../checks.js';
import type { OverviewData } from '../overview/report.js';
import { consumeHledger, HledgerExecutionError, readHledger } from '../process.js';
import { ReportStreamReader } from '../report-stream.js';
import { readPreparationMetadata } from './metadata.js';
import type { PreparationTransactions } from '../transactions/store.js';
import { writePreparedAccountRows, type AccountRowWriter } from './account-stream.js';
import {
planInvestmentOverview,
type PreparedInvestmentOverview
} from './investment-overview/prepare.js';
import {
readPreparedReports,
planPreparedReportCommands,
type PreparedAccountSummary
} from './batch.js';
/** A native report command completed with a nonzero exit, not an interruption. */
export class ReportCommandExitedNonzero extends Error {
constructor() {
super('Prepared transactions could not be read. Check the journal.');
}
}
export async function prepareReports(
journal: string,
options: {
transactions: PreparationTransactions;
writeRows: AccountRowWriter;
investmentAccounts?: readonly string[];
signal?: AbortSignal;
}
): Promise<{
overview: OverviewData;
accounts: PreparedAccountSummary[];
investmentOverview?: PreparedInvestmentOverview;
}> {
try {
options.signal?.throwIfAborted();
await getHledgerVersion((args) => readHledger(args, { signal: options.signal }));
options.signal?.throwIfAborted();
const inputFlags = ['--no-conf', '--lang=en', '--strict', '-f', journal];
const metadata = await readPreparationMetadata(inputFlags, { signal: options.signal });
options.signal?.throwIfAborted();
const { args, overviewPlan } = planPreparedReportCommands(inputFlags, metadata);
const investmentPlan = await planInvestmentOverview({
configuredInvestmentAccounts: options.investmentAccounts ?? [],
journalStats: metadata.journal,
journalAccounts: metadata.accounts,
lotCommodities: metadata.investment.lotCommodities,
readPreflight: (command) =>
readHledger([...inputFlags, ...command], { signal: options.signal })
});
for (const command of investmentPlan?.commands ?? []) args.push('--', ...command);
const { overview, accounts, investmentOverview } = await consumeHledger(
args,
{ signal: options.signal },
async (output, check) => {
const reader = new ReportStreamReader(output, check);
await reader.array('object', async (json) => {
await options.transactions.insertOriginal(json);
});
await reader.array('object', async (json) => {
await options.transactions.attachTransacted(json);
});
check();
await options.transactions.assertComplete();
check();
const summary = await options.transactions.readSummary();
check();
// Native report spans can include posting dates; compare the latest primary date instead.
if (
summary.transactionCount !== metadata.journal.journalCoverage.transactionCount ||
summary.lastDate !== metadata.journal.asOf
)
throw new Error('Native transactions do not match preparation metadata.');
const transactionCounts: number[] = [];
for (const range of overviewPlan.incomeRanges) {
transactionCounts.push(
await options.transactions.countInPeriod(range.begin, range.endExclusive)
);
check();
}
const { overview, accounts } = await readPreparedReports(
reader,
metadata,
overviewPlan,
transactionCounts
);
for (const account of accounts) {
await writePreparedAccountRows(
reader,
account,
metadata.investment,
options.transactions,
options.writeRows,
check
);
}
const investmentOverview = await investmentPlan?.read(reader);
await reader.eof();
return { overview, accounts, investmentOverview };
}
);
return {
overview: {
...overview,
hledgerVersion: supportedHledgerVersion,
preparedAt: new Date().toISOString()
},
accounts,
...(investmentOverview ? { investmentOverview } : {})
};
} catch (error) {
if (
!options.signal?.aborted &&
error instanceof HledgerExecutionError &&
error.kind === 'nonzero-exit'
)
throw new ReportCommandExitedNonzero();
// eslint-disable-next-line preserve-caught-error -- native errors can contain private diagnostics.
throw new Error('Prepared transactions could not be read. Check the journal.');
}
}
@@ -4,10 +4,10 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
import { expect, it } from 'vitest';
import { lotsJournal } from '../../../../apps/worker/fixtures/journal.js';
import { formatQuantity, parseExactJson, type Amount } from '../amounts.js';
import { prepareReports } from '../prepare-reports/run.js';
import { MemoryPreparationTransactions } from '../prepare-reports/transactions.fixture.js';
import { lotsJournal } from '../../../../../apps/worker/fixtures/journal.js';
import { formatQuantity, parseExactJson, type Amount } from '../../amounts.js';
import { generateSavedReport } from '../generate.js';
import { MemoryPreparationTransactions } from '../transactions.fixture.js';
const exec = promisify(execFile);
@@ -19,7 +19,7 @@ const amounts = (bag: Amount[]) =>
}));
async function compareNativeSubtree(journal: string, name: string) {
const prepared = await prepareReports(journal, {
const prepared = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
async writeRows() {}
});
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
import { ReportStreamReader } from '../report-stream.js';
import { ReportStreamReader } from '../../report-stream.js';
import { organizeAccountBalance, planAccountBalances, readAccountBalances } from './balances.js';
const asOf = '2026-04-02';
@@ -1,7 +1,12 @@
import { parseExactJson, reportedAmounts, type Amount, type ReportedAmount } from '../amounts.js';
import type { NativeValue } from '../overview/report.js';
import { isoDate } from '../report-date.js';
import type { ReportStreamReader } from '../report-stream.js';
import {
parseExactJson,
reportedAmounts,
type Amount,
type ReportedAmount
} from '../../amounts.js';
import type { NativeValue } from '../cash-and-net-worth/report.js';
import { isoDate } from '../../report-date.js';
import type { ReportStreamReader } from '../../report-stream.js';
export type PreparedBalance =
| { status: 'ambiguous' }
@@ -1,14 +1,17 @@
import type { ReportStreamReader } from '../report-stream.js';
import type { ReportStreamReader } from '../../report-stream.js';
import {
parseAccountRegisterRow,
organizeAccountRow,
type PreparedAccountRow
} from '../transactions/account-rows.js';
import { decodeNativeTransaction } from '../transactions/export.js';
import { accountInvestmentContext, type InvestmentMetadata } from '../transactions/investment.js';
import type { NativeTransactionPair, PreparationTransactions } from '../transactions/store.js';
import { prepareTransaction, requireTransactionIndex } from '../transactions/transaction.js';
import type { PreparedAccountSummary } from './batch.js';
} from '../../transactions/account-rows.js';
import { decodeNativeTransaction } from '../../transactions/export.js';
import {
accountInvestmentContext,
type InvestmentMetadata
} from '../../transactions/investment.js';
import type { NativeTransactionPair, PreparationTransactions } from '../../transactions/store.js';
import { prepareTransaction, requireTransactionIndex } from '../../transactions/transaction.js';
import type { PreparedAccountSummary } from '../report-sequence.js';
export type AccountRowWriter = (
accountName: string,
@@ -36,7 +39,6 @@ export async function writePreparedAccountRows(
writeRows: AccountRowWriter,
check: () => void
): Promise<void> {
if (account.access === 'ambiguous') return;
async function* history() {
for await (const pair of transactions.accountHistory(account.name)) {
check();
@@ -2,12 +2,12 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { prepareReports, getHledgerVersion } from '../index.js';
import { MemoryPreparationTransactions } from '../prepare-reports/transactions.fixture.js';
import { balanceReports, decodeOverviewFixture, incomeReports } from '../../test-fixtures.js';
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 { journalMetadata } from '../journal-stats.js';
import { journalMetadata } from '../../journal-stats.js';
const dates = [
'2025-05-31',
'2025-06-30',
@@ -193,7 +193,7 @@ describe('native market assets minus liabilities snapshots', () => {
txn('2026-03-01', 'Debt', 'Wallet', '100.00 USD') +
txn('2026-04-16', 'Costs', 'Wallet', '1000.00 USD')
);
const { overview: data } = await prepareReports(journal, {
const { overview: data } = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
});
@@ -220,7 +220,7 @@ describe('native market assets minus liabilities snapshots', () => {
journal,
'commodity USD 1.00\n' + accounts + txn('2026-04-16', 'Wallet', 'Debt', '100.00 USD')
);
const { overview: data } = await prepareReports(journal, {
const { overview: data } = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
});
@@ -243,7 +243,7 @@ describe('native market assets minus liabilities snapshots', () => {
txn('2025-01-01', 'Shares', 'Equity', '2 STOCK') +
txn('2026-04-16', 'Wallet', 'Equity', '1.00 USD')
);
const { overview: data } = await prepareReports(journal, {
const { overview: data } = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
});
@@ -266,7 +266,7 @@ describe('native market assets minus liabilities snapshots', () => {
accounts +
'P 2025-01-01 USD 1.00 USD\n\n2026-04-16 Purchase\n Shares 2 STOCK @ 50.00 USD\n Wallet -100.00 USD\n'
);
const { overview: data } = await prepareReports(journal, {
const { overview: data } = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
});
@@ -286,7 +286,7 @@ describe('native market assets minus liabilities snapshots', () => {
'P 2025-01-01 STOCK 10.00 EUR\nP 2099-01-01 EUR 2.00 USD\nP 2099-02-01 EUR 3.00 USD\n' +
txn('2026-04-16', 'Shares', 'Equity', '2 STOCK')
);
const { overview: data } = await prepareReports(journal, {
const { overview: data } = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
});
@@ -306,7 +306,7 @@ describe('native market assets minus liabilities snapshots', () => {
'P 2025-01-01 USD 1.00 USD\n' +
txn('2026-04-16', 'Shares', 'Debt', '2 STOCK')
);
const { overview: data } = await prepareReports(journal, {
const { overview: data } = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
});
@@ -329,7 +329,7 @@ describe('native market assets minus liabilities snapshots', () => {
accounts +
txn('2026-04-16', 'Wallet', 'Equity', `42.00 ${symbol}`)
);
const { overview: data } = await prepareReports(journal, {
const { overview: data } = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
});
@@ -1,4 +1,4 @@
import { reportedAmounts, type Amount } from '../amounts.js';
import { reportedAmounts, type Amount } from '../../amounts.js';
import type { OverviewReports } from './plan.js';
import type { NativeValue, OverviewData } from './report.js';
@@ -1,8 +1,8 @@
import { expect, it } from 'vitest';
import { planOverviewReports, readOverviewReports } from './plan.js';
import { journalMetadata } from '../journal-stats.js';
import { ReportStreamReader } from '../report-stream.js';
import { balanceReports, incomeReports } from '../../test-fixtures.js';
import { journalMetadata } from '../../journal-stats.js';
import { ReportStreamReader } from '../../report-stream.js';
import { balanceReports, incomeReports } from '../../../test-fixtures.js';
const aprilJournal = journalMetadata(`Base currency : USD
Last txn : 2026-04-16
@@ -2,15 +2,15 @@ import {
historicalBalanceSheetCommand,
parseBalanceSheet,
type HledgerBalanceSheet
} from '../commands/balance-sheet.js';
} 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';
} 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 };
@@ -3,11 +3,14 @@ import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import { planIncomeRanges, organizeIncomeRange } from './ranges.js';
import { parseIncomeStatement, type HledgerIncomeStatement } from '../commands/income-statement.js';
import { incomeReports } from '../../test-fixtures.js';
import type { Amount } from '../amounts.js';
import { prepareReports, getHledgerVersion } from '../index.js';
import { MemoryPreparationTransactions } from '../prepare-reports/transactions.fixture.js';
import {
parseIncomeStatement,
type HledgerIncomeStatement
} from '../../commands/income-statement.js';
import { incomeReports } from '../../../test-fixtures.js';
import type { Amount } from '../../amounts.js';
import { generateSavedReport, getHledgerVersion } from '../../index.js';
import { MemoryPreparationTransactions } from '../transactions.fixture.js';
const plan = planIncomeRanges('2026-04-16')[3];
function statement(range = plan): HledgerIncomeStatement {
@@ -153,7 +156,7 @@ describe('native hledger 1.99.5 finite overview ranges', () => {
'\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);
const { overview } = await prepareReports(journal, {
const { overview } = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
});
@@ -1,6 +1,6 @@
import { reportedAmounts, type ReportedAmount } from '../amounts.js';
import { isoDate } from '../report-date.js';
import type { HledgerIncomeStatement } from '../commands/income-statement.js';
import { reportedAmounts, type ReportedAmount } from '../../amounts.js';
import { isoDate } from '../../report-date.js';
import type { HledgerIncomeStatement } from '../../commands/income-statement.js';
export type OverviewMonths = 1 | 3 | 6 | 12;
export interface OverviewRange {
@@ -2,9 +2,9 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
import { prepareReports, getHledgerVersion } from '../index.js';
import { MemoryPreparationTransactions } from '../prepare-reports/transactions.fixture.js';
import { balanceReports, decodeOverviewFixture, incomeReports } from '../../test-fixtures.js';
import { generateSavedReport, getHledgerVersion } from '../../index.js';
import { MemoryPreparationTransactions } from '../transactions.fixture.js';
import { balanceReports, decodeOverviewFixture, incomeReports } from '../../../test-fixtures.js';
const stats =
'Base currency : USD\nLast txn : 2026-04-16\nTxns : 12\nTxns span : 2025-05-01 to 2026-04-17\n';
@@ -130,7 +130,7 @@ describe('native hledger 1.99.5 journal-anchored income statement', () => {
it('keeps twelve empty income columns and four empty ranges with a leap-day asset anchor', async () => {
await writeFile(journal, declarations + posting('2024-02-29', 'Wallet', 'Reserve', '1.00 USD'));
const { overview: data } = await prepareReports(journal, {
const { overview: data } = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
});
@@ -156,7 +156,7 @@ describe('native hledger 1.99.5 journal-anchored income statement', () => {
declarations +
'P 2099-12-31 EUR 2.00 USD\n\n~ monthly from 2099-01-01\n Spending 1.00 USD\n Wallet\n'
);
const { overview: data } = await prepareReports(journal, {
const { overview: data } = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
});
@@ -184,7 +184,7 @@ describe('native hledger 1.99.5 journal-anchored income statement', () => {
'\n2040-06-01 Earlier posting date\n Wallet 2.00 USD\n Paycheck -2.00 USD ; date:2039-01-01\n' +
'\n~ monthly from 2099-01-01\n Spending 1.00 USD\n Wallet\n'
);
const { overview: data } = await prepareReports(journal, {
const { overview: data } = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
});
@@ -208,7 +208,7 @@ describe('native hledger 1.99.5 journal-anchored income statement', () => {
posting('2026-04-02', 'Spending', 'Wallet', '100.00 USD') +
posting('2026-05-03', 'Wallet', 'Investment gains', '250.00 USD')
);
const { overview: data } = await prepareReports(journal, {
const { overview: data } = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
});
@@ -232,7 +232,7 @@ describe('native hledger 1.99.5 journal-anchored income statement', () => {
'\n2026-04-02 Stock expense\n Spending 2 STOCK @ 50.00 USD\n Wallet -100.00 USD\n' +
'\n2026-04-03 Other stock cost\n Spending 3 STOCK @ 60.00 USD\n Wallet -180.00 USD\n'
);
const { overview: data } = await prepareReports(journal, {
const { overview: data } = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
});
@@ -256,7 +256,7 @@ describe('native hledger 1.99.5 journal-anchored income statement', () => {
journal,
declarations + posting('2026-04-15', 'SECRET undeclared', 'Wallet', '123.45 USD')
);
const error: unknown = await prepareReports(journal, {
const error: unknown = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
}).catch((error: unknown) => error);
@@ -1,6 +1,6 @@
import type { ReportedAmount } from '../amounts.js';
import type { ReportedAmount } from '../../amounts.js';
import type { OverviewReports } from './plan.js';
import type { JournalCoverage } from '../journal-stats.js';
import type { JournalCoverage } from '../../journal-stats.js';
import { organizeNetWorth } from './net-worth.js';
import { organizeIncomeRange, type OverviewMonths, type OverviewRange } from './ranges.js';
@@ -2,9 +2,9 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, beforeAll, expect, it } from 'vitest';
import { transactionCountsJournal } from '../../fixtures/transaction-counts.fixture.js';
import { prepareReports } from '../prepare-reports/run.js';
import { MemoryPreparationTransactions } from '../prepare-reports/transactions.fixture.js';
import { transactionCountsJournal } from '../../../fixtures/transaction-counts.fixture.js';
import { generateSavedReport } from '../generate.js';
import { MemoryPreparationTransactions } from '../transactions.fixture.js';
let directory: string;
let journal: string;
@@ -19,7 +19,7 @@ afterAll(async () => {
const expected = { 1: 2, 3: 4, 6: 6, 12: 8 };
it('prepares all four native counts alongside whole coverage and the existing financial set', async () => {
const { overview } = await prepareReports(journal, {
const { overview } = await generateSavedReport(journal, {
transactions: new MemoryPreparationTransactions(),
writeRows: async () => {}
});
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { readHledger } from '../process.js';
import { readPreparationMetadata } from './metadata.js';
import { discoverJournal } from './discover-journal.js';
vi.mock('../process.js', () => ({ readHledger: vi.fn() }));
@@ -11,7 +11,7 @@ beforeEach(() => {
read.mockReset();
});
describe('readPreparationMetadata', () => {
describe('discoverJournal', () => {
it('keeps native types, canonical access and raw lot commodities independent', async () => {
const inputFlags = ['-f', 'fictional.journal'];
const options = { signal: new AbortController().signal };
@@ -28,7 +28,7 @@ describe('readPreparationMetadata', () => {
'Wallet\nalias=資産[USD].*\nconversion\nequity\nholdings\nholdings:child\nliabilities\nrevenue\nrevenue:realized\nspending\nuntyped\nWallet\n'
);
const metadata = await readPreparationMetadata(inputFlags, options);
const metadata = await discoverJournal(inputFlags, options);
expect(metadata).toEqual({
journal: {
@@ -80,7 +80,7 @@ describe('readPreparationMetadata', () => {
.mockResolvedValueOnce(names)
.mockResolvedValueOnce('')
.mockResolvedValueOnce('i\u0307\nunexpected\nz[USD].*\nİ\n');
const metadata = await readPreparationMetadata([], {});
const metadata = await discoverJournal([], {});
expect(metadata.accounts).toEqual([
{ name: 'i\u0307', access: 'ready' },
{ name: 'wrong', access: 'ambiguous' },
@@ -112,7 +112,7 @@ describe('readPreparationMetadata', () => {
.mockResolvedValueOnce('')
.mockResolvedValueOnce('assets:cash \nassets:literal ; type: C\n');
const metadata = await readPreparationMetadata([], {});
const metadata = await discoverJournal([], {});
expect(metadata.accounts).toEqual([
{ name: 'assets:cash ', access: 'ready' },
@@ -130,9 +130,7 @@ describe('readPreparationMetadata', () => {
.mockResolvedValueOnce('assets\n')
.mockResolvedValueOnce('liabilities ; type: L\n');
await expect(readPreparationMetadata([], {})).rejects.toThrow(
'Invalid native preparation metadata.'
);
await expect(discoverJournal([], {})).rejects.toThrow('Invalid native preparation metadata.');
expect(read).toHaveBeenCalledTimes(3);
});
@@ -143,7 +141,7 @@ describe('readPreparationMetadata', () => {
.mockResolvedValueOnce('')
.mockResolvedValueOnce('\nLOT\n');
const metadata = await readPreparationMetadata([], {});
const metadata = await discoverJournal([], {});
expect(metadata.accounts).toEqual([]);
expect(metadata.investment).toEqual({
@@ -172,9 +170,7 @@ describe('readPreparationMetadata', () => {
releaseStats = resolve;
})
);
const outcome = readPreparationMetadata([], { signal: controller.signal }).catch(
(error) => error
);
const outcome = discoverJournal([], { signal: controller.signal }).catch((error) => error);
try {
expect(read).toHaveBeenCalledTimes(1);
} finally {
@@ -1,3 +1,4 @@
import { hledgerRunArgs } from '../commands/run.js';
import { journalMetadata } from '../journal-stats.js';
import { readHledger } from '../process.js';
import type { InvestmentMetadata } from '../transactions/investment.js';
@@ -7,7 +8,7 @@ export interface QualifiedAccount {
access: 'ready' | 'ambiguous';
}
export interface PreparationMetadata {
export interface JournalDiscovery {
journal: ReturnType<typeof journalMetadata>;
accounts: QualifiedAccount[];
investment: InvestmentMetadata;
@@ -97,13 +98,11 @@ function investmentMetadata(
};
}
function canonicalLookups(names: readonly string[]): string[] {
const args = ['run'];
for (const name of names) {
function canonicalAccountLookups(names: readonly string[]): string[][] {
return names.map((name) => {
const escaped = name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
args.push('--', 'accounts', '--find', `^${escaped}$`);
}
return args;
return ['accounts', '--find', `^${escaped}$`];
});
}
function qualifyAccounts(names: readonly string[], text: string): QualifiedAccount[] {
@@ -120,10 +119,10 @@ function qualifyAccounts(names: readonly string[], text: string): QualifiedAccou
});
}
export async function readPreparationMetadata(
export async function discoverJournal(
inputFlags: readonly string[],
options: { signal?: AbortSignal }
): Promise<PreparationMetadata> {
): Promise<JournalDiscovery> {
async function read(command: readonly string[]): Promise<string> {
options.signal?.throwIfAborted();
return readHledger([...inputFlags, ...command], options);
@@ -134,7 +133,10 @@ export async function readPreparationMetadata(
const lotSymbols = lotCommodities(await read(['commodities', 'tag:lots']));
const orderedNames = [...names].sort();
const accounts = orderedNames.length
? qualifyAccounts(orderedNames, await read(canonicalLookups(orderedNames)))
? qualifyAccounts(
orderedNames,
await read(hledgerRunArgs([], canonicalAccountLookups(orderedNames)))
)
: [];
options.signal?.throwIfAborted();
const investment = investmentMetadata(typed, lotSymbols);
@@ -6,7 +6,7 @@ import { cashJournal } from '../../fixtures/cash.fixture.js';
import type { PreparedAccountRow } from '../transactions/account-rows.js';
import { decodeNativeTransaction } from '../transactions/export.js';
import { prepareTransaction } from '../transactions/transaction.js';
import { prepareReports } from './run.js';
import { generateSavedReport } from './generate.js';
import { MemoryPreparationTransactions } from './transactions.fixture.js';
const directories: string[] = [];
@@ -48,7 +48,7 @@ account liquid:daily
equity:opening -1.00 USD
`);
const collected = collectRows();
const prepared = await prepareReports(journal, collected);
const prepared = await generateSavedReport(journal, collected);
const rows = collected.rowsByAccount.get('assets:Cash')!;
expect(rows.find((row) => row.transaction.description === 'Dated payment')).toMatchObject({
accountDate: '2026-01-08',
@@ -94,11 +94,13 @@ include detail.journal
`;
await writeFile(detail, contents('1.00'));
const before = collectRows();
const beforeReports = await prepareReports(journal, before);
const investmentAccounts = ['assets:cash'];
const beforeReports = await generateSavedReport(journal, { ...before, investmentAccounts });
const during = collectRows();
let changed = false;
const reports = await prepareReports(journal, {
const reports = await generateSavedReport(journal, {
transactions: during.transactions,
investmentAccounts,
async writeRows(name, rows) {
await during.writeRows(name, rows);
if (!changed) {
@@ -113,11 +115,15 @@ include detail.journal
...beforeReports.overview,
preparedAt: ''
});
const after = await prepareReports(journal, {
expect(reports.investmentOverview).toEqual(beforeReports.investmentOverview);
expect(reports.investmentOverview?.portfolioValue?.quantity).toBe('1.00');
const after = await generateSavedReport(journal, {
investmentAccounts,
transactions: new MemoryPreparationTransactions(),
async writeRows() {}
});
expect(after.overview.netWorth).not.toEqual(reports.overview.netWorth);
expect(after.investmentOverview?.portfolioValue?.quantity).toBe('2.00');
});
it('withholds both accounts when native selection resolves their identities to the same account', async () => {
@@ -135,7 +141,7 @@ account equity
assets:Case -3 USD
`);
const collected = collectRows();
const prepared = await prepareReports(journal, collected);
const prepared = await generateSavedReport(journal, collected);
const collisions = prepared.accounts.filter((account) => account.name.startsWith('assets:'));
expect(collisions).toHaveLength(2);
for (const account of collisions) {
@@ -2,8 +2,9 @@ import type { ChildProcessWithoutNullStreams } from 'node:child_process';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { balanceReports, incomeReports } from '../../test-fixtures.js';
import { supportedHledgerVersion } from '../checks.js';
import type { PreparedAccountRow } from '../transactions/account-rows.js';
import { transactionFixture } from '../transactions/transaction.fixture.js';
import { ReportCommandExitedNonzero, prepareReports } from './run.js';
import { ReportCommandExitedNonzero, generateSavedReport } from './generate.js';
import { MemoryPreparationTransactions } from './transactions.fixture.js';
const processMock = vi.hoisted(() => ({ spawn: vi.fn() }));
@@ -134,8 +135,10 @@ function mockPreparationProcesses(
async function expectRejected(fixture: NativeFixture, exitCode = 0) {
const child = mockPreparationProcesses(fixture, { exitCode });
const writeRows = vi.fn(async () => {});
const error = await prepareReports('/private/SECRET', {
const writeRows = vi.fn<(account: string, rows: readonly PreparedAccountRow[]) => Promise<void>>(
async () => {}
);
const error = await generateSavedReport('/private/SECRET', {
transactions: new MemoryPreparationTransactions(),
writeRows
}).catch((error: unknown) => error);
@@ -158,7 +161,7 @@ describe('preparation completion and failure', () => {
child.once('close', () => {
vi.setSystemTime(new Date('2026-01-01T00:01:00Z'));
});
const result = await prepareReports('/private', {
const result = await generateSavedReport('/private', {
transactions: new MemoryPreparationTransactions(),
async writeRows() {
await children.get(child);
@@ -184,7 +187,7 @@ describe('preparation completion and failure', () => {
it('prepares an undated journal without consuming overview or balance documents', async () => {
mockPreparationProcesses(accountFixture(0));
const writeRows = vi.fn(async () => {});
const result = await prepareReports('/private', {
const result = await generateSavedReport('/private', {
transactions: new MemoryPreparationTransactions(),
writeRows
});
@@ -227,7 +230,7 @@ describe('preparation completion and failure', () => {
const readSummary = vi.spyOn(transactions, 'readSummary');
const countInPeriod = vi.spyOn(transactions, 'countInPeriod');
const writeRows = vi.fn(async () => {});
await expect(prepareReports('/private', { transactions, writeRows })).rejects.toThrow();
await expect(generateSavedReport('/private', { transactions, writeRows })).rejects.toThrow();
expect(readSummary).toHaveBeenCalledOnce();
expect(countInPeriod).not.toHaveBeenCalled();
expect(writeRows).not.toHaveBeenCalled();
@@ -261,7 +264,7 @@ describe('preparation completion and failure', () => {
const assertComplete = vi.spyOn(transactions, 'assertComplete');
const writeRows = vi.fn(async () => {});
await expect(
prepareReports('/private', {
generateSavedReport('/private', {
transactions,
writeRows
})
@@ -272,8 +275,8 @@ describe('preparation completion and failure', () => {
it('rejects a late native nonzero exit even after row writes', async () => {
const { writeRows, error } = await expectRejected(accountFixture(51), 9);
expect(writeRows.mock.calls.map(([, rows]) => rows.length)).toEqual([50, 1]);
expect(error).toBeInstanceOf(ReportCommandExitedNonzero);
expect(writeRows).toHaveBeenCalled();
});
it.each([
@@ -286,7 +289,7 @@ describe('preparation completion and failure', () => {
it('kills the child and withholds private diagnostics when a row callback fails', async () => {
const child = mockPreparationProcesses(accountFixture(51), { keepOpen: true });
const error = await prepareReports('/private', {
const error = await generateSavedReport('/private', {
transactions: new MemoryPreparationTransactions(),
async writeRows() {
throw new Error('SECRET /private 123.45 USD');
@@ -301,7 +304,12 @@ describe('preparation completion and failure', () => {
it.each(['original import', 'account rows'] as const)(
'kills the child on abort but waits for the active %s write',
async (phase) => {
const child = mockPreparationProcesses(accountFixture(50), { keepOpen: true });
const fixture = accountFixture(50);
if (phase === 'account rows') {
// Withhold the closing bracket: the first write must start before the full register arrives.
fixture.output = fixture.output.slice(0, -1);
}
const child = mockPreparationProcesses(fixture, { keepOpen: true });
const childClosed = new Promise<void>((resolve) => {
child.once('close', () => resolve());
});
@@ -330,7 +338,7 @@ describe('preparation completion and failure', () => {
await insertOriginal(json);
});
}
const result = prepareReports('/private', {
const result = generateSavedReport('/private', {
transactions,
signal: controller.signal,
async writeRows() {
@@ -366,7 +374,7 @@ describe('preparation completion and failure', () => {
{ keepOpen: true }
);
const controller = new AbortController();
const result = prepareReports('/private', {
const result = generateSavedReport('/private', {
transactions: new MemoryPreparationTransactions(),
signal: controller.signal,
async writeRows() {}
@@ -387,7 +395,7 @@ describe('preparation completion and failure', () => {
return child;
});
const controller = new AbortController();
const result = prepareReports('/private', {
const result = generateSavedReport('/private', {
transactions: new MemoryPreparationTransactions(),
signal: controller.signal,
async writeRows() {}
@@ -406,7 +414,7 @@ describe('metadata qualification', () => {
queueChildOutput(versionOutput);
queueChildOutput(emptyStats);
queueChildOutput('assets:\tSECRET\n');
const error = await prepareReports('/private/SECRET', {
const error = await generateSavedReport('/private/SECRET', {
transactions: new MemoryPreparationTransactions(),
async writeRows() {}
}).catch((error: unknown) => error);
+83
View File
@@ -0,0 +1,83 @@
import { getHledgerVersion, supportedHledgerVersion } from '../checks.js';
import { runJsonCommands } from '../commands/run.js';
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 {
planInvestmentOverview,
type PreparedInvestmentOverview
} from './investment-overview/prepare.js';
import { discoverJournal } from './discover-journal.js';
import { buildReportSequence, type PreparedAccountSummary } from './report-sequence.js';
/** A native report command completed with a nonzero exit, not an interruption. */
export class ReportCommandExitedNonzero extends Error {
constructor() {
super('Prepared transactions could not be read. Check the journal.');
}
}
export async function generateSavedReport(
journal: string,
options: {
transactions: PreparationTransactions;
writeRows: AccountRowWriter;
investmentAccounts?: readonly string[];
signal?: AbortSignal;
}
): Promise<{
overview: OverviewData;
accounts: PreparedAccountSummary[];
investmentOverview?: PreparedInvestmentOverview;
}> {
try {
options.signal?.throwIfAborted();
await getHledgerVersion((args) => readHledger(args, { signal: options.signal }));
options.signal?.throwIfAborted();
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);
// Discover cash commodities for eligible investment accounts before the batch.
const investmentPlan = await planInvestmentOverview({
configuredInvestmentAccounts: options.investmentAccounts ?? [],
journalStats: journalDiscovery.journal,
journalAccounts: journalDiscovery.accounts,
lotCommodities: journalDiscovery.investment.lotCommodities,
readPreflight: (command) =>
readHledger([...inputFlags, ...command], { signal: options.signal })
});
const reportSequence = buildReportSequence({ journalDiscovery, overviewPlan, investmentPlan });
const { overview, accounts, investmentOverview } = await runJsonCommands(
inputFlags,
reportSequence.commands,
{ signal: options.signal },
(reader, check) =>
reportSequence.read(reader, {
transactions: options.transactions,
writeRows: options.writeRows,
check
})
);
return {
overview: {
...overview,
hledgerVersion: supportedHledgerVersion,
preparedAt: new Date().toISOString()
},
accounts,
...(investmentOverview ? { investmentOverview } : {})
};
} catch (error) {
if (
!options.signal?.aborted &&
error instanceof HledgerExecutionError &&
error.kind === 'nonzero-exit'
)
throw new ReportCommandExitedNonzero();
// eslint-disable-next-line preserve-caught-error -- native errors can contain private diagnostics.
throw new Error('Prepared transactions could not be read. Check the journal.');
}
}
@@ -1,4 +1,4 @@
import type { decodeBalanceReport } from '../../accounts/balances.js';
import type { decodeBalanceReport } from '../accounts/balances.js';
import type { ReportedAmount } from '../../amounts.js';
import {
isUnitlessZero,
@@ -1,6 +1,6 @@
import { decodeBalanceReport } from '../../accounts/balances.js';
import { decodeBalanceReport } from '../accounts/balances.js';
import { parseExactJson, reportedAmounts, type Amount } from '../../amounts.js';
import type { Period } from '../../overview/ranges.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';
@@ -2,7 +2,7 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { expect, it } from 'vitest';
import { prepareReports } from '../run.js';
import { generateSavedReport } from '../generate.js';
import { MemoryPreparationTransactions } from '../transactions.fixture.js';
const parent = 'Assets:Invest.1';
@@ -64,7 +64,7 @@ async function prepare(text: string, investmentAccounts: string[]) {
try {
const path = join(directory, 'main.journal');
await writeFile(path, text);
return await prepareReports(path, {
return await generateSavedReport(path, {
transactions: new MemoryPreparationTransactions(),
async writeRows() {},
investmentAccounts
@@ -1,9 +1,9 @@
import type { ReportedAmount } from '../../amounts.js';
import type { Period } from '../../overview/ranges.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 '../metadata.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';
@@ -0,0 +1,43 @@
import { expect, it } from 'vitest';
import { journalMetadata } from '../journal-stats.js';
import { planOverviewReports } from './cash-and-net-worth/plan.js';
import { buildReportSequence } from './report-sequence.js';
it('plans one pair of journal exports and registers only for unambiguous accounts', () => {
const journal = journalMetadata(
'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),
investmentPlan: null,
journalDiscovery: {
journal,
accounts: [
{ name: 'assets:cash', access: 'ready' },
{ name: 'assets:cash:daily', access: 'ready' },
{ name: 'assets:Case', access: 'ambiguous' }
],
investment: {
assets: new Set(),
cash: new Set(),
liabilities: new Set(),
income: new Set(),
expenses: new Set(),
gains: new Set(),
lotCommodities: new Set()
}
}
});
const exports = commands.filter(([command]) => command === 'print');
expect(exports).toEqual([
['print', '--round=none', '-Ojson'],
['print', '--round=none', '--value=transacted', '-Ojson']
]);
expect(commands.slice(0, 2)).toEqual(exports);
const registers = commands.filter(([command]) => command === 'aregister');
expect(registers.map((command) => command.at(-1))).toEqual([
'^assets:cash$',
'^assets:cash:daily$'
]);
expect(commands.slice(-2)).toEqual(registers);
});
@@ -0,0 +1,133 @@
import {
organizeAccountBalance,
planAccountBalances,
readAccountBalances,
type PreparedBalance
} from './accounts/balances.js';
import { planOverviewReports, readOverviewReports } from './cash-and-net-worth/plan.js';
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 { JournalDiscovery, QualifiedAccount } from './discover-journal.js';
export interface PreparedAccountSummary extends QualifiedAccount {
rowCount: number | null;
summary: PreparedBalance;
}
export function buildReportSequence({
journalDiscovery,
overviewPlan,
investmentPlan
}: {
journalDiscovery: JournalDiscovery;
overviewPlan: ReturnType<typeof planOverviewReports>;
investmentPlan: Awaited<ReturnType<typeof planInvestmentOverview>>;
}) {
const { journal: journalStats, accounts: journalAccounts, investment } = journalDiscovery;
const accountBalanceCommands = planAccountBalances(journalStats);
const accountRegisters = journalAccounts.flatMap(({ name, access }, index) =>
access === 'ready' ? [{ index, command: accountRegisterCommand(name) }] : []
);
// The reader below consumes these reports in this order.
const commands = [
['print', '--round=none', '-Ojson'],
['print', '--round=none', '--value=transacted', '-Ojson'],
...overviewPlan.commands,
...accountBalanceCommands,
...accountRegisters.map(({ command }) => command),
...(investmentPlan?.commands ?? [])
];
return {
commands,
async read(
reader: ReportStreamReader,
{
transactions,
writeRows,
check
}: {
transactions: PreparationTransactions;
writeRows: AccountRowWriter;
check: () => void;
}
) {
await importTransactionExports(reader, transactions, journalStats, check);
const overview = await readOverview(reader, overviewPlan, journalStats, transactions, check);
const accounts = await readAccountSummaries(reader, journalAccounts, journalStats);
for (const { index } of accountRegisters) {
await writePreparedAccountRows(
reader,
accounts[index],
investment,
transactions,
writeRows,
check
);
}
const investmentOverview = await investmentPlan?.read(reader);
return { overview, accounts, investmentOverview };
}
};
}
function accountRegisterCommand(accountName: string): string[] {
const escapedName = accountName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
return ['aregister', '--historical', '--empty', '-Ojson', `^${escapedName}$`];
}
async function importTransactionExports(
reader: ReportStreamReader,
transactions: PreparationTransactions,
journalStats: JournalDiscovery['journal'],
check: () => void
): Promise<void> {
await reader.array('object', (json) => transactions.insertOriginal(json));
await reader.array('object', (json) => transactions.attachTransacted(json));
check();
await transactions.assertComplete();
check();
const summary = await transactions.readSummary();
check();
// hledger spans can include posting dates. Compare the latest primary transaction date.
if (
summary.transactionCount !== journalStats.journalCoverage.transactionCount ||
summary.lastDate !== journalStats.asOf
) {
throw new Error('Native transactions do not match preparation metadata.');
}
}
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)
);
}
async function readAccountSummaries(
reader: ReportStreamReader,
journalAccounts: readonly QualifiedAccount[],
{ asOf, baseCurrency }: JournalDiscovery['journal']
): Promise<PreparedAccountSummary[]> {
const balances = await readAccountBalances(reader, asOf);
return journalAccounts.map(({ name, access }) => ({
name,
access,
rowCount: access === 'ambiguous' ? null : 0,
summary: organizeAccountBalance(name, access, asOf, baseCurrency, balances)
}));
}
+6 -3
View File
@@ -1,9 +1,12 @@
import { journalMetadata } from './src/journal-stats.js';
import { planOverviewReports, type OverviewReports } from './src/overview/plan.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 { organizeOverviewData } from './src/overview/report.js';
import { planIncomeRanges } from './src/overview/ranges.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(