diff --git a/packages/db/src/reports/account-activity-row.ts b/packages/db/src/reports/account-activity-row.ts new file mode 100644 index 0000000..0887760 --- /dev/null +++ b/packages/db/src/reports/account-activity-row.ts @@ -0,0 +1,50 @@ +import type { PreparedAccountRow } from '@hledger-reports/hledger'; +import { decodeNativeTransaction, prepareTransaction } from '@hledger-reports/hledger/transactions'; +import type { ReportDatabase } from '../schema.js'; +import { hasAccountContextForPostings } from './data.js'; + +export type StoredActivityRow = Pick< + ReportDatabase['account_activity'], + 'ordinal' | 'account_date' | 'native_transaction_index' | 'context_json' +> & { + canonical_native_index: number | null; + original_json: string | null; + transacted_json: string | null; +}; + +export function decodeAccountRow(record: StoredActivityRow, rowCount: number): PreparedAccountRow { + if ( + !Number.isSafeInteger(record.ordinal) || + record.ordinal < 0 || + record.ordinal >= rowCount || + typeof record.account_date !== 'string' || + typeof record.context_json !== 'string' || + !Number.isSafeInteger(record.native_transaction_index) || + record.native_transaction_index <= 0 || + record.canonical_native_index !== record.native_transaction_index || + typeof record.original_json !== 'string' || + typeof record.transacted_json !== 'string' + ) + throw new Error('Invalid account data.'); + const context: unknown = JSON.parse(record.context_json); + const original = decodeNativeTransaction(record.original_json); + const transacted = decodeNativeTransaction(record.transacted_json); + if ( + original.tindex !== record.native_transaction_index || + transacted.tindex !== record.native_transaction_index + ) + throw new Error('Invalid account data.'); + const transaction = prepareTransaction(original, transacted); + if (!hasAccountContextForPostings(context, transaction.postings.length)) + throw new Error('Invalid account data.'); + return { + accountDate: record.account_date, + isSplit: context.isSplit, + otherAccounts: context.otherAccounts, + change: context.change, + balance: context.balance, + accountPostingIndexes: context.accountPostingIndexes, + investment: context.investment, + transaction + }; +} diff --git a/packages/db/src/reports/index.ts b/packages/db/src/reports/index.ts index ba253c0..7789a5f 100644 --- a/packages/db/src/reports/index.ts +++ b/packages/db/src/reports/index.ts @@ -28,5 +28,13 @@ export { writeRegisterRowsAndPostingCount, type RegisterPageOptions } from './prepared-register-rows.js'; +export { searchRegisterTransactions } from './transaction-search.js'; +export type { + SearchRegister, + SearchRegisters, + TransactionSearch, + TransactionSearchCursor, + TransactionSearchResult +} from './transaction-search.js'; export { AccountActivitySummaryBuilder } from './account-activity-summary.js'; export type { AccountActivitySummary } from './account-activity-summary.js'; diff --git a/packages/db/src/reports/prepared-register-rows.ts b/packages/db/src/reports/prepared-register-rows.ts index 92d83a9..1a1d5e4 100644 --- a/packages/db/src/reports/prepared-register-rows.ts +++ b/packages/db/src/reports/prepared-register-rows.ts @@ -17,6 +17,12 @@ export interface RegisterPageOptions { export type RegisterRowKind = ReportDatabase['prepared_register_rows']['row_kind']; +// For one transaction in one register, check the prepared row count and don't count a posting twice. +export const hasExpectedRegisterRows = sql`( + count(*) = min(entry_row_count) and count(*) = max(entry_row_count) + and (min(row_kind) = 'entry' or count(distinct posting_ordinal) = count(*)) +)`; + export async function readRegisterRowReferencePage( database: Kysely, accountName: string, @@ -68,12 +74,10 @@ export async function findRegisterEntryLocation( from prepared_register_rows where account_name = ${accountName} and row_kind = ${rowKind} and entry_ordinal = ${entryOrdinal} ), target_entry_integrity as ( - select count(*) = min(entry_row_count) and count(*) = max(entry_row_count) as has_all_siblings, - ${rowKind} = 'entry' or count(distinct posting_ordinal) = count(*) as has_unique_postings - from target_entry_rows + select ${hasExpectedRegisterRows} as has_expected_rows from target_entry_rows ), first_visible_row as ( select * from target_entry_rows - where (select has_all_siblings and has_unique_postings from target_entry_integrity) + where (select has_expected_rows from target_entry_integrity) order by display_date ${dateOrder}, entry_ordinal, position_in_entry limit 1 ) select ( diff --git a/packages/db/src/reports/queries.test.ts b/packages/db/src/reports/queries.test.ts index 9648728..50e9117 100644 --- a/packages/db/src/reports/queries.test.ts +++ b/packages/db/src/reports/queries.test.ts @@ -31,6 +31,7 @@ import { import { insertNativeTransaction, attachTransactedTransaction } from '../transactions/index.js'; import { richNativeExportsFixture } from '../transactions/native.fixture.js'; import type { StoredReportData } from './data.js'; +import { searchRegisterTransactions, type SearchRegisters } from './transaction-search.js'; import { amount, accountTransactionExportsFixture, @@ -408,6 +409,210 @@ it('reads date-ordered pages with native ties and exact account scope', async () ); }); +it('seeks through saved entry dates and shows one result with both original register changes', async () => { + const database = await createDatabase(); + const cash = 'assets:cash'; + const brokerage = 'assets:brokerage'; + const transfersAt = 103; + const olderEntryAt = 104; + const exports = accountTransactionExportsFixture(104, 'Find example').map((pair, ordinal) => { + if (ordinal + 1 !== transfersAt && ordinal + 1 !== olderEntryAt) return pair; + const native = JSON.parse(pair.originalJson); + if (ordinal + 1 === olderEntryAt) native.tdate = '2026-04-28'; + else { + native.tpostings[1].paccount = brokerage; + native.tpostings[2].paccount = brokerage; + native.tpostings[2].pamount[0].acommodity = 'VTI'; + } + const json = JSON.stringify(native); + return { originalJson: json, transactedJson: json }; + }); + const cashRows = preparedAccountRowsFromExports(exports); + cashRows[transfersAt - 1].change = [amount('-100.00'), amount('-0.000')]; + const [brokerageRow] = preparedAccountRowsFromExports([exports[transfersAt - 1]]); + brokerageRow.accountPostingIndexes = [1, 2]; + brokerageRow.investment.cash.change = [amount('75.0000')]; + brokerageRow.investment.securities = [ + { + commodity: 'VTI', + action: 'transfer-in', + postingIndexes: [2], + change: [{ commodity: 'VTI', quantity: '25.0000' }], + prices: [], + transactedAmounts: null + } + ]; + const cashAccount = { id: 'cash0001', ...ready(cash, cashRows.length) }; + const brokerageAccount = { id: 'broker01', ...ready(brokerage) }; + const registers: SearchRegisters = [ + { account: cashAccount, kind: 'cash' }, + { account: brokerageAccount, kind: 'investment' } + ]; + const writer = await database.startTransaction().execute(); + try { + await importTransactions(writer, exports); + await writeAccountRows(writer, cash, 0, cashRows); + await writeAccountRows(writer, brokerage, 0, [brokerageRow]); + await writeReportData(writer, { + journal, + overview: preparedOverview(), + accounts: [cashAccount, brokerageAccount] + }); + await writeAccountActivitySummaries( + writer, + new Map([ + [cash, preparedActivitySummary(cashRows)], + [brokerage, preparedActivitySummary([brokerageRow])] + ]) + ); + await writeRegisterRowsAndPostingCount(writer, cash, cashRows.length); + await writeRegisterRowsAndPostingCount(writer, brokerage, 1); + // Unscoped journal entries fill a candidate window but aren't search matches. + const outside = exports[0].originalJson.replaceAll('assets:cash', 'assets:outside'); + await sql`with recursive indexes(i) as (values (1000) union all select i + 1 from indexes where i < 1256) + insert into transactions (native_index, transaction_date, status, original_json, transacted_json) + select i, '2026-04-29', 'Cleared', json_set(${outside}, '$.tindex', i), json_set(${outside}, '$.tindex', i) + from indexes`.execute(writer); + await writer.commit().execute(); + } finally { + if (!writer.isCommitted && !writer.isRolledBack) await writer.rollback().execute(); + } + + const range = { fromDate: '2026-04-29', throughDate: '2026-04-29' }; + const first = await searchRegisterTransactions(database, registers, range); + expect(first.transactions.map((transaction) => transaction.nativeTransactionIndex)).toEqual( + Array.from({ length: 50 }, (_, index) => transfersAt - index) + ); + expect(first.transactions[0]).toEqual({ + transactionDate: '2026-04-29', + nativeTransactionIndex: transfersAt, + description: cashRows[transfersAt - 1].transaction.description, + registerChanges: [ + { + kind: 'cash', + accountId: cashAccount.id, + change: [ + { commodity: '$', quantity: '-100.00' }, + { commodity: '$', quantity: '-0.000' } + ] + }, + { + kind: 'investment', + accountId: brokerageAccount.id, + cashChange: [{ commodity: '$', quantity: '75.0000' }], + hasUnclassifiedChange: false, + securities: [{ commodity: 'VTI', change: [{ commodity: 'VTI', quantity: '25.0000' }] }] + } + ] + }); + expect(first.previous).toBeNull(); + if (!first.next) throw new Error('Missing next page.'); + const second = await searchRegisterTransactions(database, registers, { + ...range, + pageBoundary: { kind: 'after', cursor: first.next } + }); + expect(second.transactions.map((transaction) => transaction.nativeTransactionIndex)).toEqual( + Array.from({ length: 50 }, (_, index) => transfersAt - 50 - index) + ); + if (!second.next) throw new Error('Missing next page.'); + const third = await searchRegisterTransactions(database, registers, { + ...range, + pageBoundary: { kind: 'after', cursor: second.next } + }); + expect(third.transactions.map((transaction) => transaction.nativeTransactionIndex)).toEqual([ + 3, 2, 1 + ]); + expect(third.next).toBeNull(); + if (!third.previous) throw new Error('Missing previous page.'); + const middleAgain = await searchRegisterTransactions(database, registers, { + ...range, + pageBoundary: { kind: 'before', cursor: third.previous } + }); + expect(middleAgain).toEqual(second); + if (!middleAgain.previous) throw new Error('Missing return to first page.'); + expect( + await searchRegisterTransactions(database, registers, { + ...range, + pageBoundary: { kind: 'before', cursor: middleAgain.previous } + }) + ).toEqual(first); + const outsideScopeCursor = { transactionDate: '2026-04-29', nativeTransactionIndex: 1256 }; + expect( + await searchRegisterTransactions(database, registers, { + ...range, + pageBoundary: { kind: 'after', cursor: outsideScopeCursor } + }) + ).toEqual({ transactions: [], previous: null, next: null }); + const brokerageOnly = await searchRegisterTransactions(database, [registers[1]], range); + expect( + brokerageOnly.transactions.map(({ nativeTransactionIndex, registerChanges }) => [ + nativeTransactionIndex, + registerChanges.map(({ accountId }) => accountId) + ]) + ).toEqual([[transfersAt, [brokerageAccount.id]]]); + + // A bad lookahead isn't hydrated; the same row fails when it enters the displayed page. + await database + .updateTable('account_activity') + .set({ context_json: sql`json_set(context_json, '$.change[0].quantity', 4)` }) + .where('account_name', '=', cash) + .where('native_transaction_index', '=', 3) + .execute(); + expect( + await searchRegisterTransactions(database, registers, { + ...range, + pageBoundary: { kind: 'after', cursor: first.next } + }) + ).toEqual(second); + await expect( + searchRegisterTransactions(database, registers, { + ...range, + pageBoundary: { kind: 'after', cursor: second.next } + }) + ).rejects.toThrow('Invalid recorded register change.'); + + const storedBrokerage = database.updateTable('accounts').where('name', '=', brokerage); + await storedBrokerage.set({ id: 'wrong001' }).execute(); + await expect(searchRegisterTransactions(database, registers, range)).rejects.toThrow( + 'Invalid account data.' + ); + await storedBrokerage.set({ id: brokerageAccount.id }).execute(); + + const firstBrokeragePosting = database + .updateTable('prepared_register_rows') + .where('account_name', '=', brokerage) + .where('row_kind', '=', 'posting') + .where('position_in_entry', '=', 1); + await firstBrokeragePosting.set({ posting_ordinal: 0 }).execute(); + await expect(searchRegisterTransactions(database, registers, range)).rejects.toThrow( + 'Invalid prepared register rows.' + ); + await firstBrokeragePosting.set({ posting_ordinal: 1 }).execute(); + const deletedPosting = await database + .deleteFrom('prepared_register_rows') + .where('account_name', '=', brokerage) + .where('row_kind', '=', 'posting') + .where('position_in_entry', '=', 2) + .returningAll() + .executeTakeFirstOrThrow(); + await expect(searchRegisterTransactions(database, registers, range)).rejects.toThrow( + 'Invalid prepared register rows.' + ); + await database.insertInto('prepared_register_rows').values(deletedPosting).execute(); + + const native = new DatabaseSync(path); + try { + native.exec('PRAGMA foreign_keys = OFF'); + native.prepare('delete from accounts where name = ?').run(brokerage); + } finally { + native.close(); + } + // Missing account metadata must not turn a transfer into a Cash-only result. + await expect(searchRegisterTransactions(database, registers, range)).rejects.toThrow( + 'Invalid account data.' + ); +}); + it('decodes only the requested page and rejects damaged saved row contexts', async () => { const database = await createDatabase(); const secondPageOffset = 50; diff --git a/packages/db/src/reports/queries.ts b/packages/db/src/reports/queries.ts index 67865f0..f4ced0c 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -1,5 +1,4 @@ import type { PreparedAccountRow } from '@hledger-reports/hledger'; -import { decodeNativeTransaction, prepareTransaction } from '@hledger-reports/hledger/transactions'; import { sql, type Kysely } from 'kysely'; import type { ReportDatabase } from '../schema.js'; import { @@ -8,12 +7,12 @@ import { type AccountActivitySummary } from './account-activity-summary.js'; import { - hasAccountContextForPostings, hasAccountRowContainers, hasStoredReportData, type StoredAccount, type StoredReportData } from './data.js'; +import { decodeAccountRow } from './account-activity-row.js'; import { findRegisterEntryLocation, readRegisterRowReferencePage, @@ -40,15 +39,6 @@ export interface AccountInvestmentActivityPage { summary: AccountActivitySummary; } -type StoredActivityRow = Pick< - ReportDatabase['account_activity'], - 'ordinal' | 'account_date' | 'native_transaction_index' | 'context_json' -> & { - canonical_native_index: number | null; - original_json: string | null; - transacted_json: string | null; -}; - export async function writeAccountRows( database: Kysely, name: string, @@ -231,42 +221,6 @@ function selectAccountRowsWithTransactions(database: Kysely) { ]); } -function decodeAccountRow(record: StoredActivityRow, rowCount: number): PreparedAccountRow { - if ( - !Number.isSafeInteger(record.ordinal) || - record.ordinal < 0 || - record.ordinal >= rowCount || - typeof record.account_date !== 'string' || - !Number.isSafeInteger(record.native_transaction_index) || - record.native_transaction_index <= 0 || - record.canonical_native_index !== record.native_transaction_index || - typeof record.original_json !== 'string' || - typeof record.transacted_json !== 'string' - ) - throw new Error('Invalid account data.'); - const context = decodePayload(record.context_json); - const original = decodeNativeTransaction(record.original_json); - const transacted = decodeNativeTransaction(record.transacted_json); - if ( - original.tindex !== record.native_transaction_index || - transacted.tindex !== record.native_transaction_index - ) - throw new Error('Invalid account data.'); - const transaction = prepareTransaction(original, transacted); - if (!hasAccountContextForPostings(context, transaction.postings.length)) - throw new Error('Invalid account data.'); - return { - accountDate: record.account_date, - isSplit: context.isSplit, - otherAccounts: context.otherAccounts, - change: context.change, - balance: context.balance, - accountPostingIndexes: context.accountPostingIndexes, - investment: context.investment, - transaction - }; -} - function decodeActivitySummary( record: ReportDatabase['account_activity_summaries'] ): AccountActivitySummary { diff --git a/packages/db/src/reports/transaction-search.ts b/packages/db/src/reports/transaction-search.ts new file mode 100644 index 0000000..7b10e0b --- /dev/null +++ b/packages/db/src/reports/transaction-search.ts @@ -0,0 +1,319 @@ +import type { PreparedAccountRow, ReportedAmount } from '@hledger-reports/hledger'; +import { sql, type Kysely, type RawBuilder } from 'kysely'; +import { setImmediate } from 'node:timers/promises'; +import { registerPageSize } from '../register-page.js'; +import type { ReportDatabase } from '../schema.js'; +import { isAmountBag } from './account-activity-summary.js'; +import type { StoredAccount } from './data.js'; +import { hasExpectedRegisterRows } from './prepared-register-rows.js'; +import { decodeAccountRow, type StoredActivityRow } from './account-activity-row.js'; + +const candidateWindowSize = 256; + +export interface SearchRegister { + account: Extract; + kind: 'cash' | 'investment'; +} + +export type SearchRegisters = readonly [SearchRegister, ...SearchRegister[]]; + +export interface TransactionSearchCursor { + transactionDate: string; + nativeTransactionIndex: number; +} + +interface SearchAfter { + kind: 'after'; + cursor: TransactionSearchCursor; +} +interface SearchBefore { + kind: 'before'; + cursor: TransactionSearchCursor; +} + +export interface TransactionSearch { + fromDate?: string; + throughDate?: string; + pageBoundary?: SearchAfter | SearchBefore; +} + +interface CashRegisterChange { + kind: 'cash'; + accountId: string; + change: ReportedAmount[]; +} +interface InvestmentRegisterChange { + kind: 'investment'; + accountId: string; + cashChange: ReportedAmount[]; + hasUnclassifiedChange: boolean; + securities: { commodity: string; change: ReportedAmount[] }[]; +} + +type RegisterChange = CashRegisterChange | InvestmentRegisterChange; + +interface MatchedTransaction extends TransactionSearchCursor { + description: string; + registerChanges: RegisterChange[]; +} + +export interface TransactionSearchResult { + transactions: MatchedTransaction[]; + previous: TransactionSearchCursor | null; + next: TransactionSearchCursor | null; +} + +/** The caller resolves configured registers and validates the requested date bounds and cursor. */ +export async function searchRegisterTransactions( + database: Kysely, + registers: SearchRegisters, + search: TransactionSearch +): Promise { + const { pageBoundary } = search; + // An old boundary that no longer matches can't establish a link back across it. + if ( + pageBoundary && + !(await isSearchCursorCurrent(database, registers, search, pageBoundary.cursor)) + ) { + return { transactions: [], previous: null, next: null }; + } + const backwards = pageBoundary?.kind === 'before'; + const order = backwards ? 'asc' : 'desc'; + const transactionPositions = await selectTransactionPositions(database, registers, search, order); + const hasLookahead = transactionPositions.length > registerPageSize; + const hasPreviousPage = backwards ? hasLookahead : pageBoundary?.kind === 'after'; + const hasNextPage = backwards || hasLookahead; + const displayedPositions = transactionPositions.slice(0, registerPageSize); + if (backwards) displayedPositions.reverse(); + + const rows = displayedPositions.length + ? await selectRegisterRowsForTransactions(database, registers, displayedPositions) + : []; + return { + transactions: buildMatchedTransactions(registers, displayedPositions, rows), + previous: hasPreviousPage ? (displayedPositions[0] ?? null) : null, + next: hasNextPage ? (displayedPositions.at(-1) ?? null) : null + }; +} + +function hasRegisterActivity(registers: SearchRegisters, nativeIndex: RawBuilder) { + const names = sql.join(registers.map(({ account }) => account.name)); + return sql`exists ( + select 1 from account_activity a + where a.native_transaction_index = ${nativeIndex} and a.account_name in (${names}) + )`; +} + +async function isSearchCursorCurrent( + database: Kysely, + registers: SearchRegisters, + search: TransactionSearch, + cursor: TransactionSearchCursor +): Promise { + if ( + (search.fromDate !== undefined && cursor.transactionDate < search.fromDate) || + (search.throughDate !== undefined && cursor.transactionDate > search.throughDate) + ) + return false; + const { rows } = await sql` + select 1 from transactions t + where t.native_index = ${cursor.nativeTransactionIndex} and t.transaction_date = ${cursor.transactionDate} + and ${hasRegisterActivity(registers, sql`t.native_index`)} + `.execute(database); + return rows.length !== 0; +} + +async function selectTransactionPositions( + database: Kysely, + registers: SearchRegisters, + search: TransactionSearch, + order: 'asc' | 'desc' +): Promise { + const positions: TransactionSearchCursor[] = []; + let cursor = search.pageBoundary?.cursor; + while (positions.length <= registerPageSize) { + const window = await selectCandidatePositions(database, registers, search, order, cursor); + for (const { transactionDate, nativeTransactionIndex, inRegisterScope } of window) { + if (inRegisterScope) positions.push({ transactionDate, nativeTransactionIndex }); + if (positions.length > registerPageSize) break; + } + if (positions.length > registerPageSize || window.length < candidateWindowSize) break; + cursor = window[window.length - 1]; + await setImmediate(); + } + return positions; +} + +interface CandidatePosition extends TransactionSearchCursor { + inRegisterScope: 0 | 1; +} + +async function selectCandidatePositions( + database: Kysely, + registers: SearchRegisters, + search: TransactionSearch, + order: 'asc' | 'desc', + cursor: TransactionSearchCursor | undefined +): Promise { + let { fromDate, throughDate } = search; + if (cursor) { + // Narrow the date range on the index as well as excluding the cursor tuple. + if (order === 'asc' && (fromDate === undefined || fromDate < cursor.transactionDate)) { + fromDate = cursor.transactionDate; + } else if ( + order === 'desc' && + (throughDate === undefined || throughDate > cursor.transactionDate) + ) { + throughDate = cursor.transactionDate; + } + } + const direction = order === 'asc' ? sql`asc` : sql`desc`; + const comparison = order === 'asc' ? sql`>` : sql`<`; + const from = fromDate === undefined ? sql`` : sql`and transaction_date >= ${fromDate}`; + const through = throughDate === undefined ? sql`` : sql`and transaction_date <= ${throughDate}`; + const afterBoundary = cursor + ? sql`and (transaction_date, native_index) ${comparison} (${cursor.transactionDate}, ${cursor.nativeTransactionIndex})` + : sql``; + // Membership selects candidates; displayed transactions must also have their prepared register rows. + const { rows } = await sql` + with candidates as materialized ( + select transaction_date, native_index from transactions + where true ${from} ${through} ${afterBoundary} + order by transaction_date ${direction}, native_index ${direction} + limit ${candidateWindowSize} + ) + select k.transaction_date as transactionDate, k.native_index as nativeTransactionIndex, + ${hasRegisterActivity(registers, sql`k.native_index`)} as inRegisterScope + from candidates k + order by k.transaction_date ${direction}, k.native_index ${direction} + `.execute(database); + return rows; +} + +interface SearchActivityRecord extends StoredActivityRow { + account_name: string; + account_id: string | null; + account_access: StoredAccount['access'] | null; + account_row_count: number | null; + display_date: string | null; + posting_ordinal: number | null; + has_expected_register_rows: 0 | 1 | null; +} + +async function selectRegisterRowsForTransactions( + database: Kysely, + registers: SearchRegisters, + positions: readonly TransactionSearchCursor[] +): Promise { + const scope = sql.join( + registers.map(({ account, kind }, index) => { + const rowKind = kind === 'cash' ? 'entry' : 'posting'; + return sql`(${account.name}, ${rowKind}, ${index})`; + }) + ); + const indexes = sql.join(positions.map(({ nativeTransactionIndex }) => nativeTransactionIndex)); + // Left joins keep missing accounts or references visible to the result builder. + const { rows } = await sql` + with scope(account_name, row_kind, position) as (values ${scope}) + select a.account_name, a.ordinal, a.account_date, a.native_transaction_index, a.context_json, + account.id as account_id, account.access as account_access, account.row_count as account_row_count, + t.native_index as canonical_native_index, t.original_json, t.transacted_json, + r.display_date, r.posting_ordinal, + (select ${hasExpectedRegisterRows} from prepared_register_rows siblings + where siblings.account_name = a.account_name and siblings.row_kind = s.row_kind + and siblings.entry_ordinal = a.ordinal) as has_expected_register_rows + from scope s join account_activity a on a.account_name = s.account_name + left join accounts account on account.name = a.account_name + join transactions t on t.native_index = a.native_transaction_index + left join prepared_register_rows r on r.account_name = a.account_name + and r.entry_ordinal = a.ordinal and r.row_kind = s.row_kind and r.position_in_entry = 1 + where a.native_transaction_index in (${indexes}) + order by s.position + `.execute(database); + return rows; +} + +function buildMatchedTransactions( + registers: SearchRegisters, + positions: readonly TransactionSearchCursor[], + rows: readonly SearchActivityRecord[] +): MatchedTransaction[] { + const registersByName = new Map(registers.map((register) => [register.account.name, register])); + const transactions = new Map(); + for (const record of rows) { + const register = registersByName.get(record.account_name); + if ( + !register || + record.account_id !== register.account.id || + record.account_access !== register.account.access || + record.account_row_count !== register.account.rowCount + ) + throw new Error('Invalid account data.'); + const row = decodeAccountRow(record, register.account.rowCount); + requirePreparedRegisterReference(register, record, row); + const nativeTransactionIndex = row.transaction.index; + let transaction = transactions.get(nativeTransactionIndex); + if (!transaction) { + transaction = { + nativeTransactionIndex, + transactionDate: row.transaction.date, + description: row.transaction.description, + registerChanges: [] + }; + transactions.set(nativeTransactionIndex, transaction); + } + transaction.registerChanges.push(recordedRegisterChange(register, row)); + } + return positions.map((position) => { + const transaction = transactions.get(position.nativeTransactionIndex); + if (!transaction || transaction.transactionDate !== position.transactionDate) + throw new Error('Invalid saved transaction data.'); + return transaction; + }); +} + +function requirePreparedRegisterReference( + register: SearchRegister, + record: SearchActivityRecord, + row: PreparedAccountRow +): void { + if (!record.has_expected_register_rows) throw new Error('Invalid prepared register rows.'); + if (register.kind === 'cash') { + if (record.display_date !== row.accountDate) throw new Error('Invalid prepared register rows.'); + return; + } + const postingIndex = record.posting_ordinal; + if (postingIndex === null || !row.accountPostingIndexes.includes(postingIndex)) + throw new Error('Invalid prepared register rows.'); + const posting = row.transaction.postings[postingIndex]; + const accountName = register.account.name; + if ( + (posting.account !== accountName && !posting.account.startsWith(`${accountName}:`)) || + record.display_date !== (posting.date ?? row.transaction.date) + ) + throw new Error('Invalid prepared register rows.'); +} + +function recordedRegisterChange(register: SearchRegister, row: PreparedAccountRow): RegisterChange { + const accountId = register.account.id; + if (register.kind === 'cash') { + return { kind: 'cash', accountId, change: copyReportedAmounts(row.change) }; + } + const { cash, securities } = row.investment; + if (!isAmountBag(cash.unclassifiedChange)) throw new Error('Invalid recorded register change.'); + return { + kind: 'investment', + accountId, + cashChange: copyReportedAmounts(cash.change), + hasUnclassifiedChange: cash.unclassifiedChange.length > 0, + securities: securities.map((security) => { + if (typeof security?.commodity !== 'string') throw new Error('Invalid recorded security.'); + return { commodity: security.commodity, change: copyReportedAmounts(security.change) }; + }) + }; +} + +function copyReportedAmounts(amounts: readonly ReportedAmount[]): ReportedAmount[] { + if (!isAmountBag(amounts)) throw new Error('Invalid recorded register change.'); + return amounts.map(({ commodity, quantity }) => ({ commodity, quantity })); +} diff --git a/packages/snapshots/src/index.ts b/packages/snapshots/src/index.ts index 2e0ffb6..01bff6a 100644 --- a/packages/snapshots/src/index.ts +++ b/packages/snapshots/src/index.ts @@ -2,6 +2,7 @@ export { createReportStage, readOverview, readReportPublication, + searchTransactions, readInvestmentOverview, readAccountPage, readFocusedAccountPage, @@ -19,7 +20,12 @@ export type { StoredAccount, AccountActivitySummary, AccountActivityPage, - AccountInvestmentActivityPage + AccountInvestmentActivityPage, + SearchRegister, + SearchRegisters, + TransactionSearch, + TransactionSearchCursor, + TransactionSearchResult } from '@hledger-reports/db/reports'; export { hasFailedReportUpdate, diff --git a/packages/snapshots/src/reports/publication.test.ts b/packages/snapshots/src/reports/publication.test.ts index 383f922..44fc42d 100644 --- a/packages/snapshots/src/reports/publication.test.ts +++ b/packages/snapshots/src/reports/publication.test.ts @@ -13,6 +13,7 @@ import { readInvestmentActivityCount, createReportStage, readAccountPage, + searchTransactions, readFocusedAccountPage, readFocusedInvestmentActivityPage, readAccountTransaction, @@ -336,6 +337,36 @@ it('does not mix two publications from different attempts of the same request', ); }); +it('finishes a transaction search on the original report when the file is replaced', async () => { + await publish(); + const originalReport = await selected(); + const [account] = originalReport.accounts; + if (account?.access !== 'ready') throw new Error('Missing the prepared Cash register.'); + const registers = [{ account, kind: 'cash' }] as const; + const search = { throughDate: '2026-04-29' }; + const stage = await createReportStage(snapshots, newer, originalReport.accounts); + await importNativeExports(stage, 1, 'replacement transaction'); + await stage.writeRows(account.name, rows(1, 'replacement transaction')); + const readKey = reports.readPublicationRequest; + vi.spyOn(reports, 'readPublicationRequest').mockImplementationOnce(async (database) => { + const key = await readKey(database); + await stage.publish(fixture(), [ready()], journal); + return key; + }); + + const originalResults = await searchTransactions(originalReport, registers, search); + expect(originalResults.transactions.map(({ description }) => description)).toEqual([ + 'exact producer strings 0' + ]); + await expect(searchTransactions(originalReport, registers, search)).rejects.toSatisfy( + safeError('Unable to search prepared reports') + ); + const currentResults = await searchTransactions(await selected(), registers, search); + expect(currentResults.transactions.map(({ description }) => description)).toEqual([ + 'replacement transaction 0' + ]); +}); + it('locates and reads the ordinary Cash page on the same checked connection', async () => { const original = await createReportStage(snapshots, older); await importNativeExports(original, 52); diff --git a/packages/snapshots/src/reports/publication.ts b/packages/snapshots/src/reports/publication.ts index db1eefe..f1e069d 100644 --- a/packages/snapshots/src/reports/publication.ts +++ b/packages/snapshots/src/reports/publication.ts @@ -20,6 +20,7 @@ import { isAccountId, isStorableAccountSummary, findRegisterFocusLocation, + searchRegisterTransactions, readCashRegisterPage, readAccountActivityDetail, readAccountInvestmentActivityCount, @@ -36,6 +37,9 @@ import { type AccountActivitySummary, type AccountActivityPage, type AccountInvestmentActivityPage, + type SearchRegisters, + type TransactionSearch, + type TransactionSearchResult, type RegisterPageOptions, type StoredAccount, type StoredReportData @@ -159,7 +163,7 @@ export async function readInvestmentOverview( publication: ReportPublication ): Promise { try { - return await readFromSelectedPublication(publication, async (database) => { + return await withSelectedReportConnection(publication, async (database) => { const json = await readPublicationInvestmentJson(database); return json === null ? null @@ -170,24 +174,38 @@ export async function readInvestmentOverview( } } -async function readFromSelectedPublication( - publication: ReportPublication, - read: (database: ReportConnection) => Promise +async function withSelectedReportConnection( + report: ReportPublication, + useConnection: (database: ReportConnection) => Promise ): Promise { - const database = await openReadOnlyReportDatabase(publication.reportFile); - if (!database) throw new Error('Publication database is unavailable.'); + const database = await openReadOnlyReportDatabase(report.reportFile); + if (!database) throw new Error('Saved report database is unavailable.'); try { - // Check the same connection that will serve the read; the slot can change between opens. - const openedPublicationKey = await readPublicationRequest(database); - if (openedPublicationKey !== publication.publicationKey) { + // The file may have been replaced since the caller selected the report. + const openedReportKey = await readPublicationRequest(database); + if (openedReportKey !== report.publicationKey) { throw new Error('Saved report was replaced.'); } - return await read(database); + return await useConnection(database); } finally { await database.destroy(); } } +export async function searchTransactions( + report: ReportPublication, + registers: SearchRegisters, + search: TransactionSearch +): Promise { + try { + return await withSelectedReportConnection(report, (database) => + searchRegisterTransactions(database, registers, search) + ); + } catch { + throw new Error('Unable to search prepared reports'); + } +} + export async function readAccountPage( publication: ReportPublication, id: string, @@ -197,7 +215,7 @@ export async function readAccountPage( if (!isAccountId(id)) throw new Error(); const account = publication.accounts.find((entry) => entry.id === id); if (!account) throw new Error(); - return await readFromSelectedPublication(publication, (database) => + return await withSelectedReportConnection(publication, (database) => readCashRegisterPage(database, account, options.order, options.offset) ); } catch { @@ -214,7 +232,7 @@ export async function readFocusedAccountPage( try { const account = publication.accounts.find((entry) => entry.id === id); if (account?.access !== 'ready') throw new Error('Account activity is unavailable.'); - return await readFromSelectedPublication(publication, async (database) => { + return await withSelectedReportConnection(publication, async (database) => { const location = await findRegisterFocusLocation( database, account, @@ -248,7 +266,7 @@ export async function readInvestmentActivityCount( if (!isAccountId(id)) throw new Error(); const account = publication.accounts.find((entry) => entry.id === id); if (!account) throw new Error(); - return await readFromSelectedPublication(publication, (database) => + return await withSelectedReportConnection(publication, (database) => readAccountInvestmentActivityCount(database, account) ); } catch { @@ -265,7 +283,7 @@ export async function readInvestmentActivityPage( if (!isAccountId(id)) throw new Error(); const account = publication.accounts.find((entry) => entry.id === id); if (!account) throw new Error(); - return await readFromSelectedPublication(publication, (database) => + return await withSelectedReportConnection(publication, (database) => readAccountInvestmentActivityPage(database, account, options) ); } catch { @@ -282,7 +300,7 @@ export async function readFocusedInvestmentActivityPage( try { const account = publication.accounts.find((entry) => entry.id === id); if (account?.access !== 'ready') throw new Error('Account activity is unavailable.'); - return await readFromSelectedPublication(publication, async (database) => { + return await withSelectedReportConnection(publication, async (database) => { const location = await findRegisterFocusLocation( database, account, @@ -316,7 +334,7 @@ export async function readAccountTransaction( throw new Error(); const account = publication.accounts.find((entry) => entry.id === id); if (!account) throw new Error(); - return await readFromSelectedPublication(publication, (database) => + return await withSelectedReportConnection(publication, (database) => readAccountActivityDetail(database, account, nativeIndex) ); } catch {