diff --git a/.changeset/separate-investment-entry-and-posting.md b/.changeset/separate-investment-entry-and-posting.md new file mode 100644 index 0000000..2b1531b --- /dev/null +++ b/.changeset/separate-investment-entry-and-posting.md @@ -0,0 +1,6 @@ +--- +'@hledger-reports/worker': patch +'@hledger-reports/web': patch +--- + +Separate investment entry interpretation during preparation from reading one original posting for the register. Saved data and visible rows are unchanged. diff --git a/packages/db/src/reports/queries.ts b/packages/db/src/reports/queries.ts index e32086b..09e1b2d 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -209,6 +209,26 @@ export async function readReportData(database: Kysely): Promise< return data; } +function selectAccountRowsWithTransactions(database: Kysely) { + // Keep an activity with a missing transaction so the decoder rejects it. + return database + .selectFrom('account_activity') + .leftJoin( + 'transactions', + 'transactions.native_index', + 'account_activity.native_transaction_index' + ) + .select([ + 'account_activity.ordinal', + 'account_activity.account_date', + 'account_activity.native_transaction_index', + 'account_activity.context_json', + 'transactions.native_index as canonical_native_index', + 'transactions.original_json', + 'transactions.transacted_json' + ]); +} + function decodeAccountRow(record: StoredActivityRow, rowCount: number): PreparedAccountRow { if ( !Number.isSafeInteger(record.ordinal) || @@ -306,22 +326,7 @@ export async function readAccountActivityDetail( rowCount < 0 ) throw new Error('Invalid account data.'); - const record = await database - .selectFrom('account_activity') - .leftJoin( - 'transactions', - 'transactions.native_index', - 'account_activity.native_transaction_index' - ) - .select([ - 'account_activity.ordinal', - 'account_activity.account_date', - 'account_activity.native_transaction_index', - 'account_activity.context_json', - 'transactions.native_index as canonical_native_index', - 'transactions.original_json', - 'transactions.transacted_json' - ]) + const record = await selectAccountRowsWithTransactions(database) .where('account_activity.account_name', '=', account.name) .where('account_activity.native_transaction_index', '=', nativeIndex) .limit(1) @@ -384,22 +389,7 @@ export async function readAccountActivityPage( if (!context) return null; const { rowCount, summary } = context; const { order, offset, limit } = options; - const records = await database - .selectFrom('account_activity') - .leftJoin( - 'transactions', - 'transactions.native_index', - 'account_activity.native_transaction_index' - ) - .select([ - 'account_activity.ordinal', - 'account_activity.account_date', - 'account_activity.native_transaction_index', - 'account_activity.context_json', - 'transactions.native_index as canonical_native_index', - 'transactions.original_json', - 'transactions.transacted_json' - ]) + const records = await selectAccountRowsWithTransactions(database) .where('account_activity.account_name', '=', account.name) .orderBy('account_activity.account_date', order) .orderBy('account_activity.ordinal', 'asc') @@ -570,22 +560,7 @@ export async function readAccountInvestmentActivityPage( // Several action references can share one full canonical account row. const parents = new Map(); if (references.length > 0) { - const records = await database - .selectFrom('account_activity') - .leftJoin( - 'transactions', - 'transactions.native_index', - 'account_activity.native_transaction_index' - ) - .select([ - 'account_activity.ordinal', - 'account_activity.account_date', - 'account_activity.native_transaction_index', - 'account_activity.context_json', - 'transactions.native_index as canonical_native_index', - 'transactions.original_json', - 'transactions.transacted_json' - ]) + const records = await selectAccountRowsWithTransactions(database) .where('account_activity.account_name', '=', account.name) .where('account_activity.ordinal', 'in', [ ...new Set(references.map(({ ordinal }) => ordinal)) diff --git a/packages/hledger/README.md b/packages/hledger/README.md index 888a417..f3ac06a 100644 --- a/packages/hledger/README.md +++ b/packages/hledger/README.md @@ -31,3 +31,8 @@ exports already in hand, without running hledger. 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/`. +- **Investment entries and postings:** Under `src/transactions/investment/`, + `account-context.ts` gathers evidence from related account history. `entry.ts` + interprets the native entry for the selected account during preparation. + `posting.ts` uses that saved interpretation to describe one selected original + posting. It does not decide which postings the saved register pages include. diff --git a/packages/hledger/src/index.ts b/packages/hledger/src/index.ts index 89f4cd9..836ed10 100644 --- a/packages/hledger/src/index.ts +++ b/packages/hledger/src/index.ts @@ -30,7 +30,7 @@ export type { PreparedInvestmentPosting, PreparedSecurityActivity, InvestmentIssue -} from './transactions/investment.js'; +} from './transactions/investment/types.js'; export type { PreparedTransaction, PreparedPosting, diff --git a/packages/hledger/src/reports/accounts/register-rows.ts b/packages/hledger/src/reports/accounts/register-rows.ts index 774bbac..1e6e914 100644 --- a/packages/hledger/src/reports/accounts/register-rows.ts +++ b/packages/hledger/src/reports/accounts/register-rows.ts @@ -6,9 +6,9 @@ import { } from '../../transactions/account-rows.js'; import { decodeNativeTransaction } from '../../transactions/export.js'; import { - accountInvestmentContext, + investmentContextFromHistory, type InvestmentMetadata -} from '../../transactions/investment.js'; +} from '../../transactions/investment/account-context.js'; import type { NativeTransactionPair, PreparationTransactions } from '../../transactions/store.js'; import { prepareTransaction, requireTransactionIndex } from '../../transactions/transaction.js'; import type { PreparedAccountSummary } from '../report-sequence.js'; @@ -45,7 +45,7 @@ export async function writePreparedAccountRows( yield prepareAccountTransaction(pair, account.name); } } - const context = await accountInvestmentContext(history(), metadata, account.name); + const context = await investmentContextFromHistory(history(), metadata, account.name); const indexes = new Set(); let chunk: PreparedAccountRow[] = []; const write = async () => { diff --git a/packages/hledger/src/reports/discover-journal.ts b/packages/hledger/src/reports/discover-journal.ts index 8e4abb6..ca41738 100644 --- a/packages/hledger/src/reports/discover-journal.ts +++ b/packages/hledger/src/reports/discover-journal.ts @@ -1,7 +1,7 @@ import { hledgerRunArgs } from '../commands/run.js'; import { journalMetadata } from '../journal-stats.js'; import { readHledger } from '../process.js'; -import type { InvestmentMetadata } from '../transactions/investment.js'; +import type { InvestmentMetadata } from '../transactions/investment/account-context.js'; export interface QualifiedAccount { name: string; diff --git a/packages/hledger/src/transactions/account-rows.test.ts b/packages/hledger/src/transactions/account-rows.test.ts index 0103f70..d64d06b 100644 --- a/packages/hledger/src/transactions/account-rows.test.ts +++ b/packages/hledger/src/transactions/account-rows.test.ts @@ -1,7 +1,10 @@ import { expect, it } from 'vitest'; import { organizeAccountRow, parseAccountRegisterRow } from './account-rows.js'; import { prepareTransaction } from './transaction.js'; -import { accountInvestmentContext, type InvestmentMetadata } from './investment.js'; +import { + investmentContextFromHistory, + type InvestmentMetadata +} from './investment/account-context.js'; import { transactionFixture } from './transaction.fixture.js'; const metadata: InvestmentMetadata = { @@ -19,7 +22,7 @@ async function organize(input: ReturnType, account: string) { input, account, transaction, - await accountInvestmentContext([transaction], metadata, account) + await investmentContextFromHistory([transaction], metadata, account) ); } @@ -136,7 +139,7 @@ it('recomputes selected indexes from original print, not stripped register posti input, 'assets:cash', transaction, - await accountInvestmentContext([transaction], metadata, 'assets:cash') + await investmentContextFromHistory([transaction], metadata, 'assets:cash') ); expect(result.accountPostingIndexes).toEqual([1]); expect(result.transaction).toBe(transaction); @@ -151,7 +154,7 @@ it.each(['tindex', 'ttags'] as const)( if (field === 'tindex') print[field]++; else print[field].push(['different', '']); const transaction = prepareTransaction(print, structuredClone(print)); - const context = await accountInvestmentContext([transaction], metadata, 'assets:cash'); + const context = await investmentContextFromHistory([transaction], metadata, 'assets:cash'); expect(() => organizeAccountRow(input, 'assets:cash', transaction, context)).toThrow('header'); } ); @@ -170,7 +173,11 @@ it.each([ earlier.tpostings[1].paccount = virtualAccount; earlier.tpostings[1].preal = 'VirtualPosting'; const history = prepareTransaction(earlier, structuredClone(earlier)); - const context = await accountInvestmentContext([history, transaction], metadata, 'assets:cash'); + const context = await investmentContextFromHistory( + [history, transaction], + metadata, + 'assets:cash' + ); const row = organizeAccountRow(input, 'assets:cash', transaction, context); const amounts = [{ commodity: 'USD', quantity: '-100.00' }]; expect(row.investment.cash.change).toEqual(unclassified ? [] : amounts); diff --git a/packages/hledger/src/transactions/account-rows.ts b/packages/hledger/src/transactions/account-rows.ts index 834560b..c7a1db5 100644 --- a/packages/hledger/src/transactions/account-rows.ts +++ b/packages/hledger/src/transactions/account-rows.ts @@ -7,11 +7,9 @@ import { type NativeTransaction, type PreparedTransaction } from './transaction.js'; -import { - prepareInvestmentActivity, - type AccountInvestmentContext, - type PreparedInvestmentData -} from './investment.js'; +import type { AccountInvestmentContext } from './investment/account-context.js'; +import { interpretInvestmentEntry } from './investment/entry.js'; +import type { PreparedInvestmentData } from './investment/types.js'; /** The six fields returned by hledger 1.99.5 aregister JSON, before projection. */ export type HledgerAccountRegisterRow = [ @@ -77,5 +75,5 @@ export function organizeAccountRow( transaction, accountPostingIndexes }; - return { ...baseRow, investment: prepareInvestmentActivity(baseRow, context) }; + return { ...baseRow, investment: interpretInvestmentEntry(baseRow, context) }; } diff --git a/packages/hledger/src/transactions/index.ts b/packages/hledger/src/transactions/index.ts index c568152..ae76083 100644 --- a/packages/hledger/src/transactions/index.ts +++ b/packages/hledger/src/transactions/index.ts @@ -1,8 +1,8 @@ export { decodeNativeTransaction } from './export.js'; export { assertTransactionExportsMatch, prepareTransaction } from './transaction.js'; export type { NativeTransaction } from './transaction.js'; -export { prepareInvestmentPosting } from './investment.js'; -export type { PreparedInvestmentPosting } from './investment.js'; +export { prepareInvestmentPosting } from './investment/posting.js'; +export type { PreparedInvestmentPosting } from './investment/types.js'; export type { NativeTransactionPair, NativeTransactionSummary, diff --git a/packages/hledger/src/transactions/investment.ts b/packages/hledger/src/transactions/investment.ts deleted file mode 100644 index e73d190..0000000 --- a/packages/hledger/src/transactions/investment.ts +++ /dev/null @@ -1,565 +0,0 @@ -import type { ReportedAmount } from '../amounts.js'; -import type { PreparedAccountRow } from './account-rows.js'; -import type { PreparedPosting, PreparedTransaction } from './transaction.js'; - -/** Native account-query results. Subtype sets (A/C and R/G) may overlap. */ -export interface InvestmentMetadata { - assets: ReadonlySet; - cash: ReadonlySet; - liabilities: ReadonlySet; - income: ReadonlySet; - expenses: ReadonlySet; - gains: ReadonlySet; - lotCommodities: ReadonlySet; -} - -export interface AccountInvestmentContext extends InvestmentMetadata { - securityCommodities: ReadonlySet; - cashCommodities: ReadonlySet; - /** Account/subtree history can contribute virtual amounts to later native balances. */ - hasVirtualAccountPostings: boolean; - /** Non-asset account/subtree history also prevents isolating cash in native net bags. */ - hasNonAssetAccountPostings: boolean; -} - -export type InvestmentIssue = - | 'unclassified-commodity' - | 'unattributed-income' - | 'mixed-security-actions' - | 'mixed-security-posting' - | 'unknown-native-role' - | 'unsupported-short' - | 'virtual-postings' - | 'unavailable-transacted-values'; - -export interface PreparedSecurityActivity { - commodity: string; - action: - | 'buy' - | 'sell' - | 'transfer-in' - | 'transfer-out' - | 'acquire' - | 'dispose' - | 'mixed' - | 'unknown'; - /** Native account net change for activity rows; original components for posting rows. */ - change: ReportedAmount[]; - /** Selected legs' indexes in the original transaction, not the account register. */ - postingIndexes: number[]; - /** Reported UnitCost annotations only; never a computed execution price. */ - prices: ReportedAmount[]; - /** Ordered concatenation of attributable posting bags, not a sum; null if unpriced, shared or missing. */ - transactedAmounts: ReportedAmount[] | null; -} - -export interface PreparedInvestmentData { - securities: PreparedSecurityActivity[]; - /** Selected-account/subtree change and balance, unlike transaction-wide cash posting evidence. */ - cash: { - direction: 'in' | 'out' | 'mixed' | 'none' | 'unknown'; - change: ReportedAmount[]; - balance: ReportedAmount[]; - unclassifiedChange: ReportedAmount[]; - unclassifiedBalance: ReportedAmount[]; - }; - /** Original-transaction indexes, including cash legs outside the selected account/subtree. */ - cashPostingIndexes: number[]; - /** Original-transaction income indexes; not allocated to securities. */ - incomePostingIndexes: number[]; - /** Original-transaction expense indexes; not allocated to securities. */ - expensePostingIndexes: number[]; - /** Original-transaction gain indexes; not allocated to securities. */ - gainPostingIndexes: number[]; - issues: InvestmentIssue[]; -} - -/** One selected original posting, without transaction-wide allocation or netting. */ -export interface PreparedInvestmentPosting { - securities: PreparedSecurityActivity[]; - /** Whole native posting bag when entirely priced securities; [] without securities, null if unavailable. */ - transactedAmounts: ReportedAmount[] | null; - cash: { - direction: PreparedInvestmentData['cash']['direction']; - change: ReportedAmount[]; - unclassifiedChange: ReportedAmount[]; - }; - issues: InvestmentIssue[]; -} - -type NativeRole = 'acquire' | 'dispose' | 'transfer-from' | 'transfer-to' | 'gain'; -type Role = NativeRole | 'unknown' | null; - -/** These tags are native-consumed evidence, not authenticated provenance. */ -function nativeRole(posting: PreparedPosting): Role { - const values = new Set( - posting.tags.filter(([key]) => key === '_ptype').map(([, value]) => value) - ); - if (values.size === 0) return null; - if (values.size !== 1) return 'unknown'; - const [value] = values; - switch (value) { - case 'acquire': - case 'dispose': - case 'transfer-from': - case 'transfer-to': - case 'gain': - return value; - default: - return 'unknown'; - } -} - -function isAsset(posting: PreparedPosting, metadata: InvestmentMetadata): boolean { - return ( - (metadata.assets.has(posting.account) || metadata.cash.has(posting.account)) && - !metadata.liabilities.has(posting.account) && - !metadata.income.has(posting.account) && - !metadata.expenses.has(posting.account) && - !metadata.gains.has(posting.account) - ); -} - -/** Only related original transactions establish cash units; annotations are not cash legs. */ -export async function accountInvestmentContext( - transactions: Iterable | AsyncIterable, - metadata: InvestmentMetadata, - canonicalAccount: string -): Promise { - const securityCommodities = new Set(metadata.lotCommodities); - const cashCandidates = new Set(); - let hasVirtualAccountPostings = false; - let hasNonAssetAccountPostings = false; - for await (const transaction of transactions) { - for (const posting of transaction.postings) { - if ( - posting.account === canonicalAccount || - posting.account.startsWith(`${canonicalAccount}:`) - ) { - if (posting.kind !== 'RealPosting') hasVirtualAccountPostings = true; - if (!isAsset(posting, metadata)) hasNonAssetAccountPostings = true; - } - const role = nativeRole(posting); - for (const amount of posting.amounts) { - if (role !== null && role !== 'unknown' && role !== 'gain' && amount.costBasis !== null) { - securityCommodities.add(amount.commodity); - } - if ( - posting.kind === 'RealPosting' && - metadata.cash.has(posting.account) && - isAsset(posting, metadata) - ) { - cashCandidates.add(amount.commodity); - } - } - } - } - // Exclude securities after the entire iterable: later basis evidence takes precedence. - const cashCommodities = new Set( - [...cashCandidates].filter((commodity) => !securityCommodities.has(commodity)) - ); - return { - ...metadata, - securityCommodities, - cashCommodities, - hasVirtualAccountPostings, - hasNonAssetAccountPostings - }; -} - -function reported(amount: ReportedAmount): ReportedAmount { - return { commodity: amount.commodity, quantity: amount.quantity }; -} - -type Sign = 'positive' | 'negative' | 'zero' | 'unknown'; - -/** Inspect exact decimal text, including negative zero, without monetary arithmetic. */ -function sign(quantity: string): Sign { - if (!/^[+-]?\d+(?:\.\d+)?$/.test(quantity)) return 'unknown'; - if (!/[1-9]/.test(quantity)) return 'zero'; - return quantity.startsWith('-') ? 'negative' : 'positive'; -} - -function cashDirection(change: ReportedAmount[]): PreparedInvestmentData['cash']['direction'] { - const signs = new Set(change.map((amount) => sign(amount.quantity))); - if (signs.has('unknown')) return 'unknown'; - if (signs.has('positive') && signs.has('negative')) return 'mixed'; - if (signs.has('positive')) return 'in'; - if (signs.has('negative')) return 'out'; - return 'none'; -} - -function securityAction( - commodity: string, - postings: PreparedPosting[], - row: Omit, - context: AccountInvestmentContext, - cashPostingIndexes: number[], - hasIncome: boolean, - transactedAmounts: ReportedAmount[] | null, - issues: Set -): PreparedSecurityActivity['action'] { - const roles = new Set(); - let unknown = false; - for (const posting of postings) { - const role = nativeRole(posting); - if (role === null || role === 'unknown' || role === 'gain') { - issues.add('unknown-native-role'); - unknown = true; - } else { - roles.add(role); - const expected = role === 'acquire' || role === 'transfer-to' ? 'positive' : 'negative'; - if ( - posting.amounts.some( - (amount) => amount.commodity === commodity && sign(amount.quantity) !== expected - ) - ) { - issues.add( - role === 'acquire' || role === 'dispose' ? 'unsupported-short' : 'unknown-native-role' - ); - unknown = true; - } - } - if (posting.kind !== 'RealPosting') { - issues.add('virtual-postings'); - unknown = true; - } - if (context.liabilities.has(posting.account)) { - issues.add('unsupported-short'); - unknown = true; - } - } - if ( - row.balance.some( - (amount) => amount.commodity === commodity && sign(amount.quantity) === 'negative' - ) - ) { - issues.add('unsupported-short'); - unknown = true; - } - if (roles.size > 1) issues.add('mixed-security-actions'); - if (unknown) return 'unknown'; - if (roles.size > 1) return 'mixed'; - const [role] = roles; - if (role === 'transfer-from') return 'transfer-out'; - if (role === 'transfer-to') return 'transfer-in'; - if (role !== 'acquire' && role !== 'dispose') return 'unknown'; - - // Evidence for an ordinary long trade, not a claim about funding or fee allocation. - const cashSign = role === 'acquire' ? 'negative' : 'positive'; - const hasCashLeg = cashPostingIndexes.some((index) => - row.transaction.postings[index].amounts.some( - (amount) => - context.cashCommodities.has(amount.commodity) && - sign(amount.quantity) === cashSign && - transactedAmounts?.some((value) => value.commodity === amount.commodity) - ) - ); - // An opposite cash leg may be just a fee on a gift/opening, not trade funding. - // Unknown/equity/liability counterparts do not establish an ordinary asset trade. - const supportedCounterparts = row.transaction.postings.every((posting) => { - const counterpartRole = nativeRole(posting); - return ( - posting.kind === 'RealPosting' && - counterpartRole !== 'unknown' && - !context.liabilities.has(posting.account) && - (isAsset(posting, context) || - context.expenses.has(posting.account) || - context.gains.has(posting.account) || - counterpartRole === 'gain') - ); - }); - if ( - !hasIncome && - transactedAmounts !== null && - postings.every((posting) => isAsset(posting, context)) && - supportedCounterparts && - hasCashLeg - ) { - return role === 'acquire' ? 'buy' : 'sell'; - } - return role; -} - -/** Attribute whole native value bags only when every posting belongs to this priced security. */ -function securityValuation( - commodity: string, - postings: PreparedPosting[], - issues: Set -): Pick { - const prices: ReportedAmount[] = []; - let attributable = true; - const values: ReportedAmount[] = []; - for (const posting of postings) { - if (posting.amounts.some((amount) => amount.commodity !== commodity)) { - issues.add('mixed-security-posting'); - attributable = false; - } - if ( - posting.amounts.some((amount) => amount.cost === null) || - posting.transactedAmounts === null || - posting.transactedAmounts.length === 0 - ) { - attributable = false; - } - for (const amount of posting.amounts) { - if (amount.commodity !== commodity || amount.cost?.kind !== 'UnitCost') continue; - const price = reported(amount.cost.amount); - if ( - !prices.some( - (other) => other.commodity === price.commodity && other.quantity === price.quantity - ) - ) { - prices.push(price); - } - } - if (posting.transactedAmounts !== null) { - values.push(...posting.transactedAmounts.map(reported)); - } - } - const transactedAmounts = attributable ? values : null; - if (!attributable) issues.add('unavailable-transacted-values'); - return { prices, transactedAmounts }; -} - -function postingSecurityAction( - group: PreparedSecurityActivity, - posting: PreparedPosting, - row: PreparedAccountRow, - issues: Set -): PreparedSecurityActivity['action'] { - const role = nativeRole(posting); - let unsafe = false; - if (posting.kind !== 'RealPosting') { - issues.add('virtual-postings'); - unsafe = true; - } - if (role === null || role === 'unknown' || role === 'gain') { - issues.add('unknown-native-role'); - return 'unknown'; - } - const expected = role === 'acquire' || role === 'transfer-to' ? 'positive' : 'negative'; - if ( - posting.amounts.some( - (amount) => amount.commodity === group.commodity && sign(amount.quantity) !== expected - ) - ) { - issues.add( - role === 'acquire' || role === 'dispose' ? 'unsupported-short' : 'unknown-native-role' - ); - unsafe = true; - } - if ( - row.balance.some( - (amount) => amount.commodity === group.commodity && sign(amount.quantity) === 'negative' - ) - ) { - issues.add('unsupported-short'); - unsafe = true; - } - if (unsafe) return 'unknown'; - - const action = - role === 'transfer-from' ? 'transfer-out' : role === 'transfer-to' ? 'transfer-in' : role; - if (group.action === 'buy' && action === 'acquire') return 'buy'; - if (group.action === 'sell' && action === 'dispose') return 'sell'; - if (group.action === 'mixed' || group.action === action) return action; - // Unknown prepared actions may depend on account classification absent from the saved row. - return 'unknown'; -} - -/** Project one selected original posting using saved native classification, never account names. */ -export function prepareInvestmentPosting( - row: PreparedAccountRow, - postingIndex: number -): PreparedInvestmentPosting { - if ( - !Number.isSafeInteger(postingIndex) || - postingIndex < 0 || - postingIndex >= row.transaction.postings.length - ) { - throw new RangeError('Invalid original posting index.'); - } - if (!row.accountPostingIndexes.includes(postingIndex)) { - throw new Error('Original posting is not selected by this account row.'); - } - const posting = row.transaction.postings[postingIndex]; - const issues = new Set(); - if (posting.kind !== 'RealPosting') issues.add('virtual-postings'); - if (nativeRole(posting) === 'unknown') issues.add('unknown-native-role'); - const securities: PreparedSecurityActivity[] = []; - for (const group of row.investment.securities) { - if (!group.postingIndexes.includes(postingIndex)) continue; - const components = posting.amounts.filter((amount) => amount.commodity === group.commodity); - if (components.length === 0) continue; - const valuationIssues = new Set(); - const { transactedAmounts } = securityValuation(group.commodity, [posting], valuationIssues); - // Per-security attribution can fail while the whole posting value remains available. - for (const issue of valuationIssues) { - if (issue !== 'unavailable-transacted-values') issues.add(issue); - } - securities.push({ - commodity: group.commodity, - action: postingSecurityAction(group, posting, row, issues), - change: components.map(reported), - postingIndexes: [postingIndex], - prices: components.flatMap((amount) => - amount.cost?.kind === 'UnitCost' ? [reported(amount.cost.amount)] : [] - ), - transactedAmounts - }); - } - - const securityCommodities = new Set(securities.map((security) => security.commodity)); - let transactedAmounts: ReportedAmount[] | null = null; - if (securities.length === 0) { - transactedAmounts = []; - } else if ( - posting.amounts.every( - (amount) => securityCommodities.has(amount.commodity) && amount.cost !== null - ) && - posting.transactedAmounts !== null - ) { - transactedAmounts = posting.transactedAmounts.map(reported); - } - if (transactedAmounts === null) issues.add('unavailable-transacted-values'); - const knownCash = new Set( - [...row.investment.cash.change, ...row.investment.cash.balance].map( - (amount) => amount.commodity - ) - ); - const safeCashPosting = - posting.kind === 'RealPosting' && - nativeRole(posting) !== 'unknown' && - row.investment.cashPostingIndexes.includes(postingIndex); - const change: ReportedAmount[] = []; - const unclassifiedChange: ReportedAmount[] = []; - for (const amount of posting.amounts) { - if (securityCommodities.has(amount.commodity)) continue; - if (safeCashPosting && knownCash.has(amount.commodity)) change.push(reported(amount)); - else unclassifiedChange.push(reported(amount)); - } - if (unclassifiedChange.length > 0) issues.add('unclassified-commodity'); - return { - securities, - transactedAmounts, - cash: { - direction: unclassifiedChange.length > 0 ? 'unknown' : cashDirection(change), - change, - unclassifiedChange - }, - issues: [...issues] - }; -} - -export function prepareInvestmentActivity( - row: Omit, - context: AccountInvestmentContext -): PreparedInvestmentData { - const issues = new Set(); - if (context.hasVirtualAccountPostings) issues.add('virtual-postings'); - const cashPostingIndexes: number[] = []; - const incomePostingIndexes: number[] = []; - const expensePostingIndexes: number[] = []; - const gainPostingIndexes: number[] = []; - for (const [index, posting] of row.transaction.postings.entries()) { - const role = nativeRole(posting); - if (role === 'unknown') issues.add('unknown-native-role'); - const isGain = context.gains.has(posting.account) || role === 'gain'; - if (isGain) gainPostingIndexes.push(index); - if ( - context.income.has(posting.account) && - !isGain && - !posting.tags.some(([key]) => key === '_generated-posting') - ) { - incomePostingIndexes.push(index); - } - if (context.expenses.has(posting.account)) expensePostingIndexes.push(index); - if ( - posting.kind === 'RealPosting' && - isAsset(posting, context) && - posting.amounts.some((amount) => context.cashCommodities.has(amount.commodity)) - ) { - cashPostingIndexes.push(index); - } - } - if (incomePostingIndexes.length > 0) issues.add('unattributed-income'); - - const selected = new Set(row.accountPostingIndexes); - const selectedPostings: PreparedPosting[] = []; - const groups = new Map(); - // Original posting order, not commodity sorting or register posting positions. - for (const [index, posting] of row.transaction.postings.entries()) { - if (!selected.has(index)) continue; - selectedPostings.push(posting); - if (posting.kind !== 'RealPosting') issues.add('virtual-postings'); - for (const commodity of new Set(posting.amounts.map((amount) => amount.commodity))) { - if (!context.securityCommodities.has(commodity)) continue; - const indexes = groups.get(commodity); - if (indexes) indexes.push(index); - else groups.set(commodity, [index]); - } - } - - const securities: PreparedSecurityActivity[] = []; - for (const [commodity, postingIndexes] of groups) { - const postings = postingIndexes.map((index) => row.transaction.postings[index]); - const { prices, transactedAmounts } = securityValuation(commodity, postings, issues); - const action = securityAction( - commodity, - postings, - row, - context, - cashPostingIndexes, - incomePostingIndexes.length > 0, - transactedAmounts, - issues - ); - securities.push({ - commodity, - action, - change: row.change.filter((amount) => amount.commodity === commodity).map(reported), - postingIndexes, - prices, - transactedAmounts - }); - } - - // A native net bag cannot be split into real/virtual or asset/liability portions here. - const eligibleCash = - !context.hasVirtualAccountPostings && - !context.hasNonAssetAccountPostings && - selectedPostings.length > 0 && - selectedPostings.every( - (posting) => posting.kind === 'RealPosting' && isAsset(posting, context) - ); - const isCash = (amount: ReportedAmount) => - eligibleCash && - context.cashCommodities.has(amount.commodity) && - !context.securityCommodities.has(amount.commodity); - const isUnclassified = (amount: ReportedAmount) => - !isCash(amount) && !context.securityCommodities.has(amount.commodity); - const change = row.change.filter(isCash).map(reported); - const balance = row.balance.filter(isCash).map(reported); - const unclassifiedChange = row.change.filter(isUnclassified).map(reported); - const unclassifiedBalance = row.balance.filter(isUnclassified).map(reported); - if (unclassifiedChange.length > 0 || unclassifiedBalance.length > 0) { - issues.add('unclassified-commodity'); - } - const direction = unclassifiedChange.length > 0 ? 'unknown' : cashDirection(change); - return { - securities, - cash: { - direction, - change, - balance, - unclassifiedChange, - unclassifiedBalance - }, - cashPostingIndexes, - incomePostingIndexes, - expensePostingIndexes, - gainPostingIndexes, - issues: [...issues] - }; -} diff --git a/packages/hledger/src/transactions/investment/account-context.ts b/packages/hledger/src/transactions/investment/account-context.ts new file mode 100644 index 0000000..1b474eb --- /dev/null +++ b/packages/hledger/src/transactions/investment/account-context.ts @@ -0,0 +1,79 @@ +import type { PreparedPosting, PreparedTransaction } from '../transaction.js'; +import { nativeRole } from './posting-evidence.js'; + +/** Native account-query results. Subtype sets (A/C and R/G) may overlap. */ +export interface InvestmentMetadata { + assets: ReadonlySet; + cash: ReadonlySet; + liabilities: ReadonlySet; + income: ReadonlySet; + expenses: ReadonlySet; + gains: ReadonlySet; + lotCommodities: ReadonlySet; +} + +export interface AccountInvestmentContext extends InvestmentMetadata { + securityCommodities: ReadonlySet; + cashCommodities: ReadonlySet; + /** Account/subtree history can contribute virtual amounts to later native balances. */ + hasVirtualAccountPostings: boolean; + /** Non-asset account/subtree history also prevents isolating cash in native net bags. */ + hasNonAssetAccountPostings: boolean; +} + +export function isAsset(posting: PreparedPosting, metadata: InvestmentMetadata): boolean { + return ( + (metadata.assets.has(posting.account) || metadata.cash.has(posting.account)) && + !metadata.liabilities.has(posting.account) && + !metadata.income.has(posting.account) && + !metadata.expenses.has(posting.account) && + !metadata.gains.has(posting.account) + ); +} + +/** Only related original transactions establish cash units; annotations are not cash legs. */ +export async function investmentContextFromHistory( + transactions: Iterable | AsyncIterable, + metadata: InvestmentMetadata, + canonicalAccount: string +): Promise { + const securityCommodities = new Set(metadata.lotCommodities); + const cashCandidates = new Set(); + let hasVirtualAccountPostings = false; + let hasNonAssetAccountPostings = false; + for await (const transaction of transactions) { + for (const posting of transaction.postings) { + if ( + posting.account === canonicalAccount || + posting.account.startsWith(`${canonicalAccount}:`) + ) { + if (posting.kind !== 'RealPosting') hasVirtualAccountPostings = true; + if (!isAsset(posting, metadata)) hasNonAssetAccountPostings = true; + } + const role = nativeRole(posting); + for (const amount of posting.amounts) { + if (role !== null && role !== 'unknown' && role !== 'gain' && amount.costBasis !== null) { + securityCommodities.add(amount.commodity); + } + if ( + posting.kind === 'RealPosting' && + metadata.cash.has(posting.account) && + isAsset(posting, metadata) + ) { + cashCandidates.add(amount.commodity); + } + } + } + } + // Exclude securities after the entire iterable: later basis evidence takes precedence. + const cashCommodities = new Set( + [...cashCandidates].filter((commodity) => !securityCommodities.has(commodity)) + ); + return { + ...metadata, + securityCommodities, + cashCommodities, + hasVirtualAccountPostings, + hasNonAssetAccountPostings + }; +} diff --git a/packages/hledger/src/transactions/investment.test.ts b/packages/hledger/src/transactions/investment/entry.test.ts similarity index 97% rename from packages/hledger/src/transactions/investment.test.ts rename to packages/hledger/src/transactions/investment/entry.test.ts index a3787b9..97512b7 100644 --- a/packages/hledger/src/transactions/investment.test.ts +++ b/packages/hledger/src/transactions/investment/entry.test.ts @@ -1,12 +1,9 @@ import { expect, it } from 'vitest'; -import type { ReportedAmount } from '../amounts.js'; -import type { PreparedAccountRow } from './account-rows.js'; -import { - accountInvestmentContext, - prepareInvestmentActivity, - type InvestmentMetadata -} from './investment.js'; -import type { DetailedAmount, PreparedPosting, PreparedTransaction } from './transaction.js'; +import type { ReportedAmount } from '../../amounts.js'; +import type { PreparedAccountRow } from '../account-rows.js'; +import type { DetailedAmount, PreparedPosting, PreparedTransaction } from '../transaction.js'; +import { investmentContextFromHistory, type InvestmentMetadata } from './account-context.js'; +import { interpretInvestmentEntry } from './entry.js'; function amount(commodity: string, quantity: string): DetailedAmount { return { commodity, quantity, cost: null, costBasis: null, style: null }; @@ -118,9 +115,9 @@ async function prepare( roles = metadata(), canonicalAccount = 'holdings' ) { - return prepareInvestmentActivity( + return interpretInvestmentEntry( input, - await accountInvestmentContext([...related, input.transaction], roles, canonicalAccount) + await investmentContextFromHistory([...related, input.transaction], roles, canonicalAccount) ); } @@ -699,13 +696,13 @@ it.each([ [amount('USD', '5.00')], [amount('USD', '15.00')] ); - const context = await accountInvestmentContext( + const context = await investmentContextFromHistory( [cashEvidence(), prior, input.transaction], metadata(), 'holdings' ); const before = structuredClone({ prior, input, context }); - const result = prepareInvestmentActivity(input, context); + const result = interpretInvestmentEntry(input, context); expect(context.hasVirtualAccountPostings).toBe(contaminated); expect(result.cash).toEqual( contaminated @@ -787,9 +784,13 @@ it.each([ [amount('USD', '200.00')], [amount('USD', contaminated ? '100.00' : '200.00')] ); - const context = await accountInvestmentContext([prior, input.transaction], roles, 'portfolio'); + const context = await investmentContextFromHistory( + [prior, input.transaction], + roles, + 'portfolio' + ); expect(context.hasNonAssetAccountPostings).toBe(contaminated); - const result = prepareInvestmentActivity(input, context); + const result = interpretInvestmentEntry(input, context); expect(result.cash.direction).toBe(contaminated ? 'unknown' : 'in'); expect(result.cash.balance).toEqual(contaminated ? [] : [value('USD', '200.00')]); expect(result.cash.unclassifiedBalance).toEqual(contaminated ? [value('USD', '100.00')] : []); @@ -951,7 +952,7 @@ it('builds context in one pass without mutating metadata and excludes later disc yield early; yield later; } - const context = await accountInvestmentContext(related(), roles, 'holdings'); + const context = await investmentContextFromHistory(related(), roles, 'holdings'); expect(context.securityCommodities).toEqual(new Set(['VTI', 'BND', 'special'])); expect(context.cashCommodities).toEqual(new Set(['tokens'])); expect(roles).toEqual(before); @@ -968,9 +969,9 @@ it('preparation leaves the source row, tags, annotations, amount bags and contex [amount('VTI', '1.0000')], [amount('VTI', '4.0000')] ); - const context = await accountInvestmentContext([input.transaction], metadata(), 'holdings'); + const context = await investmentContextFromHistory([input.transaction], metadata(), 'holdings'); const before = structuredClone({ input, context }); - const result = prepareInvestmentActivity(input, context); + const result = interpretInvestmentEntry(input, context); expect({ input, context }).toEqual(before); expect(JSON.parse(JSON.stringify(result))).toEqual(result); }); diff --git a/packages/hledger/src/transactions/investment/entry.ts b/packages/hledger/src/transactions/investment/entry.ts new file mode 100644 index 0000000..954f45c --- /dev/null +++ b/packages/hledger/src/transactions/investment/entry.ts @@ -0,0 +1,217 @@ +import type { ReportedAmount } from '../../amounts.js'; +import type { PreparedAccountRow } from '../account-rows.js'; +import type { PreparedPosting } from '../transaction.js'; +import { isAsset, type AccountInvestmentContext } from './account-context.js'; +import { + cashDirection, + nativeRole, + quantitySign, + reported, + securityValuation, + type NativeRole +} from './posting-evidence.js'; +import type { InvestmentIssue, PreparedInvestmentData, PreparedSecurityActivity } from './types.js'; + +export function interpretInvestmentEntry( + row: Omit, + context: AccountInvestmentContext +): PreparedInvestmentData { + const issues = new Set(); + if (context.hasVirtualAccountPostings) issues.add('virtual-postings'); + const cashPostingIndexes: number[] = []; + const incomePostingIndexes: number[] = []; + const expensePostingIndexes: number[] = []; + const gainPostingIndexes: number[] = []; + for (const [index, posting] of row.transaction.postings.entries()) { + const role = nativeRole(posting); + if (role === 'unknown') issues.add('unknown-native-role'); + const isGain = context.gains.has(posting.account) || role === 'gain'; + if (isGain) gainPostingIndexes.push(index); + if ( + context.income.has(posting.account) && + !isGain && + !posting.tags.some(([key]) => key === '_generated-posting') + ) { + incomePostingIndexes.push(index); + } + if (context.expenses.has(posting.account)) expensePostingIndexes.push(index); + if ( + posting.kind === 'RealPosting' && + isAsset(posting, context) && + posting.amounts.some((amount) => context.cashCommodities.has(amount.commodity)) + ) { + cashPostingIndexes.push(index); + } + } + if (incomePostingIndexes.length > 0) issues.add('unattributed-income'); + + const selected = new Set(row.accountPostingIndexes); + const selectedPostings: PreparedPosting[] = []; + const groups = new Map(); + // Original posting order, not commodity sorting or register posting positions. + for (const [index, posting] of row.transaction.postings.entries()) { + if (!selected.has(index)) continue; + selectedPostings.push(posting); + if (posting.kind !== 'RealPosting') issues.add('virtual-postings'); + for (const commodity of new Set(posting.amounts.map((amount) => amount.commodity))) { + if (!context.securityCommodities.has(commodity)) continue; + const indexes = groups.get(commodity); + if (indexes) indexes.push(index); + else groups.set(commodity, [index]); + } + } + + const securities: PreparedSecurityActivity[] = []; + for (const [commodity, postingIndexes] of groups) { + const postings = postingIndexes.map((index) => row.transaction.postings[index]); + const { prices, transactedAmounts } = securityValuation(commodity, postings, issues); + const action = securityAction( + commodity, + postings, + row, + context, + cashPostingIndexes, + incomePostingIndexes.length > 0, + transactedAmounts, + issues + ); + securities.push({ + commodity, + action, + change: row.change.filter((amount) => amount.commodity === commodity).map(reported), + postingIndexes, + prices, + transactedAmounts + }); + } + + // A native net bag cannot be split into real/virtual or asset/liability portions here. + const eligibleCash = + !context.hasVirtualAccountPostings && + !context.hasNonAssetAccountPostings && + selectedPostings.length > 0 && + selectedPostings.every( + (posting) => posting.kind === 'RealPosting' && isAsset(posting, context) + ); + const isCash = (amount: ReportedAmount) => + eligibleCash && + context.cashCommodities.has(amount.commodity) && + !context.securityCommodities.has(amount.commodity); + const isUnclassified = (amount: ReportedAmount) => + !isCash(amount) && !context.securityCommodities.has(amount.commodity); + const change = row.change.filter(isCash).map(reported); + const balance = row.balance.filter(isCash).map(reported); + const unclassifiedChange = row.change.filter(isUnclassified).map(reported); + const unclassifiedBalance = row.balance.filter(isUnclassified).map(reported); + if (unclassifiedChange.length > 0 || unclassifiedBalance.length > 0) { + issues.add('unclassified-commodity'); + } + const direction = unclassifiedChange.length > 0 ? 'unknown' : cashDirection(change); + return { + securities, + cash: { + direction, + change, + balance, + unclassifiedChange, + unclassifiedBalance + }, + cashPostingIndexes, + incomePostingIndexes, + expensePostingIndexes, + gainPostingIndexes, + issues: [...issues] + }; +} + +function securityAction( + commodity: string, + postings: PreparedPosting[], + row: Omit, + context: AccountInvestmentContext, + cashPostingIndexes: number[], + hasIncome: boolean, + transactedAmounts: ReportedAmount[] | null, + issues: Set +): PreparedSecurityActivity['action'] { + const roles = new Set(); + let unknown = false; + for (const posting of postings) { + const role = nativeRole(posting); + if (role === null || role === 'unknown' || role === 'gain') { + issues.add('unknown-native-role'); + unknown = true; + } else { + roles.add(role); + const expected = role === 'acquire' || role === 'transfer-to' ? 'positive' : 'negative'; + if ( + posting.amounts.some( + (amount) => amount.commodity === commodity && quantitySign(amount.quantity) !== expected + ) + ) { + issues.add( + role === 'acquire' || role === 'dispose' ? 'unsupported-short' : 'unknown-native-role' + ); + unknown = true; + } + } + if (posting.kind !== 'RealPosting') { + issues.add('virtual-postings'); + unknown = true; + } + if (context.liabilities.has(posting.account)) { + issues.add('unsupported-short'); + unknown = true; + } + } + if ( + row.balance.some( + (amount) => amount.commodity === commodity && quantitySign(amount.quantity) === 'negative' + ) + ) { + issues.add('unsupported-short'); + unknown = true; + } + if (roles.size > 1) issues.add('mixed-security-actions'); + if (unknown) return 'unknown'; + if (roles.size > 1) return 'mixed'; + const [role] = roles; + if (role === 'transfer-from') return 'transfer-out'; + if (role === 'transfer-to') return 'transfer-in'; + if (role !== 'acquire' && role !== 'dispose') return 'unknown'; + + // Evidence for an ordinary long trade, not a claim about funding or fee allocation. + const cashSign = role === 'acquire' ? 'negative' : 'positive'; + const hasCashLeg = cashPostingIndexes.some((index) => + row.transaction.postings[index].amounts.some( + (amount) => + context.cashCommodities.has(amount.commodity) && + quantitySign(amount.quantity) === cashSign && + transactedAmounts?.some((value) => value.commodity === amount.commodity) + ) + ); + // An opposite cash leg may be just a fee on a gift/opening, not trade funding. + // Unknown/equity/liability counterparts do not establish an ordinary asset trade. + const supportedCounterparts = row.transaction.postings.every((posting) => { + const counterpartRole = nativeRole(posting); + return ( + posting.kind === 'RealPosting' && + counterpartRole !== 'unknown' && + !context.liabilities.has(posting.account) && + (isAsset(posting, context) || + context.expenses.has(posting.account) || + context.gains.has(posting.account) || + counterpartRole === 'gain') + ); + }); + if ( + !hasIncome && + transactedAmounts !== null && + postings.every((posting) => isAsset(posting, context)) && + supportedCounterparts && + hasCashLeg + ) { + return role === 'acquire' ? 'buy' : 'sell'; + } + return role; +} diff --git a/packages/hledger/src/transactions/investment/posting-evidence.ts b/packages/hledger/src/transactions/investment/posting-evidence.ts new file mode 100644 index 0000000..f3aaafd --- /dev/null +++ b/packages/hledger/src/transactions/investment/posting-evidence.ts @@ -0,0 +1,91 @@ +import type { ReportedAmount } from '../../amounts.js'; +import type { PreparedPosting } from '../transaction.js'; +import type { InvestmentIssue, PreparedInvestmentData, PreparedSecurityActivity } from './types.js'; + +export type NativeRole = 'acquire' | 'dispose' | 'transfer-from' | 'transfer-to' | 'gain'; +type Role = NativeRole | 'unknown' | null; + +/** These tags are native-consumed evidence, not authenticated provenance. */ +export function nativeRole(posting: PreparedPosting): Role { + const values = new Set( + posting.tags.filter(([key]) => key === '_ptype').map(([, value]) => value) + ); + if (values.size === 0) return null; + if (values.size !== 1) return 'unknown'; + const [value] = values; + switch (value) { + case 'acquire': + case 'dispose': + case 'transfer-from': + case 'transfer-to': + case 'gain': + return value; + default: + return 'unknown'; + } +} + +export function reported(amount: ReportedAmount): ReportedAmount { + return { commodity: amount.commodity, quantity: amount.quantity }; +} + +type Sign = 'positive' | 'negative' | 'zero' | 'unknown'; + +/** Inspect exact decimal text, including negative zero, without monetary arithmetic. */ +export function quantitySign(quantity: string): Sign { + if (!/^[+-]?\d+(?:\.\d+)?$/.test(quantity)) return 'unknown'; + if (!/[1-9]/.test(quantity)) return 'zero'; + return quantity.startsWith('-') ? 'negative' : 'positive'; +} + +export function cashDirection( + change: ReportedAmount[] +): PreparedInvestmentData['cash']['direction'] { + const signs = new Set(change.map((amount) => quantitySign(amount.quantity))); + if (signs.has('unknown')) return 'unknown'; + if (signs.has('positive') && signs.has('negative')) return 'mixed'; + if (signs.has('positive')) return 'in'; + if (signs.has('negative')) return 'out'; + return 'none'; +} + +/** Attribute whole native value bags only when every posting belongs to this priced security. */ +export function securityValuation( + commodity: string, + postings: PreparedPosting[], + issues: Set +): Pick { + const prices: ReportedAmount[] = []; + let attributable = true; + const values: ReportedAmount[] = []; + for (const posting of postings) { + if (posting.amounts.some((amount) => amount.commodity !== commodity)) { + issues.add('mixed-security-posting'); + attributable = false; + } + if ( + posting.amounts.some((amount) => amount.cost === null) || + posting.transactedAmounts === null || + posting.transactedAmounts.length === 0 + ) { + attributable = false; + } + for (const amount of posting.amounts) { + if (amount.commodity !== commodity || amount.cost?.kind !== 'UnitCost') continue; + const price = reported(amount.cost.amount); + if ( + !prices.some( + (other) => other.commodity === price.commodity && other.quantity === price.quantity + ) + ) { + prices.push(price); + } + } + if (posting.transactedAmounts !== null) { + values.push(...posting.transactedAmounts.map(reported)); + } + } + const transactedAmounts = attributable ? values : null; + if (!attributable) issues.add('unavailable-transacted-values'); + return { prices, transactedAmounts }; +} diff --git a/packages/hledger/src/transactions/investment-posting.test.ts b/packages/hledger/src/transactions/investment/posting.test.ts similarity index 97% rename from packages/hledger/src/transactions/investment-posting.test.ts rename to packages/hledger/src/transactions/investment/posting.test.ts index 449bd2b..2aab66a 100644 --- a/packages/hledger/src/transactions/investment-posting.test.ts +++ b/packages/hledger/src/transactions/investment/posting.test.ts @@ -1,9 +1,10 @@ import { expect, it } from 'vitest'; -import type { ReportedAmount } from '../amounts.js'; -import type { PreparedAccountRow } from './account-rows.js'; -import { prepareInvestmentPosting } from './index.js'; -import { prepareInvestmentActivity, type AccountInvestmentContext } from './investment.js'; -import type { DetailedAmount, PreparedPosting } from './transaction.js'; +import type { ReportedAmount } from '../../amounts.js'; +import type { PreparedAccountRow } from '../account-rows.js'; +import { prepareInvestmentPosting } from '../index.js'; +import type { DetailedAmount, PreparedPosting } from '../transaction.js'; +import type { AccountInvestmentContext } from './account-context.js'; +import { interpretInvestmentEntry } from './entry.js'; function amount(commodity: string, quantity: string): DetailedAmount { return { commodity, quantity, cost: null, costBasis: null, style: null }; @@ -87,7 +88,7 @@ function row( sourcePositions: [] } }; - return { ...base, investment: prepareInvestmentActivity(base, context) }; + return { ...base, investment: interpretInvestmentEntry(base, context) }; } it('keeps each same-security posting component, price and native value instead of group nets', () => { diff --git a/packages/hledger/src/transactions/investment/posting.ts b/packages/hledger/src/transactions/investment/posting.ts new file mode 100644 index 0000000..d886d92 --- /dev/null +++ b/packages/hledger/src/transactions/investment/posting.ts @@ -0,0 +1,146 @@ +import type { ReportedAmount } from '../../amounts.js'; +import type { PreparedAccountRow } from '../account-rows.js'; +import type { PreparedPosting } from '../transaction.js'; +import { + cashDirection, + nativeRole, + quantitySign, + reported, + securityValuation +} from './posting-evidence.js'; +import type { + InvestmentIssue, + PreparedInvestmentPosting, + PreparedSecurityActivity +} from './types.js'; + +/** Project one selected original posting using saved native classification, never account names. */ +export function prepareInvestmentPosting( + row: PreparedAccountRow, + postingIndex: number +): PreparedInvestmentPosting { + if ( + !Number.isSafeInteger(postingIndex) || + postingIndex < 0 || + postingIndex >= row.transaction.postings.length + ) { + throw new RangeError('Invalid original posting index.'); + } + if (!row.accountPostingIndexes.includes(postingIndex)) { + throw new Error('Original posting is not selected by this account row.'); + } + const posting = row.transaction.postings[postingIndex]; + const issues = new Set(); + if (posting.kind !== 'RealPosting') issues.add('virtual-postings'); + if (nativeRole(posting) === 'unknown') issues.add('unknown-native-role'); + const securities: PreparedSecurityActivity[] = []; + for (const group of row.investment.securities) { + if (!group.postingIndexes.includes(postingIndex)) continue; + const components = posting.amounts.filter((amount) => amount.commodity === group.commodity); + if (components.length === 0) continue; + const valuationIssues = new Set(); + const { transactedAmounts } = securityValuation(group.commodity, [posting], valuationIssues); + // Per-security attribution can fail while the whole posting value remains available. + for (const issue of valuationIssues) { + if (issue !== 'unavailable-transacted-values') issues.add(issue); + } + securities.push({ + commodity: group.commodity, + action: postingSecurityAction(group, posting, row, issues), + change: components.map(reported), + postingIndexes: [postingIndex], + prices: components.flatMap((amount) => + amount.cost?.kind === 'UnitCost' ? [reported(amount.cost.amount)] : [] + ), + transactedAmounts + }); + } + + const securityCommodities = new Set(securities.map((security) => security.commodity)); + let transactedAmounts: ReportedAmount[] | null = null; + if (securities.length === 0) { + transactedAmounts = []; + } else if ( + posting.amounts.every( + (amount) => securityCommodities.has(amount.commodity) && amount.cost !== null + ) && + posting.transactedAmounts !== null + ) { + transactedAmounts = posting.transactedAmounts.map(reported); + } + if (transactedAmounts === null) issues.add('unavailable-transacted-values'); + const knownCash = new Set( + [...row.investment.cash.change, ...row.investment.cash.balance].map( + (amount) => amount.commodity + ) + ); + const safeCashPosting = + posting.kind === 'RealPosting' && + nativeRole(posting) !== 'unknown' && + row.investment.cashPostingIndexes.includes(postingIndex); + const change: ReportedAmount[] = []; + const unclassifiedChange: ReportedAmount[] = []; + for (const amount of posting.amounts) { + if (securityCommodities.has(amount.commodity)) continue; + if (safeCashPosting && knownCash.has(amount.commodity)) change.push(reported(amount)); + else unclassifiedChange.push(reported(amount)); + } + if (unclassifiedChange.length > 0) issues.add('unclassified-commodity'); + return { + securities, + transactedAmounts, + cash: { + direction: unclassifiedChange.length > 0 ? 'unknown' : cashDirection(change), + change, + unclassifiedChange + }, + issues: [...issues] + }; +} + +function postingSecurityAction( + group: PreparedSecurityActivity, + posting: PreparedPosting, + row: PreparedAccountRow, + issues: Set +): PreparedSecurityActivity['action'] { + const role = nativeRole(posting); + let unsafe = false; + if (posting.kind !== 'RealPosting') { + issues.add('virtual-postings'); + unsafe = true; + } + if (role === null || role === 'unknown' || role === 'gain') { + issues.add('unknown-native-role'); + return 'unknown'; + } + const expected = role === 'acquire' || role === 'transfer-to' ? 'positive' : 'negative'; + if ( + posting.amounts.some( + (amount) => amount.commodity === group.commodity && quantitySign(amount.quantity) !== expected + ) + ) { + issues.add( + role === 'acquire' || role === 'dispose' ? 'unsupported-short' : 'unknown-native-role' + ); + unsafe = true; + } + if ( + row.balance.some( + (amount) => + amount.commodity === group.commodity && quantitySign(amount.quantity) === 'negative' + ) + ) { + issues.add('unsupported-short'); + unsafe = true; + } + if (unsafe) return 'unknown'; + + const action = + role === 'transfer-from' ? 'transfer-out' : role === 'transfer-to' ? 'transfer-in' : role; + if (group.action === 'buy' && action === 'acquire') return 'buy'; + if (group.action === 'sell' && action === 'dispose') return 'sell'; + if (group.action === 'mixed' || group.action === action) return action; + // Unknown prepared actions may depend on account classification absent from the saved row. + return 'unknown'; +} diff --git a/packages/hledger/src/transactions/investment/types.ts b/packages/hledger/src/transactions/investment/types.ts new file mode 100644 index 0000000..c695858 --- /dev/null +++ b/packages/hledger/src/transactions/investment/types.ts @@ -0,0 +1,66 @@ +import type { ReportedAmount } from '../../amounts.js'; + +export type InvestmentIssue = + | 'unclassified-commodity' + | 'unattributed-income' + | 'mixed-security-actions' + | 'mixed-security-posting' + | 'unknown-native-role' + | 'unsupported-short' + | 'virtual-postings' + | 'unavailable-transacted-values'; + +export interface PreparedSecurityActivity { + commodity: string; + action: + | 'buy' + | 'sell' + | 'transfer-in' + | 'transfer-out' + | 'acquire' + | 'dispose' + | 'mixed' + | 'unknown'; + /** Native account net change for activity rows; original components for posting rows. */ + change: ReportedAmount[]; + /** Selected legs' indexes in the original transaction, not the account register. */ + postingIndexes: number[]; + /** Reported UnitCost annotations only; never a computed execution price. */ + prices: ReportedAmount[]; + /** Ordered concatenation of attributable posting bags, not a sum; null if unpriced, shared or missing. */ + transactedAmounts: ReportedAmount[] | null; +} + +export interface PreparedInvestmentData { + securities: PreparedSecurityActivity[]; + /** Selected-account/subtree change and balance, unlike transaction-wide cash posting evidence. */ + cash: { + direction: 'in' | 'out' | 'mixed' | 'none' | 'unknown'; + change: ReportedAmount[]; + balance: ReportedAmount[]; + unclassifiedChange: ReportedAmount[]; + unclassifiedBalance: ReportedAmount[]; + }; + /** Original-transaction indexes, including cash legs outside the selected account/subtree. */ + cashPostingIndexes: number[]; + /** Original-transaction income indexes; not allocated to securities. */ + incomePostingIndexes: number[]; + /** Original-transaction expense indexes; not allocated to securities. */ + expensePostingIndexes: number[]; + /** Original-transaction gain indexes; not allocated to securities. */ + gainPostingIndexes: number[]; + issues: InvestmentIssue[]; +} + +/** One selected original posting, without transaction-wide allocation or netting. */ +export interface PreparedInvestmentPosting { + securities: PreparedSecurityActivity[]; + /** Whole native posting bag when entirely priced securities; [] without securities, null if unavailable. */ + transactedAmounts: ReportedAmount[] | null; + cash: { + direction: PreparedInvestmentData['cash']['direction']; + change: ReportedAmount[]; + unclassifiedChange: ReportedAmount[]; + }; + issues: InvestmentIssue[]; +}