Separate Cash date windows from income and spending #74
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'@hledger-reports/worker': patch
|
||||
---
|
||||
|
||||
Separate Cash date windows from the code that prepares income, spending, and category values. Report values and the saved format are unchanged.
|
||||
@@ -25,7 +25,9 @@ exports already in hand, without running hledger.
|
||||
- **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. For
|
||||
Investment Overview, start at `investment-overview/prepare.ts`. It checks
|
||||
scope, gathers shared balances and holdings through `native-reports.ts`,
|
||||
and assembles the values from `displays/`.
|
||||
`investment-overview` folders define their parts of the saved report. In
|
||||
`cash-and-net-worth`, `income-ranges.ts` chooses the dates and
|
||||
`income-spending.ts` turns each statement into totals, monthly values, and
|
||||
spending categories. For Investment Overview, start at `prepare.ts`. It
|
||||
checks scope, gathers shared balances and holdings through
|
||||
`native-reports.ts`, and assembles the values from `displays/`.
|
||||
@@ -1,3 +1,8 @@
|
||||
export interface Period {
|
||||
begin: string;
|
||||
endExclusive: string;
|
||||
}
|
||||
|
||||
export function isoDate(date: Date): string {
|
||||
const text = date.toISOString().slice(0, 10);
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(text) || text < '0001-01-01') {
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { isoDate, type Period } from '../../report-date.js';
|
||||
|
||||
export type OverviewMonths = 1 | 3 | 6 | 12;
|
||||
|
||||
export interface IncomeRange {
|
||||
months: OverviewMonths;
|
||||
begin: string;
|
||||
asOfCutoffExclusive: string;
|
||||
calendarEndExclusive: string;
|
||||
periods: Period[];
|
||||
}
|
||||
|
||||
export function incomeRangesAsOf(asOf: string): IncomeRange[] {
|
||||
const cutoff = new Date(`${asOf}T00:00:00Z`);
|
||||
cutoff.setUTCDate(cutoff.getUTCDate() + 1);
|
||||
const asOfCutoffExclusive = isoDate(cutoff);
|
||||
const date = new Date(`${asOf}T00:00:00Z`);
|
||||
date.setUTCDate(1);
|
||||
date.setUTCMonth(date.getUTCMonth() - 11);
|
||||
const history: Period[] = Array.from({ length: 12 }, () => {
|
||||
const begin = isoDate(date);
|
||||
date.setUTCMonth(date.getUTCMonth() + 1);
|
||||
return { begin, endExclusive: isoDate(date) };
|
||||
});
|
||||
const calendarEndExclusive = history[history.length - 1].endExclusive;
|
||||
return ([1, 3, 6, 12] as const).map((months) => {
|
||||
const periods = history.slice(-months);
|
||||
return { months, begin: periods[0].begin, asOfCutoffExclusive, calendarEndExclusive, periods };
|
||||
});
|
||||
}
|
||||
+38
-26
@@ -2,22 +2,23 @@ import { mkdtemp, readFile, 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 { planIncomeRanges, organizeIncomeRange } from './ranges.js';
|
||||
import { incomeRangesAsOf } from './income-ranges.js';
|
||||
import { incomeSpendingForRange } from './income-spending.js';
|
||||
import {
|
||||
monthlyIncomeStatementCommand,
|
||||
type HledgerIncomeStatement
|
||||
} from '../../commands/income-statement.js';
|
||||
import { incomeReports } from '../../../test-fixtures.js';
|
||||
import { balanceReports, decodeOverviewFixture, 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 {
|
||||
const twelveMonthRange = incomeRangesAsOf('2026-04-16')[3];
|
||||
function statement(range = twelveMonthRange): HledgerIncomeStatement {
|
||||
const command = monthlyIncomeStatementCommand({
|
||||
begin: range.begin,
|
||||
calendarEndExclusive: range.periods.at(-1)!.endExclusive,
|
||||
postingCutoffExclusive: range.endExclusive,
|
||||
calendarEndExclusive: range.calendarEndExclusive,
|
||||
postingCutoffExclusive: range.asOfCutoffExclusive,
|
||||
depth: 2,
|
||||
excludeCapitalGains: true
|
||||
});
|
||||
@@ -49,7 +50,7 @@ it('copies native range totals, NET, signs and cost-distinguished bags, never mo
|
||||
{ prrName: 'Fees', prrTotal: [] }
|
||||
];
|
||||
const before = structuredClone(parsed);
|
||||
const data = organizeIncomeRange(parsed, plan, 17);
|
||||
const data = incomeSpendingForRange(parsed, twelveMonthRange, 17);
|
||||
expect(data.range).toEqual({
|
||||
transactionCount: 17,
|
||||
begin: '2025-05-01',
|
||||
@@ -105,14 +106,19 @@ it.each<[string, (report: HledgerIncomeStatement) => void]>([
|
||||
])('rejects %s before publishing a range', (_name, mutate) => {
|
||||
const report = statement();
|
||||
mutate(report);
|
||||
expect(() => organizeIncomeRange(report, plan, 0)).toThrow();
|
||||
expect(() => incomeSpendingForRange(report, twelveMonthRange, 0)).toThrow();
|
||||
});
|
||||
|
||||
it('validates shorter statements even though their monthly columns are not published', () => {
|
||||
const shorter = planIncomeRanges('2026-04-16')[0];
|
||||
const report = statement(shorter);
|
||||
report.cbrSubreports[0][1].prTotals.prrAmounts.pop();
|
||||
expect(() => organizeIncomeRange(report, shorter, 0)).toThrow();
|
||||
it('rejects the entire overview when an unpublished short-range column is missing', async () => {
|
||||
const stats =
|
||||
'Base currency : USD\nLast txn : 2026-04-16\nTxns : 12\nTxns span : 2025-05-01 to 2026-04-17\n';
|
||||
const incomeStatements = incomeReports();
|
||||
const shortStatement = JSON.parse(incomeStatements[0]);
|
||||
shortStatement.cbrSubreports[0][1].prTotals.prrAmounts.pop();
|
||||
incomeStatements[0] = JSON.stringify(shortStatement);
|
||||
await expect(
|
||||
decodeOverviewFixture(stats, { incomeStatements, snapshots: balanceReports() })
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
const declarations = `commodity USD 1.00
|
||||
@@ -191,20 +197,26 @@ describe('native hledger 1.99.5 finite overview ranges', () => {
|
||||
]
|
||||
});
|
||||
}
|
||||
expect(overview.incomeExpenses.months).toHaveLength(12);
|
||||
expect(overview.incomeExpenses.months[0]).toEqual({
|
||||
begin: '2025-05-01',
|
||||
endExclusive: '2025-06-01',
|
||||
income: usd('100.00'),
|
||||
expenses: usd('10.00')
|
||||
const month = (begin: string, endExclusive: string, income?: string, expenses?: string) => ({
|
||||
begin,
|
||||
endExclusive,
|
||||
income: income === undefined ? [] : usd(income),
|
||||
expenses: expenses === undefined ? [] : usd(expenses)
|
||||
});
|
||||
expect(overview.incomeExpenses.months[11]).toEqual({
|
||||
begin: '2026-04-01',
|
||||
endExclusive: '2026-05-01',
|
||||
income: usd('400.00'),
|
||||
expenses: usd('36.00')
|
||||
});
|
||||
expect(overview.incomeExpenses.months[1]).toMatchObject({ income: [], expenses: [] });
|
||||
expect(overview.incomeExpenses.months).toEqual([
|
||||
month('2025-05-01', '2025-06-01', '100.00', '10.00'),
|
||||
month('2025-06-01', '2025-07-01'),
|
||||
month('2025-07-01', '2025-08-01'),
|
||||
month('2025-08-01', '2025-09-01'),
|
||||
month('2025-09-01', '2025-10-01'),
|
||||
month('2025-10-01', '2025-11-01'),
|
||||
month('2025-11-01', '2025-12-01', '200.00', '20.00'),
|
||||
month('2025-12-01', '2026-01-01'),
|
||||
month('2026-01-01', '2026-02-01'),
|
||||
month('2026-02-01', '2026-03-01', '300.00', '30.00'),
|
||||
month('2026-03-01', '2026-04-01'),
|
||||
month('2026-04-01', '2026-05-01', '400.00', '36.00')
|
||||
]);
|
||||
expect(await readFile(journal, 'utf8')).toBe(text);
|
||||
});
|
||||
});
|
||||
+17
-45
@@ -1,8 +1,6 @@
|
||||
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;
|
||||
import type { IncomeRange } from './income-ranges.js';
|
||||
export interface OverviewRange {
|
||||
transactionCount: number;
|
||||
begin: string;
|
||||
@@ -16,38 +14,8 @@ export interface OverviewRange {
|
||||
};
|
||||
}
|
||||
|
||||
export interface Period {
|
||||
begin: string;
|
||||
endExclusive: string;
|
||||
}
|
||||
|
||||
export interface IncomeRangePlan {
|
||||
months: OverviewMonths;
|
||||
begin: string;
|
||||
endExclusive: string;
|
||||
periods: Period[];
|
||||
}
|
||||
|
||||
const failureMessage = 'Invalid hledger Overview range.';
|
||||
|
||||
export function planIncomeRanges(asOf: string): IncomeRangePlan[] {
|
||||
const cutoff = new Date(`${asOf}T00:00:00Z`);
|
||||
cutoff.setUTCDate(cutoff.getUTCDate() + 1);
|
||||
const endExclusive = isoDate(cutoff);
|
||||
const date = new Date(`${asOf}T00:00:00Z`);
|
||||
date.setUTCDate(1);
|
||||
date.setUTCMonth(date.getUTCMonth() - 11);
|
||||
const history: Period[] = Array.from({ length: 12 }, () => {
|
||||
const begin = isoDate(date);
|
||||
date.setUTCMonth(date.getUTCMonth() + 1);
|
||||
return { begin, endExclusive: isoDate(date) };
|
||||
});
|
||||
return ([1, 3, 6, 12] as const).map((months) => {
|
||||
const periods = history.slice(-months);
|
||||
return { months, begin: periods[0].begin, endExclusive, periods };
|
||||
});
|
||||
}
|
||||
|
||||
function incomeSections(report: HledgerIncomeStatement) {
|
||||
const [income, expenses] = report.cbrSubreports;
|
||||
if (
|
||||
@@ -63,20 +31,23 @@ function incomeSections(report: HledgerIncomeStatement) {
|
||||
return { income: income[1], expenses: expenses[1] };
|
||||
}
|
||||
|
||||
function organizeMonths(report: HledgerIncomeStatement, plan: IncomeRangePlan) {
|
||||
const { income, expenses } = incomeSections(report);
|
||||
function monthlyIncomeAndSpending(
|
||||
report: HledgerIncomeStatement,
|
||||
window: IncomeRange,
|
||||
{ income, expenses }: ReturnType<typeof incomeSections>
|
||||
) {
|
||||
const incomeByMonth = income?.prTotals?.prrAmounts;
|
||||
const expensesByMonth = expenses?.prTotals?.prrAmounts;
|
||||
if (
|
||||
report.cbrDates.length !== plan.months ||
|
||||
report.cbrDates.length !== window.months ||
|
||||
!Array.isArray(incomeByMonth) ||
|
||||
incomeByMonth.length !== plan.months ||
|
||||
incomeByMonth.length !== window.months ||
|
||||
!Array.isArray(expensesByMonth) ||
|
||||
expensesByMonth.length !== plan.months
|
||||
expensesByMonth.length !== window.months
|
||||
)
|
||||
throw new Error(failureMessage);
|
||||
return report.cbrDates.map((period, index) => {
|
||||
const expected = plan.periods[index];
|
||||
const expected = window.periods[index];
|
||||
if (
|
||||
!Array.isArray(period) ||
|
||||
period.length !== 2 ||
|
||||
@@ -94,20 +65,21 @@ function organizeMonths(report: HledgerIncomeStatement, plan: IncomeRangePlan) {
|
||||
});
|
||||
}
|
||||
|
||||
export function organizeIncomeRange(
|
||||
export function incomeSpendingForRange(
|
||||
report: HledgerIncomeStatement,
|
||||
plan: IncomeRangePlan,
|
||||
window: IncomeRange,
|
||||
transactionCount: number
|
||||
) {
|
||||
const sections = incomeSections(report);
|
||||
// Validate every native column, even though only the twelve-month history is published.
|
||||
const months = organizeMonths(report, plan);
|
||||
const { income, expenses } = incomeSections(report);
|
||||
const months = monthlyIncomeAndSpending(report, window, sections);
|
||||
const { income, expenses } = sections;
|
||||
const rows = expenses?.prRows;
|
||||
if (!Array.isArray(rows)) throw new Error(failureMessage);
|
||||
const range: OverviewRange = {
|
||||
transactionCount,
|
||||
begin: plan.begin,
|
||||
endExclusive: plan.endExclusive,
|
||||
begin: window.begin,
|
||||
endExclusive: window.asOfCutoffExclusive,
|
||||
income: reportedAmounts(income?.prTotals?.prrTotal),
|
||||
expenses: reportedAmounts(expenses?.prTotals?.prrTotal),
|
||||
net: reportedAmounts(report.cbrTotals?.prrTotal),
|
||||
@@ -99,7 +99,7 @@ it.each([
|
||||
const reports = await overview.read(reader, () => 0);
|
||||
expect(reports.incomeStatements.find(({ months }) => months === 12)).toMatchObject({
|
||||
begin,
|
||||
endExclusive: cutoff
|
||||
asOfCutoffExclusive: cutoff
|
||||
});
|
||||
expect(reports.snapshots.slice(-2).map(({ date }) => date)).toEqual([previous, asOf]);
|
||||
await reader.eof();
|
||||
|
||||
@@ -8,8 +8,8 @@ import {
|
||||
} 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';
|
||||
import { isoDate, type Period } from '../../report-date.js';
|
||||
import { incomeRangesAsOf, type IncomeRange } from './income-ranges.js';
|
||||
|
||||
type SnapshotPeriod = Period & { date: string };
|
||||
|
||||
@@ -17,7 +17,7 @@ export interface OverviewReports {
|
||||
asOf: string | null;
|
||||
baseCurrency: string;
|
||||
journalCoverage: JournalCoverage;
|
||||
incomeStatements: (IncomeRangePlan & {
|
||||
incomeStatements: (IncomeRange & {
|
||||
transactionCount: number;
|
||||
report: HledgerIncomeStatement;
|
||||
})[];
|
||||
@@ -26,14 +26,14 @@ export interface OverviewReports {
|
||||
|
||||
export function cashAndNetWorthReports(metadata: ReturnType<typeof journalMetadata>) {
|
||||
const { asOf, baseCurrency } = metadata;
|
||||
const incomeRanges = asOf === null ? [] : planIncomeRanges(asOf);
|
||||
const incomeRanges = asOf === null ? [] : incomeRangesAsOf(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,
|
||||
calendarEndExclusive: range.calendarEndExclusive,
|
||||
postingCutoffExclusive: range.asOfCutoffExclusive,
|
||||
depth: 2,
|
||||
excludeCapitalGains: true
|
||||
})
|
||||
@@ -61,7 +61,7 @@ export function cashAndNetWorthReports(metadata: ReturnType<typeof journalMetada
|
||||
for (const { range, command } of incomeStatements) {
|
||||
const transactionCount = await countTransactionsByPrimaryDate(
|
||||
range.begin,
|
||||
range.endExclusive
|
||||
range.asOfCutoffExclusive
|
||||
);
|
||||
countedStatements.push({ range, command, transactionCount });
|
||||
}
|
||||
@@ -83,7 +83,7 @@ export function cashAndNetWorthReports(metadata: ReturnType<typeof journalMetada
|
||||
}
|
||||
|
||||
function netWorthSnapshotPeriods(
|
||||
incomeRanges: readonly IncomeRangePlan[],
|
||||
incomeRanges: readonly IncomeRange[],
|
||||
asOf: string
|
||||
): SnapshotPeriod[] {
|
||||
const twelveMonthRange = incomeRanges.find(({ months }) => months === 12);
|
||||
@@ -97,7 +97,7 @@ function netWorthSnapshotPeriods(
|
||||
});
|
||||
const asOfSnapshot = {
|
||||
begin: asOfMonth.begin,
|
||||
endExclusive: twelveMonthRange.endExclusive,
|
||||
endExclusive: twelveMonthRange.asOfCutoffExclusive,
|
||||
date: asOf
|
||||
};
|
||||
return [...monthEndSnapshots, asOfSnapshot];
|
||||
|
||||
@@ -2,9 +2,11 @@ import type { ReportedAmount } from '../../amounts.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';
|
||||
import type { OverviewMonths } from './income-ranges.js';
|
||||
import { incomeSpendingForRange, type OverviewRange } from './income-spending.js';
|
||||
|
||||
export type { OverviewMonths, OverviewRange } from './ranges.js';
|
||||
export type { OverviewMonths } from './income-ranges.js';
|
||||
export type { OverviewRange } from './income-spending.js';
|
||||
|
||||
export type NativeValue = {
|
||||
amounts: ReportedAmount[];
|
||||
@@ -48,21 +50,23 @@ export function organizeOverviewData(
|
||||
};
|
||||
}
|
||||
if (incomeStatements.length !== 4) throw new Error('Invalid hledger Overview ranges.');
|
||||
const organized = incomeStatements.map((statement, index) => {
|
||||
if (statement.months !== ([1, 3, 6, 12] as const)[index])
|
||||
throw new Error('Invalid hledger Overview ranges.');
|
||||
return organizeIncomeRange(statement.report, statement, statement.transactionCount);
|
||||
});
|
||||
const [oneMonth, threeMonths, sixMonths, twelveMonths] = incomeStatements.map(
|
||||
(statement, index) => {
|
||||
if (statement.months !== ([1, 3, 6, 12] as const)[index])
|
||||
throw new Error('Invalid hledger Overview ranges.');
|
||||
return incomeSpendingForRange(statement.report, statement, statement.transactionCount);
|
||||
}
|
||||
);
|
||||
return {
|
||||
asOf,
|
||||
journalCoverage,
|
||||
ranges: {
|
||||
1: organized[0].range,
|
||||
3: organized[1].range,
|
||||
6: organized[2].range,
|
||||
12: organized[3].range
|
||||
1: oneMonth.range,
|
||||
3: threeMonths.range,
|
||||
6: sixMonths.range,
|
||||
12: twelveMonths.range
|
||||
},
|
||||
incomeExpenses: { months: organized[3].months },
|
||||
incomeExpenses: { months: twelveMonths.months },
|
||||
netWorth,
|
||||
balanceSheet
|
||||
};
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { isoDate } from '../../../report-date.js';
|
||||
import type { Period } from '../../cash-and-net-worth/ranges.js';
|
||||
import { isoDate, type Period } from '../../../report-date.js';
|
||||
import { reportedTotalInCurrency } from '../balances.js';
|
||||
import type { InvestmentReports } from '../native-reports.js';
|
||||
|
||||
|
||||
@@ -4,8 +4,7 @@ import {
|
||||
monthlyHistoricalBalanceCommand,
|
||||
type BalanceValuation
|
||||
} from '../../commands/balance.js';
|
||||
import type { Period } from '../cash-and-net-worth/ranges.js';
|
||||
import { isoDate } from '../../report-date.js';
|
||||
import { isoDate, type Period } from '../../report-date.js';
|
||||
import type { ReportStreamReader } from '../../report-stream.js';
|
||||
import { identifyCashCommodities } from './cash.js';
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { journalMetadata } from './src/journal-stats.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';
|
||||
import { incomeRangesAsOf } from './src/reports/cash-and-net-worth/income-ranges.js';
|
||||
|
||||
export function reportReader(documents: readonly string[]): ReportStreamReader {
|
||||
return new ReportStreamReader(
|
||||
@@ -52,7 +52,7 @@ export function balanceReports(asOf = '2026-04-16'): string[] {
|
||||
}
|
||||
|
||||
export function incomeReports(asOf = '2026-04-16'): string[] {
|
||||
return planIncomeRanges(asOf).map((range) => {
|
||||
return incomeRangesAsOf(asOf).map((range) => {
|
||||
const totals = () => ({ prrAmounts: range.periods.map(() => []), prrTotal: [] });
|
||||
const report = {
|
||||
cbrDates: range.periods.map(({ begin, endExclusive }) =>
|
||||
|
||||
Reference in new issue
Block a user