From e22b8f657d0194240c83d840ec5e659e6aaa79ff Mon Sep 17 00:00:00 2001 From: eleith Date: Tue, 1 Dec 2026 11:14:46 -0800 Subject: [PATCH 01/19] feat(db): locate a Cash register entry in oldest-first order --- packages/db/src/reports/queries.test.ts | 16 ++++++++++++++++ packages/db/src/reports/queries.ts | 23 +++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/packages/db/src/reports/queries.test.ts b/packages/db/src/reports/queries.test.ts index 115ab22..5495488 100644 --- a/packages/db/src/reports/queries.test.ts +++ b/packages/db/src/reports/queries.test.ts @@ -15,6 +15,7 @@ import { readAccountActivityDetail, countAccountInvestmentActivities, readAccountInvestmentActivityPage, + findOldestFirstAccountActivityOffset, readReportData, writeAccountRows, writeAccountActivitySummaries, @@ -342,6 +343,21 @@ it('reads date-ordered pages with native ties and exact account scope', async () expect(await readPage('desc', 50)).toEqual(rows.slice(50)); expect(await readPage('asc', 53)).toEqual([]); expect(Math.max(...resultRowCounts)).toBe(50); + + const secondPageOffset = 50; + const targetIndex = ascending[secondPageOffset].transaction.index; + expect(await findOldestFirstAccountActivityOffset(database, account.name, targetIndex)).toBe( + secondPageOffset + ); + expect(await findOldestFirstAccountActivityOffset(database, other.name, targetIndex)).toBeNull(); + expect( + await findOldestFirstAccountActivityOffset( + database, + account.name, + ascending[0].transaction.index + ) + ).toBe(0); + expect( await readAccountActivityPage(database, other, { order: 'asc', offset: 0, limit: 50 }) ).toEqual({ rows: otherRows, summary: preparedActivitySummary(otherRows) }); diff --git a/packages/db/src/reports/queries.ts b/packages/db/src/reports/queries.ts index 09e1b2d..5c1535e 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -401,6 +401,29 @@ export async function readAccountActivityPage( return { rows: records.map((record) => decodeAccountRow(record, rowCount)), summary }; } +export async function findOldestFirstAccountActivityOffset( + database: Kysely, + storedAccountName: string, + nativeIndex: number +): Promise { + const target = await database + .selectFrom('account_activity') + .select(['account_date', 'ordinal']) + .where('account_name', '=', storedAccountName) + .where('native_transaction_index', '=', nativeIndex) + .executeTakeFirst(); + if (!target) return null; + + const precedesTarget = sql`(account_date, ordinal) < (${target.account_date}, ${target.ordinal})`; + const { offset } = await database + .selectFrom('account_activity') + .select(({ fn }) => fn.countAll().as('offset')) + .where('account_name', '=', storedAccountName) + .where(precedesTarget) + .executeTakeFirstOrThrow(); + return offset; +} + function accountPostingReferences(accountName: string) { return sql` from account_activity as activity -- 2.54.1 From a3bb814b2010391e79df45bbacabafa05ad7e130 Mon Sep 17 00:00:00 2001 From: eleith Date: Tue, 1 Dec 2026 13:36:38 -0800 Subject: [PATCH 02/19] refactor(db): give Investment row selection one home --- .../db/src/reports/investment-posting-rows.ts | 75 ++++++++++++++++++ packages/db/src/reports/queries.ts | 76 ++----------------- 2 files changed, 81 insertions(+), 70 deletions(-) create mode 100644 packages/db/src/reports/investment-posting-rows.ts diff --git a/packages/db/src/reports/investment-posting-rows.ts b/packages/db/src/reports/investment-posting-rows.ts new file mode 100644 index 0000000..82d28a1 --- /dev/null +++ b/packages/db/src/reports/investment-posting-rows.ts @@ -0,0 +1,75 @@ +import { sql } from 'kysely'; + +export function fromRawAccountPostingReferences(accountName: string) { + return sql` + from account_activity as activity + left join json_each(activity.context_json, '$.accountPostingIndexes') as reference on true + left join transaction_postings as posting + on posting.native_transaction_index = activity.native_transaction_index + and posting.posting_ordinal = reference.value + left join transactions as parent on parent.native_index = activity.native_transaction_index + where activity.account_name = ${accountName} + `; +} + +export function isVisibleInvestmentActivity() { + return sql`not ${isSupportingCashPosting()}`; +} + +function isSupportingCashPosting() { + const accountHasSecurityAnchor = sql`exists ( + select 1 ${securityAnchorReferences()} + where anchor.value in ( + select value from json_each(activity.context_json, '$.accountPostingIndexes') + ) + )`; + const postingIsSecurityAnchor = sql`exists ( + select 1 ${securityAnchorReferences()} + where anchor.value = reference.value + )`; + return sql`( + ${accountHasSecurityAnchor} + and exists ( + select 1 from json_each(activity.context_json, '$.investment.cashPostingIndexes') as cash + where cash.value = reference.value + ) + and not ${postingIsSecurityAnchor} + and ${isSafelyClassifiedCashOnlyPosting()} + )`; +} + +function securityAnchorReferences() { + return sql` + from json_each(activity.context_json, '$.investment.securities') as security + join json_each(security.value, '$.postingIndexes') as anchor on true + `; +} + +function isSafelyClassifiedCashOnlyPosting() { + return sql`exists ( + select 1 from json_each(parent.original_json, '$.tpostings') as original + where original.key = reference.value + and json_extract(original.value, '$.preal') = 'RealPosting' + and json_type(original.value, '$.pamount') = 'array' + and json_array_length(original.value, '$.pamount') > 0 + and not exists ( + select 1 from json_each(original.value, '$.pamount') as component + where json_type(component.value, '$.acommodity') is not 'text' + or not exists ( + select 1 from json_each(activity.context_json, '$.investment.cash.change') as cash + where json_extract(cash.value, '$.commodity') = json_extract(component.value, '$.acommodity') + union all + select 1 from json_each(activity.context_json, '$.investment.cash.balance') as cash + where json_extract(cash.value, '$.commodity') = json_extract(component.value, '$.acommodity') + ) + ) + and not exists ( + select count(*) from json_each(original.value, '$.ptags') as role + where json_extract(role.value, '$[0]') = '_ptype' + having count(distinct json_extract(role.value, '$[1]')) > 1 + or sum(case when json_extract(role.value, '$[1]') in + ('acquire', 'dispose', 'transfer-from', 'transfer-to', 'gain') + then 0 else 1 end) > 0 + ) + )`; +} diff --git a/packages/db/src/reports/queries.ts b/packages/db/src/reports/queries.ts index 5c1535e..a7f6834 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -14,6 +14,10 @@ import { type StoredAccount, type StoredReportData } from './data.js'; +import { + fromRawAccountPostingReferences, + isVisibleInvestmentActivity +} from './investment-posting-rows.js'; const insertBatchSize = 50; const maxPageRows = 50; @@ -424,74 +428,6 @@ export async function findOldestFirstAccountActivityOffset( return offset; } -function accountPostingReferences(accountName: string) { - return sql` - from account_activity as activity - left join json_each(activity.context_json, '$.accountPostingIndexes') as reference on true - left join transaction_postings as posting - on posting.native_transaction_index = activity.native_transaction_index - and posting.posting_ordinal = reference.value - left join transactions as parent on parent.native_index = activity.native_transaction_index - where activity.account_name = ${accountName} - `; -} - -function securityAnchorReferences() { - return sql` - from json_each(activity.context_json, '$.investment.securities') as security - join json_each(security.value, '$.postingIndexes') as anchor on true - `; -} - -function isSafelyClassifiedCashOnlyPosting() { - return sql`exists ( - select 1 from json_each(parent.original_json, '$.tpostings') as original - where original.key = reference.value - and json_extract(original.value, '$.preal') = 'RealPosting' - and json_type(original.value, '$.pamount') = 'array' - and json_array_length(original.value, '$.pamount') > 0 - and not exists ( - select 1 from json_each(original.value, '$.pamount') as component - where json_type(component.value, '$.acommodity') is not 'text' - or not exists ( - select 1 from json_each(activity.context_json, '$.investment.cash.change') as cash - where json_extract(cash.value, '$.commodity') = json_extract(component.value, '$.acommodity') - union all - select 1 from json_each(activity.context_json, '$.investment.cash.balance') as cash - where json_extract(cash.value, '$.commodity') = json_extract(component.value, '$.acommodity') - ) - ) - and not exists ( - select count(*) from json_each(original.value, '$.ptags') as role - where json_extract(role.value, '$[0]') = '_ptype' - having count(distinct json_extract(role.value, '$[1]')) > 1 - or sum(case when json_extract(role.value, '$[1]') in - ('acquire', 'dispose', 'transfer-from', 'transfer-to', 'gain') - then 0 else 1 end) > 0 - ) - )`; -} - -function isVisibleInvestmentActivity() { - return sql`not ( - exists ( - select 1 ${securityAnchorReferences()} - where anchor.value in ( - select value from json_each(activity.context_json, '$.accountPostingIndexes') - ) - ) - and exists ( - select 1 from json_each(activity.context_json, '$.investment.cashPostingIndexes') as cash - where cash.value = reference.value - ) - and not exists ( - select 1 ${securityAnchorReferences()} - where anchor.value = reference.value - ) - and ${isSafelyClassifiedCashOnlyPosting()} - )`; -} - async function countStoredAccountInvestmentActivities( database: Kysely, account: StoredAccount, @@ -523,7 +459,7 @@ async function countStoredAccountInvestmentActivities( and posting.account_name < ${`${account.name};`})) or parent.native_index is null or parent.transacted_json is null then 1 else 0 end) as invalid_count - ${accountPostingReferences(account.name)} + ${fromRawAccountPostingReferences(account.name)} `.execute(database); if ( !counts || @@ -571,7 +507,7 @@ export async function readAccountInvestmentActivityPage( select activity.ordinal, posting.posting_ordinal as posting_index, row_number() over (partition by activity.ordinal order by posting.posting_ordinal asc) as entry_activity_position, count(*) over (partition by activity.ordinal) as entry_activity_count - ${accountPostingReferences(account.name)} + ${fromRawAccountPostingReferences(account.name)} and ${isVisibleInvestmentActivity()} order by coalesce(posting.posting_date, parent.transaction_date) ${order === 'asc' ? sql`asc` : sql`desc`}, activity.ordinal asc, posting.posting_ordinal asc -- 2.54.1 From aa7669f857a3a664185b93c5830f4d4747803f64 Mon Sep 17 00:00:00 2001 From: eleith Date: Tue, 1 Dec 2026 14:06:53 -0800 Subject: [PATCH 03/19] feat(db): write prepared register row references --- .../db/src/reports/investment-posting-rows.ts | 9 ++ .../db/src/reports/prepared-register-rows.ts | 51 ++++++++++ packages/db/src/reports/queries.test.ts | 92 +++++++++++++++++++ packages/db/src/reports/queries.ts | 15 +-- 4 files changed, 161 insertions(+), 6 deletions(-) create mode 100644 packages/db/src/reports/prepared-register-rows.ts diff --git a/packages/db/src/reports/investment-posting-rows.ts b/packages/db/src/reports/investment-posting-rows.ts index 82d28a1..9ac57a0 100644 --- a/packages/db/src/reports/investment-posting-rows.ts +++ b/packages/db/src/reports/investment-posting-rows.ts @@ -1,5 +1,9 @@ import { sql } from 'kysely'; +export const displayedPostingDate = sql`coalesce(posting.posting_date, parent.transaction_date)`; +export const postingPositionInOriginalOrder = sql`row_number() over (partition by activity.ordinal order by posting.posting_ordinal asc)`; +export const postingCountInEntry = sql`count(*) over (partition by activity.ordinal)`; + export function fromRawAccountPostingReferences(accountName: string) { return sql` from account_activity as activity @@ -12,6 +16,11 @@ export function fromRawAccountPostingReferences(accountName: string) { `; } +export function fromVisibleInvestmentPostings(accountName: string) { + return sql`${fromRawAccountPostingReferences(accountName)} + and ${isVisibleInvestmentActivity()}`; +} + export function isVisibleInvestmentActivity() { return sql`not ${isSupportingCashPosting()}`; } diff --git a/packages/db/src/reports/prepared-register-rows.ts b/packages/db/src/reports/prepared-register-rows.ts new file mode 100644 index 0000000..75164c2 --- /dev/null +++ b/packages/db/src/reports/prepared-register-rows.ts @@ -0,0 +1,51 @@ +import { sql, type Kysely } from 'kysely'; +import type { ReportTransaction } from '../database.js'; +import type { ReportDatabase } from '../schema.js'; +import { + displayedPostingDate, + fromVisibleInvestmentPostings, + postingCountInEntry, + postingPositionInOriginalOrder +} from './investment-posting-rows.js'; + +export async function createPreparedRegisterRowsTable(database: Kysely) { + await sql` + create table prepared_register_rows ( + account_name text collate binary not null, + row_kind text not null, + display_date text not null, + entry_ordinal integer not null, + posting_ordinal integer, + position_in_entry integer not null check (position_in_entry >= 1), + entry_row_count integer not null check (entry_row_count >= position_in_entry), + primary key (account_name, row_kind, entry_ordinal, position_in_entry), + foreign key (account_name, entry_ordinal) references account_activity (account_name, ordinal), + check ( + (row_kind = 'entry' and posting_ordinal is null and position_in_entry = 1 and entry_row_count = 1) + or (row_kind = 'posting' and posting_ordinal is not null and posting_ordinal >= 0) + ) + ) strict, without rowid + `.execute(database); +} + +export async function insertRegisterRowsForAccount( + database: ReportTransaction, + accountName: string +) { + await sql` + insert into prepared_register_rows ( + account_name, row_kind, display_date, entry_ordinal, posting_ordinal, position_in_entry, entry_row_count + ) + select account_name, 'entry', account_date, ordinal, null, 1, 1 + from account_activity where account_name = ${accountName} + `.execute(database); + + await sql` + insert into prepared_register_rows ( + account_name, row_kind, display_date, entry_ordinal, posting_ordinal, position_in_entry, entry_row_count + ) + select activity.account_name, 'posting', ${displayedPostingDate}, activity.ordinal, posting.posting_ordinal, + ${postingPositionInOriginalOrder}, ${postingCountInEntry} + ${fromVisibleInvestmentPostings(accountName)} + `.execute(database); +} diff --git a/packages/db/src/reports/queries.test.ts b/packages/db/src/reports/queries.test.ts index 5495488..459924f 100644 --- a/packages/db/src/reports/queries.test.ts +++ b/packages/db/src/reports/queries.test.ts @@ -22,6 +22,10 @@ import { writeReportData as writePublicationData } from './queries.js'; import type { ReportTransaction } from '../database.js'; +import { + createPreparedRegisterRowsTable, + insertRegisterRowsForAccount +} from './prepared-register-rows.js'; import { insertNativeTransaction, attachTransactedTransaction } from '../transactions/index.js'; import { richNativeExportsFixture } from '../transactions/native.fixture.js'; import type { StoredReportData } from './data.js'; @@ -685,6 +689,94 @@ it('pages original selected-account postings across a shared security group and expect(await readFile(path)).toEqual(before); }); +it('prepares entry and posting rows with the original last visible sibling', async () => { + const database = await createDatabase(); + await createPreparedRegisterRowsTable(database); + const account = { id: 'invest01', ...ready('assets:cash') }; + const otherAccount = { id: 'cash0002', ...ready('assets:other') }; + const accountDate = '2026-04-28'; + const entryDate = '2026-04-29'; + const laterPostingDate = '2026-04-30'; + const native = JSON.parse(accountTransactionExportsFixture()[0].originalJson); + native.tdate = entryDate; + for (const posting of native.tpostings) posting.paccount = account.name; + const [laterSecurity, supportingCash, earlierSecurity] = native.tpostings; + laterSecurity.pamount[0].acommodity = 'STOCK'; + laterSecurity.pdate = laterPostingDate; + earlierSecurity.pamount[0].acommodity = 'STOCK'; + earlierSecurity.pdate = null; + native.tpostings.push({ ...supportingCash, paccount: otherAccount.name }); + const json = JSON.stringify(native); + const exports = [{ originalJson: json, transactedJson: json }]; + const [row] = preparedAccountRowsFromExports(exports); + row.accountDate = accountDate; + row.accountPostingIndexes = [0, 1, 2]; + row.investment.cashPostingIndexes = [1]; + row.investment.securities = [ + { + commodity: 'STOCK', + action: 'buy', + change: [], + postingIndexes: [0, 2], + prices: [], + transactedAmounts: [] + } + ]; + const [otherRow] = preparedAccountRowsFromExports(exports); + otherRow.accountPostingIndexes = [3]; + otherRow.investment.cashPostingIndexes = [3]; + + const transaction = await database.startTransaction().execute(); + try { + await importTransactions(transaction, exports); + await writeReportData(transaction, { + journal, + overview: preparedOverview(), + accounts: [account, otherAccount] + }); + await writeAccountRows(transaction, account.name, 0, [row]); + await writeAccountRows(transaction, otherAccount.name, 0, [otherRow]); + await insertRegisterRowsForAccount(transaction, account.name); + await transaction.commit().execute(); + } finally { + if (!transaction.isCommitted && !transaction.isRolledBack) + await transaction.rollback().execute(); + } + + const { rows } = await sql` + select account_name, entry_ordinal, row_kind, display_date, posting_ordinal, position_in_entry, entry_row_count + from prepared_register_rows + order by row_kind, display_date, position_in_entry + `.execute(database); + const entryKey = { account_name: account.name, entry_ordinal: 0 }; + expect(rows).toEqual([ + { + ...entryKey, + row_kind: 'entry', + display_date: accountDate, + posting_ordinal: null, + position_in_entry: 1, + entry_row_count: 1 + }, + { + ...entryKey, + row_kind: 'posting', + display_date: entryDate, + posting_ordinal: 2, + position_in_entry: 2, + entry_row_count: 2 + }, + { + ...entryKey, + row_kind: 'posting', + display_date: laterPostingDate, + posting_ordinal: 0, + position_in_entry: 1, + entry_row_count: 2 + } + ]); +}); + it('keeps security anchors and standalone activities while retaining supporting cash only as context', async () => { const database = await createDatabase(); const cases = [ diff --git a/packages/db/src/reports/queries.ts b/packages/db/src/reports/queries.ts index a7f6834..a40cdc8 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -15,8 +15,12 @@ import { type StoredReportData } from './data.js'; import { + displayedPostingDate, fromRawAccountPostingReferences, - isVisibleInvestmentActivity + fromVisibleInvestmentPostings, + isVisibleInvestmentActivity, + postingCountInEntry, + postingPositionInOriginalOrder } from './investment-posting-rows.js'; const insertBatchSize = 50; @@ -505,11 +509,10 @@ export async function readAccountInvestmentActivityPage( entry_activity_count: number; }>` select activity.ordinal, posting.posting_ordinal as posting_index, - row_number() over (partition by activity.ordinal order by posting.posting_ordinal asc) as entry_activity_position, - count(*) over (partition by activity.ordinal) as entry_activity_count - ${fromRawAccountPostingReferences(account.name)} - and ${isVisibleInvestmentActivity()} - order by coalesce(posting.posting_date, parent.transaction_date) ${order === 'asc' ? sql`asc` : sql`desc`}, + ${postingPositionInOriginalOrder} as entry_activity_position, + ${postingCountInEntry} as entry_activity_count + ${fromVisibleInvestmentPostings(account.name)} + order by ${displayedPostingDate} ${order === 'asc' ? sql`asc` : sql`desc`}, activity.ordinal asc, posting.posting_ordinal asc limit ${limit} offset ${offset} `.execute(database); -- 2.54.1 From 8eff7704945504cf07bb5341cb4a180a2f7a0631 Mon Sep 17 00:00:00 2001 From: eleith Date: Tue, 1 Dec 2026 14:50:22 -0800 Subject: [PATCH 04/19] fix(db): validate raw posting references before preparing rows --- .../db/src/reports/investment-posting-rows.ts | 100 +++++++++++++++++- .../db/src/reports/prepared-register-rows.ts | 8 +- packages/db/src/reports/queries.test.ts | 18 +++- packages/db/src/reports/queries.ts | 66 ++---------- 4 files changed, 129 insertions(+), 63 deletions(-) diff --git a/packages/db/src/reports/investment-posting-rows.ts b/packages/db/src/reports/investment-posting-rows.ts index 9ac57a0..63e69dc 100644 --- a/packages/db/src/reports/investment-posting-rows.ts +++ b/packages/db/src/reports/investment-posting-rows.ts @@ -1,10 +1,11 @@ -import { sql } from 'kysely'; +import { sql, type Kysely } from 'kysely'; +import type { ReportDatabase } from '../schema.js'; export const displayedPostingDate = sql`coalesce(posting.posting_date, parent.transaction_date)`; export const postingPositionInOriginalOrder = sql`row_number() over (partition by activity.ordinal order by posting.posting_ordinal asc)`; export const postingCountInEntry = sql`count(*) over (partition by activity.ordinal)`; -export function fromRawAccountPostingReferences(accountName: string) { +function fromRawAccountPostingReferences(accountName: string) { return sql` from account_activity as activity left join json_each(activity.context_json, '$.accountPostingIndexes') as reference on true @@ -21,7 +22,100 @@ export function fromVisibleInvestmentPostings(accountName: string) { and ${isVisibleInvestmentActivity()}`; } -export function isVisibleInvestmentActivity() { +interface PostingReferenceCounts { + activity_count: number; + first_ordinal: number | null; + last_ordinal: number | null; + posting_count: number; + distinct_posting_count: number; + visiblePostingCount: number | null; + invalid_count: number | null; +} + +export async function validateRawAccountPostingReferences( + database: Kysely, + accountName: string, + expectedEntryCount: number +): Promise { + const counts = await readPostingReferenceCounts(database, accountName); + validatePostingReferenceCounts(counts, expectedEntryCount); +} + +export function readInvestmentPostingCounts( + database: Kysely, + accountName: string +): Promise { + return readPostingReferenceCounts( + database, + accountName, + sql`count(case when ${isVisibleInvestmentActivity()} then reference.key end)` + ); +} + +export function validateInvestmentPostingCounts( + counts: PostingReferenceCounts, + expectedEntryCount: number +): asserts counts is PostingReferenceCounts & { visiblePostingCount: number } { + validatePostingReferenceCounts(counts, expectedEntryCount); + const { visiblePostingCount } = counts; + if ( + visiblePostingCount === null || + !Number.isSafeInteger(visiblePostingCount) || + visiblePostingCount < 0 || + visiblePostingCount > counts.posting_count + ) + throw new Error('Invalid account posting data.'); +} + +async function readPostingReferenceCounts( + database: Kysely, + accountName: string, + visibleCount = sql`null` +): Promise { + const postingBelongsToAccountTree = sql`(posting.account_name = ${accountName} + or (posting.account_name >= ${`${accountName}:`} + and posting.account_name < ${`${accountName};`}))`; + // Hidden supporting cash still participates in every raw membership integrity check. + const { + rows: [counts] + } = await sql` + select count(distinct activity.ordinal) as activity_count, + min(activity.ordinal) as first_ordinal, max(activity.ordinal) as last_ordinal, + count(reference.key) as posting_count, + count(distinct activity.ordinal || ':' || reference.value) as distinct_posting_count, + ${visibleCount} as visiblePostingCount, + sum(case when + json_type(activity.context_json, '$.accountPostingIndexes') is not 'array' + or reference.type is not 'integer' or reference.value < 0 + or posting.posting_ordinal is null + or not ${postingBelongsToAccountTree} + or parent.native_index is null or parent.transacted_json is null + then 1 else 0 end) as invalid_count + ${fromRawAccountPostingReferences(accountName)} + `.execute(database); + if (!counts) throw new Error('Invalid account posting data.'); + return counts; +} + +function validatePostingReferenceCounts( + counts: PostingReferenceCounts, + expectedEntryCount: number +): void { + const hasExpectedEntryOrdinals = + expectedEntryCount === 0 || + (counts.first_ordinal === 0 && counts.last_ordinal === expectedEntryCount - 1); + if ( + counts.activity_count !== expectedEntryCount || + !hasExpectedEntryOrdinals || + !Number.isSafeInteger(counts.posting_count) || + counts.posting_count < 0 || + counts.posting_count !== counts.distinct_posting_count || + (counts.invalid_count !== null && counts.invalid_count !== 0) + ) + throw new Error('Invalid account posting data.'); +} + +function isVisibleInvestmentActivity() { return sql`not ${isSupportingCashPosting()}`; } diff --git a/packages/db/src/reports/prepared-register-rows.ts b/packages/db/src/reports/prepared-register-rows.ts index 75164c2..b849806 100644 --- a/packages/db/src/reports/prepared-register-rows.ts +++ b/packages/db/src/reports/prepared-register-rows.ts @@ -5,7 +5,8 @@ import { displayedPostingDate, fromVisibleInvestmentPostings, postingCountInEntry, - postingPositionInOriginalOrder + postingPositionInOriginalOrder, + validateRawAccountPostingReferences } from './investment-posting-rows.js'; export async function createPreparedRegisterRowsTable(database: Kysely) { @@ -30,8 +31,11 @@ export async function createPreparedRegisterRowsTable(database: Kysely, - account: StoredAccount, - rowCount: number -): Promise { - // Hidden supporting cash still participates in every raw membership integrity check. - const { - rows: [counts] - } = await sql<{ - activity_count: number; - first_ordinal: number | null; - last_ordinal: number | null; - posting_count: number; - distinct_posting_count: number; - investment_activity_count: number; - invalid_count: number | null; - }>` - select count(distinct activity.ordinal) as activity_count, - min(activity.ordinal) as first_ordinal, max(activity.ordinal) as last_ordinal, - count(reference.key) as posting_count, - count(distinct activity.ordinal || ':' || reference.value) as distinct_posting_count, - count(case when ${isVisibleInvestmentActivity()} then reference.key end) as investment_activity_count, - sum(case when - json_type(activity.context_json, '$.accountPostingIndexes') is not 'array' - or reference.type is not 'integer' or reference.value < 0 - or posting.posting_ordinal is null - or not (posting.account_name = ${account.name} - or (posting.account_name >= ${`${account.name}:`} - and posting.account_name < ${`${account.name};`})) - or parent.native_index is null or parent.transacted_json is null - then 1 else 0 end) as invalid_count - ${fromRawAccountPostingReferences(account.name)} - `.execute(database); - if ( - !counts || - counts.activity_count !== rowCount || - (rowCount > 0 && (counts.first_ordinal !== 0 || counts.last_ordinal !== rowCount - 1)) || - !Number.isSafeInteger(counts.posting_count) || - counts.posting_count < 0 || - counts.posting_count !== counts.distinct_posting_count || - !Number.isSafeInteger(counts.investment_activity_count) || - counts.investment_activity_count < 0 || - counts.investment_activity_count > counts.posting_count || - (counts.invalid_count !== null && counts.invalid_count !== 0) - ) - throw new Error('Invalid account posting data.'); - return counts.investment_activity_count; -} - export async function countAccountInvestmentActivities( database: Kysely, account: StoredAccount ): Promise { const context = await readAccountPageContext(database, account); - return context - ? countStoredAccountInvestmentActivities(database, account, context.rowCount) - : null; + if (!context) return null; + const counts = await readInvestmentPostingCounts(database, account.name); + validateInvestmentPostingCounts(counts, context.rowCount); + return counts.visiblePostingCount; } export async function readAccountInvestmentActivityPage( @@ -500,7 +452,9 @@ export async function readAccountInvestmentActivityPage( const context = await readAccountPageContext(database, account); if (!context) return null; const { rowCount, summary } = context; - const activityCount = await countStoredAccountInvestmentActivities(database, account, rowCount); + const counts = await readInvestmentPostingCounts(database, account.name); + validateInvestmentPostingCounts(counts, rowCount); + const activityCount = counts.visiblePostingCount; const { order, offset, limit } = options; const { rows: references } = await sql<{ ordinal: number; -- 2.54.1 From 63c5ce657d7d101dac832166497f7d14c9e3a1d2 Mon Sep 17 00:00:00 2001 From: eleith Date: Tue, 1 Dec 2026 16:13:59 -0800 Subject: [PATCH 05/19] feat(snapshots): publish prepared register row references --- .changeset/prepare-register-rows.md | 5 + packages/db/src/migrate.ts | 4 +- .../migrations/008_prepared_register_rows.ts | 23 ++++ packages/db/src/reports/index.ts | 1 + .../db/src/reports/prepared-register-rows.ts | 23 +--- packages/db/src/reports/queries.test.ts | 6 +- packages/db/src/schema.ts | 13 ++- .../snapshots/src/reports/publication.test.ts | 109 ++++++++++++++---- packages/snapshots/src/reports/publication.ts | 9 ++ 9 files changed, 143 insertions(+), 50 deletions(-) create mode 100644 .changeset/prepare-register-rows.md create mode 100644 packages/db/src/migrations/008_prepared_register_rows.ts diff --git a/.changeset/prepare-register-rows.md b/.changeset/prepare-register-rows.md new file mode 100644 index 0000000..f0a5d40 --- /dev/null +++ b/.changeset/prepare-register-rows.md @@ -0,0 +1,5 @@ +--- +'@hledger-reports/web': patch +--- + +Save register row references during preparation. Upgrade web and worker together, then use Settings to prepare a new report. The upgraded app cannot read the previous saved report and does not change it in place. After preparing, reopen bookmarked registers from Accounts because their links may have changed. diff --git a/packages/db/src/migrate.ts b/packages/db/src/migrate.ts index e293743..191cf40 100644 --- a/packages/db/src/migrate.ts +++ b/packages/db/src/migrate.ts @@ -7,6 +7,7 @@ import * as nativeTransactions from './migrations/004_native_transactions.js'; import * as sharedAccountTransactions from './migrations/005_shared_account_transactions.js'; import * as transactionDates from './migrations/006_transaction_dates.js'; import * as singleSavedReport from './migrations/007_single_saved_report.js'; +import * as preparedRegisterRows from './migrations/008_prepared_register_rows.js'; import type { ReportDatabase } from './schema.js'; export async function runMigrations(database: Kysely): Promise { @@ -21,7 +22,8 @@ export async function runMigrations(database: Kysely): Promise): Promise { + await sql` + create table prepared_register_rows ( + account_name text collate binary not null, + row_kind text not null, + display_date text not null, + entry_ordinal integer not null, + posting_ordinal integer, + position_in_entry integer not null check (position_in_entry >= 1), + entry_row_count integer not null check (entry_row_count >= position_in_entry), + primary key (account_name, row_kind, entry_ordinal, position_in_entry), + foreign key (account_name, entry_ordinal) references account_activity (account_name, ordinal), + check ( + (row_kind = 'entry' and posting_ordinal is null and position_in_entry = 1 and entry_row_count = 1) + or (row_kind = 'posting' and posting_ordinal is not null and posting_ordinal >= 0) + ) + ) strict, without rowid + `.execute(database); + await sql`PRAGMA user_version = 5`.execute(database); +} diff --git a/packages/db/src/reports/index.ts b/packages/db/src/reports/index.ts index 9dba059..467228c 100644 --- a/packages/db/src/reports/index.ts +++ b/packages/db/src/reports/index.ts @@ -27,5 +27,6 @@ export type { AccountActivityPageOptions, AccountInvestmentActivityPage } from './queries.js'; +export { insertRegisterRowsForAccount } from './prepared-register-rows.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 b849806..d7489a9 100644 --- a/packages/db/src/reports/prepared-register-rows.ts +++ b/packages/db/src/reports/prepared-register-rows.ts @@ -1,6 +1,5 @@ -import { sql, type Kysely } from 'kysely'; +import { sql } from 'kysely'; import type { ReportTransaction } from '../database.js'; -import type { ReportDatabase } from '../schema.js'; import { displayedPostingDate, fromVisibleInvestmentPostings, @@ -9,26 +8,6 @@ import { validateRawAccountPostingReferences } from './investment-posting-rows.js'; -export async function createPreparedRegisterRowsTable(database: Kysely) { - await sql` - create table prepared_register_rows ( - account_name text collate binary not null, - row_kind text not null, - display_date text not null, - entry_ordinal integer not null, - posting_ordinal integer, - position_in_entry integer not null check (position_in_entry >= 1), - entry_row_count integer not null check (entry_row_count >= position_in_entry), - primary key (account_name, row_kind, entry_ordinal, position_in_entry), - foreign key (account_name, entry_ordinal) references account_activity (account_name, ordinal), - check ( - (row_kind = 'entry' and posting_ordinal is null and position_in_entry = 1 and entry_row_count = 1) - or (row_kind = 'posting' and posting_ordinal is not null and posting_ordinal >= 0) - ) - ) strict, without rowid - `.execute(database); -} - export async function insertRegisterRowsForAccount( database: ReportTransaction, accountName: string, diff --git a/packages/db/src/reports/queries.test.ts b/packages/db/src/reports/queries.test.ts index 22d5c0b..0e18616 100644 --- a/packages/db/src/reports/queries.test.ts +++ b/packages/db/src/reports/queries.test.ts @@ -22,10 +22,7 @@ import { writeReportData as writePublicationData } from './queries.js'; import type { ReportTransaction } from '../database.js'; -import { - createPreparedRegisterRowsTable, - insertRegisterRowsForAccount -} from './prepared-register-rows.js'; +import { insertRegisterRowsForAccount } from './prepared-register-rows.js'; import { insertNativeTransaction, attachTransactedTransaction } from '../transactions/index.js'; import { richNativeExportsFixture } from '../transactions/native.fixture.js'; import type { StoredReportData } from './data.js'; @@ -691,7 +688,6 @@ it('pages original selected-account postings across a shared security group and it('prepares entry and posting rows with the original last visible sibling', async () => { const database = await createDatabase(); - await createPreparedRegisterRowsTable(database); const account = { id: 'invest01', ...ready('assets:cash') }; const otherAccount = { id: 'cash0002', ...ready('assets:other') }; const accountDate = '2026-04-28'; diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 3a2e630..3f4896f 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -1,4 +1,4 @@ -export const reportSchemaVersion = 4; +export const reportSchemaVersion = 5; interface PublicationTable { singleton: 1; @@ -26,6 +26,16 @@ interface AccountActivityTable { context_json: string; } +interface PreparedRegisterRowTable { + account_name: string; + row_kind: 'entry' | 'posting'; + display_date: string; + entry_ordinal: number; + posting_ordinal: number | null; + position_in_entry: number; + entry_row_count: number; +} + interface AccountActivitySummaryTable { account_name: string; has_multiple_amounts: 0 | 1; @@ -55,6 +65,7 @@ export interface ReportDatabase { publication: PublicationTable; accounts: AccountTable; account_activity: AccountActivityTable; + prepared_register_rows: PreparedRegisterRowTable; account_activity_summaries: AccountActivitySummaryTable; transactions: NativeTransactionTable; transaction_postings: TransactionPostingTable; diff --git a/packages/snapshots/src/reports/publication.test.ts b/packages/snapshots/src/reports/publication.test.ts index b4fd9f9..c8547ee 100644 --- a/packages/snapshots/src/reports/publication.test.ts +++ b/packages/snapshots/src/reports/publication.test.ts @@ -24,6 +24,7 @@ import { ambiguous, accountTransactionExportsFixture, preparedOverview as fixture, + preparedAccountRowsFromExports, journal, ready, preparedAccountRows as rows @@ -157,6 +158,14 @@ it('commits and closes the complete report before replacing the slot', async () await stage.writeRows('assets:cash', transactions.slice(0, 50)); await stage.writeRows('assets:cash', transactions.slice(50)); await stage.writeRows('assets:cash', []); + const otherAccount = 'assets:comparison'; + const otherTransaction = JSON.stringify(nativeTransactionFixture(53, [otherAccount])); + await stage.transactions.insertOriginal(otherTransaction); + await stage.transactions.attachTransacted(otherTransaction); + const otherRows = preparedAccountRowsFromExports([ + { originalJson: otherTransaction, transactedJson: otherTransaction } + ]); + await stage.writeRows(otherAccount, otherRows); const rename = fs.rename; const inspected = vi.fn(); vi.spyOn(fs, 'rename').mockImplementation(async (source, destination) => { @@ -164,11 +173,35 @@ it('commits and closes the complete report before replacing the slot', async () expect(await selected()).toEqual(pinned); expect(await readInvestmentOverview(pinned)).toBeNull(); expect(closed).toHaveBeenCalledOnce(); + const staged = new DatabaseSync(source, { readOnly: true }); + try { + const preparedCounts = staged + .prepare( + ` + select account_name, row_kind, count(*) as total from prepared_register_rows + group by account_name, row_kind order by account_name, row_kind + ` + ) + .all(); + expect(preparedCounts).toEqual([ + { account_name: 'assets:cash', row_kind: 'entry', total: 52 }, + { account_name: 'assets:cash', row_kind: 'posting', total: 52 }, + { account_name: otherAccount, row_kind: 'entry', total: 1 }, + { account_name: otherAccount, row_kind: 'posting', total: 1 } + ]); + } finally { + staged.close(); + } inspected(); } await rename(source, destination); }); - await stage.publish(fixture(), [ready('assets:cash', 52)], journal, investment); + await stage.publish( + fixture(), + [ready('assets:cash', 52), ready(otherAccount)], + journal, + investment + ); expect(inspected).toHaveBeenCalledOnce(); const publication = await selected(); expect(publication.overview).toEqual(fixture()); @@ -208,6 +241,22 @@ it('commits and closes the complete report before replacing the slot', async () expect((await fs.stat(reportPath())).mode & 0o777).toBe(0o600); }); +it('keeps the previous publication if preparing register rows fails', async () => { + await publish(); + const incumbent = await fs.readFile(reportPath()); + const incumbentFiles = await filesInSlot(); + const stage = await createReportStage(snapshots, newer); + await importNativeExports(stage); + const [row] = rows(); + await stage.writeRows('assets:cash', [{ ...row, accountPostingIndexes: [0, 0] }]); + + await expect(stage.publish(fixture(), [ready()], journal)).rejects.toSatisfy( + safeError('Unable to prepare reports') + ); + expect(await fs.readFile(reportPath())).toEqual(incumbent); + expect(await filesInSlot()).toEqual(incumbentFiles); +}); + it('does not mix two publications from different attempts of the same request', async () => { vi.spyOn(crypto, 'randomUUID') .mockReturnValueOnce('00000000-0000-4000-8000-000000000000') @@ -523,27 +572,32 @@ it('reuses IDs by exact account identity and avoids collisions with removed and expect(previous.accounts.map((account) => account.id)).toEqual(['00000000', '00000001']); generated.push(0, 1, 2, 2, 3); const stage = await createReportStage(snapshots, newer, previous.accounts); - const names = ['資産/../銀行:Ω', 'new:Ω', 'NEW:Ω']; - await importNativeExports(stage); - for (const name of names) await stage.writeRows(name, rows()); + const accounts = [ + { name: '資産/../銀行:Ω', id: '00000001', nativeIndex: 1 }, + { name: 'new:Ω', id: '00000002', nativeIndex: 2 }, + { name: 'NEW:Ω', id: '00000003', nativeIndex: 3 } + ]; + for (const { name, nativeIndex } of accounts) { + const json = JSON.stringify(nativeTransactionFixture(nativeIndex, [name])); + await stage.transactions.insertOriginal(json); + await stage.transactions.attachTransacted(json); + await stage.writeRows( + name, + preparedAccountRowsFromExports([{ originalJson: json, transactedJson: json }]) + ); + } await stage.publish( fixture(), - names.map((name) => ready(name)), + accounts.map(({ name }) => ready(name)), journal ); const publication = await selected(); - expect(publication.accounts.map((account) => account.id)).toEqual([ - '00000001', - '00000002', - '00000003' - ]); - for (const account of publication.accounts) { - const page = await readAccountPage(publication, account.id, { - order: 'asc', - offset: 0, - limit: 50 - }); - expect(page?.rows).toEqual(rows()); + expect(publication.accounts.map(({ name, id }) => ({ name, id }))).toEqual( + accounts.map(({ name, id }) => ({ name, id })) + ); + for (const { id, nativeIndex } of accounts) { + const page = await readAccountPage(publication, id, { order: 'asc', offset: 0, limit: 50 }); + expect(page?.rows.map(({ transaction }) => transaction.index)).toEqual([nativeIndex]); } }); @@ -926,16 +980,29 @@ it('leaves a slot with an unexpected SQLite sidecar untouched, even on explicit expect(await fs.readFile(wal, 'utf8')).toBe('fictional external sidecar'); }); -it('does not migrate an unsupported slot on read; explicit preparation can replace it', async () => { +it('does not migrate a version 4 slot on read; explicit preparation replaces it', async () => { await publish(); - withReportFile((db) => db.exec('PRAGMA user_version = 3')); + withReportFile((db) => + db.exec(` + DROP TABLE prepared_register_rows; + DELETE FROM kysely_migration WHERE name = '008_prepared_register_rows'; + PRAGMA user_version = 4; + `) + ); const bytes = await fs.readFile(reportPath()); await expect(readReportPublication(snapshots)).rejects.toSatisfy( safeError('Unable to read overview') ); expect(await fs.readFile(reportPath())).toEqual(bytes); - await publish(newer); - expect(await readOverview(snapshots)).toEqual(fixture()); + const rename = fs.rename; + const replace = vi.spyOn(fs, 'rename').mockImplementation(async (source, destination) => { + if (destination === reportPath()) expect(await fs.readFile(reportPath())).toEqual(bytes); + await rename(source, destination); + }); + const replacement = { ...fixture(), preparedAt: 'explicit version 5 preparation' }; + await publish(newer, replacement); + expect(replace).toHaveBeenCalledWith(expect.any(String), reportPath()); + expect(await readOverview(snapshots)).toEqual(replacement); }); it('starts with an empty slot and never reads or modifies legacy report sets', async () => { diff --git a/packages/snapshots/src/reports/publication.ts b/packages/snapshots/src/reports/publication.ts index 58b8793..3edaddf 100644 --- a/packages/snapshots/src/reports/publication.ts +++ b/packages/snapshots/src/reports/publication.ts @@ -16,6 +16,7 @@ import { import { AccountActivitySummaryBuilder, hasOverviewContainers, + insertRegisterRowsForAccount, isAccountCatalog, isAccountId, isAccountSummary, @@ -316,6 +317,13 @@ export async function createReportStage( { id: string; rowCount: number; summaryBuilder: AccountActivitySummaryBuilder } >(); let currentName: string | undefined; + + async function writePreparedRegisterRows() { + for (const [name, { rowCount: entryCount }] of writtenAccounts) { + if (entryCount > 0) await insertRegisterRowsForAccount(writer, name, entryCount); + } + } + async function operation(action: () => Promise): Promise { try { if (state !== 'active') throw new Error(); @@ -433,6 +441,7 @@ export async function createReportStage( } ); await writeAccountActivitySummaries(writer, activitySummaries); + await writePreparedRegisterRows(); await writer.commit().execute(); await closeDatabase(); const outcome = await replaceSavedReportIfNewer( -- 2.54.1 From e2689cb957b9dda61578c274a78c3840a1cfbd31 Mon Sep 17 00:00:00 2001 From: eleith Date: Tue, 1 Dec 2026 16:36:45 -0800 Subject: [PATCH 06/19] feat(db): page prepared register row references --- .../migrations/008_prepared_register_rows.ts | 13 ++++++++ .../db/src/reports/prepared-register-rows.ts | 30 +++++++++++++++++- packages/db/src/reports/queries.test.ts | 31 ++++++++++++++++++- 3 files changed, 72 insertions(+), 2 deletions(-) diff --git a/packages/db/src/migrations/008_prepared_register_rows.ts b/packages/db/src/migrations/008_prepared_register_rows.ts index 0422008..ac3a16b 100644 --- a/packages/db/src/migrations/008_prepared_register_rows.ts +++ b/packages/db/src/migrations/008_prepared_register_rows.ts @@ -19,5 +19,18 @@ export async function up(database: Kysely): Promise { ) ) strict, without rowid `.execute(database); + for (const order of ['asc', 'desc'] as const) { + await database.schema + .createIndex(`prepared_register_rows_date_${order}`) + .on('prepared_register_rows') + .columns([ + 'account_name', + 'row_kind', + `display_date ${order}`, + 'entry_ordinal asc', + 'position_in_entry asc' + ]) + .execute(); + } await sql`PRAGMA user_version = 5`.execute(database); } diff --git a/packages/db/src/reports/prepared-register-rows.ts b/packages/db/src/reports/prepared-register-rows.ts index d7489a9..795b40d 100644 --- a/packages/db/src/reports/prepared-register-rows.ts +++ b/packages/db/src/reports/prepared-register-rows.ts @@ -1,5 +1,6 @@ -import { sql } from 'kysely'; +import { sql, type Kysely } from 'kysely'; import type { ReportTransaction } from '../database.js'; +import type { ReportDatabase } from '../schema.js'; import { displayedPostingDate, fromVisibleInvestmentPostings, @@ -8,6 +9,33 @@ import { validateRawAccountPostingReferences } from './investment-posting-rows.js'; +const registerPageSize = 50; + +export function readRegisterRowReferencePage( + database: Kysely, + accountName: string, + rowKind: ReportDatabase['prepared_register_rows']['row_kind'], + { order, offset }: { order: 'asc' | 'desc'; offset: number } +) { + return database + .selectFrom('prepared_register_rows') + .select([ + 'display_date', + 'entry_ordinal', + 'posting_ordinal', + 'position_in_entry', + 'entry_row_count' + ]) + .where('account_name', '=', accountName) + .where('row_kind', '=', rowKind) + .orderBy('display_date', order) + .orderBy('entry_ordinal', 'asc') + .orderBy('position_in_entry', 'asc') + .offset(offset) + .limit(registerPageSize) + .execute(); +} + export async function insertRegisterRowsForAccount( database: ReportTransaction, accountName: string, diff --git a/packages/db/src/reports/queries.test.ts b/packages/db/src/reports/queries.test.ts index 0e18616..68b2cac 100644 --- a/packages/db/src/reports/queries.test.ts +++ b/packages/db/src/reports/queries.test.ts @@ -22,7 +22,10 @@ import { writeReportData as writePublicationData } from './queries.js'; import type { ReportTransaction } from '../database.js'; -import { insertRegisterRowsForAccount } from './prepared-register-rows.js'; +import { + insertRegisterRowsForAccount, + readRegisterRowReferencePage +} from './prepared-register-rows.js'; import { insertNativeTransaction, attachTransactedTransaction } from '../transactions/index.js'; import { richNativeExportsFixture } from '../transactions/native.fixture.js'; import type { StoredReportData } from './data.js'; @@ -612,6 +615,7 @@ it('pages original selected-account postings across a shared security group and transaction, new Map([[account.name, preparedActivitySummary(rows)]]) ); + await insertRegisterRowsForAccount(transaction, account.name, rows.length); await transaction.commit().execute(); } finally { if (!transaction.isCommitted && !transaction.isRolledBack) @@ -640,6 +644,24 @@ it('pages original selected-account postings across a shared security group and const main = rows[0].accountPostingIndexes.map((index) => reference(0, index)); const ascending = [reference(1, 1), reference(2, 1), ...main, reference(1, 0), reference(2, 0)]; const descending = [...main, reference(1, 0), reference(2, 0), reference(1, 1), reference(2, 1)]; + for (const [order, ordered] of [ + ['asc', ascending], + ['desc', descending] + ] as const) { + for (const offset of [0, 50]) { + const storedPage = await readRegisterRowReferencePage(reader, account.name, 'posting', { + order, + offset + }); + expect( + storedPage.map(({ entry_ordinal, posting_ordinal }) => [entry_ordinal, posting_ordinal]) + ).toEqual( + ordered + .slice(offset, offset + 50) + .map(({ row, postingIndex }) => [rows.indexOf(row), postingIndex]) + ); + } + } expect(await countAccountInvestmentActivities(reader, account)).toBe(59); const first = await readAccountInvestmentActivityPage(pageReader, account, { order: 'desc', @@ -785,6 +807,13 @@ it('prepares entry and posting rows with the original last visible sibling', asy entry_row_count: 2 } ]); + + const entryPage = { order: 'asc', offset: 0 } as const; + const entryRows = await readRegisterRowReferencePage(database, account.name, 'entry', entryPage); + expect(entryRows.map(({ display_date }) => display_date)).toEqual([accountDate]); + expect( + await readRegisterRowReferencePage(database, otherAccount.name, 'entry', entryPage) + ).toEqual([]); }); it('keeps security anchors and standalone activities while retaining supporting cash only as context', async () => { -- 2.54.1 From ef91cef71d342c30ab7e6b42a17b60a81b2d3aa4 Mon Sep 17 00:00:00 2001 From: eleith Date: Wed, 2 Dec 2026 05:21:55 -0800 Subject: [PATCH 07/19] refactor(registers): share the saved page size --- apps/web/src/lib/registers/cash/data.ts | 2 +- apps/web/src/lib/registers/investment/data.ts | 2 +- packages/db/package.json | 5 +++++ packages/db/src/register-page.ts | 1 + packages/db/src/reports/prepared-register-rows.ts | 3 +-- packages/db/src/reports/queries.ts | 4 ++-- packages/snapshots/package.json | 5 +++++ packages/snapshots/src/register-page.ts | 1 + 8 files changed, 17 insertions(+), 6 deletions(-) create mode 100644 packages/db/src/register-page.ts create mode 100644 packages/snapshots/src/register-page.ts diff --git a/apps/web/src/lib/registers/cash/data.ts b/apps/web/src/lib/registers/cash/data.ts index 0d468e9..a7800cd 100644 --- a/apps/web/src/lib/registers/cash/data.ts +++ b/apps/web/src/lib/registers/cash/data.ts @@ -12,7 +12,7 @@ export interface RegisterRow { balance: ReportedAmount[]; } -export const rowBatchSize = 50; +export { registerPageSize as rowBatchSize } from '@hledger-reports/snapshots/register-page'; export interface RegisterPageRequest { accountId: string; diff --git a/apps/web/src/lib/registers/investment/data.ts b/apps/web/src/lib/registers/investment/data.ts index 61f15a3..642d26c 100644 --- a/apps/web/src/lib/registers/investment/data.ts +++ b/apps/web/src/lib/registers/investment/data.ts @@ -5,7 +5,7 @@ import type { ReportedAmount } from '@hledger-reports/hledger'; -export const activityBatchSize = 50; +export { registerPageSize as activityBatchSize } from '@hledger-reports/snapshots/register-page'; export interface ActivityBatchRequest { accountId: string; diff --git a/packages/db/package.json b/packages/db/package.json index 8177827..22c3f72 100644 --- a/packages/db/package.json +++ b/packages/db/package.json @@ -14,6 +14,11 @@ "types": "./dist/src/reports/index.d.ts", "import": "./dist/src/reports/index.js" }, + "./register-page": { + "development": "./src/register-page.ts", + "types": "./dist/src/register-page.d.ts", + "import": "./dist/src/register-page.js" + }, "./transactions": { "development": "./src/transactions/index.ts", "types": "./dist/src/transactions/index.d.ts", diff --git a/packages/db/src/register-page.ts b/packages/db/src/register-page.ts new file mode 100644 index 0000000..d5716e1 --- /dev/null +++ b/packages/db/src/register-page.ts @@ -0,0 +1 @@ +export const registerPageSize = 50; diff --git a/packages/db/src/reports/prepared-register-rows.ts b/packages/db/src/reports/prepared-register-rows.ts index 795b40d..f6b8d89 100644 --- a/packages/db/src/reports/prepared-register-rows.ts +++ b/packages/db/src/reports/prepared-register-rows.ts @@ -1,5 +1,6 @@ import { sql, type Kysely } from 'kysely'; import type { ReportTransaction } from '../database.js'; +import { registerPageSize } from '../register-page.js'; import type { ReportDatabase } from '../schema.js'; import { displayedPostingDate, @@ -9,8 +10,6 @@ import { validateRawAccountPostingReferences } from './investment-posting-rows.js'; -const registerPageSize = 50; - export function readRegisterRowReferencePage( database: Kysely, accountName: string, diff --git a/packages/db/src/reports/queries.ts b/packages/db/src/reports/queries.ts index 400af5f..fe11666 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -1,6 +1,7 @@ import type { PreparedAccountRow } from '@hledger-reports/hledger'; import { decodeNativeTransaction, prepareTransaction } from '@hledger-reports/hledger/transactions'; import { sql, type Kysely } from 'kysely'; +import { registerPageSize } from '../register-page.js'; import type { ReportDatabase } from '../schema.js'; import { hasAccountActivitySummary, @@ -24,7 +25,6 @@ import { } from './investment-posting-rows.js'; const insertBatchSize = 50; -const maxPageRows = 50; export interface AccountActivityPage { rows: PreparedAccountRow[]; @@ -349,7 +349,7 @@ function assertPageOptions({ order, offset, limit }: AccountActivityPageOptions) offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || - limit > maxPageRows + limit > registerPageSize ) throw new Error('Invalid account page.'); } diff --git a/packages/snapshots/package.json b/packages/snapshots/package.json index 6548ba3..6f66e14 100644 --- a/packages/snapshots/package.json +++ b/packages/snapshots/package.json @@ -8,6 +8,11 @@ "development": "./src/index.ts", "types": "./dist/src/index.d.ts", "import": "./dist/src/index.js" + }, + "./register-page": { + "development": "./src/register-page.ts", + "types": "./dist/src/register-page.d.ts", + "import": "./dist/src/register-page.js" } }, "files": [ diff --git a/packages/snapshots/src/register-page.ts b/packages/snapshots/src/register-page.ts new file mode 100644 index 0000000..71cb873 --- /dev/null +++ b/packages/snapshots/src/register-page.ts @@ -0,0 +1 @@ +export { registerPageSize } from '@hledger-reports/db/register-page'; -- 2.54.1 From 497682d03c42d14b9a497f31a9fb564a9f9f4760 Mon Sep 17 00:00:00 2001 From: eleith Date: Wed, 2 Dec 2026 06:41:38 -0800 Subject: [PATCH 08/19] feat(snapshots): record prepared register posting counts --- .../migrations/008_prepared_register_rows.ts | 6 ++ packages/db/src/reports/index.ts | 2 +- .../db/src/reports/prepared-register-rows.ts | 13 +++- packages/db/src/reports/queries.test.ts | 27 ++++++-- packages/db/src/reports/queries.ts | 1 + packages/db/src/schema.ts | 1 + .../snapshots/src/reports/publication.test.ts | 65 ++++++++++++++++++- packages/snapshots/src/reports/publication.ts | 10 +-- 8 files changed, 109 insertions(+), 16 deletions(-) diff --git a/packages/db/src/migrations/008_prepared_register_rows.ts b/packages/db/src/migrations/008_prepared_register_rows.ts index ac3a16b..0e34017 100644 --- a/packages/db/src/migrations/008_prepared_register_rows.ts +++ b/packages/db/src/migrations/008_prepared_register_rows.ts @@ -32,5 +32,11 @@ export async function up(database: Kysely): Promise { ]) .execute(); } + await database.schema + .alterTable('account_activity_summaries') + .addColumn('posting_row_count', 'integer', (column) => + column.check(sql`posting_row_count >= 0`) + ) + .execute(); await sql`PRAGMA user_version = 5`.execute(database); } diff --git a/packages/db/src/reports/index.ts b/packages/db/src/reports/index.ts index 467228c..9ce7dc7 100644 --- a/packages/db/src/reports/index.ts +++ b/packages/db/src/reports/index.ts @@ -27,6 +27,6 @@ export type { AccountActivityPageOptions, AccountInvestmentActivityPage } from './queries.js'; -export { insertRegisterRowsForAccount } from './prepared-register-rows.js'; +export { writeRegisterRowsAndPostingCount } from './prepared-register-rows.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 f6b8d89..cf4b754 100644 --- a/packages/db/src/reports/prepared-register-rows.ts +++ b/packages/db/src/reports/prepared-register-rows.ts @@ -35,7 +35,7 @@ export function readRegisterRowReferencePage( .execute(); } -export async function insertRegisterRowsForAccount( +export async function writeRegisterRowsAndPostingCount( database: ReportTransaction, accountName: string, expectedEntryCount: number @@ -50,7 +50,7 @@ export async function insertRegisterRowsForAccount( from account_activity where account_name = ${accountName} `.execute(database); - await sql` + const { numAffectedRows } = await sql` insert into prepared_register_rows ( account_name, row_kind, display_date, entry_ordinal, posting_ordinal, position_in_entry, entry_row_count ) @@ -58,4 +58,13 @@ export async function insertRegisterRowsForAccount( ${postingPositionInOriginalOrder}, ${postingCountInEntry} ${fromVisibleInvestmentPostings(accountName)} `.execute(database); + const insertedPostingRowCount = Number(numAffectedRows); + if (!Number.isSafeInteger(insertedPostingRowCount) || insertedPostingRowCount < 0) + throw new Error('Invalid prepared posting count.'); + const { numUpdatedRows } = await database + .updateTable('account_activity_summaries') + .set({ posting_row_count: insertedPostingRowCount }) + .where('account_name', '=', accountName) + .executeTakeFirstOrThrow(); + if (numUpdatedRows !== 1n) throw new Error('Missing account activity summary.'); } diff --git a/packages/db/src/reports/queries.test.ts b/packages/db/src/reports/queries.test.ts index 68b2cac..0bd1b31 100644 --- a/packages/db/src/reports/queries.test.ts +++ b/packages/db/src/reports/queries.test.ts @@ -23,8 +23,8 @@ import { } from './queries.js'; import type { ReportTransaction } from '../database.js'; import { - insertRegisterRowsForAccount, - readRegisterRowReferencePage + readRegisterRowReferencePage, + writeRegisterRowsAndPostingCount } from './prepared-register-rows.js'; import { insertNativeTransaction, attachTransactedTransaction } from '../transactions/index.js'; import { richNativeExportsFixture } from '../transactions/native.fixture.js'; @@ -615,7 +615,7 @@ it('pages original selected-account postings across a shared security group and transaction, new Map([[account.name, preparedActivitySummary(rows)]]) ); - await insertRegisterRowsForAccount(transaction, account.name, rows.length); + await writeRegisterRowsAndPostingCount(transaction, account.name, rows.length); await transaction.commit().execute(); } finally { if (!transaction.isCommitted && !transaction.isRolledBack) @@ -752,10 +752,17 @@ it('prepares entry and posting rows with the original last visible sibling', asy overview: preparedOverview(), accounts: [account, otherAccount] }); + await writeAccountActivitySummaries( + transaction, + new Map([ + [account.name, preparedActivitySummary([row])], + [otherAccount.name, preparedActivitySummary([otherRow])] + ]) + ); await writeAccountRows(transaction, otherAccount.name, 0, [otherRow]); const duplicateSupportingCash = { ...row, accountPostingIndexes: [0, 1, 1, 2] }; await writeAccountRows(transaction, account.name, 0, [duplicateSupportingCash]); - await expect(insertRegisterRowsForAccount(transaction, account.name, 1)).rejects.toThrow( + await expect(writeRegisterRowsAndPostingCount(transaction, account.name, 1)).rejects.toThrow( 'Invalid account posting data.' ); const { rows: partialRows } = await sql`select 1 from prepared_register_rows`.execute( @@ -768,7 +775,7 @@ it('prepares entry and posting rows with the original last visible sibling', asy .where('account_name', '=', account.name) .execute(); await writeAccountRows(transaction, account.name, 0, [row]); - await insertRegisterRowsForAccount(transaction, account.name, 1); + await writeRegisterRowsAndPostingCount(transaction, account.name, 1); await transaction.commit().execute(); } finally { if (!transaction.isCommitted && !transaction.isRolledBack) @@ -808,6 +815,16 @@ it('prepares entry and posting rows with the original last visible sibling', asy } ]); + const postingCounts = await database + .selectFrom('account_activity_summaries') + .select(['account_name', 'posting_row_count']) + .orderBy('account_name') + .execute(); + expect(postingCounts).toEqual([ + { account_name: account.name, posting_row_count: 2 }, + { account_name: otherAccount.name, posting_row_count: null } + ]); + const entryPage = { order: 'asc', offset: 0 } as const; const entryRows = await readRegisterRowReferencePage(database, account.name, 'entry', entryPage); expect(entryRows.map(({ display_date }) => display_date)).toEqual([accountDate]); diff --git a/packages/db/src/reports/queries.ts b/packages/db/src/reports/queries.ts index fe11666..5ac5941 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -143,6 +143,7 @@ export async function writeAccountActivitySummaries( throw new Error('Invalid account activity summary.'); return { account_name: name, + posting_row_count: null, has_multiple_amounts: summary.hasMultipleAmounts ? 1 : 0, has_multiple_commodities: summary.hasMultipleCommodities ? 1 : 0, ending_balance_json: JSON.stringify(summary.endingBalance), diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 3f4896f..a691d42 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -38,6 +38,7 @@ interface PreparedRegisterRowTable { interface AccountActivitySummaryTable { account_name: string; + posting_row_count: number | null; has_multiple_amounts: 0 | 1; has_multiple_commodities: 0 | 1; ending_balance_json: string; diff --git a/packages/snapshots/src/reports/publication.test.ts b/packages/snapshots/src/reports/publication.test.ts index c8547ee..26cb319 100644 --- a/packages/snapshots/src/reports/publication.test.ts +++ b/packages/snapshots/src/reports/publication.test.ts @@ -189,6 +189,18 @@ it('commits and closes the complete report before replacing the slot', async () { account_name: otherAccount, row_kind: 'entry', total: 1 }, { account_name: otherAccount, row_kind: 'posting', total: 1 } ]); + const storedPostingCounts = staged + .prepare( + ` + select account_name, posting_row_count as total from account_activity_summaries order by account_name + ` + ) + .all(); + expect(storedPostingCounts).toEqual( + preparedCounts + .filter(({ row_kind }) => row_kind === 'posting') + .map(({ account_name, total }) => ({ account_name, total })) + ); } finally { staged.close(); } @@ -241,18 +253,51 @@ it('commits and closes the complete report before replacing the slot', async () expect((await fs.stat(reportPath())).mode & 0o777).toBe(0o600); }); -it('keeps the previous publication if preparing register rows fails', async () => { +it('keeps the previous publication if the posting count cannot be saved', async () => { await publish(); const incumbent = await fs.readFile(reportPath()); const incumbentFiles = await filesInSlot(); const stage = await createReportStage(snapshots, newer); await importNativeExports(stage); - const [row] = rows(); - await stage.writeRows('assets:cash', [{ ...row, accountPostingIndexes: [0, 0] }]); + await stage.writeRows('assets:cash', rows()); + const writeSummaries = reports.writeAccountActivitySummaries; + vi.spyOn(reports, 'writeAccountActivitySummaries').mockImplementationOnce( + async (database, summaries) => { + await writeSummaries(database, summaries); + await database + .deleteFrom('account_activity_summaries') + .where('account_name', '=', 'assets:cash') + .execute(); + } + ); + const writeRegisterRows = reports.writeRegisterRowsAndPostingCount; + let failedWrite: + | { error: unknown; rowKinds: string[]; writer: databases.ReportTransaction } + | undefined; + vi.spyOn(reports, 'writeRegisterRowsAndPostingCount').mockImplementationOnce( + async (writer, accountName, entryCount) => { + try { + await writeRegisterRows(writer, accountName, entryCount); + } catch (error) { + const inserted = await writer + .selectFrom('prepared_register_rows') + .select('row_kind') + .orderBy('row_kind') + .execute(); + failedWrite = { error, rowKinds: inserted.map(({ row_kind }) => row_kind), writer }; + throw error; + } + } + ); await expect(stage.publish(fixture(), [ready()], journal)).rejects.toSatisfy( safeError('Unable to prepare reports') ); + expect(failedWrite).toMatchObject({ + error: { message: 'Missing account activity summary.' }, + rowKinds: ['entry', 'posting'] + }); + expect(failedWrite?.writer.isRolledBack).toBe(true); expect(await fs.readFile(reportPath())).toEqual(incumbent); expect(await filesInSlot()).toEqual(incumbentFiles); }); @@ -538,6 +583,19 @@ it('distinguishes empty-ready accounts from ambiguous access without requiring e [ready('empty', 0), ready('empty callback', 0), ambiguous()], journal ); + const postingCounts = withReportFile((database) => + database + .prepare( + ` + select account_name, posting_row_count from account_activity_summaries order by account_name + ` + ) + .all() + ); + expect(postingCounts).toEqual([ + { account_name: 'empty', posting_row_count: 0 }, + { account_name: 'empty callback', posting_row_count: 0 } + ]); const publication = await selected(); for (const account of publication.accounts) { const page = await readAccountPage(publication, account.id, { @@ -985,6 +1043,7 @@ it('does not migrate a version 4 slot on read; explicit preparation replaces it' withReportFile((db) => db.exec(` DROP TABLE prepared_register_rows; + ALTER TABLE account_activity_summaries DROP COLUMN posting_row_count; DELETE FROM kysely_migration WHERE name = '008_prepared_register_rows'; PRAGMA user_version = 4; `) diff --git a/packages/snapshots/src/reports/publication.ts b/packages/snapshots/src/reports/publication.ts index 3edaddf..ba9ce87 100644 --- a/packages/snapshots/src/reports/publication.ts +++ b/packages/snapshots/src/reports/publication.ts @@ -16,7 +16,6 @@ import { import { AccountActivitySummaryBuilder, hasOverviewContainers, - insertRegisterRowsForAccount, isAccountCatalog, isAccountId, isAccountSummary, @@ -32,6 +31,7 @@ import { writeAccountRows, writeAccountActivitySummaries, writeReportData, + writeRegisterRowsAndPostingCount, type AccountActivitySummary, type AccountActivityPage, type AccountActivityPageOptions, @@ -318,9 +318,9 @@ export async function createReportStage( >(); let currentName: string | undefined; - async function writePreparedRegisterRows() { - for (const [name, { rowCount: entryCount }] of writtenAccounts) { - if (entryCount > 0) await insertRegisterRowsForAccount(writer, name, entryCount); + async function writePreparedRegisterRows(catalog: readonly StoredAccount[]) { + for (const { name, rowCount: entryCount } of catalog) { + if (entryCount !== null) await writeRegisterRowsAndPostingCount(writer, name, entryCount); } } @@ -441,7 +441,7 @@ export async function createReportStage( } ); await writeAccountActivitySummaries(writer, activitySummaries); - await writePreparedRegisterRows(); + await writePreparedRegisterRows(catalog); await writer.commit().execute(); await closeDatabase(); const outcome = await replaceSavedReportIfNewer( -- 2.54.1 From 031ca4fd63f5150c7a9e3fb3927503f00b1acb1f Mon Sep 17 00:00:00 2001 From: eleith Date: Wed, 2 Dec 2026 08:10:55 -0800 Subject: [PATCH 09/19] refactor(registers): page saved Cash entry references --- .../server/registers/cash/register.test.ts | 3 +- .../src/lib/server/registers/cash/register.ts | 4 +- .../cash/[accountId]/page.server.test.ts | 32 ++-- .../prepare-reports/run.integration.test.ts | 6 +- packages/db/src/reports/index.ts | 5 +- .../db/src/reports/prepared-register-rows.ts | 32 +++- packages/db/src/reports/queries.test.ts | 168 +++++++++++------- packages/db/src/reports/queries.ts | 106 ++++++----- .../snapshots/src/reports/publication.test.ts | 30 ++-- packages/snapshots/src/reports/publication.ts | 3 +- 10 files changed, 231 insertions(+), 158 deletions(-) diff --git a/apps/web/src/lib/server/registers/cash/register.test.ts b/apps/web/src/lib/server/registers/cash/register.test.ts index 49cc01a..17af76b 100644 --- a/apps/web/src/lib/server/registers/cash/register.test.ts +++ b/apps/web/src/lib/server/registers/cash/register.test.ts @@ -174,8 +174,7 @@ it('reads a bounded batch and returns only public rows', async () => { const result = await readRowBatch(locals(), batchRequest); expect(readAccountPage).toHaveBeenCalledExactlyOnceWith(batchPublication, accountId, { order: 'desc', - offset: 250, - limit: 50 + offset: 250 }); expect(result).toMatchObject({ batchStart: 250, diff --git a/apps/web/src/lib/server/registers/cash/register.ts b/apps/web/src/lib/server/registers/cash/register.ts index 382f9ba..6a104e9 100644 --- a/apps/web/src/lib/server/registers/cash/register.ts +++ b/apps/web/src/lib/server/registers/cash/register.ts @@ -89,7 +89,6 @@ async function readInitialActivity( endingBalance: null, readFailed: false }; - if (account.rowCount === 0) return { ...activity, endingBalance: [] }; try { const page = await readSavedActivityPage( account, @@ -121,8 +120,7 @@ async function readSavedActivityPage( ): Promise { const page = await readAccountPage(account.publication, account.id, { order, - offset: batchStart, - limit: rowBatchSize + offset: batchStart }); if (!page) throw new Error('Prepared account rows unavailable.'); return page; diff --git a/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts b/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts index a2b504a..606765b 100644 --- a/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts +++ b/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts @@ -104,8 +104,7 @@ it('loads a member from one pinned publication and delegates its requested page' expect(readReportPublication).toHaveBeenCalledOnce(); expect(readAccountPage).toHaveBeenCalledExactlyOnceWith(publication, id, { order: 'desc', - offset: 50, - limit: 50 + offset: 50 }); expect(projectActivityPage).toHaveBeenCalledExactlyOnceWith(accountPage); expect(request.parent).toHaveBeenCalledOnce(); @@ -152,8 +151,7 @@ it('returns a safe read failure when the saved body cannot be read', async () => }); expect(readAccountPage).toHaveBeenCalledExactlyOnceWith(publication, id, { order: 'desc', - offset: 0, - limit: 50 + offset: 0 }); expect(projectActivityPage).not.toHaveBeenCalled(); expect(queue).not.toHaveBeenCalled(); @@ -164,8 +162,7 @@ it('opens the newest recorded activity on the first descending page by default', await load(event()); expect(readAccountPage).toHaveBeenCalledExactlyOnceWith(publication, id, { order: 'desc', - offset: 0, - limit: 50 + offset: 0 }); expect(projectActivityPage).toHaveBeenCalledExactlyOnceWith(firstPage); }); @@ -173,8 +170,7 @@ it('opens the last page when ascending order is requested', async () => { await load(event('order=asc')); expect(readAccountPage).toHaveBeenCalledExactlyOnceWith(publication, id, { order: 'asc', - offset: 50, - limit: 50 + offset: 50 }); expect(projectActivityPage).toHaveBeenCalledExactlyOnceWith(accountPage); }); @@ -183,7 +179,7 @@ it('rejects a disabled register before IO', async () => { expect(readReportPublication).not.toHaveBeenCalled(); expect(readAccountPage).not.toHaveBeenCalled(); }); -it('does not read or project ambiguous or empty account activity', async () => { +it('does not read or project activity for an ambiguous account', async () => { vi.mocked(readReportPublication).mockResolvedValue({ ...publication, accounts: [{ id, name, access: 'ambiguous', rowCount: null, summary: { status: 'ambiguous' } }] @@ -195,21 +191,17 @@ it('does not read or project ambiguous or empty account activity', async () => { rowCount: null, endingBalance: null }); + expect(readAccountPage).not.toHaveBeenCalled(); + expect(projectActivityPage).not.toHaveBeenCalled(); +}); + +it('reports unreadable activity even if the catalog says the account is empty', async () => { vi.mocked(readReportPublication).mockResolvedValue({ ...publication, accounts: [{ id, name, access: 'ready', rowCount: 0, summary: { status: 'undated' } }] }); - expect(await load(event())).toMatchObject({ - readFailed: false, - access: 'ready', - rows: [], - rowCount: 0, - page: 1, - pageCount: 1, - endingBalance: [] - }); - expect(readAccountPage).not.toHaveBeenCalled(); - expect(projectActivityPage).not.toHaveBeenCalled(); + vi.mocked(readAccountPage).mockRejectedValue(new Error('Unable to read account transactions')); + expect(await load(event())).toMatchObject({ readFailed: true, rows: [], endingBalance: null }); }); it('rejects an unknown member before reading activity', async () => { const request = event(); diff --git a/apps/worker/src/workflows/prepare-reports/run.integration.test.ts b/apps/worker/src/workflows/prepare-reports/run.integration.test.ts index 8a29a9a..733377b 100644 --- a/apps/worker/src/workflows/prepare-reports/run.integration.test.ts +++ b/apps/worker/src/workflows/prepare-reports/run.integration.test.ts @@ -189,8 +189,7 @@ it('explicitly prepares a saved overview through the real SDK without a browser }); const page = (await readAccountPage(publication, account.id, { order: 'asc', - offset: 0, - limit: 50 + offset: 0 }))!; const salary = page.rows.find((row) => row.transaction.note === 'Salary')!; expect(salary.change).toEqual([ @@ -211,8 +210,7 @@ it('explicitly prepares a saved overview through the real SDK without a browser const savedPublication = (await readReportPublication(f.snapshots))!; const savedPage = await readAccountPage(savedPublication, account.id, { order: 'asc', - offset: 0, - limit: 50 + offset: 0 }); expect(savedPage).toEqual(page); expectSavedNativeExports(savedPublication, page.rows.length, f.included); diff --git a/packages/db/src/reports/index.ts b/packages/db/src/reports/index.ts index 9ce7dc7..c92cb97 100644 --- a/packages/db/src/reports/index.ts +++ b/packages/db/src/reports/index.ts @@ -27,6 +27,9 @@ export type { AccountActivityPageOptions, AccountInvestmentActivityPage } from './queries.js'; -export { writeRegisterRowsAndPostingCount } from './prepared-register-rows.js'; +export { + writeRegisterRowsAndPostingCount, + type RegisterPageOptions +} from './prepared-register-rows.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 cf4b754..cff8f03 100644 --- a/packages/db/src/reports/prepared-register-rows.ts +++ b/packages/db/src/reports/prepared-register-rows.ts @@ -10,29 +10,49 @@ import { validateRawAccountPostingReferences } from './investment-posting-rows.js'; -export function readRegisterRowReferencePage( +export interface RegisterPageOptions { + order: 'asc' | 'desc'; + offset: number; +} + +export function assertRegisterPageOptions({ order, offset }: RegisterPageOptions): void { + if ((order !== 'asc' && order !== 'desc') || !Number.isSafeInteger(offset) || offset < 0) + throw new Error('Invalid account page.'); +} + +export async function readRegisterRowReferencePage( database: Kysely, accountName: string, rowKind: ReportDatabase['prepared_register_rows']['row_kind'], - { order, offset }: { order: 'asc' | 'desc'; offset: number } + expectedRowCount: number, + { order, offset }: RegisterPageOptions ) { - return database + const registerRows = database .selectFrom('prepared_register_rows') + .where('account_name', '=', accountName) + .where('row_kind', '=', rowKind); + const { rowCount } = await registerRows + .select(({ fn }) => fn.countAll().as('rowCount')) + .executeTakeFirstOrThrow(); + if (rowCount !== expectedRowCount) throw new Error('Invalid prepared register rows.'); + + const references = await registerRows .select([ 'display_date', - 'entry_ordinal', + 'entry_ordinal as accountOrdinal', 'posting_ordinal', 'position_in_entry', 'entry_row_count' ]) - .where('account_name', '=', accountName) - .where('row_kind', '=', rowKind) .orderBy('display_date', order) .orderBy('entry_ordinal', 'asc') .orderBy('position_in_entry', 'asc') .offset(offset) .limit(registerPageSize) .execute(); + if (references.length !== Math.min(registerPageSize, Math.max(0, expectedRowCount - offset))) + throw new Error('Invalid prepared register rows.'); + return references; } export async function writeRegisterRowsAndPostingCount( diff --git a/packages/db/src/reports/queries.test.ts b/packages/db/src/reports/queries.test.ts index 0bd1b31..3fbc430 100644 --- a/packages/db/src/reports/queries.test.ts +++ b/packages/db/src/reports/queries.test.ts @@ -168,6 +168,9 @@ it('stores exact prepared payloads and native row order using the migrated schem await writeAccountRows(transaction, 'assets:Cash', 0, otherRows); await writeReportData(transaction, data); await writeAccountActivitySummaries(transaction, summaries); + for (const { name, rowCount } of data.accounts) { + if (rowCount !== null) await writeRegisterRowsAndPostingCount(transaction, name, rowCount); + } await transaction.commit().execute(); } finally { if (!transaction.isCommitted && !transaction.isRolledBack) @@ -179,7 +182,7 @@ it('stores exact prepared payloads and native row order using the migrated schem if (!reader) throw new Error('Expected the current report schema.'); databases.add(reader); expect(await readReportData(reader)).toEqual(data); - const firstPage = { order: 'asc', offset: 0, limit: 50 } as const; + const firstPage = { order: 'asc', offset: 0 } as const; expect(await readAccountActivityPage(reader, data.accounts[0], firstPage)).toEqual({ rows: [], summary: preparedActivitySummary() @@ -250,6 +253,8 @@ it('shares one canonical transaction without embedding its body in account conte [other.name, preparedActivitySummary(otherRows)] ]) ); + await writeRegisterRowsAndPostingCount(transaction, account.name, rows.length); + await writeRegisterRowsAndPostingCount(transaction, other.name, otherRows.length); await transaction.commit().execute(); } finally { if (!transaction.isCommitted && !transaction.isRolledBack) @@ -275,7 +280,7 @@ it('shares one canonical transaction without embedding its body in account conte investment: expected.investment }); } - const page = { order: 'asc', offset: 0, limit: 50 } as const; + const page = { order: 'asc', offset: 0 } as const; expect((await readAccountActivityPage(database, account, page))?.rows).toEqual(rows); expect((await readAccountActivityPage(database, other, page))?.rows).toEqual(otherRows); expect(await readAccountActivityDetail(database, account, 1)).toEqual(rows[0]); @@ -323,6 +328,8 @@ it('reads date-ordered pages with native ties and exact account scope', async () [other.name, preparedActivitySummary(otherRows)] ]) ); + await writeRegisterRowsAndPostingCount(transaction, account.name, rows.length); + await writeRegisterRowsAndPostingCount(transaction, other.name, otherRows.length); await transaction.commit().execute(); } finally { if (!transaction.isCommitted && !transaction.isRolledBack) @@ -340,7 +347,7 @@ it('reads date-ordered pages with native ties and exact account scope', async () const earlierDateRows = rows.slice(26); const ascending = [...earlierDateRows, ...laterDateRows]; const readPage = async (order: 'asc' | 'desc', offset: number) => - (await readAccountActivityPage(pageReader, account, { order, offset, limit: 50 }))?.rows; + (await readAccountActivityPage(pageReader, account, { order, offset }))?.rows; expect(await readPage('asc', 0)).toEqual(ascending.slice(0, 50)); expect(await readPage('asc', 50)).toEqual(ascending.slice(50)); expect(await readPage('desc', 0)).toEqual(rows.slice(0, 50)); @@ -362,35 +369,43 @@ it('reads date-ordered pages with native ties and exact account scope', async () ) ).toBe(0); - expect( - await readAccountActivityPage(database, other, { order: 'asc', offset: 0, limit: 50 }) - ).toEqual({ rows: otherRows, summary: preparedActivitySummary(otherRows) }); + expect(await readAccountActivityPage(database, other, { order: 'asc', offset: 0 })).toEqual({ + rows: otherRows, + summary: preparedActivitySummary(otherRows) + }); const mismatchedAccount = { ...other, id: account.id }; await expect(readAccountActivityDetail(database, mismatchedAccount, 1)).rejects.toThrow(); await expect(readAccountActivityDetail(database, account, 0)).rejects.toThrow(); await expect( - readAccountActivityPage(database, mismatchedAccount, { order: 'asc', offset: 0, limit: 50 }) - ).rejects.toThrow(); - await expect( - readAccountActivityPage(database, account, { order: 'asc', offset: 0, limit: -1 }) - ).rejects.toThrow(); - await expect( - readAccountActivityPage(database, account, { order: 'asc', offset: 0, limit: 51 }) + readAccountActivityPage(database, mismatchedAccount, { order: 'asc', offset: 0 }) ).rejects.toThrow(); + await expect(readPage('asc', -1)).rejects.toThrow('Invalid account page.'); await database - .deleteFrom('account_activity') + .updateTable('prepared_register_rows') + .set({ display_date: '2026-04-28' }) .where('account_name', '=', account.name) - .where('ordinal', '=', 0) + .where('row_kind', '=', 'entry') + .where('entry_ordinal', '=', 0) .execute(); - await expect(readPage('desc', 50)).rejects.toThrow(); - expect(await readAccountActivityDetail(database, account, rows[0].transaction.index)).toBeNull(); + await expect(readPage('asc', 0)).rejects.toThrow('Invalid account data.'); + await database + .deleteFrom('prepared_register_rows') + .where('account_name', '=', account.name) + .where('row_kind', '=', 'entry') + .where('entry_ordinal', '=', 0) + .execute(); + // 52 references remain, enough to fill the page but not enough to trust its offsets. + await expect(readPage('asc', 0)).rejects.toThrow('Invalid prepared register rows.'); + expect(await readAccountActivityDetail(database, account, rows[0].transaction.index)).toEqual( + rows[0] + ); }); it('decodes only the requested page and rejects invalid posting references', async () => { const database = await createDatabase(); - const account = { id: 'cash0001', ...ready('assets:cash', 2) }; - const exports = accountTransactionExportsFixture(2); + const exports = accountTransactionExportsFixture(51); const rows = preparedAccountRowsFromExports(exports); + const account = { id: 'cash0001', ...ready('assets:cash', rows.length) }; await writeReportData(database, { journal, overview: preparedOverview(), accounts: [account] }); await writeAccountActivitySummaries( database, @@ -400,6 +415,7 @@ it('decodes only the requested page and rejects invalid posting references', asy try { await importTransactions(transaction, exports); await writeAccountRows(transaction, account.name, 0, rows); + await writeRegisterRowsAndPostingCount(transaction, account.name, rows.length); await transaction.commit().execute(); } finally { if (!transaction.isCommitted && !transaction.isRolledBack) @@ -411,15 +427,15 @@ it('decodes only the requested page and rejects invalid posting references', asy const native = new DatabaseSync(path); try { const saved = native - .prepare('SELECT context_json FROM account_activity WHERE ordinal = 1') + .prepare('SELECT context_json FROM account_activity WHERE ordinal = 50') .get(); const badContext = { ...JSON.parse(String(saved!.context_json)), - accountPostingIndexes: [rows[1].transaction.postings.length] + accountPostingIndexes: [rows[50].transaction.postings.length] }; native .prepare( - 'UPDATE account_activity SET context_json = ? WHERE account_name = ? AND ordinal = 1' + 'UPDATE account_activity SET context_json = ? WHERE account_name = ? AND ordinal = 50' ) .run(JSON.stringify(badContext), account.name); } finally { @@ -429,15 +445,16 @@ it('decodes only the requested page and rejects invalid posting references', asy if (!reader) throw new Error('Expected the current report schema.'); databases.add(reader); expect((await readReportData(reader)).accounts).toEqual([account]); - expect( - await readAccountActivityPage(reader, account, { order: 'asc', offset: 0, limit: 1 }) - ).toEqual({ rows: rows.slice(0, 1), summary: preparedActivitySummary(rows) }); + expect(await readAccountActivityPage(reader, account, { order: 'asc', offset: 0 })).toEqual({ + rows: rows.slice(0, 50), + summary: preparedActivitySummary(rows) + }); await expect( - readAccountActivityPage(reader, account, { order: 'asc', offset: 1, limit: 1 }) + readAccountActivityPage(reader, account, { order: 'asc', offset: 50 }) ).rejects.toThrow(); }); -it('rejects selected missing or invalid canonical exports without decoding off-page transactions', async () => { +it('rejects an orphaned Cash row without shifting later rows', async () => { const database = await createDatabase(); const exports = accountTransactionExportsFixture(4); const rows = preparedAccountRowsFromExports(exports); @@ -455,6 +472,7 @@ it('rejects selected missing or invalid canonical exports without decoding off-p transaction, new Map([[account.name, preparedActivitySummary(rows)]]) ); + await writeRegisterRowsAndPostingCount(transaction, account.name, rows.length); await transaction.commit().execute(); } finally { if (!transaction.isCommitted && !transaction.isRolledBack) @@ -462,10 +480,35 @@ it('rejects selected missing or invalid canonical exports without decoding off-p } await closeDatabase(database); + const reader = await openReadOnlyReportDatabase(path); + if (!reader) throw new Error('Expected the current report schema.'); + databases.add(reader); + const readPage = (offset: number) => + readAccountActivityPage(reader, account, { order: 'asc', offset }); + const summary = preparedActivitySummary(rows); + const suffix = { rows: rows.slice(1), summary }; + expect(await readPage(0)).toEqual({ rows, summary }); + const native = new DatabaseSync(path); try { - // Simulate damaged publication storage, including an orphan that normal writes forbid. - native.exec('PRAGMA foreign_keys = OFF'); + native.exec(` + PRAGMA foreign_keys = OFF; + CREATE TEMP TABLE retained_transaction AS SELECT * FROM transactions WHERE native_index = 1; + DELETE FROM transactions WHERE native_index = 1; + `); + await expect(readPage(0)).rejects.toThrow('Invalid account data.'); + expect(await readPage(1)).toEqual(suffix); + await expect(readAccountActivityDetail(reader, account, 1)).rejects.toThrow( + 'Invalid account data.' + ); + + native.exec('INSERT INTO transactions SELECT * FROM retained_transaction'); + native + .prepare('DELETE FROM account_activity WHERE account_name = ? AND ordinal = 0') + .run(account.name); + await expect(readPage(0)).rejects.toThrow('Invalid account data.'); + expect(await readPage(1)).toEqual(suffix); + const wrongIdentity = accountTransactionExportsFixture(1, 'wrong canonical identity', 99)[0]; native .prepare( @@ -473,24 +516,15 @@ it('rejects selected missing or invalid canonical exports without decoding off-p ) .run(wrongIdentity.originalJson, wrongIdentity.transactedJson); native.prepare('UPDATE transactions SET transacted_json = NULL WHERE native_index = 3').run(); - native.prepare('DELETE FROM transactions WHERE native_index = 1').run(); + await expect(readAccountActivityDetail(reader, account, 2)).rejects.toThrow( + 'Invalid account data.' + ); + await expect(readAccountActivityDetail(reader, account, 3)).rejects.toThrow( + 'Invalid account data.' + ); } finally { native.close(); } - const reader = await openReadOnlyReportDatabase(path); - if (!reader) throw new Error('Expected the current report schema.'); - databases.add(reader); - expect((await readReportData(reader)).accounts).toEqual([account]); - const readRow = (offset: number) => - readAccountActivityPage(reader, account, { order: 'asc', offset, limit: 1 }); - // The orphan still occupies its ordinal; a join must not shift later rows into the page. - expect(await readRow(3)).toEqual({ rows: rows.slice(3), summary: preparedActivitySummary(rows) }); - expect(await readAccountActivityDetail(reader, account, 4)).toEqual(rows[3]); - await expect(readAccountActivityDetail(reader, account, 1)).rejects.toThrow(); - await expect(readAccountActivityDetail(reader, account, 2)).rejects.toThrow(); - await expect(readRow(0)).rejects.toThrow(); - await expect(readRow(1)).rejects.toThrow(); - await expect(readRow(2)).rejects.toThrow(); }); it('rejects missing summaries and malformed native bags rather than inferring from a page', async () => { @@ -498,31 +532,33 @@ it('rejects missing summaries and malformed native bags rather than inferring fr const account = { id: 'cash0001', ...ready() }; const exports = accountTransactionExportsFixture(); const rows = preparedAccountRowsFromExports(exports); + const summary = preparedActivitySummary(rows); await writeReportData(database, { journal, overview: preparedOverview(), accounts: [account] }); const transaction = await database.startTransaction().execute(); try { await importTransactions(transaction, exports); await writeAccountRows(transaction, account.name, 0, rows); + await writeAccountActivitySummaries(transaction, new Map([[account.name, summary]])); + await writeRegisterRowsAndPostingCount(transaction, account.name, rows.length); await transaction.commit().execute(); } finally { if (!transaction.isCommitted && !transaction.isRolledBack) await transaction.rollback().execute(); } - const page = { order: 'asc', offset: 0, limit: 50 } as const; - await expect(readAccountActivityPage(database, account, page)).rejects.toThrow(); + const readPage = () => readAccountActivityPage(database, account, { order: 'asc', offset: 0 }); + expect(await readPage()).toEqual({ rows, summary }); await expect(writeAccountActivitySummaries(database, new Map())).rejects.toThrow(); - - await writeAccountActivitySummaries( - database, - new Map([[account.name, preparedActivitySummary(rows)]]) - ); await database .updateTable('account_activity_summaries') .set({ ending_cash_json: '[{"commodity":"$","quantity":0}]' }) .where('account_name', '=', account.name) .execute(); - expect((await readReportData(database)).accounts).toEqual([account]); - await expect(readAccountActivityPage(database, account, page)).rejects.toThrow(); + await expect(readPage()).rejects.toThrow('Invalid account activity summary.'); + await database + .deleteFrom('account_activity_summaries') + .where('account_name', '=', account.name) + .execute(); + await expect(readPage()).rejects.toThrow('Missing account activity summary.'); }); it('does not create missing storage or replace an existing report file', async () => { @@ -649,12 +685,18 @@ it('pages original selected-account postings across a shared security group and ['desc', descending] ] as const) { for (const offset of [0, 50]) { - const storedPage = await readRegisterRowReferencePage(reader, account.name, 'posting', { - order, - offset - }); + const storedPage = await readRegisterRowReferencePage( + reader, + account.name, + 'posting', + ordered.length, + { + order, + offset + } + ); expect( - storedPage.map(({ entry_ordinal, posting_ordinal }) => [entry_ordinal, posting_ordinal]) + storedPage.map(({ accountOrdinal, posting_ordinal }) => [accountOrdinal, posting_ordinal]) ).toEqual( ordered .slice(offset, offset + 50) @@ -826,10 +868,16 @@ it('prepares entry and posting rows with the original last visible sibling', asy ]); const entryPage = { order: 'asc', offset: 0 } as const; - const entryRows = await readRegisterRowReferencePage(database, account.name, 'entry', entryPage); + const entryRows = await readRegisterRowReferencePage( + database, + account.name, + 'entry', + 1, + entryPage + ); expect(entryRows.map(({ display_date }) => display_date)).toEqual([accountDate]); expect( - await readRegisterRowReferencePage(database, otherAccount.name, 'entry', entryPage) + await readRegisterRowReferencePage(database, otherAccount.name, 'entry', 0, entryPage) ).toEqual([]); }); diff --git a/packages/db/src/reports/queries.ts b/packages/db/src/reports/queries.ts index 5ac5941..8a0de04 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -23,6 +23,11 @@ import { readInvestmentPostingCounts, validateInvestmentPostingCounts } from './investment-posting-rows.js'; +import { + assertRegisterPageOptions, + readRegisterRowReferencePage, + type RegisterPageOptions +} from './prepared-register-rows.js'; const insertBatchSize = 50; @@ -41,9 +46,7 @@ export interface AccountInvestmentActivityPage { summary: AccountActivitySummary; } -export interface AccountActivityPageOptions { - order: 'asc' | 'desc'; - offset: number; +export interface AccountActivityPageOptions extends RegisterPageOptions { limit: number; } @@ -343,15 +346,10 @@ export async function readAccountActivityDetail( return record ? decodeAccountRow(record, rowCount) : null; } -function assertPageOptions({ order, offset, limit }: AccountActivityPageOptions): void { - if ( - (order !== 'asc' && order !== 'desc') || - !Number.isSafeInteger(offset) || - offset < 0 || - !Number.isSafeInteger(limit) || - limit < 1 || - limit > registerPageSize - ) +function assertPageOptions(options: AccountActivityPageOptions): void { + assertRegisterPageOptions(options); + const { limit } = options; + if (!Number.isSafeInteger(limit) || limit < 1 || limit > registerPageSize) throw new Error('Invalid account page.'); } @@ -388,26 +386,53 @@ async function readAccountPageContext( return { rowCount, summary: decodeActivitySummary(storedSummary) }; } +async function readAccountEntriesByOrdinal( + database: Kysely, + accountName: string, + totalAccountEntryCount: number, + pageAccountOrdinals: readonly number[] +): Promise> { + const entriesByAccountOrdinal = new Map(); + if (pageAccountOrdinals.length === 0) return entriesByAccountOrdinal; + const uniqueOrdinals = [...new Set(pageAccountOrdinals)]; + const records = await selectAccountRowsWithTransactions(database) + .where('account_activity.account_name', '=', accountName) + .where('account_activity.ordinal', 'in', uniqueOrdinals) + .execute(); + for (const record of records) { + entriesByAccountOrdinal.set(record.ordinal, decodeAccountRow(record, totalAccountEntryCount)); + } + return entriesByAccountOrdinal; +} + export async function readAccountActivityPage( database: Kysely, account: StoredAccount, - options: AccountActivityPageOptions + options: RegisterPageOptions ): Promise { - assertPageOptions(options); + assertRegisterPageOptions(options); const context = await readAccountPageContext(database, account); if (!context) return null; const { rowCount, summary } = context; - const { order, offset, limit } = options; - const records = await selectAccountRowsWithTransactions(database) - .where('account_activity.account_name', '=', account.name) - .orderBy('account_activity.account_date', order) - .orderBy('account_activity.ordinal', 'asc') - .limit(limit) - .offset(offset) - .execute(); - const expectedRows = Math.min(limit, Math.max(0, rowCount - offset)); - if (records.length !== expectedRows) throw new Error('Invalid account data.'); - return { rows: records.map((record) => decodeAccountRow(record, rowCount)), summary }; + const orderedReferences = await readRegisterRowReferencePage( + database, + account.name, + 'entry', + rowCount, + options + ); + const entriesByAccountOrdinal = await readAccountEntriesByOrdinal( + database, + account.name, + rowCount, + orderedReferences.map(({ accountOrdinal }) => accountOrdinal) + ); + const rows = orderedReferences.map(({ accountOrdinal, display_date }) => { + const row = entriesByAccountOrdinal.get(accountOrdinal); + if (!row || row.accountDate !== display_date) throw new Error('Invalid account data.'); + return row; + }); + return { rows, summary }; } export async function findOldestFirstAccountActivityOffset( @@ -457,13 +482,13 @@ export async function readAccountInvestmentActivityPage( validateInvestmentPostingCounts(counts, rowCount); const activityCount = counts.visiblePostingCount; const { order, offset, limit } = options; - const { rows: references } = await sql<{ - ordinal: number; + const { rows: orderedReferences } = await sql<{ + accountOrdinal: number; posting_index: number; entry_activity_position: number; entry_activity_count: number; }>` - select activity.ordinal, posting.posting_ordinal as posting_index, + select activity.ordinal as accountOrdinal, posting.posting_ordinal as posting_index, ${postingPositionInOriginalOrder} as entry_activity_position, ${postingCountInEntry} as entry_activity_count ${fromVisibleInvestmentPostings(account.name)} @@ -471,28 +496,23 @@ export async function readAccountInvestmentActivityPage( activity.ordinal asc, posting.posting_ordinal asc limit ${limit} offset ${offset} `.execute(database); - if (references.length !== Math.min(limit, Math.max(0, activityCount - offset))) + if (orderedReferences.length !== Math.min(limit, Math.max(0, activityCount - offset))) throw new Error('Invalid account posting data.'); - // Several action references can share one full canonical account row. - const parents = new Map(); - if (references.length > 0) { - const records = await selectAccountRowsWithTransactions(database) - .where('account_activity.account_name', '=', account.name) - .where('account_activity.ordinal', 'in', [ - ...new Set(references.map(({ ordinal }) => ordinal)) - ]) - .execute(); - for (const record of records) parents.set(record.ordinal, decodeAccountRow(record, rowCount)); - } - const rows = references.map( + const entriesByAccountOrdinal = await readAccountEntriesByOrdinal( + database, + account.name, + rowCount, + orderedReferences.map(({ accountOrdinal }) => accountOrdinal) + ); + const rows = orderedReferences.map( ({ - ordinal, + accountOrdinal, posting_index: postingIndex, entry_activity_position: entryActivityPosition, entry_activity_count: entryActivityCount }) => { - const row = parents.get(ordinal); + const row = entriesByAccountOrdinal.get(accountOrdinal); if ( !row || !row.accountPostingIndexes.includes(postingIndex) || diff --git a/packages/snapshots/src/reports/publication.test.ts b/packages/snapshots/src/reports/publication.test.ts index 26cb319..50f1149 100644 --- a/packages/snapshots/src/reports/publication.test.ts +++ b/packages/snapshots/src/reports/publication.test.ts @@ -222,13 +222,11 @@ it('commits and closes the complete report before replacing the slot', async () expect(account).toMatchObject(ready('assets:cash', 52)); const firstPage = await readAccountPage(publication, account.id, { order: 'desc', - offset: 0, - limit: 50 + offset: 0 }); const secondPage = await readAccountPage(publication, account.id, { order: 'desc', - offset: 50, - limit: 50 + offset: 50 }); expect(firstPage?.rows).toEqual(transactions.slice(0, 50)); expect(secondPage?.rows).toEqual(transactions.slice(50)); @@ -314,7 +312,7 @@ it('does not mix two publications from different attempts of the same request', await stage.writeRows('assets:cash', rows(1, 'new rows')); await stage.publish(fixture(), [ready()], journal); const next = await selected(); - const options = { order: 'asc', offset: 0, limit: 50 } as const; + const options = { order: 'asc', offset: 0 } as const; expect(next.accounts[0].id).toBe(id); expect((await readAccountPage(next, id, options))?.rows).toEqual(rows(1, 'new rows')); expect(await readInvestmentOverview(next)).toBeNull(); @@ -327,7 +325,7 @@ it('does not mix two publications from different attempts of the same request', await expect(countInvestmentActivities(pinned, id)).rejects.toSatisfy( safeError('Unable to read account activity') ); - await expect(readInvestmentActivityPage(pinned, id, options)).rejects.toSatisfy( + await expect(readInvestmentActivityPage(pinned, id, { ...options, limit: 50 })).rejects.toSatisfy( safeError('Unable to read account activity') ); await expect(readInvestmentOverview(pinned)).rejects.toSatisfy( @@ -350,8 +348,7 @@ it('reads from the connection it verified even if the report is replaced after t }); const page = await readAccountPage(pinned, pinned.accounts[0].id, { order: 'asc', - offset: 0, - limit: 50 + offset: 0 }); expect(page?.rows).toEqual(rows()); expect(await readOverview(snapshots)).toEqual(next); @@ -454,8 +451,7 @@ it('keeps other saved reports readable until preparation replaces the old invest expect(publication.overview).toEqual(fixture()); const page = await readAccountPage(publication, publication.accounts[0].id, { order: 'desc', - offset: 0, - limit: 1 + offset: 0 }); expect(page?.rows).toEqual(rows()); @@ -600,8 +596,7 @@ it('distinguishes empty-ready accounts from ambiguous access without requiring e for (const account of publication.accounts) { const page = await readAccountPage(publication, account.id, { order: 'asc', - offset: 0, - limit: 50 + offset: 0 }); expect(page).toEqual( account.access === 'ready' @@ -654,7 +649,7 @@ it('reuses IDs by exact account identity and avoids collisions with removed and accounts.map(({ name, id }) => ({ name, id })) ); for (const { id, nativeIndex } of accounts) { - const page = await readAccountPage(publication, id, { order: 'asc', offset: 0, limit: 50 }); + const page = await readAccountPage(publication, id, { order: 'asc', offset: 0 }); expect(page?.rows.map(({ transaction }) => transaction.index)).toEqual([nativeIndex]); } }); @@ -882,7 +877,7 @@ it('releases read connections on successful and failed saved reads', async () => const publication = await selected(); expect(connectionClosures.shift()).toHaveBeenCalledOnce(); const account = publication.accounts[0]; - const options = { order: 'asc', offset: 0, limit: 50 } as const; + const options = { order: 'asc', offset: 0 } as const; holdNextClose = true; const page = readAccountPage(publication, account.id, options); try { @@ -933,10 +928,10 @@ it('rejects unsafe and uncatalogued account IDs before opening financial data', }; const reader = vi.spyOn(databases, 'openReadOnlyReportDatabase'); await expect( - readAccountPage(publication, '../escape', { order: 'asc', offset: 0, limit: 50 }) + readAccountPage(publication, '../escape', { order: 'asc', offset: 0 }) ).rejects.toSatisfy(safeError('Unable to read account transactions')); await expect( - readAccountPage(publication, '00000000', { order: 'asc', offset: 0, limit: 50 }) + readAccountPage(publication, '00000000', { order: 'asc', offset: 0 }) ).rejects.toSatisfy(safeError('Unable to read account transactions')); await expect(readAccountTransaction(publication, '../escape', 1)).rejects.toSatisfy( safeError('Unable to read account transactions') @@ -1099,8 +1094,7 @@ it.each(['directory', 'file'])( await expect( readAccountPage(publication, publication.accounts[0].id, { order: 'asc', - offset: 0, - limit: 50 + offset: 0 }) ).rejects.toSatisfy(safeError('Unable to read account transactions')); await expect( diff --git a/packages/snapshots/src/reports/publication.ts b/packages/snapshots/src/reports/publication.ts index ba9ce87..81db3b0 100644 --- a/packages/snapshots/src/reports/publication.ts +++ b/packages/snapshots/src/reports/publication.ts @@ -36,6 +36,7 @@ import { type AccountActivityPage, type AccountActivityPageOptions, type AccountInvestmentActivityPage, + type RegisterPageOptions, type StoredAccount, type StoredReportData } from '@hledger-reports/db/reports'; @@ -183,7 +184,7 @@ async function readFromSelectedPublication( export async function readAccountPage( publication: ReportPublication, id: string, - options: AccountActivityPageOptions + options: RegisterPageOptions ): Promise { try { if (!isAccountId(id)) throw new Error(); -- 2.54.1 From e095d85fd88c14dddf9628b74a8c9493de3ed963 Mon Sep 17 00:00:00 2001 From: eleith Date: Wed, 2 Dec 2026 09:28:08 -0800 Subject: [PATCH 10/19] refactor(registers): use the saved Investment activity count --- .../registers/investment/register.test.ts | 50 ++++++++--------- .../server/registers/investment/register.ts | 12 ++--- .../[accountId]/page.server.test.ts | 40 ++++++++------ packages/db/src/reports/index.ts | 2 +- .../db/src/reports/prepared-register-rows.ts | 16 ++---- packages/db/src/reports/queries.test.ts | 54 +++++++++++-------- packages/db/src/reports/queries.ts | 30 ++++++++--- packages/snapshots/src/index.ts | 2 +- .../snapshots/src/reports/publication.test.ts | 6 +-- packages/snapshots/src/reports/publication.ts | 6 +-- 10 files changed, 123 insertions(+), 95 deletions(-) diff --git a/apps/web/src/lib/server/registers/investment/register.test.ts b/apps/web/src/lib/server/registers/investment/register.test.ts index a559d17..3760338 100644 --- a/apps/web/src/lib/server/registers/investment/register.test.ts +++ b/apps/web/src/lib/server/registers/investment/register.test.ts @@ -1,6 +1,6 @@ import type { AccountConfig } from '@hledger-reports/config'; import { - countInvestmentActivities, + readInvestmentActivityCount, readInvestmentActivityPage, readReportPublication, type AccountInvestmentActivityPage @@ -17,7 +17,7 @@ import { loadRegisterPage, readActivityBatch } from './register.js'; vi.mock('@hledger-reports/snapshots', () => ({ readReportPublication: vi.fn(), - countInvestmentActivities: vi.fn(), + readInvestmentActivityCount: vi.fn(), readInvestmentActivityPage: vi.fn() })); vi.mock('@hledger-reports/hledger', () => { @@ -93,7 +93,7 @@ it('reads one pinned publication at fixed size without separately recounting and offset: 50, limit: 50 }); - expect(countInvestmentActivities).not.toHaveBeenCalled(); + expect(readInvestmentActivityCount).not.toHaveBeenCalled(); expect(Object.keys(result)).toEqual(['batchStart', 'activities']); expect(result.batchStart).toBe(50); expect(result.activities).toHaveLength(5); @@ -167,7 +167,7 @@ it('uses the integrity-verified empty result for out-of-range positions, not the body: { message: 'History position not found.' } }); expect(readInvestmentActivityPage).toHaveBeenCalledOnce(); - expect(countInvestmentActivities).not.toHaveBeenCalled(); + expect(readInvestmentActivityCount).not.toHaveBeenCalled(); }); it('permits only batch zero for declared-empty accounts without reading a body', async () => { @@ -181,7 +181,7 @@ it('permits only batch zero for declared-empty accounts without reading a body', }); await expect(readActivityBatch(locals(), request)).rejects.toMatchObject({ status: 404 }); expect(readInvestmentActivityPage).not.toHaveBeenCalled(); - expect(countInvestmentActivities).not.toHaveBeenCalled(); + expect(readInvestmentActivityCount).not.toHaveBeenCalled(); }); it('sanitizes missing, foreign and unreadable publications before activity reads', async () => { @@ -200,27 +200,29 @@ it('sanitizes missing, foreign and unreadable publications before activity reads expect(readInvestmentActivityPage).not.toHaveBeenCalled(); }); -it.each([null, 0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1])( - 'rejects an unreadable initial activity count (%s) before reading a saved body', - async (activityCount) => { - vi.mocked(countInvestmentActivities).mockResolvedValue(activityCount); - const result = await loadRegisterPage( - { locals: locals(), parent: async () => ({}) }, - { accountId, order: 'asc', page: null } - ); - expect(result).toMatchObject({ - readFailed: true, - accountName: name, - access: 'ready', - register: null - }); - expect(countInvestmentActivities).toHaveBeenCalledExactlyOnceWith(publication, accountId); - expect(readInvestmentActivityPage).not.toHaveBeenCalled(); - } -); +it('reports a saved count read failure for a declared-empty account', async () => { + vi.mocked(readReportPublication).mockResolvedValue({ + ...publication, + accounts: publication.accounts.map((account) => ({ ...account, rowCount: 0 })) + }); + vi.mocked(readInvestmentActivityCount).mockRejectedValue( + new Error('Unable to read account activity') + ); + const result = await loadRegisterPage( + { locals: locals(), parent: async () => ({}) }, + { accountId, order: 'asc', page: null } + ); + expect(result).toMatchObject({ + readFailed: true, + accountName: name, + access: 'ready', + register: null + }); + expect(readInvestmentActivityPage).not.toHaveBeenCalled(); +}); it('returns an SSR read failure when a counted initial page cannot be projected', async () => { - vi.mocked(countInvestmentActivities).mockResolvedValue(55); + vi.mocked(readInvestmentActivityCount).mockResolvedValue(55); vi.mocked(readInvestmentActivityPage).mockResolvedValue({ ...page, rows: [{ ...page.rows[0], postingIndex: 999 }] diff --git a/apps/web/src/lib/server/registers/investment/register.ts b/apps/web/src/lib/server/registers/investment/register.ts index c15759c..437a8e4 100644 --- a/apps/web/src/lib/server/registers/investment/register.ts +++ b/apps/web/src/lib/server/registers/investment/register.ts @@ -1,5 +1,5 @@ import { - countInvestmentActivities, + readInvestmentActivityCount, readInvestmentActivityPage, type AccountInvestmentActivityPage } from '@hledger-reports/snapshots'; @@ -61,11 +61,9 @@ export async function readActivityBatch( return { batchStart: request.batchStart, activities }; } -async function countReadableActivities(account: ReadableAccount): Promise { - if (account.rowCount === 0) return 0; - const activityCount = await countInvestmentActivities(account.publication, account.id); - if (activityCount === null || !Number.isSafeInteger(activityCount) || activityCount < 1) - throw new Error('Prepared activity count unavailable.'); +async function readSavedActivityCount(account: ReadableAccount): Promise { + const activityCount = await readInvestmentActivityCount(account.publication, account.id); + if (activityCount === null) throw new Error('Prepared activity count unavailable.'); return activityCount; } @@ -85,7 +83,7 @@ async function readInitialRegisterPage( ): Promise> { let activityCount: number; try { - activityCount = await countReadableActivities(account); + activityCount = await readSavedActivityCount(account); } catch { return { register: null, readFailed: true }; } diff --git a/apps/web/src/routes/(protected)/registers/investments/[accountId]/page.server.test.ts b/apps/web/src/routes/(protected)/registers/investments/[accountId]/page.server.test.ts index 15f6263..482a5bc 100644 --- a/apps/web/src/routes/(protected)/registers/investments/[accountId]/page.server.test.ts +++ b/apps/web/src/routes/(protected)/registers/investments/[accountId]/page.server.test.ts @@ -4,7 +4,7 @@ import { testConfig } from '#lib/server/application.fixture.js'; import { beforeEach, expect, it, vi } from 'vitest'; import { readReportPublication, - countInvestmentActivities, + readInvestmentActivityCount, readInvestmentActivityPage, type AccountInvestmentActivityPage } from '@hledger-reports/snapshots'; @@ -15,7 +15,7 @@ import { load } from './+page.server.js'; vi.mock('@hledger-reports/snapshots', () => ({ readReportPublication: vi.fn(), - countInvestmentActivities: vi.fn(), + readInvestmentActivityCount: vi.fn(), readInvestmentActivityPage: vi.fn() })); vi.mock('#lib/server/registers/investment/projection.js', () => ({ @@ -84,13 +84,13 @@ function event( beforeEach(() => { vi.resetAllMocks(); vi.mocked(readReportPublication).mockResolvedValue(publication); - vi.mocked(countInvestmentActivities).mockResolvedValue(51); + vi.mocked(readInvestmentActivityCount).mockResolvedValue(51); vi.mocked(readInvestmentActivityPage).mockResolvedValue(activityPage); vi.mocked(projectInvestmentActivityPage).mockReturnValue(projection); }); -it('counts and pages original activities in one publication, not the enclosing transaction count', async () => { - vi.mocked(countInvestmentActivities).mockImplementation(async (pinned) => { +it('pages by the saved posting count in one publication, not the enclosing entry count', async () => { + vi.mocked(readInvestmentActivityCount).mockImplementation(async (pinned) => { expect(pinned).toBe(publication); vi.mocked(readReportPublication).mockResolvedValue(null); return 51; @@ -113,7 +113,7 @@ it('counts and pages original activities in one publication, not the enclosing t } }); expect(readReportPublication).toHaveBeenCalledOnce(); - expect(countInvestmentActivities).toHaveBeenCalledExactlyOnceWith(publication, id); + expect(readInvestmentActivityCount).toHaveBeenCalledExactlyOnceWith(publication, id); expect(readInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(publication, id, { order: 'desc', offset: 50, @@ -127,8 +127,8 @@ it.each(['count', 'page'] as const)( 'returns a safe read failure when the saved %s cannot be read', async (operation) => { if (operation === 'count') - vi.mocked(countInvestmentActivities).mockRejectedValue( - new Error('PRIVATE native count diagnostic') + vi.mocked(readInvestmentActivityCount).mockRejectedValue( + new Error('PRIVATE saved count diagnostic') ); else vi.mocked(readInvestmentActivityPage).mockRejectedValue( @@ -172,20 +172,26 @@ it('rejects disabled and wrong-kind members without activity reads', async () => ]) ) ).rejects.toMatchObject({ status: 404 }); - expect(countInvestmentActivities).not.toHaveBeenCalled(); + expect(readInvestmentActivityCount).not.toHaveBeenCalled(); expect(readInvestmentActivityPage).not.toHaveBeenCalled(); }); -it('does not count, read or project ambiguous or declared-empty accounts', async () => { +it('does not count or read activity for an ambiguous account', async () => { vi.mocked(readReportPublication).mockResolvedValue({ ...publication, accounts: [{ id, name, access: 'ambiguous', rowCount: null, summary: { status: 'ambiguous' } }] }); expect(await load(event())).toMatchObject({ access: 'ambiguous', register: null }); + expect(readInvestmentActivityCount).not.toHaveBeenCalled(); + expect(readInvestmentActivityPage).not.toHaveBeenCalled(); +}); + +it('uses the saved posting count for a readable empty account', async () => { vi.mocked(readReportPublication).mockResolvedValue({ ...publication, accounts: [{ id, name, access: 'ready', rowCount: 0, summary: { status: 'undated' } }] }); + vi.mocked(readInvestmentActivityCount).mockResolvedValue(0); expect(await load(event())).toMatchObject({ readFailed: false, register: { @@ -197,7 +203,7 @@ it('does not count, read or project ambiguous or declared-empty accounts', async unclassifiedEndingCash: [] } }); - expect(countInvestmentActivities).not.toHaveBeenCalled(); + expect(readInvestmentActivityCount).toHaveBeenCalledOnce(); expect(readInvestmentActivityPage).not.toHaveBeenCalled(); expect(projectInvestmentActivityPage).not.toHaveBeenCalled(); }); @@ -206,13 +212,13 @@ it('rejects unknown accounts before activity IO', async () => { const request = event(); request.params.accountId = 'unknown1'; await expect(load(request)).rejects.toMatchObject({ status: 404 }); - expect(countInvestmentActivities).not.toHaveBeenCalled(); + expect(readInvestmentActivityCount).not.toHaveBeenCalled(); expect(readInvestmentActivityPage).not.toHaveBeenCalled(); }); it('rejects pages outside the activity count before reading canonical activity bodies', async () => { await expect(load(event('page=3'))).rejects.toMatchObject({ status: 404 }); - expect(countInvestmentActivities).toHaveBeenCalledOnce(); + expect(readInvestmentActivityCount).toHaveBeenCalledOnce(); expect(readInvestmentActivityPage).not.toHaveBeenCalled(); }); @@ -232,13 +238,13 @@ it('waits for the parent layout before using the request-pinned publication', as expect(await Promise.race([loading, nextTurn])).toBe(pending); expect(parent).toHaveBeenCalledOnce(); expect(readReportPublication).not.toHaveBeenCalled(); - expect(countInvestmentActivities).not.toHaveBeenCalled(); + expect(readInvestmentActivityCount).not.toHaveBeenCalled(); } finally { releaseParent.resolve(); await loading; } expect(readReportPublication).not.toHaveBeenCalled(); - expect(countInvestmentActivities).toHaveBeenCalledExactlyOnceWith(publication, id); + expect(readInvestmentActivityCount).toHaveBeenCalledExactlyOnceWith(publication, id); expect(readInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(publication, id, { order: 'asc', offset: 50, @@ -252,7 +258,7 @@ it('requires an application without reading reports or parent data', async () => await expect(load(request)).rejects.toMatchObject({ status: 503 }); expect(request.parent).not.toHaveBeenCalled(); expect(readReportPublication).not.toHaveBeenCalled(); - expect(countInvestmentActivities).not.toHaveBeenCalled(); + expect(readInvestmentActivityCount).not.toHaveBeenCalled(); expect(readInvestmentActivityPage).not.toHaveBeenCalled(); }); @@ -263,7 +269,7 @@ it.each(['missing', 'unreadable', 'journal-changed'] as const)( request.locals.savedReports = Promise.resolve({ status }); await expect(load(request)).rejects.toMatchObject({ status: 503 }); expect(readReportPublication).not.toHaveBeenCalled(); - expect(countInvestmentActivities).not.toHaveBeenCalled(); + expect(readInvestmentActivityCount).not.toHaveBeenCalled(); expect(readInvestmentActivityPage).not.toHaveBeenCalled(); } ); diff --git a/packages/db/src/reports/index.ts b/packages/db/src/reports/index.ts index c92cb97..2545904 100644 --- a/packages/db/src/reports/index.ts +++ b/packages/db/src/reports/index.ts @@ -19,7 +19,7 @@ export { readPublicationInvestmentJson, readAccountActivityPage, readAccountActivityDetail, - countAccountInvestmentActivities, + readAccountInvestmentActivityCount, readAccountInvestmentActivityPage } from './queries.js'; export type { diff --git a/packages/db/src/reports/prepared-register-rows.ts b/packages/db/src/reports/prepared-register-rows.ts index cff8f03..c69fa57 100644 --- a/packages/db/src/reports/prepared-register-rows.ts +++ b/packages/db/src/reports/prepared-register-rows.ts @@ -24,19 +24,13 @@ export async function readRegisterRowReferencePage( database: Kysely, accountName: string, rowKind: ReportDatabase['prepared_register_rows']['row_kind'], - expectedRowCount: number, + savedTotalRowCount: number, { order, offset }: RegisterPageOptions ) { - const registerRows = database + const references = await database .selectFrom('prepared_register_rows') .where('account_name', '=', accountName) - .where('row_kind', '=', rowKind); - const { rowCount } = await registerRows - .select(({ fn }) => fn.countAll().as('rowCount')) - .executeTakeFirstOrThrow(); - if (rowCount !== expectedRowCount) throw new Error('Invalid prepared register rows.'); - - const references = await registerRows + .where('row_kind', '=', rowKind) .select([ 'display_date', 'entry_ordinal as accountOrdinal', @@ -50,8 +44,8 @@ export async function readRegisterRowReferencePage( .offset(offset) .limit(registerPageSize) .execute(); - if (references.length !== Math.min(registerPageSize, Math.max(0, expectedRowCount - offset))) - throw new Error('Invalid prepared register rows.'); + const expectedPageLength = Math.min(registerPageSize, Math.max(0, savedTotalRowCount - offset)); + if (references.length !== expectedPageLength) throw new Error('Invalid prepared register rows.'); return references; } diff --git a/packages/db/src/reports/queries.test.ts b/packages/db/src/reports/queries.test.ts index 3fbc430..9670d56 100644 --- a/packages/db/src/reports/queries.test.ts +++ b/packages/db/src/reports/queries.test.ts @@ -13,7 +13,7 @@ import { import { readAccountActivityPage, readAccountActivityDetail, - countAccountInvestmentActivities, + readAccountInvestmentActivityCount, readAccountInvestmentActivityPage, findOldestFirstAccountActivityOffset, readReportData, @@ -394,8 +394,7 @@ it('reads date-ordered pages with native ties and exact account scope', async () .where('row_kind', '=', 'entry') .where('entry_ordinal', '=', 0) .execute(); - // 52 references remain, enough to fill the page but not enough to trust its offsets. - await expect(readPage('asc', 0)).rejects.toThrow('Invalid prepared register rows.'); + await expect(readPage('asc', 50)).rejects.toThrow('Invalid prepared register rows.'); expect(await readAccountActivityDetail(database, account, rows[0].transaction.index)).toEqual( rows[0] ); @@ -704,7 +703,7 @@ it('pages original selected-account postings across a shared security group and ); } } - expect(await countAccountInvestmentActivities(reader, account)).toBe(59); + expect(await readAccountInvestmentActivityCount(reader, account)).toBe(59); const first = await readAccountInvestmentActivityPage(pageReader, account, { order: 'desc', offset: 0, @@ -857,15 +856,18 @@ it('prepares entry and posting rows with the original last visible sibling', asy } ]); - const postingCounts = await database - .selectFrom('account_activity_summaries') - .select(['account_name', 'posting_row_count']) - .orderBy('account_name') + expect(await readAccountInvestmentActivityCount(database, account)).toBe(2); + await expect(readAccountInvestmentActivityCount(database, otherAccount)).rejects.toThrow( + 'Invalid prepared posting count.' + ); + await database + .updateTable('account_activity_summaries') + .set({ posting_row_count: 0 }) + .where('account_name', '=', otherAccount.name) .execute(); - expect(postingCounts).toEqual([ - { account_name: account.name, posting_row_count: 2 }, - { account_name: otherAccount.name, posting_row_count: null } - ]); + await expect(readAccountInvestmentActivityCount(database, otherAccount)).rejects.toThrow( + 'Invalid prepared posting count.' + ); const entryPage = { order: 'asc', offset: 0 } as const; const entryRows = await readRegisterRowReferencePage( @@ -879,6 +881,16 @@ it('prepares entry and posting rows with the original last visible sibling', asy expect( await readRegisterRowReferencePage(database, otherAccount.name, 'entry', 0, entryPage) ).toEqual([]); + + await database + .updateTable('account_activity') + .set({ context_json: sql`json_remove(context_json, '$.accountPostingIndexes')` }) + .where('account_name', '=', account.name) + .execute(); + expect(await readAccountInvestmentActivityCount(database, account)).toBe(2); + await expect( + readAccountInvestmentActivityPage(database, account, { ...entryPage, limit: 50 }) + ).rejects.toThrow('Invalid account posting data.'); }); it('keeps security anchors and standalone activities while retaining supporting cash only as context', async () => { @@ -956,7 +968,6 @@ it('keeps security anchors and standalone activities while retaining supporting entryActivityPosition: position + 1, entryActivityCount: cases[index].visible.length })); - expect(await countAccountInvestmentActivities(database, account)).toBe(expected.length); const page = await readAccountInvestmentActivityPage(database, account, { order: 'asc', offset: 0, @@ -1007,7 +1018,6 @@ it('keeps security anchors and standalone activities while retaining supporting }) .where('account_name', '=', accounts[0].name) .execute(); - await expect(countAccountInvestmentActivities(database, accounts[0])).rejects.toThrow(); await expect( readAccountInvestmentActivityPage(database, accounts[0], { order: 'asc', @@ -1093,7 +1103,6 @@ it('retains uncertain original cash actions and numbers the full visible entry b entryActivityPosition: postingIndex + 1, entryActivityCount: 7 })); - expect(await countAccountInvestmentActivities(database, account)).toBe(7); for (const order of ['asc', 'desc'] as const) { const ordered = order === 'asc' ? [...expected].reverse() : expected; for (let offset = 0; offset < 8; offset += 2) { @@ -1144,21 +1153,23 @@ it('enforces account membership, access, summaries and bounded posting page opti [empty.name, preparedActivitySummary()] ]) ); + await writeRegisterRowsAndPostingCount(transaction, account.name, rows.length); + await writeRegisterRowsAndPostingCount(transaction, empty.name, 0); await transaction.commit().execute(); } finally { if (!transaction.isCommitted && !transaction.isRolledBack) await transaction.rollback().execute(); } const options = { order: 'asc', offset: 0, limit: 50 } as const; - expect(await countAccountInvestmentActivities(database, empty)).toBe(0); + expect(await readAccountInvestmentActivityCount(database, empty)).toBe(0); expect(await readAccountInvestmentActivityPage(database, empty, options)).toEqual({ rows: [], summary: preparedActivitySummary() }); - expect(await countAccountInvestmentActivities(database, unavailable)).toBeNull(); + expect(await readAccountInvestmentActivityCount(database, unavailable)).toBeNull(); expect(await readAccountInvestmentActivityPage(database, unavailable, options)).toBeNull(); const wrongAccount = { ...account, name: empty.name }; - await expect(countAccountInvestmentActivities(database, wrongAccount)).rejects.toThrow(); + await expect(readAccountInvestmentActivityCount(database, wrongAccount)).rejects.toThrow(); await expect( readAccountInvestmentActivityPage(database, wrongAccount, options) ).rejects.toThrow(); @@ -1171,7 +1182,9 @@ it('enforces account membership, access, summaries and bounded posting page opti .deleteFrom('account_activity_summaries') .where('account_name', '=', account.name) .execute(); - await expect(countAccountInvestmentActivities(database, account)).rejects.toThrow(); + await expect(readAccountInvestmentActivityCount(database, account)).rejects.toThrow( + 'Missing account activity summary.' + ); await expect(readAccountInvestmentActivityPage(database, account, options)).rejects.toThrow(); }); @@ -1209,7 +1222,6 @@ it('fails closed for missing or malformed saved posting references and selected .updateTable('account_activity') .set({ context_json: JSON.stringify({ ...context, accountPostingIndexes: refs }) }) .execute(); - await expect(countAccountInvestmentActivities(database, account)).rejects.toThrow(); await expect(readAccountInvestmentActivityPage(database, account, options)).rejects.toThrow(); } await database @@ -1224,9 +1236,7 @@ it('fails closed for missing or malformed saved posting references and selected .set({ original_json: exports[0].originalJson }) .execute(); await database.deleteFrom('transaction_postings').where('posting_ordinal', '=', 0).execute(); - await expect(countAccountInvestmentActivities(database, account)).rejects.toThrow(); await expect(readAccountInvestmentActivityPage(database, account, options)).rejects.toThrow(); await database.deleteFrom('account_activity').execute(); - await expect(countAccountInvestmentActivities(database, account)).rejects.toThrow(); await expect(readAccountInvestmentActivityPage(database, account, options)).rejects.toThrow(); }); diff --git a/packages/db/src/reports/queries.ts b/packages/db/src/reports/queries.ts index 8a0de04..ac7c433 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -356,7 +356,11 @@ function assertPageOptions(options: AccountActivityPageOptions): void { async function readAccountPageContext( database: Kysely, account: StoredAccount -): Promise<{ rowCount: number; summary: AccountActivitySummary } | null> { +): Promise<{ + rowCount: number; + postingRowCount: number | null; + summary: AccountActivitySummary; +} | null> { await assertStoredAccount(database, account); const storedSummary = await database .selectFrom('account_activity_summaries') @@ -383,7 +387,11 @@ async function readAccountPageContext( ) throw new Error('Invalid account data.'); if (!storedSummary) throw new Error('Missing account activity summary.'); - return { rowCount, summary: decodeActivitySummary(storedSummary) }; + return { + rowCount, + postingRowCount: storedSummary.posting_row_count, + summary: decodeActivitySummary(storedSummary) + }; } async function readAccountEntriesByOrdinal( @@ -458,15 +466,25 @@ export async function findOldestFirstAccountActivityOffset( return offset; } -export async function countAccountInvestmentActivities( +function isPlausibleSavedPostingCount( + visiblePostingCount: number | null, + entryCount: number +): visiblePostingCount is number { + if (visiblePostingCount === null || !Number.isSafeInteger(visiblePostingCount)) return false; + if (entryCount === 0) return visiblePostingCount === 0; + return visiblePostingCount >= entryCount; +} + +export async function readAccountInvestmentActivityCount( database: Kysely, account: StoredAccount ): Promise { const context = await readAccountPageContext(database, account); if (!context) return null; - const counts = await readInvestmentPostingCounts(database, account.name); - validateInvestmentPostingCounts(counts, context.rowCount); - return counts.visiblePostingCount; + const { rowCount: entryCount, postingRowCount: visiblePostingCount } = context; + if (!isPlausibleSavedPostingCount(visiblePostingCount, entryCount)) + throw new Error('Invalid prepared posting count.'); + return visiblePostingCount; } export async function readAccountInvestmentActivityPage( diff --git a/packages/snapshots/src/index.ts b/packages/snapshots/src/index.ts index 7504ac3..4e0100d 100644 --- a/packages/snapshots/src/index.ts +++ b/packages/snapshots/src/index.ts @@ -4,7 +4,7 @@ export { readReportPublication, readInvestmentOverview, readAccountPage, - countInvestmentActivities, + readInvestmentActivityCount, readInvestmentActivityPage, readAccountTransaction } from './reports/publication.js'; diff --git a/packages/snapshots/src/reports/publication.test.ts b/packages/snapshots/src/reports/publication.test.ts index 50f1149..2fa6e6f 100644 --- a/packages/snapshots/src/reports/publication.test.ts +++ b/packages/snapshots/src/reports/publication.test.ts @@ -10,7 +10,7 @@ import { DatabaseSync } from 'node:sqlite'; import * as timers from 'node:timers/promises'; import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import { - countInvestmentActivities, + readInvestmentActivityCount, createReportStage, readAccountPage, readAccountTransaction, @@ -322,7 +322,7 @@ it('does not mix two publications from different attempts of the same request', await expect(readAccountTransaction(pinned, id, 1)).rejects.toSatisfy( safeError('Unable to read account transactions') ); - await expect(countInvestmentActivities(pinned, id)).rejects.toSatisfy( + await expect(readInvestmentActivityCount(pinned, id)).rejects.toSatisfy( safeError('Unable to read account activity') ); await expect(readInvestmentActivityPage(pinned, id, { ...options, limit: 50 })).rejects.toSatisfy( @@ -942,7 +942,7 @@ it('rejects unsafe and uncatalogued account IDs before opening financial data', await expect(readAccountTransaction(publication, 'cash0001', 0)).rejects.toSatisfy( safeError('Unable to read account transactions') ); - await expect(countInvestmentActivities(publication, '../escape')).rejects.toSatisfy( + await expect(readInvestmentActivityCount(publication, '../escape')).rejects.toSatisfy( safeError('Unable to read account activity') ); await expect( diff --git a/packages/snapshots/src/reports/publication.ts b/packages/snapshots/src/reports/publication.ts index 81db3b0..f298137 100644 --- a/packages/snapshots/src/reports/publication.ts +++ b/packages/snapshots/src/reports/publication.ts @@ -21,7 +21,7 @@ import { isAccountSummary, readAccountActivityPage, readAccountActivityDetail, - countAccountInvestmentActivities, + readAccountInvestmentActivityCount, readAccountInvestmentActivityPage, readReportData, readPublicationRequest, @@ -198,7 +198,7 @@ export async function readAccountPage( } } -export async function countInvestmentActivities( +export async function readInvestmentActivityCount( publication: ReportPublication, id: string ): Promise { @@ -207,7 +207,7 @@ export async function countInvestmentActivities( const account = publication.accounts.find((entry) => entry.id === id); if (!account) throw new Error(); return await readFromSelectedPublication(publication, (database) => - countAccountInvestmentActivities(database, account) + readAccountInvestmentActivityCount(database, account) ); } catch { throw new Error('Unable to read account activity'); -- 2.54.1 From df1804a8ab5f2055f39711c52e0bba17e0be2ae4 Mon Sep 17 00:00:00 2001 From: eleith Date: Wed, 2 Dec 2026 11:11:16 -0800 Subject: [PATCH 11/19] refactor(registers): page saved Investment posting references --- .../registers/investment/projection.test.ts | 1 + .../server/registers/investment/projection.ts | 3 +- .../registers/investment/register.test.ts | 23 +- .../server/registers/investment/register.ts | 11 +- .../[accountId]/page.server.test.ts | 13 +- packages/db/src/reports/index.ts | 6 +- .../db/src/reports/investment-posting-rows.ts | 31 +-- packages/db/src/reports/queries.test.ts | 206 +++++++++--------- packages/db/src/reports/queries.ts | 149 ++++++------- packages/snapshots/src/index.ts | 1 - .../snapshots/src/reports/publication.test.ts | 4 +- packages/snapshots/src/reports/publication.ts | 3 +- 12 files changed, 198 insertions(+), 253 deletions(-) diff --git a/apps/web/src/lib/server/registers/investment/projection.test.ts b/apps/web/src/lib/server/registers/investment/projection.test.ts index 826a412..37ea240 100644 --- a/apps/web/src/lib/server/registers/investment/projection.test.ts +++ b/apps/web/src/lib/server/registers/investment/projection.test.ts @@ -110,6 +110,7 @@ function page(record: PreparedAccountRow, indexes = [0, 1], entryOrder = [0, 1]) rows: indexes.map((postingIndex) => ({ row: record, postingIndex, + displayDate: record.transaction.postings[postingIndex].date ?? record.transaction.date, entryActivityPosition: entryOrder.indexOf(postingIndex) + 1, entryActivityCount: entryOrder.length })), diff --git a/apps/web/src/lib/server/registers/investment/projection.ts b/apps/web/src/lib/server/registers/investment/projection.ts index 1e23654..7543a92 100644 --- a/apps/web/src/lib/server/registers/investment/projection.ts +++ b/apps/web/src/lib/server/registers/investment/projection.ts @@ -53,6 +53,7 @@ function projectInvestmentActivity( { row: accountRow, postingIndex, + displayDate, entryActivityPosition, entryActivityCount }: AccountInvestmentActivityPage['rows'][number], @@ -92,7 +93,7 @@ function projectInvestmentActivity( ) ] : [], - date: posting.date ?? transaction.date, + date: displayDate, statuses: [posting.effectiveStatus], payee: transaction.payee, notes, diff --git a/apps/web/src/lib/server/registers/investment/register.test.ts b/apps/web/src/lib/server/registers/investment/register.test.ts index 3760338..7560fbd 100644 --- a/apps/web/src/lib/server/registers/investment/register.test.ts +++ b/apps/web/src/lib/server/registers/investment/register.test.ts @@ -46,6 +46,7 @@ const page: AccountInvestmentActivityPage = { rows: row.accountPostingIndexes.slice(50).map((postingIndex) => ({ row, postingIndex, + displayDate: selectedPosting.date ?? row.transaction.date, entryActivityPosition: postingIndex + 1, entryActivityCount: 55 })), @@ -90,8 +91,7 @@ it('reads one pinned publication at fixed size without separately recounting and expect(readReportPublication).toHaveBeenCalledOnce(); expect(readInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(publication, accountId, { order: 'desc', - offset: 50, - limit: 50 + offset: 50 }); expect(readInvestmentActivityCount).not.toHaveBeenCalled(); expect(Object.keys(result)).toEqual(['batchStart', 'activities']); @@ -170,18 +170,20 @@ it('uses the integrity-verified empty result for out-of-range positions, not the expect(readInvestmentActivityCount).not.toHaveBeenCalled(); }); -it('permits only batch zero for declared-empty accounts without reading a body', async () => { +it('permits only batch zero for empty accounts and checks the saved page', async () => { vi.mocked(readReportPublication).mockResolvedValue({ ...publication, accounts: publication.accounts.map((account) => ({ ...account, rowCount: 0 })) }); - expect(await readActivityBatch(locals(), { ...request, batchStart: 0 })).toEqual({ - batchStart: 0, - activities: [] - }); + vi.mocked(readInvestmentActivityPage).mockResolvedValue({ ...page, rows: [] }); + const batchZero = { ...request, batchStart: 0 }; + expect(await readActivityBatch(locals(), batchZero)).toEqual({ batchStart: 0, activities: [] }); await expect(readActivityBatch(locals(), request)).rejects.toMatchObject({ status: 404 }); - expect(readInvestmentActivityPage).not.toHaveBeenCalled(); - expect(readInvestmentActivityCount).not.toHaveBeenCalled(); + expect(readInvestmentActivityPage).toHaveBeenCalledOnce(); + vi.mocked(readInvestmentActivityPage).mockRejectedValue( + new Error('Unable to read account activity') + ); + await expect(readActivityBatch(locals(), batchZero)).rejects.toMatchObject({ status: 503 }); }); it('sanitizes missing, foreign and unreadable publications before activity reads', async () => { @@ -234,8 +236,7 @@ it('returns an SSR read failure when a counted initial page cannot be projected' expect(result).toMatchObject({ readFailed: true, register: null }); expect(readInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(publication, accountId, { order: 'asc', - offset: 50, - limit: 50 + offset: 50 }); expect(JSON.stringify(result)).not.toContain('PRIVATE'); }); diff --git a/apps/web/src/lib/server/registers/investment/register.ts b/apps/web/src/lib/server/registers/investment/register.ts index 437a8e4..90c8779 100644 --- a/apps/web/src/lib/server/registers/investment/register.ts +++ b/apps/web/src/lib/server/registers/investment/register.ts @@ -44,10 +44,7 @@ export async function readActivityBatch( 'investment', request.accountId ); - if (account.rowCount === 0) { - if (request.batchStart !== 0) error(404, 'History position not found.'); - return { batchStart: 0, activities: [] }; - } + if (account.rowCount === 0 && request.batchStart !== 0) error(404, 'History position not found.'); let page: AccountInvestmentActivityPage; let activities: ActivityBatch['activities']; try { @@ -56,8 +53,7 @@ export async function readActivityBatch( } catch { error(503, 'Prepared history could not be read.'); } - // The saved reader already verifies the visible count and the exact page length. - if (page.rows.length === 0) error(404, 'History position not found.'); + if (page.rows.length === 0 && account.rowCount > 0) error(404, 'History position not found.'); return { batchStart: request.batchStart, activities }; } @@ -122,8 +118,7 @@ async function readSavedActivityPage( ): Promise { const page = await readInvestmentActivityPage(account.publication, account.id, { order, - offset: batchStart, - limit: activityBatchSize + offset: batchStart }); if (!page) throw new Error('Prepared account rows unavailable.'); return page; diff --git a/apps/web/src/routes/(protected)/registers/investments/[accountId]/page.server.test.ts b/apps/web/src/routes/(protected)/registers/investments/[accountId]/page.server.test.ts index 482a5bc..6f13dfa 100644 --- a/apps/web/src/routes/(protected)/registers/investments/[accountId]/page.server.test.ts +++ b/apps/web/src/routes/(protected)/registers/investments/[accountId]/page.server.test.ts @@ -34,6 +34,7 @@ const activityPage: AccountInvestmentActivityPage = { rows: preparedAccountRows().map((row) => ({ row, postingIndex: 0, + displayDate: row.transaction.postings[0].date ?? row.transaction.date, entryActivityPosition: 1, entryActivityCount: 1 })), @@ -116,8 +117,7 @@ it('pages by the saved posting count in one publication, not the enclosing entry expect(readInvestmentActivityCount).toHaveBeenCalledExactlyOnceWith(publication, id); expect(readInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(publication, id, { order: 'desc', - offset: 50, - limit: 50 + offset: 50 }); expect(projectInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(activityPage, name); expect(request.setHeaders).toHaveBeenCalledWith({ 'cache-control': 'no-store' }); @@ -151,14 +151,12 @@ it('defaults descending to the first activity page and ascending to the last', a await load(event('order=desc')); expect(readInvestmentActivityPage).toHaveBeenLastCalledWith(publication, id, { order: 'desc', - offset: 0, - limit: 50 + offset: 0 }); await load(event()); expect(readInvestmentActivityPage).toHaveBeenLastCalledWith(publication, id, { order: 'asc', - offset: 50, - limit: 50 + offset: 50 }); }); @@ -247,8 +245,7 @@ it('waits for the parent layout before using the request-pinned publication', as expect(readInvestmentActivityCount).toHaveBeenCalledExactlyOnceWith(publication, id); expect(readInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(publication, id, { order: 'asc', - offset: 50, - limit: 50 + offset: 50 }); }); diff --git a/packages/db/src/reports/index.ts b/packages/db/src/reports/index.ts index 2545904..bc89095 100644 --- a/packages/db/src/reports/index.ts +++ b/packages/db/src/reports/index.ts @@ -22,11 +22,7 @@ export { readAccountInvestmentActivityCount, readAccountInvestmentActivityPage } from './queries.js'; -export type { - AccountActivityPage, - AccountActivityPageOptions, - AccountInvestmentActivityPage -} from './queries.js'; +export type { AccountActivityPage, AccountInvestmentActivityPage } from './queries.js'; export { writeRegisterRowsAndPostingCount, type RegisterPageOptions diff --git a/packages/db/src/reports/investment-posting-rows.ts b/packages/db/src/reports/investment-posting-rows.ts index 63e69dc..5ffa4c6 100644 --- a/packages/db/src/reports/investment-posting-rows.ts +++ b/packages/db/src/reports/investment-posting-rows.ts @@ -28,7 +28,6 @@ interface PostingReferenceCounts { last_ordinal: number | null; posting_count: number; distinct_posting_count: number; - visiblePostingCount: number | null; invalid_count: number | null; } @@ -41,36 +40,9 @@ export async function validateRawAccountPostingReferences( validatePostingReferenceCounts(counts, expectedEntryCount); } -export function readInvestmentPostingCounts( - database: Kysely, - accountName: string -): Promise { - return readPostingReferenceCounts( - database, - accountName, - sql`count(case when ${isVisibleInvestmentActivity()} then reference.key end)` - ); -} - -export function validateInvestmentPostingCounts( - counts: PostingReferenceCounts, - expectedEntryCount: number -): asserts counts is PostingReferenceCounts & { visiblePostingCount: number } { - validatePostingReferenceCounts(counts, expectedEntryCount); - const { visiblePostingCount } = counts; - if ( - visiblePostingCount === null || - !Number.isSafeInteger(visiblePostingCount) || - visiblePostingCount < 0 || - visiblePostingCount > counts.posting_count - ) - throw new Error('Invalid account posting data.'); -} - async function readPostingReferenceCounts( database: Kysely, - accountName: string, - visibleCount = sql`null` + accountName: string ): Promise { const postingBelongsToAccountTree = sql`(posting.account_name = ${accountName} or (posting.account_name >= ${`${accountName}:`} @@ -83,7 +55,6 @@ async function readPostingReferenceCounts( min(activity.ordinal) as first_ordinal, max(activity.ordinal) as last_ordinal, count(reference.key) as posting_count, count(distinct activity.ordinal || ':' || reference.value) as distinct_posting_count, - ${visibleCount} as visiblePostingCount, sum(case when json_type(activity.context_json, '$.accountPostingIndexes') is not 'array' or reference.type is not 'integer' or reference.value < 0 diff --git a/packages/db/src/reports/queries.test.ts b/packages/db/src/reports/queries.test.ts index 9670d56..290b6f4 100644 --- a/packages/db/src/reports/queries.test.ts +++ b/packages/db/src/reports/queries.test.ts @@ -22,6 +22,7 @@ import { writeReportData as writePublicationData } from './queries.js'; import type { ReportTransaction } from '../database.js'; +import { validateRawAccountPostingReferences } from './investment-posting-rows.js'; import { readRegisterRowReferencePage, writeRegisterRowsAndPostingCount @@ -673,46 +674,21 @@ it('pages original selected-account postings across a shared security group and const reference = (ordinal: number, postingIndex: number) => ({ row: rows[ordinal], postingIndex, + displayDate: ordinal !== 0 && postingIndex === 1 ? '2026-04-28' : '2026-04-29', entryActivityPosition: postingIndex + 1, entryActivityCount: rows[ordinal].accountPostingIndexes.length }); const main = rows[0].accountPostingIndexes.map((index) => reference(0, index)); const ascending = [reference(1, 1), reference(2, 1), ...main, reference(1, 0), reference(2, 0)]; const descending = [...main, reference(1, 0), reference(2, 0), reference(1, 1), reference(2, 1)]; - for (const [order, ordered] of [ - ['asc', ascending], - ['desc', descending] - ] as const) { - for (const offset of [0, 50]) { - const storedPage = await readRegisterRowReferencePage( - reader, - account.name, - 'posting', - ordered.length, - { - order, - offset - } - ); - expect( - storedPage.map(({ accountOrdinal, posting_ordinal }) => [accountOrdinal, posting_ordinal]) - ).toEqual( - ordered - .slice(offset, offset + 50) - .map(({ row, postingIndex }) => [rows.indexOf(row), postingIndex]) - ); - } - } expect(await readAccountInvestmentActivityCount(reader, account)).toBe(59); const first = await readAccountInvestmentActivityPage(pageReader, account, { order: 'desc', - offset: 0, - limit: 50 + offset: 0 }); const last = await readAccountInvestmentActivityPage(pageReader, account, { order: 'desc', - offset: 50, - limit: 50 + offset: 50 }); expect(first).toEqual({ rows: descending.slice(0, 50), summary: preparedActivitySummary(rows) }); expect(last).toEqual({ rows: descending.slice(50), summary: first?.summary }); @@ -722,8 +698,7 @@ it('pages original selected-account postings across a shared security group and ( await readAccountInvestmentActivityPage(reader, account, { order: 'asc', - offset: 0, - limit: 50 + offset: 0 }) )?.rows ).toEqual(ascending.slice(0, 50)); @@ -731,8 +706,7 @@ it('pages original selected-account postings across a shared security group and ( await readAccountInvestmentActivityPage(reader, account, { order: 'asc', - offset: 50, - limit: 50 + offset: 50 }) )?.rows ).toEqual(ascending.slice(50)); @@ -740,13 +714,32 @@ it('pages original selected-account postings across a shared security group and ( await readAccountInvestmentActivityPage(reader, account, { order: 'asc', - offset: 59, - limit: 50 + offset: 59 }) )?.rows ).toEqual([]); expect(await readAccountActivityDetail(reader, account, 3)).toEqual(rows[0]); expect(await readFile(path)).toEqual(before); + + const native = new DatabaseSync(path); + try { + native + .prepare( + ` + UPDATE account_activity SET context_json = json_remove(context_json, '$.accountPostingIndexes') + WHERE account_name = ? AND ordinal = 1 + ` + ) + .run(account.name); + } finally { + native.close(); + } + expect( + await readAccountInvestmentActivityPage(reader, account, { order: 'desc', offset: 0 }) + ).toEqual(first); + await expect( + readAccountInvestmentActivityPage(reader, account, { order: 'desc', offset: 50 }) + ).rejects.toThrow('Invalid account data.'); }); it('prepares entry and posting rows with the original last visible sibling', async () => { @@ -888,9 +881,9 @@ it('prepares entry and posting rows with the original last visible sibling', asy .where('account_name', '=', account.name) .execute(); expect(await readAccountInvestmentActivityCount(database, account)).toBe(2); - await expect( - readAccountInvestmentActivityPage(database, account, { ...entryPage, limit: 50 }) - ).rejects.toThrow('Invalid account posting data.'); + await expect(readAccountInvestmentActivityPage(database, account, entryPage)).rejects.toThrow( + 'Invalid account data.' + ); }); it('keeps security anchors and standalone activities while retaining supporting cash only as context', async () => { @@ -956,6 +949,8 @@ it('keeps security anchors and standalone activities while retaining supporting accounts.map((account, index) => [account.name, preparedActivitySummary([rows[index]])]) ) ); + for (const account of accounts) + await writeRegisterRowsAndPostingCount(transaction, account.name, 1); await transaction.commit().execute(); } finally { if (!transaction.isCommitted && !transaction.isRolledBack) @@ -965,39 +960,29 @@ it('keeps security anchors and standalone activities while retaining supporting const expected = cases[index].visible.map((postingIndex, position) => ({ row: rows[index], postingIndex, + displayDate: '2026-04-30', entryActivityPosition: position + 1, entryActivityCount: cases[index].visible.length })); const page = await readAccountInvestmentActivityPage(database, account, { order: 'asc', - offset: 0, - limit: 50 + offset: 0 }); expect(page).toEqual({ rows: expected, summary: preparedActivitySummary([rows[index]]) }); if (expected.length > 1) expect(page?.rows[0].row).toBe(page?.rows[1].row); } - for (let offset = 0; offset <= 2; offset++) { - expect( - ( - await readAccountInvestmentActivityPage(database, accounts[1], { - order: 'asc', - offset, - limit: 1 - }) - )?.rows - ).toMatchObject( - offset < 2 - ? [ - { - row: rows[1], - postingIndex: offset, - entryActivityPosition: offset + 1, - entryActivityCount: 2 - } - ] - : [] - ); - } + + const twoBuys = accounts[1]; + await database + .updateTable('prepared_register_rows') + .set({ posting_ordinal: 0 }) + .where('account_name', '=', twoBuys.name) + .where('row_kind', '=', 'posting') + .where('position_in_entry', '=', 2) + .execute(); + await expect( + readAccountInvestmentActivityPage(database, twoBuys, { order: 'asc', offset: 0 }) + ).rejects.toThrow('Invalid account posting data.'); const saved = await database .selectFrom('account_activity') @@ -1005,7 +990,7 @@ it('keeps security anchors and standalone activities while retaining supporting .where('account_name', '=', accounts[0].name) .executeTakeFirstOrThrow(); const context = JSON.parse(saved.context_json); - // Even an off-page supporting cash reference must retain raw membership integrity. + // Preparation validates supporting cash before it omits those references. for (const hiddenRefs of [[999], [2], ['1'], [1, 1]]) { await database .updateTable('account_activity') @@ -1019,12 +1004,8 @@ it('keeps security anchors and standalone activities while retaining supporting .where('account_name', '=', accounts[0].name) .execute(); await expect( - readAccountInvestmentActivityPage(database, accounts[0], { - order: 'asc', - offset: 50, - limit: 1 - }) - ).rejects.toThrow(); + validateRawAccountPostingReferences(database, accounts[0].name, 1) + ).rejects.toThrow('Invalid account posting data.'); } }); @@ -1092,6 +1073,7 @@ it('retains uncertain original cash actions and numbers the full visible entry b transaction, new Map([[account.name, preparedActivitySummary(rows)]]) ); + await writeRegisterRowsAndPostingCount(transaction, account.name, rows.length); await transaction.commit().execute(); } finally { if (!transaction.isCommitted && !transaction.isRolledBack) @@ -1100,24 +1082,18 @@ it('retains uncertain original cash actions and numbers the full visible entry b const expected = Array.from({ length: 7 }, (_, postingIndex) => ({ row, postingIndex, + displayDate: `2026-05-${20 - postingIndex}`, entryActivityPosition: postingIndex + 1, entryActivityCount: 7 })); for (const order of ['asc', 'desc'] as const) { const ordered = order === 'asc' ? [...expected].reverse() : expected; - for (let offset = 0; offset < 8; offset += 2) { - const page = await readAccountInvestmentActivityPage(database, account, { - order, - offset, - limit: 2 - }); - expect(page?.rows).toMatchObject(ordered.slice(offset, offset + 2)); - } + const page = await readAccountInvestmentActivityPage(database, account, { order, offset: 0 }); + expect(page?.rows).toEqual(ordered); } const page = await readAccountInvestmentActivityPage(database, account, { order: 'desc', - offset: 1, - limit: 1 + offset: 1 }); expect(page?.rows[0].row.transaction.postings[1]).toMatchObject({ date: '2026-05-19', @@ -1160,12 +1136,20 @@ it('enforces account membership, access, summaries and bounded posting page opti if (!transaction.isCommitted && !transaction.isRolledBack) await transaction.rollback().execute(); } - const options = { order: 'asc', offset: 0, limit: 50 } as const; + const options = { order: 'asc', offset: 0 } as const; expect(await readAccountInvestmentActivityCount(database, empty)).toBe(0); expect(await readAccountInvestmentActivityPage(database, empty, options)).toEqual({ rows: [], summary: preparedActivitySummary() }); + await database + .updateTable('account_activity_summaries') + .set({ posting_row_count: null }) + .where('account_name', '=', empty.name) + .execute(); + await expect(readAccountInvestmentActivityPage(database, empty, options)).rejects.toThrow( + 'Invalid prepared posting count.' + ); expect(await readAccountInvestmentActivityCount(database, unavailable)).toBeNull(); expect(await readAccountInvestmentActivityPage(database, unavailable, options)).toBeNull(); const wrongAccount = { ...account, name: empty.name }; @@ -1173,11 +1157,9 @@ it('enforces account membership, access, summaries and bounded posting page opti await expect( readAccountInvestmentActivityPage(database, wrongAccount, options) ).rejects.toThrow(); - for (const invalid of [{ offset: -1 }, { offset: 0.5 }, { limit: 0 }, { limit: 51 }]) { - await expect( - readAccountInvestmentActivityPage(database, account, { ...options, ...invalid }) - ).rejects.toThrow(); - } + await expect( + readAccountInvestmentActivityPage(database, account, { ...options, offset: -1 }) + ).rejects.toThrow('Invalid account page.'); await database .deleteFrom('account_activity_summaries') .where('account_name', '=', account.name) @@ -1188,7 +1170,7 @@ it('enforces account membership, access, summaries and bounded posting page opti await expect(readAccountInvestmentActivityPage(database, account, options)).rejects.toThrow(); }); -it('fails closed for missing or malformed saved posting references and selected canonical parents', async () => { +it('rejects damaged selected Investment references and canonical entries', async () => { const database = await createDatabase(); const account = { id: 'cash0001', ...ready() }; const exports = accountTransactionExportsFixture(); @@ -1206,37 +1188,47 @@ it('fails closed for missing or malformed saved posting references and selected transaction, new Map([[account.name, preparedActivitySummary(rows)]]) ); + await writeRegisterRowsAndPostingCount(transaction, account.name, rows.length); await transaction.commit().execute(); } finally { if (!transaction.isCommitted && !transaction.isRolledBack) await transaction.rollback().execute(); } - const saved = await database - .selectFrom('account_activity') - .select('context_json') - .executeTakeFirstOrThrow(); - const context = JSON.parse(saved.context_json); - const options = { order: 'asc', offset: 0, limit: 50 } as const; - for (const refs of [undefined, [], ['0'], [999], [1], [0, 0]]) { - await database - .updateTable('account_activity') - .set({ context_json: JSON.stringify({ ...context, accountPostingIndexes: refs }) }) - .execute(); - await expect(readAccountInvestmentActivityPage(database, account, options)).rejects.toThrow(); - } - await database - .updateTable('account_activity') - .set({ context_json: saved.context_json }) - .execute(); + const readPage = () => + readAccountInvestmentActivityPage(database, account, { order: 'asc', offset: 0 }); + expect(await readPage()).toEqual({ + rows: [ + { + row: rows[0], + postingIndex: 0, + displayDate: '2026-04-30', + entryActivityPosition: 1, + entryActivityCount: 1 + } + ], + summary: preparedActivitySummary(rows) + }); + const wrong = accountTransactionExportsFixture(1, 'wrong identity', 99)[0]; await database.updateTable('transactions').set({ original_json: wrong.originalJson }).execute(); - await expect(readAccountInvestmentActivityPage(database, account, options)).rejects.toThrow(); + await expect(readPage()).rejects.toThrow('Invalid account data.'); await database .updateTable('transactions') .set({ original_json: exports[0].originalJson }) .execute(); - await database.deleteFrom('transaction_postings').where('posting_ordinal', '=', 0).execute(); - await expect(readAccountInvestmentActivityPage(database, account, options)).rejects.toThrow(); - await database.deleteFrom('account_activity').execute(); - await expect(readAccountInvestmentActivityPage(database, account, options)).rejects.toThrow(); + + const updateReference = database + .updateTable('prepared_register_rows') + .where('row_kind', '=', 'posting'); + const originalReference = { posting_ordinal: 0, display_date: '2026-04-30', entry_row_count: 1 }; + for (const damage of [ + { posting_ordinal: 1 }, + { display_date: '2026-05-01' }, + { entry_row_count: 2 } + ]) { + await updateReference.set({ ...originalReference, ...damage }).execute(); + await expect(readPage()).rejects.toThrow('Invalid account posting data.'); + } + await database.deleteFrom('prepared_register_rows').where('row_kind', '=', 'posting').execute(); + await expect(readPage()).rejects.toThrow('Invalid prepared register rows.'); }); diff --git a/packages/db/src/reports/queries.ts b/packages/db/src/reports/queries.ts index ac7c433..f2097d3 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -1,7 +1,6 @@ import type { PreparedAccountRow } from '@hledger-reports/hledger'; import { decodeNativeTransaction, prepareTransaction } from '@hledger-reports/hledger/transactions'; import { sql, type Kysely } from 'kysely'; -import { registerPageSize } from '../register-page.js'; import type { ReportDatabase } from '../schema.js'; import { hasAccountActivitySummary, @@ -15,14 +14,6 @@ import { type StoredAccount, type StoredReportData } from './data.js'; -import { - displayedPostingDate, - fromVisibleInvestmentPostings, - postingCountInEntry, - postingPositionInOriginalOrder, - readInvestmentPostingCounts, - validateInvestmentPostingCounts -} from './investment-posting-rows.js'; import { assertRegisterPageOptions, readRegisterRowReferencePage, @@ -40,16 +31,13 @@ export interface AccountInvestmentActivityPage { rows: { row: PreparedAccountRow; postingIndex: number; + displayDate: string; entryActivityPosition: number; entryActivityCount: number; }[]; summary: AccountActivitySummary; } -export interface AccountActivityPageOptions extends RegisterPageOptions { - limit: number; -} - type StoredActivityRow = Pick< ReportDatabase['account_activity'], 'ordinal' | 'account_date' | 'native_transaction_index' | 'context_json' @@ -346,13 +334,6 @@ export async function readAccountActivityDetail( return record ? decodeAccountRow(record, rowCount) : null; } -function assertPageOptions(options: AccountActivityPageOptions): void { - assertRegisterPageOptions(options); - const { limit } = options; - if (!Number.isSafeInteger(limit) || limit < 1 || limit > registerPageSize) - throw new Error('Invalid account page.'); -} - async function readAccountPageContext( database: Kysely, account: StoredAccount @@ -466,13 +447,16 @@ export async function findOldestFirstAccountActivityOffset( return offset; } -function isPlausibleSavedPostingCount( +function requireSavedInvestmentPostingCount( visiblePostingCount: number | null, entryCount: number -): visiblePostingCount is number { - if (visiblePostingCount === null || !Number.isSafeInteger(visiblePostingCount)) return false; - if (entryCount === 0) return visiblePostingCount === 0; - return visiblePostingCount >= entryCount; +): number { + if (visiblePostingCount !== null && Number.isSafeInteger(visiblePostingCount)) { + const agreesWithEntryCount = + entryCount === 0 ? visiblePostingCount === 0 : visiblePostingCount >= entryCount; + if (agreesWithEntryCount) return visiblePostingCount; + } + throw new Error('Invalid prepared posting count.'); } export async function readAccountInvestmentActivityCount( @@ -481,71 +465,80 @@ export async function readAccountInvestmentActivityCount( ): Promise { const context = await readAccountPageContext(database, account); if (!context) return null; - const { rowCount: entryCount, postingRowCount: visiblePostingCount } = context; - if (!isPlausibleSavedPostingCount(visiblePostingCount, entryCount)) - throw new Error('Invalid prepared posting count.'); - return visiblePostingCount; + return requireSavedInvestmentPostingCount(context.postingRowCount, context.rowCount); +} + +function resolvePreparedInvestmentActivity( + row: PreparedAccountRow | undefined, + { + display_date: displayDate, + posting_ordinal: originalPostingIndex, + position_in_entry: visiblePostingPosition, + entry_row_count: visiblePostingCount + }: Awaited>[number], + accountName: string +): AccountInvestmentActivityPage['rows'][number] { + if ( + !row || + originalPostingIndex === null || + !row.accountPostingIndexes.includes(originalPostingIndex) + ) + throw new Error('Invalid account posting data.'); + const hasValidVisiblePostingPosition = + Number.isSafeInteger(visiblePostingPosition) && + Number.isSafeInteger(visiblePostingCount) && + visiblePostingPosition >= 1 && + visiblePostingPosition <= visiblePostingCount && + visiblePostingCount <= row.accountPostingIndexes.length; + if (!hasValidVisiblePostingPosition) throw new Error('Invalid account posting data.'); + + const posting = row.transaction.postings[originalPostingIndex]; + const belongsToAccountTree = + posting.account === accountName || posting.account.startsWith(`${accountName}:`); + const matchesDisplayDate = (posting.date ?? row.transaction.date) === displayDate; + if (!belongsToAccountTree || !matchesDisplayDate) + throw new Error('Invalid account posting data.'); + return { + row, + postingIndex: originalPostingIndex, + displayDate, + entryActivityPosition: visiblePostingPosition, + entryActivityCount: visiblePostingCount + }; } export async function readAccountInvestmentActivityPage( database: Kysely, account: StoredAccount, - options: AccountActivityPageOptions + options: RegisterPageOptions ): Promise { - assertPageOptions(options); + assertRegisterPageOptions(options); const context = await readAccountPageContext(database, account); if (!context) return null; - const { rowCount, summary } = context; - const counts = await readInvestmentPostingCounts(database, account.name); - validateInvestmentPostingCounts(counts, rowCount); - const activityCount = counts.visiblePostingCount; - const { order, offset, limit } = options; - const { rows: orderedReferences } = await sql<{ - accountOrdinal: number; - posting_index: number; - entry_activity_position: number; - entry_activity_count: number; - }>` - select activity.ordinal as accountOrdinal, posting.posting_ordinal as posting_index, - ${postingPositionInOriginalOrder} as entry_activity_position, - ${postingCountInEntry} as entry_activity_count - ${fromVisibleInvestmentPostings(account.name)} - order by ${displayedPostingDate} ${order === 'asc' ? sql`asc` : sql`desc`}, - activity.ordinal asc, posting.posting_ordinal asc - limit ${limit} offset ${offset} - `.execute(database); - if (orderedReferences.length !== Math.min(limit, Math.max(0, activityCount - offset))) - throw new Error('Invalid account posting data.'); - + const { rowCount: entryCount, postingRowCount, summary } = context; + const activityCount = requireSavedInvestmentPostingCount(postingRowCount, entryCount); + const orderedReferences = await readRegisterRowReferencePage( + database, + account.name, + 'posting', + activityCount, + options + ); const entriesByAccountOrdinal = await readAccountEntriesByOrdinal( database, account.name, - rowCount, + entryCount, orderedReferences.map(({ accountOrdinal }) => accountOrdinal) ); - const rows = orderedReferences.map( - ({ - accountOrdinal, - posting_index: postingIndex, - entry_activity_position: entryActivityPosition, - entry_activity_count: entryActivityCount - }) => { - const row = entriesByAccountOrdinal.get(accountOrdinal); - if ( - !row || - !row.accountPostingIndexes.includes(postingIndex) || - !Number.isSafeInteger(entryActivityPosition) || - !Number.isSafeInteger(entryActivityCount) || - entryActivityPosition < 1 || - entryActivityPosition > entryActivityCount || - entryActivityCount > row.accountPostingIndexes.length - ) - throw new Error('Invalid account posting data.'); - const posting = row.transaction.postings[postingIndex]; - if (posting.account !== account.name && !posting.account.startsWith(`${account.name}:`)) - throw new Error('Invalid account posting data.'); - return { row, postingIndex, entryActivityPosition, entryActivityCount }; - } - ); + const selectedPostingKeys = new Set(); + const rows = orderedReferences.map((reference) => { + const { accountOrdinal: accountEntryOrdinal } = reference; + const entry = entriesByAccountOrdinal.get(accountEntryOrdinal); + const activity = resolvePreparedInvestmentActivity(entry, reference, account.name); + const postingKey = `${accountEntryOrdinal}:${activity.postingIndex}`; + if (selectedPostingKeys.has(postingKey)) throw new Error('Invalid account posting data.'); + selectedPostingKeys.add(postingKey); + return activity; + }); return { rows, summary }; } diff --git a/packages/snapshots/src/index.ts b/packages/snapshots/src/index.ts index 4e0100d..d442275 100644 --- a/packages/snapshots/src/index.ts +++ b/packages/snapshots/src/index.ts @@ -13,7 +13,6 @@ export type { StoredAccount, AccountActivitySummary, AccountActivityPage, - AccountActivityPageOptions, AccountInvestmentActivityPage } from '@hledger-reports/db/reports'; export { diff --git a/packages/snapshots/src/reports/publication.test.ts b/packages/snapshots/src/reports/publication.test.ts index 2fa6e6f..f6739ba 100644 --- a/packages/snapshots/src/reports/publication.test.ts +++ b/packages/snapshots/src/reports/publication.test.ts @@ -325,7 +325,7 @@ it('does not mix two publications from different attempts of the same request', await expect(readInvestmentActivityCount(pinned, id)).rejects.toSatisfy( safeError('Unable to read account activity') ); - await expect(readInvestmentActivityPage(pinned, id, { ...options, limit: 50 })).rejects.toSatisfy( + await expect(readInvestmentActivityPage(pinned, id, options)).rejects.toSatisfy( safeError('Unable to read account activity') ); await expect(readInvestmentOverview(pinned)).rejects.toSatisfy( @@ -946,7 +946,7 @@ it('rejects unsafe and uncatalogued account IDs before opening financial data', safeError('Unable to read account activity') ); await expect( - readInvestmentActivityPage(publication, '00000000', { order: 'asc', offset: 0, limit: 50 }) + readInvestmentActivityPage(publication, '00000000', { order: 'asc', offset: 0 }) ).rejects.toSatisfy(safeError('Unable to read account activity')); expect(reader).not.toHaveBeenCalled(); }); diff --git a/packages/snapshots/src/reports/publication.ts b/packages/snapshots/src/reports/publication.ts index f298137..1c89171 100644 --- a/packages/snapshots/src/reports/publication.ts +++ b/packages/snapshots/src/reports/publication.ts @@ -34,7 +34,6 @@ import { writeRegisterRowsAndPostingCount, type AccountActivitySummary, type AccountActivityPage, - type AccountActivityPageOptions, type AccountInvestmentActivityPage, type RegisterPageOptions, type StoredAccount, @@ -217,7 +216,7 @@ export async function readInvestmentActivityCount( export async function readInvestmentActivityPage( publication: ReportPublication, id: string, - options: AccountActivityPageOptions + options: RegisterPageOptions ): Promise { try { if (!isAccountId(id)) throw new Error(); -- 2.54.1 From 7d3b03d1f1434a306a687f77e0755643b29c91ad Mon Sep 17 00:00:00 2001 From: eleith Date: Wed, 2 Dec 2026 15:33:37 -0800 Subject: [PATCH 12/19] feat(db): locate the first register row for a saved entry --- .../db/src/reports/prepared-register-rows.ts | 35 +++++++++++- packages/db/src/reports/queries.test.ts | 53 +++++++++++++++---- packages/db/src/reports/queries.ts | 23 -------- 3 files changed, 77 insertions(+), 34 deletions(-) diff --git a/packages/db/src/reports/prepared-register-rows.ts b/packages/db/src/reports/prepared-register-rows.ts index c69fa57..3ae15b8 100644 --- a/packages/db/src/reports/prepared-register-rows.ts +++ b/packages/db/src/reports/prepared-register-rows.ts @@ -20,10 +20,12 @@ export function assertRegisterPageOptions({ order, offset }: RegisterPageOptions throw new Error('Invalid account page.'); } +type RegisterRowKind = ReportDatabase['prepared_register_rows']['row_kind']; + export async function readRegisterRowReferencePage( database: Kysely, accountName: string, - rowKind: ReportDatabase['prepared_register_rows']['row_kind'], + rowKind: RegisterRowKind, savedTotalRowCount: number, { order, offset }: RegisterPageOptions ) { @@ -49,6 +51,37 @@ export async function readRegisterRowReferencePage( return references; } +export async function findOldestFirstRegisterRowOffsetForEntry( + database: Kysely, + accountName: string, + rowKind: RegisterRowKind, + nativeEntryIndex: number +): Promise { + // Select the entry's references before sorting, so SQLite can seek by entry ordinal. + const { rows } = await sql<{ offset: number }>` + with target_entry_rows as materialized ( + select row.account_name, row.row_kind, row.display_date, row.entry_ordinal, row.position_in_entry + from account_activity as entry + join prepared_register_rows as row + on row.account_name = entry.account_name and row.entry_ordinal = entry.ordinal + where entry.account_name = ${accountName} + and entry.native_transaction_index = ${nativeEntryIndex} + and row.row_kind = ${rowKind} + ), first_visible_row as ( + select * from target_entry_rows + order by display_date, entry_ordinal, position_in_entry limit 1 + ) + select ( + select count(*) from prepared_register_rows as earlier + where earlier.account_name = target.account_name and earlier.row_kind = target.row_kind + and (earlier.display_date, earlier.entry_ordinal, earlier.position_in_entry) + < (target.display_date, target.entry_ordinal, target.position_in_entry) + ) as offset + from first_visible_row as target + `.execute(database); + return rows[0]?.offset ?? null; +} + export async function writeRegisterRowsAndPostingCount( database: ReportTransaction, accountName: string, diff --git a/packages/db/src/reports/queries.test.ts b/packages/db/src/reports/queries.test.ts index 290b6f4..bc2c585 100644 --- a/packages/db/src/reports/queries.test.ts +++ b/packages/db/src/reports/queries.test.ts @@ -15,7 +15,6 @@ import { readAccountActivityDetail, readAccountInvestmentActivityCount, readAccountInvestmentActivityPage, - findOldestFirstAccountActivityOffset, readReportData, writeAccountRows, writeAccountActivitySummaries, @@ -24,6 +23,7 @@ import { import type { ReportTransaction } from '../database.js'; import { validateRawAccountPostingReferences } from './investment-posting-rows.js'; import { + findOldestFirstRegisterRowOffsetForEntry, readRegisterRowReferencePage, writeRegisterRowsAndPostingCount } from './prepared-register-rows.js'; @@ -310,6 +310,7 @@ it('reads date-ordered pages with native ties and exact account scope', async () } const otherExports = caseDistinctExports(54); const otherRows = preparedAccountRowsFromExports(otherExports); + otherRows[0].accountDate = '2026-04-28'; const account = { id: 'cash0001', ...ready('assets:cash', rows.length) }; const other = { id: 'cash0002', ...ready('assets:Cash', otherRows.length) }; const transaction = await database.startTransaction().execute(); @@ -358,14 +359,31 @@ it('reads date-ordered pages with native ties and exact account scope', async () const secondPageOffset = 50; const targetIndex = ascending[secondPageOffset].transaction.index; - expect(await findOldestFirstAccountActivityOffset(database, account.name, targetIndex)).toBe( - secondPageOffset - ); - expect(await findOldestFirstAccountActivityOffset(database, other.name, targetIndex)).toBeNull(); expect( - await findOldestFirstAccountActivityOffset( + await findOldestFirstRegisterRowOffsetForEntry(database, account.name, 'entry', targetIndex) + ).toBe(secondPageOffset); + const sharedOrdinalEntryIndex = rows[0].transaction.index; + expect( + await findOldestFirstRegisterRowOffsetForEntry( database, account.name, + 'entry', + sharedOrdinalEntryIndex + ) + ).toBe(27); + expect( + await findOldestFirstRegisterRowOffsetForEntry( + database, + other.name, + 'entry', + sharedOrdinalEntryIndex + ) + ).toBeNull(); + expect( + await findOldestFirstRegisterRowOffsetForEntry( + database, + account.name, + 'entry', ascending[0].transaction.index ) ).toBe(0); @@ -604,7 +622,8 @@ it('pages original selected-account postings across a shared security group and const selected = Array.from({ length: selectedCount }, (_, postingIndex) => ({ ...native.tpostings[0], paccount: postingIndex % 2 === 0 ? 'assets:cash:stock' : 'assets:cash', - pdate: ordinal === 0 ? null : postingIndex === 0 ? '2026-04-29' : '2026-04-28', + pdate: + ordinal === 0 ? null : ordinal === 1 || postingIndex === 1 ? '2026-04-28' : '2026-04-29', pdate2: '2026-06-01', pstatus: ['Pending', 'Unmarked', 'Cleared'][postingIndex % 3], pamount: [ @@ -674,13 +693,27 @@ it('pages original selected-account postings across a shared security group and const reference = (ordinal: number, postingIndex: number) => ({ row: rows[ordinal], postingIndex, - displayDate: ordinal !== 0 && postingIndex === 1 ? '2026-04-28' : '2026-04-29', + displayDate: + ordinal === 1 || (ordinal === 2 && postingIndex === 1) ? '2026-04-28' : '2026-04-29', entryActivityPosition: postingIndex + 1, entryActivityCount: rows[ordinal].accountPostingIndexes.length }); const main = rows[0].accountPostingIndexes.map((index) => reference(0, index)); - const ascending = [reference(1, 1), reference(2, 1), ...main, reference(1, 0), reference(2, 0)]; - const descending = [...main, reference(1, 0), reference(2, 0), reference(1, 1), reference(2, 1)]; + const earlierPostings = [reference(1, 0), reference(1, 1), reference(2, 1)]; + const ascending = [...earlierPostings, ...main, reference(2, 0)]; + const descending = [...main, reference(2, 0), ...earlierPostings]; + // Entry 2 starts at its second original posting, after both visible postings of entry 1. + expect(await findOldestFirstRegisterRowOffsetForEntry(reader, account.name, 'posting', 2)).toBe( + 2 + ); + expect(await findOldestFirstRegisterRowOffsetForEntry(reader, account.name, 'posting', 3)).toBe( + 3 + ); + expect(await findOldestFirstRegisterRowOffsetForEntry(reader, account.name, 'entry', 3)).toBe(0); + expect(await findOldestFirstRegisterRowOffsetForEntry(reader, account.name, 'entry', 1)).toBe(1); + expect( + await findOldestFirstRegisterRowOffsetForEntry(reader, account.name, 'posting', 4) + ).toBeNull(); expect(await readAccountInvestmentActivityCount(reader, account)).toBe(59); const first = await readAccountInvestmentActivityPage(pageReader, account, { order: 'desc', diff --git a/packages/db/src/reports/queries.ts b/packages/db/src/reports/queries.ts index f2097d3..68ef209 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -424,29 +424,6 @@ export async function readAccountActivityPage( return { rows, summary }; } -export async function findOldestFirstAccountActivityOffset( - database: Kysely, - storedAccountName: string, - nativeIndex: number -): Promise { - const target = await database - .selectFrom('account_activity') - .select(['account_date', 'ordinal']) - .where('account_name', '=', storedAccountName) - .where('native_transaction_index', '=', nativeIndex) - .executeTakeFirst(); - if (!target) return null; - - const precedesTarget = sql`(account_date, ordinal) < (${target.account_date}, ${target.ordinal})`; - const { offset } = await database - .selectFrom('account_activity') - .select(({ fn }) => fn.countAll().as('offset')) - .where('account_name', '=', storedAccountName) - .where(precedesTarget) - .executeTakeFirstOrThrow(); - return offset; -} - function requireSavedInvestmentPostingCount( visiblePostingCount: number | null, entryCount: number -- 2.54.1 From a11ab7be33e0009058a310848e6c944fb216b322 Mon Sep 17 00:00:00 2001 From: eleith Date: Wed, 2 Dec 2026 16:29:55 -0800 Subject: [PATCH 13/19] feat(snapshots): read the saved Cash page containing an entry --- packages/db/src/reports/index.ts | 7 +- packages/db/src/reports/queries.test.ts | 7 +- packages/db/src/reports/queries.ts | 100 ++++++++++++++---- packages/snapshots/src/index.ts | 4 +- .../snapshots/src/reports/publication.test.ts | 35 ++++-- packages/snapshots/src/reports/publication.ts | 20 ++++ 6 files changed, 145 insertions(+), 28 deletions(-) diff --git a/packages/db/src/reports/index.ts b/packages/db/src/reports/index.ts index bc89095..c699c81 100644 --- a/packages/db/src/reports/index.ts +++ b/packages/db/src/reports/index.ts @@ -18,11 +18,16 @@ export { readPublicationRequest, readPublicationInvestmentJson, readAccountActivityPage, + readFocusedAccountActivityPage, readAccountActivityDetail, readAccountInvestmentActivityCount, readAccountInvestmentActivityPage } from './queries.js'; -export type { AccountActivityPage, AccountInvestmentActivityPage } from './queries.js'; +export type { + AccountActivityPage, + AccountInvestmentActivityPage, + FocusedAccountActivityPage +} from './queries.js'; export { writeRegisterRowsAndPostingCount, type RegisterPageOptions diff --git a/packages/db/src/reports/queries.test.ts b/packages/db/src/reports/queries.test.ts index bc2c585..6d9bcfb 100644 --- a/packages/db/src/reports/queries.test.ts +++ b/packages/db/src/reports/queries.test.ts @@ -12,6 +12,7 @@ import { } from '../index.js'; import { readAccountActivityPage, + readFocusedAccountActivityPage, readAccountActivityDetail, readAccountInvestmentActivityCount, readAccountInvestmentActivityPage, @@ -414,7 +415,11 @@ it('reads date-ordered pages with native ties and exact account scope', async () .where('entry_ordinal', '=', 0) .execute(); await expect(readPage('asc', 50)).rejects.toThrow('Invalid prepared register rows.'); - expect(await readAccountActivityDetail(database, account, rows[0].transaction.index)).toEqual( + const missingReferenceIndex = rows[0].transaction.index; + await expect( + readFocusedAccountActivityPage(database, account, missingReferenceIndex) + ).rejects.toThrow('Missing prepared Cash row.'); + expect(await readAccountActivityDetail(database, account, missingReferenceIndex)).toEqual( rows[0] ); }); diff --git a/packages/db/src/reports/queries.ts b/packages/db/src/reports/queries.ts index 68ef209..e59210c 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -1,6 +1,7 @@ import type { PreparedAccountRow } from '@hledger-reports/hledger'; import { decodeNativeTransaction, prepareTransaction } from '@hledger-reports/hledger/transactions'; import { sql, type Kysely } from 'kysely'; +import { registerPageSize } from '../register-page.js'; import type { ReportDatabase } from '../schema.js'; import { hasAccountActivitySummary, @@ -16,6 +17,7 @@ import { } from './data.js'; import { assertRegisterPageOptions, + findOldestFirstRegisterRowOffsetForEntry, readRegisterRowReferencePage, type RegisterPageOptions } from './prepared-register-rows.js'; @@ -27,6 +29,10 @@ export interface AccountActivityPage { summary: AccountActivitySummary; } +export interface FocusedAccountActivityPage extends AccountActivityPage { + pageNumber: number; +} + export interface AccountInvestmentActivityPage { rows: { row: PreparedAccountRow; @@ -394,6 +400,32 @@ async function readAccountEntriesByOrdinal( return entriesByAccountOrdinal; } +async function readCashRegisterPageRows( + database: Kysely, + accountName: string, + rowCount: number, + options: RegisterPageOptions +): Promise { + const orderedReferences = await readRegisterRowReferencePage( + database, + accountName, + 'entry', + rowCount, + options + ); + const entriesByAccountOrdinal = await readAccountEntriesByOrdinal( + database, + accountName, + rowCount, + orderedReferences.map(({ accountOrdinal }) => accountOrdinal) + ); + return orderedReferences.map(({ accountOrdinal, display_date }) => { + const row = entriesByAccountOrdinal.get(accountOrdinal); + if (!row || row.accountDate !== display_date) throw new Error('Invalid account data.'); + return row; + }); +} + export async function readAccountActivityPage( database: Kysely, account: StoredAccount, @@ -403,27 +435,59 @@ export async function readAccountActivityPage( const context = await readAccountPageContext(database, account); if (!context) return null; const { rowCount, summary } = context; - const orderedReferences = await readRegisterRowReferencePage( - database, - account.name, - 'entry', - rowCount, - options - ); - const entriesByAccountOrdinal = await readAccountEntriesByOrdinal( - database, - account.name, - rowCount, - orderedReferences.map(({ accountOrdinal }) => accountOrdinal) - ); - const rows = orderedReferences.map(({ accountOrdinal, display_date }) => { - const row = entriesByAccountOrdinal.get(accountOrdinal); - if (!row || row.accountDate !== display_date) throw new Error('Invalid account data.'); - return row; - }); + const rows = await readCashRegisterPageRows(database, account.name, rowCount, options); return { rows, summary }; } +async function findCashFocusRowPosition( + database: Kysely, + accountName: string, + nativeEntryIndex: number +): Promise { + const rowPosition = await findOldestFirstRegisterRowOffsetForEntry( + database, + accountName, + 'entry', + nativeEntryIndex + ); + if (rowPosition !== null) return rowPosition; + + const entry = await database + .selectFrom('account_activity') + .select('ordinal') + .where('account_name', '=', accountName) + .where('native_transaction_index', '=', nativeEntryIndex) + .executeTakeFirst(); + if (entry) throw new Error('Missing prepared Cash row.'); + return null; +} + +export async function readFocusedAccountActivityPage( + database: Kysely, + account: StoredAccount, + nativeEntryIndex: number +): Promise { + const context = await readAccountPageContext(database, account); + if (!context) throw new Error('Account activity is unavailable.'); + const { rowCount, summary } = context; + const targetRowPosition = await findCashFocusRowPosition( + database, + account.name, + nativeEntryIndex + ); + if (targetRowPosition === null) return null; + + const pageNumber = Math.floor(targetRowPosition / registerPageSize) + 1; + const pageStart = (pageNumber - 1) * registerPageSize; + const rows = await readCashRegisterPageRows(database, account.name, rowCount, { + order: 'asc', + offset: pageStart + }); + const targetRow = rows[targetRowPosition - pageStart]; + if (targetRow?.transaction.index !== nativeEntryIndex) throw new Error('Invalid account data.'); + return { pageNumber, rows, summary }; +} + function requireSavedInvestmentPostingCount( visiblePostingCount: number | null, entryCount: number diff --git a/packages/snapshots/src/index.ts b/packages/snapshots/src/index.ts index d442275..79adc26 100644 --- a/packages/snapshots/src/index.ts +++ b/packages/snapshots/src/index.ts @@ -4,6 +4,7 @@ export { readReportPublication, readInvestmentOverview, readAccountPage, + readFocusedAccountPage, readInvestmentActivityCount, readInvestmentActivityPage, readAccountTransaction @@ -13,7 +14,8 @@ export type { StoredAccount, AccountActivitySummary, AccountActivityPage, - AccountInvestmentActivityPage + AccountInvestmentActivityPage, + FocusedAccountActivityPage } 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 f6739ba..4c069cf 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, + readFocusedAccountPage, readAccountTransaction, readInvestmentActivityPage, readInvestmentOverview, @@ -333,9 +334,26 @@ it('does not mix two publications from different attempts of the same request', ); }); -it('reads from the connection it verified even if the report is replaced after the key lookup', async () => { - await publish(older); +it('locates and reads the ordinary Cash page on the same checked connection', async () => { + const original = await createReportStage(snapshots, older); + await importNativeExports(original, 52); + const originalRows = rows(52); + const targetRow = originalRows[0]; + targetRow.accountDate = '2026-05-01'; + const lastRow = originalRows[51]; + lastRow.accountDate = '2026-05-02'; + const offPageRow = originalRows[1]; + offPageRow.change.push({ ...offPageRow.change[0], commodity: 'EUR', quantity: '0.12' }); + await original.writeRows('assets:cash', originalRows); + await original.publish(fixture(), [ready('assets:cash', originalRows.length)], journal); const pinned = await selected(); + const id = pinned.accounts[0].id; + const target = targetRow.transaction.index; + const ordinaryPage = await readAccountPage(pinned, id, { order: 'asc', offset: 50 }); + expect(ordinaryPage?.rows).toEqual([targetRow, lastRow]); + expect(ordinaryPage?.summary.hasMultipleCommodities).toBe(true); + expect(await readFocusedAccountPage(pinned, id, 9999)).toBeNull(); + const readKey = reports.readPublicationRequest; const next = { ...fixture(), preparedAt: 'replacement during read' }; const stage = await createReportStage(snapshots, newer, pinned.accounts); @@ -346,12 +364,12 @@ it('reads from the connection it verified even if the report is replaced after t await stage.publish(next, [ready()], journal); return key; }); - const page = await readAccountPage(pinned, pinned.accounts[0].id, { - order: 'asc', - offset: 0 - }); - expect(page?.rows).toEqual(rows()); + const focusedPage = await readFocusedAccountPage(pinned, id, target); + expect(focusedPage).toEqual({ ...ordinaryPage, pageNumber: 2 }); expect(await readOverview(snapshots)).toEqual(next); + await expect(readFocusedAccountPage(pinned, id, target)).rejects.toSatisfy( + safeError('Unable to read account transactions') + ); }); it('stores only the intended overview fields and preserves absent history and null values', async () => { @@ -942,6 +960,9 @@ it('rejects unsafe and uncatalogued account IDs before opening financial data', await expect(readAccountTransaction(publication, 'cash0001', 0)).rejects.toSatisfy( safeError('Unable to read account transactions') ); + await expect(readFocusedAccountPage(publication, 'cash0001', 0)).rejects.toSatisfy( + safeError('Unable to read account transactions') + ); await expect(readInvestmentActivityCount(publication, '../escape')).rejects.toSatisfy( safeError('Unable to read account activity') ); diff --git a/packages/snapshots/src/reports/publication.ts b/packages/snapshots/src/reports/publication.ts index 1c89171..a4943f0 100644 --- a/packages/snapshots/src/reports/publication.ts +++ b/packages/snapshots/src/reports/publication.ts @@ -20,6 +20,7 @@ import { isAccountId, isAccountSummary, readAccountActivityPage, + readFocusedAccountActivityPage, readAccountActivityDetail, readAccountInvestmentActivityCount, readAccountInvestmentActivityPage, @@ -35,6 +36,7 @@ import { type AccountActivitySummary, type AccountActivityPage, type AccountInvestmentActivityPage, + type FocusedAccountActivityPage, type RegisterPageOptions, type StoredAccount, type StoredReportData @@ -197,6 +199,24 @@ export async function readAccountPage( } } +export async function readFocusedAccountPage( + publication: ReportPublication, + id: string, + nativeEntryIndex: number +): Promise { + try { + if (!isAccountId(id) || !Number.isSafeInteger(nativeEntryIndex) || nativeEntryIndex <= 0) + throw new Error(); + const account = publication.accounts.find((entry) => entry.id === id); + if (!account) throw new Error(); + return await readFromSelectedPublication(publication, (database) => + readFocusedAccountActivityPage(database, account, nativeEntryIndex) + ); + } catch { + throw new Error('Unable to read account transactions'); + } +} + export async function readInvestmentActivityCount( publication: ReportPublication, id: string -- 2.54.1 From fa4157f93ee0c3521c57f3fdcb154357bee8a5b3 Mon Sep 17 00:00:00 2001 From: eleith Date: Thu, 3 Dec 2026 10:52:05 -0800 Subject: [PATCH 14/19] feat(web): focus a saved Cash register transaction --- .changeset/focus-saved-register-row.md | 5 + apps/web/e2e/cash-register.e2e.ts | 43 +++++- apps/web/src/app.d.ts | 5 + .../src/lib/registers/cash/Register.svelte | 8 +- apps/web/src/lib/registers/cash/data.ts | 2 + .../registers/cash/register-page-request.ts | 44 ++++-- .../registers/cash/row-batch-request.test.ts | 1 + .../registers/cash/table/CellContent.svelte | 2 + .../src/lib/registers/cash/table/table.css | 8 ++ .../src/lib/server/registers/cash/register.ts | 38 +++-- .../registers/cash/[accountId]/+error.svelte | 18 +++ .../cash/[accountId]/page.server.test.ts | 36 ++++- packages/db/src/reports/index.ts | 11 +- .../db/src/reports/prepared-register-rows.ts | 46 ++++--- packages/db/src/reports/queries.test.ts | 130 +++++++----------- packages/db/src/reports/queries.ts | 87 +++--------- packages/snapshots/src/index.ts | 9 +- .../snapshots/src/reports/publication.test.ts | 25 +++- packages/snapshots/src/reports/publication.ts | 45 ++++-- 19 files changed, 337 insertions(+), 226 deletions(-) create mode 100644 .changeset/focus-saved-register-row.md create mode 100644 apps/web/src/routes/(protected)/registers/cash/[accountId]/+error.svelte diff --git a/.changeset/focus-saved-register-row.md b/.changeset/focus-saved-register-row.md new file mode 100644 index 0000000..094803b --- /dev/null +++ b/.changeset/focus-saved-register-row.md @@ -0,0 +1,5 @@ +--- +'@hledger-reports/web': patch +--- + +Use `?focus=` to open and mark a transaction in the ordinary Cash register. Changing sort keeps focus on the same transaction. If the target is missing, use **Open register** to keep browsing. Links may not find the same transaction after re-preparation. diff --git a/apps/web/e2e/cash-register.e2e.ts b/apps/web/e2e/cash-register.e2e.ts index 5939284..bf0004d 100644 --- a/apps/web/e2e/cash-register.e2e.ts +++ b/apps/web/e2e/cash-register.e2e.ts @@ -2,6 +2,10 @@ import { expect, test, type Page, type Request as BrowserRequest } from '@playwr import { prepared } from './cash-overview-fixture'; import { replayWithoutSession } from './anonymous-request'; +// Opening cash is the first native entry in the fictional base journal. +const openingCashFocus = 'focus=1'; +const openingCashDetails = /^View transaction details: Opening cash on/; + async function checkingAccountHref(page: Page): Promise { const href = await page .getByRole('complementary', { name: 'Accounts', exact: true, includeHidden: true }) @@ -13,10 +17,13 @@ async function checkingAccountHref(page: Page): Promise { test.describe('Without JavaScript', () => { test.use({ javaScriptEnabled: false }); - test('cash activity remains a readable server-rendered table', async ({ page }) => { + test('Cash focus remains readable in HTML and a missing target links back to the register', async ({ + page + }) => { await prepared(page); await page.goto('/registers/cash'); - await page.goto(await checkingAccountHref(page)); + const accountURL = new URL(await checkingAccountHref(page), page.url()).href; + await page.goto(`${accountURL}?${openingCashFocus}&order=asc`); const activity = page.getByRole('region', { name: 'Cash register activity', exact: true }); await expect( activity.getByRole('table', { name: 'Cash register transactions', exact: true }) @@ -27,6 +34,16 @@ test.describe('Without JavaScript', () => { purchase.getByRole('button', { name: /^View transaction details:/ }) ).toBeDisabled(); await expect(page.getByRole('navigation', { name: 'Pagination', exact: true })).toHaveCount(0); + await expect(activity.getByRole('button', { name: openingCashDetails })).toHaveAttribute( + 'aria-current', + 'true' + ); + + const missing = await page.goto(`${accountURL}?focus=9007199254740991`); + expect(missing?.status()).toBe(404); + await page.getByRole('link', { name: 'Open register', exact: true }).click(); + await expect(page).toHaveURL(accountURL); + await expect(activity.getByRole('table')).toBeVisible(); }); }); @@ -147,12 +164,28 @@ test('Cash register opens recent saved activity and complete transaction details await expect(dialog.getByRole('textbox', { name: 'Notes', exact: true })).toHaveValue('Salary'); await close.click(); await expect(salary).toBeFocused(); - await activity - .getByRole('button', { name: /^View transaction details: Opening cash on/ }) - .click(); + await activity.getByRole('button', { name: openingCashDetails }).click(); await expect(dialog).toBeVisible(); await expect(dialog.getByRole('region', { name: 'Transaction notes', exact: true })).toHaveCount( 0 ); await close.click(); + + await page.goto(`${accountURL}?${openingCashFocus}`); + const target = activity.getByRole('button', { name: openingCashDetails }); + await expect(target).toBeEnabled(); + await expect(target).toHaveAttribute('aria-current', 'true'); + await expect( + activity.locator('[data-row-position="0"][data-column="date"] time') + ).toHaveAttribute('datetime', '2026-04-15'); + await expect(dialog).toHaveCount(0); + + await activity + .getByRole('link', { name: 'Date: newest first; show oldest first', exact: true }) + .click(); + await expect(page).toHaveURL(/\?order=asc&focus=1$/); + await expect( + activity.locator('[data-row-position="0"][data-column="date"] time') + ).toHaveAttribute('datetime', '2026-04-01'); + await expect(target).toHaveAttribute('aria-current', 'true'); }); diff --git a/apps/web/src/app.d.ts b/apps/web/src/app.d.ts index f470663..e9546fe 100644 --- a/apps/web/src/app.d.ts +++ b/apps/web/src/app.d.ts @@ -4,6 +4,11 @@ import type { SavedReportsState } from '#lib/server/reports.js'; declare global { namespace App { + interface Error { + message: string; + code?: 'REGISTER_FOCUS_NOT_FOUND'; + } + interface Locals { application: ApplicationContext | null; session: AuthSession | null; diff --git a/apps/web/src/lib/registers/cash/Register.svelte b/apps/web/src/lib/registers/cash/Register.svelte index 15eaa20..23f45de 100644 --- a/apps/web/src/lib/registers/cash/Register.svelte +++ b/apps/web/src/lib/registers/cash/Register.svelte @@ -51,9 +51,11 @@ let loadingBatchCount = $derived( [...batches.values()].filter((batch) => batch.status === 'loading').length ); - let orderHref = $derived( - `?${new URLSearchParams({ order: data.order === 'asc' ? 'desc' : 'asc' })}` - ); + let orderHref = $derived.by(() => { + const order = data.order === 'asc' ? 'desc' : 'asc'; + const focusedRow = data.rows.find((row) => row.isFocusTarget); + return `?${new URLSearchParams(focusedRow ? { order, focus: String(focusedRow.transactionIndex) } : { order })}`; + }); onMount(() => { browserReady = true; diff --git a/apps/web/src/lib/registers/cash/data.ts b/apps/web/src/lib/registers/cash/data.ts index a7800cd..d062d56 100644 --- a/apps/web/src/lib/registers/cash/data.ts +++ b/apps/web/src/lib/registers/cash/data.ts @@ -10,6 +10,7 @@ export interface RegisterRow { statuses: string[]; change: ReportedAmount[]; balance: ReportedAmount[]; + isFocusTarget?: true; } export { registerPageSize as rowBatchSize } from '@hledger-reports/snapshots/register-page'; @@ -18,6 +19,7 @@ export interface RegisterPageRequest { accountId: string; order: RegisterPageData['order']; page: number | null; + focusTransactionIndex?: number; } export interface RowBatchRequest { diff --git a/apps/web/src/lib/registers/cash/register-page-request.ts b/apps/web/src/lib/registers/cash/register-page-request.ts index d4485e9..b62f728 100644 --- a/apps/web/src/lib/registers/cash/register-page-request.ts +++ b/apps/web/src/lib/registers/cash/register-page-request.ts @@ -9,13 +9,27 @@ export function parseRegisterPageRequest( if (!isAccountId(accountId)) error(400, 'A valid account ID is required.'); requireSupportedParameters(parameters); const order = parseOrder(parameters); - const page = parsePage(parameters); + const focusTransactionIndex = parsePositiveIntegerParameter( + parameters, + 'focus', + 'A valid transaction index is required.' + ); + if (focusTransactionIndex !== null) { + if (parameters.has('page')) error(400, 'Focus links cannot include a page number.'); + return { accountId, order, page: null, focusTransactionIndex }; + } + const page = parsePositiveIntegerParameter( + parameters, + 'page', + 'A valid page number is required.' + ); return { accountId, order, page }; } function requireSupportedParameters(parameters: URLSearchParams): void { for (const key of parameters.keys()) { - if (key !== 'order' && key !== 'page') error(400, 'Unsupported register parameter.'); + if (key !== 'order' && key !== 'page' && key !== 'focus') + error(400, 'Unsupported register parameter.'); } } @@ -26,17 +40,17 @@ function parseOrder(parameters: URLSearchParams): RegisterPageRequest['order'] { return order; } -function parsePage(parameters: URLSearchParams): RegisterPageRequest['page'] { - const pages = parameters.getAll('page'); - if (pages.length > 1) error(400, 'A valid page number is required.'); - const pageText = pages[0]; - if (pageText === undefined) return null; - if (!isPageNumberText(pageText)) error(400, 'A valid page number is required.'); - const page = Number(pageText); - if (!isPositiveSafeInteger(page)) error(400, 'A valid page number is required.'); - return page; -} - -function isPageNumberText(value: string): boolean { - return /^[1-9]/.test(value) && !/[^0-9]/.test(value); +function parsePositiveIntegerParameter( + parameters: URLSearchParams, + key: 'page' | 'focus', + message: string +): number | null { + const [text, extra] = parameters.getAll(key); + if (text === undefined) return null; + if (extra !== undefined) error(400, message); + const isCanonicalPositiveIntegerText = /^[1-9]/.test(text) && !/[^0-9]/.test(text); + if (!isCanonicalPositiveIntegerText) error(400, message); + const value = Number(text); + if (!isPositiveSafeInteger(value)) error(400, message); + return value; } diff --git a/apps/web/src/lib/registers/cash/row-batch-request.test.ts b/apps/web/src/lib/registers/cash/row-batch-request.test.ts index df3fa74..4cff21d 100644 --- a/apps/web/src/lib/registers/cash/row-batch-request.test.ts +++ b/apps/web/src/lib/registers/cash/row-batch-request.test.ts @@ -10,6 +10,7 @@ it.each([ null, { accountId: '../PRIVATE', order: 'desc', batchStart: 0 }, { accountId: 'abcd1234', order: 'desc', batchStart: 1 }, + { accountId: 'abcd1234', order: 'desc', batchStart: -50 }, { accountId: 'abcd1234', order: 'desc', batchStart: Number.MAX_SAFE_INTEGER + 1 }, { accountId: 'abcd1234', order: 'desc', batchStart: 0, limit: 1000000 } ])('rejects malformed row batch inputs before reads: %j', (input) => { diff --git a/apps/web/src/lib/registers/cash/table/CellContent.svelte b/apps/web/src/lib/registers/cash/table/CellContent.svelte index 226056c..4d13823 100644 --- a/apps/web/src/lib/registers/cash/table/CellContent.svelte +++ b/apps/web/src/lib/registers/cash/table/CellContent.svelte @@ -23,6 +23,7 @@
onOpenTransaction?.(rowPosition, event.currentTarget)} >{row.payee || 'Transaction'} { + const { order, focusTransactionIndex } = request; const pagination = resolvePagination(account.rowCount, request); - const activity: RegisterActivity = { - ...pagination, - rows: [], - endingBalance: null, - readFailed: false - }; try { - const page = await readSavedActivityPage( - account, - request.order, - (pagination.page - 1) * rowBatchSize + if (focusTransactionIndex === undefined) { + const page = await readSavedActivityPage( + account, + order, + (pagination.page - 1) * rowBatchSize + ); + return { ...pagination, ...projectActivityPage(page), readFailed: false }; + } + const focusedPage = await readFocusedAccountPage( + account.publication, + account.id, + focusTransactionIndex, + order ); - return { ...activity, ...projectActivityPage(page) }; + if (focusedPage) { + const activity = projectActivityPage(focusedPage); + const targetRow = activity.rows.find((row) => row.transactionIndex === focusTransactionIndex); + if (targetRow) targetRow.isFocusTarget = true; + return { ...pagination, page: focusedPage.pageNumber, ...activity, readFailed: false }; + } } catch { - return { ...activity, readFailed: true }; + return { ...pagination, rows: [], endingBalance: null, readFailed: true }; } + error(404, { + message: 'Transaction not found in this saved register.', + code: 'REGISTER_FOCUS_NOT_FOUND' + }); } function resolvePagination(rowCount: number, { order, page }: RegisterPageRequest) { diff --git a/apps/web/src/routes/(protected)/registers/cash/[accountId]/+error.svelte b/apps/web/src/routes/(protected)/registers/cash/[accountId]/+error.svelte new file mode 100644 index 0000000..bd54a64 --- /dev/null +++ b/apps/web/src/routes/(protected)/registers/cash/[accountId]/+error.svelte @@ -0,0 +1,18 @@ + + +
+

{page.status}

+

{page.error?.message}

+ {#if page.error?.code === 'REGISTER_FOCUS_NOT_FOUND' && page.params.accountId} +

+ Open register +

+ {/if} +
diff --git a/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts b/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts index 606765b..22769fa 100644 --- a/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts +++ b/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts @@ -5,6 +5,7 @@ import { beforeEach, expect, it, vi } from 'vitest'; import { readReportPublication, readAccountPage, + readFocusedAccountPage, type AccountActivityPage } from '@hledger-reports/snapshots'; import type { ApplicationContext } from '#lib/server/application.js'; @@ -15,6 +16,7 @@ import { load } from './+page.server.js'; vi.mock('@hledger-reports/snapshots', () => ({ readReportPublication: vi.fn(), readAccountPage: vi.fn(), + readFocusedAccountPage: vi.fn(), readAccountTransaction: vi.fn() })); vi.mock('#lib/server/registers/cash/projection.js', () => ({ @@ -110,6 +112,37 @@ it('loads a member from one pinned publication and delegates its requested page' expect(request.parent).toHaveBeenCalledOnce(); expect(request.setHeaders).toHaveBeenCalledWith({ 'cache-control': 'no-store' }); }); +it('marks only the target on the saved Cash page in the requested order', async () => { + const focusedPage = { ...accountPage, rows: preparedAccountRows(2), pageNumber: 1 }; + const [other, target] = focusedPage.rows.map((row) => row.transaction.index); + const actual = await vi.importActual( + '#lib/server/registers/cash/projection.js' + ); + vi.mocked(projectActivityPage).mockImplementationOnce(actual.projectActivityPage); + vi.mocked(readFocusedAccountPage).mockResolvedValue(focusedPage); + const result = await load(event(`focus=${target}&order=asc`)); + expect(result).toMatchObject({ page: 1, order: 'asc', readFailed: false }); + expect(result.rows[0]).toMatchObject({ transactionIndex: other }); + expect(result.rows[0]).not.toHaveProperty('isFocusTarget'); + expect(result.rows[1]).toMatchObject({ transactionIndex: target, isFocusTarget: true }); + expect(readFocusedAccountPage).toHaveBeenCalledExactlyOnceWith(publication, id, target, 'asc'); + expect(readAccountPage).not.toHaveBeenCalled(); +}); + +it('returns a safe read failure when a focused page is unreadable', async () => { + vi.mocked(readFocusedAccountPage).mockRejectedValue(new Error('PRIVATE diagnostic')); + const unreadable = await load(event('focus=100')); + expect(unreadable).toMatchObject({ readFailed: true, rows: [], endingBalance: null }); + expect(JSON.stringify(unreadable)).not.toContain('PRIVATE'); +}); + +it('rejects malformed and conflicting focus URLs before reading a report', async () => { + for (const query of ['focus=9007199254740992', 'focus=1&focus=2', 'focus=1&page=1']) + await expect(load(event(query))).rejects.toMatchObject({ status: 400 }); + expect(readReportPublication).not.toHaveBeenCalled(); + expect(readFocusedAccountPage).not.toHaveBeenCalled(); +}); + it('requires an application without reading reports or parent data', async () => { const request = event(); request.locals.application = null; @@ -184,7 +217,7 @@ it('does not read or project activity for an ambiguous account', async () => { ...publication, accounts: [{ id, name, access: 'ambiguous', rowCount: null, summary: { status: 'ambiguous' } }] }); - expect(await load(event())).toMatchObject({ + expect(await load(event('focus=1'))).toMatchObject({ readFailed: false, access: 'ambiguous', rows: [], @@ -192,6 +225,7 @@ it('does not read or project activity for an ambiguous account', async () => { endingBalance: null }); expect(readAccountPage).not.toHaveBeenCalled(); + expect(readFocusedAccountPage).not.toHaveBeenCalled(); expect(projectActivityPage).not.toHaveBeenCalled(); }); diff --git a/packages/db/src/reports/index.ts b/packages/db/src/reports/index.ts index c699c81..34f43e5 100644 --- a/packages/db/src/reports/index.ts +++ b/packages/db/src/reports/index.ts @@ -17,19 +17,16 @@ export { readReportData, readPublicationRequest, readPublicationInvestmentJson, - readAccountActivityPage, - readFocusedAccountActivityPage, + readCashRegisterPage, + findAccountEntryOrdinal, readAccountActivityDetail, readAccountInvestmentActivityCount, readAccountInvestmentActivityPage } from './queries.js'; -export type { - AccountActivityPage, - AccountInvestmentActivityPage, - FocusedAccountActivityPage -} from './queries.js'; +export type { AccountActivityPage, AccountInvestmentActivityPage } from './queries.js'; export { writeRegisterRowsAndPostingCount, + findRegisterEntryLocation, type RegisterPageOptions } from './prepared-register-rows.js'; export { AccountActivitySummaryBuilder } 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 3ae15b8..c335516 100644 --- a/packages/db/src/reports/prepared-register-rows.ts +++ b/packages/db/src/reports/prepared-register-rows.ts @@ -15,11 +15,6 @@ export interface RegisterPageOptions { offset: number; } -export function assertRegisterPageOptions({ order, offset }: RegisterPageOptions): void { - if ((order !== 'asc' && order !== 'desc') || !Number.isSafeInteger(offset) || offset < 0) - throw new Error('Invalid account page.'); -} - type RegisterRowKind = ReportDatabase['prepared_register_rows']['row_kind']; export async function readRegisterRowReferencePage( @@ -51,35 +46,48 @@ export async function readRegisterRowReferencePage( return references; } -export async function findOldestFirstRegisterRowOffsetForEntry( +export async function findRegisterEntryLocation( database: Kysely, accountName: string, rowKind: RegisterRowKind, - nativeEntryIndex: number -): Promise { + entryOrdinal: number, + pageOrder: RegisterPageOptions['order'] +): Promise<{ + pageOrder: RegisterPageOptions['order']; + pageOffset: number; + pageNumber: number; + indexOnPage: number; +} | null> { + const dateOrder = pageOrder === 'asc' ? sql`asc` : sql`desc`; + const precedingDate = pageOrder === 'asc' ? sql`<` : sql`>`; // Select the entry's references before sorting, so SQLite can seek by entry ordinal. const { rows } = await sql<{ offset: number }>` with target_entry_rows as materialized ( - select row.account_name, row.row_kind, row.display_date, row.entry_ordinal, row.position_in_entry - from account_activity as entry - join prepared_register_rows as row - on row.account_name = entry.account_name and row.entry_ordinal = entry.ordinal - where entry.account_name = ${accountName} - and entry.native_transaction_index = ${nativeEntryIndex} - and row.row_kind = ${rowKind} + select account_name, row_kind, display_date, entry_ordinal, position_in_entry + from prepared_register_rows + where account_name = ${accountName} and row_kind = ${rowKind} and entry_ordinal = ${entryOrdinal} ), first_visible_row as ( select * from target_entry_rows - order by display_date, entry_ordinal, position_in_entry limit 1 + order by display_date ${dateOrder}, entry_ordinal, position_in_entry limit 1 ) select ( select count(*) from prepared_register_rows as earlier where earlier.account_name = target.account_name and earlier.row_kind = target.row_kind - and (earlier.display_date, earlier.entry_ordinal, earlier.position_in_entry) - < (target.display_date, target.entry_ordinal, target.position_in_entry) + and earlier.display_date ${precedingDate} target.display_date + ) + ( + select count(*) from prepared_register_rows as earlier + where earlier.account_name = target.account_name and earlier.row_kind = target.row_kind + and earlier.display_date = target.display_date + and (earlier.entry_ordinal, earlier.position_in_entry) + < (target.entry_ordinal, target.position_in_entry) ) as offset from first_visible_row as target `.execute(database); - return rows[0]?.offset ?? null; + const rowOffset = rows[0]?.offset; + if (rowOffset === undefined) return null; + const indexOnPage = rowOffset % registerPageSize; + const pageOffset = rowOffset - indexOnPage; + return { pageOrder, pageOffset, pageNumber: pageOffset / registerPageSize + 1, indexOnPage }; } export async function writeRegisterRowsAndPostingCount( diff --git a/packages/db/src/reports/queries.test.ts b/packages/db/src/reports/queries.test.ts index 6d9bcfb..9c4e7f5 100644 --- a/packages/db/src/reports/queries.test.ts +++ b/packages/db/src/reports/queries.test.ts @@ -11,8 +11,8 @@ import { type ReportDatabase } from '../index.js'; import { - readAccountActivityPage, - readFocusedAccountActivityPage, + findAccountEntryOrdinal, + readCashRegisterPage, readAccountActivityDetail, readAccountInvestmentActivityCount, readAccountInvestmentActivityPage, @@ -24,7 +24,7 @@ import { import type { ReportTransaction } from '../database.js'; import { validateRawAccountPostingReferences } from './investment-posting-rows.js'; import { - findOldestFirstRegisterRowOffsetForEntry, + findRegisterEntryLocation, readRegisterRowReferencePage, writeRegisterRowsAndPostingCount } from './prepared-register-rows.js'; @@ -184,26 +184,22 @@ it('stores exact prepared payloads and native row order using the migrated schem if (!reader) throw new Error('Expected the current report schema.'); databases.add(reader); expect(await readReportData(reader)).toEqual(data); - const firstPage = { order: 'asc', offset: 0 } as const; - expect(await readAccountActivityPage(reader, data.accounts[0], firstPage)).toEqual({ + expect(await readCashRegisterPage(reader, data.accounts[0], 'asc', 0)).toEqual({ rows: [], summary: preparedActivitySummary() }); - const first = await readAccountActivityPage(reader, data.accounts[1], firstPage); - const last = await readAccountActivityPage(reader, data.accounts[1], { - ...firstPage, - offset: 50 - }); + const first = await readCashRegisterPage(reader, data.accounts[1], 'asc', 0); + const last = await readCashRegisterPage(reader, data.accounts[1], 'asc', 50); expect(first).toEqual({ rows: rows.slice(0, 50), summary: summaries.get('assets:cash') }); expect(first?.rows[0].transaction.postings[0].transactedAmounts).toEqual([ { commodity: 'USD', quantity: '90071992547409931234567.89' } ]); expect(last).toEqual({ rows: rows.slice(50), summary: first?.summary }); - expect(await readAccountActivityPage(reader, data.accounts[2], firstPage)).toEqual({ + expect(await readCashRegisterPage(reader, data.accounts[2], 'asc', 0)).toEqual({ rows: otherRows, summary: summaries.get('assets:Cash') }); - expect(await readAccountActivityPage(reader, data.accounts[3], firstPage)).toBeNull(); + expect(await readCashRegisterPage(reader, data.accounts[3], 'asc', 0)).toBeNull(); expect(await readAccountActivityDetail(reader, data.accounts[1], rich.transaction.index)).toEqual( rich ); @@ -282,9 +278,8 @@ it('shares one canonical transaction without embedding its body in account conte investment: expected.investment }); } - const page = { order: 'asc', offset: 0 } as const; - expect((await readAccountActivityPage(database, account, page))?.rows).toEqual(rows); - expect((await readAccountActivityPage(database, other, page))?.rows).toEqual(otherRows); + expect((await readCashRegisterPage(database, account, 'asc', 0))?.rows).toEqual(rows); + expect((await readCashRegisterPage(database, other, 'asc', 0))?.rows).toEqual(otherRows); expect(await readAccountActivityDetail(database, account, 1)).toEqual(rows[0]); expect(await readAccountActivityDetail(database, other, 1)).toEqual(otherRows[0]); @@ -350,7 +345,7 @@ it('reads date-ordered pages with native ties and exact account scope', async () const earlierDateRows = rows.slice(26); const ascending = [...earlierDateRows, ...laterDateRows]; const readPage = async (order: 'asc' | 'desc', offset: number) => - (await readAccountActivityPage(pageReader, account, { order, offset }))?.rows; + (await readCashRegisterPage(pageReader, account, order, offset))?.rows; expect(await readPage('asc', 0)).toEqual(ascending.slice(0, 50)); expect(await readPage('asc', 50)).toEqual(ascending.slice(50)); expect(await readPage('desc', 0)).toEqual(rows.slice(0, 50)); @@ -358,48 +353,34 @@ it('reads date-ordered pages with native ties and exact account scope', async () expect(await readPage('asc', 53)).toEqual([]); expect(Math.max(...resultRowCounts)).toBe(50); - const secondPageOffset = 50; - const targetIndex = ascending[secondPageOffset].transaction.index; + const targetEntryOrdinal = rows.indexOf(ascending[50]); expect( - await findOldestFirstRegisterRowOffsetForEntry(database, account.name, 'entry', targetIndex) - ).toBe(secondPageOffset); - const sharedOrdinalEntryIndex = rows[0].transaction.index; - expect( - await findOldestFirstRegisterRowOffsetForEntry( - database, - account.name, - 'entry', - sharedOrdinalEntryIndex - ) - ).toBe(27); - expect( - await findOldestFirstRegisterRowOffsetForEntry( - database, - other.name, - 'entry', - sharedOrdinalEntryIndex - ) - ).toBeNull(); - expect( - await findOldestFirstRegisterRowOffsetForEntry( - database, - account.name, - 'entry', - ascending[0].transaction.index - ) - ).toBe(0); + await findRegisterEntryLocation(database, account.name, 'entry', targetEntryOrdinal, 'asc') + ).toEqual({ pageOrder: 'asc', pageOffset: 50, pageNumber: 2, indexOnPage: 0 }); + expect(await findRegisterEntryLocation(database, account.name, 'entry', 0, 'asc')).toEqual({ + pageOrder: 'asc', + pageOffset: 0, + pageNumber: 1, + indexOnPage: 27 + }); + const sharedOrdinalIndex = rows[0].transaction.index; + expect(await findAccountEntryOrdinal(database, account, sharedOrdinalIndex)).toBe(0); + expect(await findAccountEntryOrdinal(database, other, sharedOrdinalIndex)).toBeNull(); + expect(await findRegisterEntryLocation(database, account.name, 'entry', 51, 'desc')).toEqual({ + pageOrder: 'desc', + pageOffset: 50, + pageNumber: 2, + indexOnPage: 1 + }); - expect(await readAccountActivityPage(database, other, { order: 'asc', offset: 0 })).toEqual({ + expect(await readCashRegisterPage(database, other, 'asc', 0)).toEqual({ rows: otherRows, summary: preparedActivitySummary(otherRows) }); const mismatchedAccount = { ...other, id: account.id }; await expect(readAccountActivityDetail(database, mismatchedAccount, 1)).rejects.toThrow(); await expect(readAccountActivityDetail(database, account, 0)).rejects.toThrow(); - await expect( - readAccountActivityPage(database, mismatchedAccount, { order: 'asc', offset: 0 }) - ).rejects.toThrow(); - await expect(readPage('asc', -1)).rejects.toThrow('Invalid account page.'); + await expect(readCashRegisterPage(database, mismatchedAccount, 'asc', 0)).rejects.toThrow(); await database .updateTable('prepared_register_rows') .set({ display_date: '2026-04-28' }) @@ -415,11 +396,7 @@ it('reads date-ordered pages with native ties and exact account scope', async () .where('entry_ordinal', '=', 0) .execute(); await expect(readPage('asc', 50)).rejects.toThrow('Invalid prepared register rows.'); - const missingReferenceIndex = rows[0].transaction.index; - await expect( - readFocusedAccountActivityPage(database, account, missingReferenceIndex) - ).rejects.toThrow('Missing prepared Cash row.'); - expect(await readAccountActivityDetail(database, account, missingReferenceIndex)).toEqual( + expect(await readAccountActivityDetail(database, account, rows[0].transaction.index)).toEqual( rows[0] ); }); @@ -468,13 +445,11 @@ it('decodes only the requested page and rejects invalid posting references', asy if (!reader) throw new Error('Expected the current report schema.'); databases.add(reader); expect((await readReportData(reader)).accounts).toEqual([account]); - expect(await readAccountActivityPage(reader, account, { order: 'asc', offset: 0 })).toEqual({ + expect(await readCashRegisterPage(reader, account, 'asc', 0)).toEqual({ rows: rows.slice(0, 50), summary: preparedActivitySummary(rows) }); - await expect( - readAccountActivityPage(reader, account, { order: 'asc', offset: 50 }) - ).rejects.toThrow(); + await expect(readCashRegisterPage(reader, account, 'asc', 50)).rejects.toThrow(); }); it('rejects an orphaned Cash row without shifting later rows', async () => { @@ -506,8 +481,7 @@ it('rejects an orphaned Cash row without shifting later rows', async () => { const reader = await openReadOnlyReportDatabase(path); if (!reader) throw new Error('Expected the current report schema.'); databases.add(reader); - const readPage = (offset: number) => - readAccountActivityPage(reader, account, { order: 'asc', offset }); + const readPage = (offset: number) => readCashRegisterPage(reader, account, 'asc', offset); const summary = preparedActivitySummary(rows); const suffix = { rows: rows.slice(1), summary }; expect(await readPage(0)).toEqual({ rows, summary }); @@ -568,7 +542,7 @@ it('rejects missing summaries and malformed native bags rather than inferring fr if (!transaction.isCommitted && !transaction.isRolledBack) await transaction.rollback().execute(); } - const readPage = () => readAccountActivityPage(database, account, { order: 'asc', offset: 0 }); + const readPage = () => readCashRegisterPage(database, account, 'asc', 0); expect(await readPage()).toEqual({ rows, summary }); await expect(writeAccountActivitySummaries(database, new Map())).rejects.toThrow(); await database @@ -582,6 +556,9 @@ it('rejects missing summaries and malformed native bags rather than inferring fr .where('account_name', '=', account.name) .execute(); await expect(readPage()).rejects.toThrow('Missing account activity summary.'); + await expect(findAccountEntryOrdinal(database, account, 2)).rejects.toThrow( + 'Missing account activity summary.' + ); }); it('does not create missing storage or replace an existing report file', async () => { @@ -707,18 +684,20 @@ it('pages original selected-account postings across a shared security group and const earlierPostings = [reference(1, 0), reference(1, 1), reference(2, 1)]; const ascending = [...earlierPostings, ...main, reference(2, 0)]; const descending = [...main, reference(2, 0), ...earlierPostings]; - // Entry 2 starts at its second original posting, after both visible postings of entry 1. - expect(await findOldestFirstRegisterRowOffsetForEntry(reader, account.name, 'posting', 2)).toBe( - 2 - ); - expect(await findOldestFirstRegisterRowOffsetForEntry(reader, account.name, 'posting', 3)).toBe( - 3 - ); - expect(await findOldestFirstRegisterRowOffsetForEntry(reader, account.name, 'entry', 3)).toBe(0); - expect(await findOldestFirstRegisterRowOffsetForEntry(reader, account.name, 'entry', 1)).toBe(1); + // Entry ordinal 2 starts at its second original posting, after both postings of ordinal 1. expect( - await findOldestFirstRegisterRowOffsetForEntry(reader, account.name, 'posting', 4) - ).toBeNull(); + (await findRegisterEntryLocation(reader, account.name, 'posting', 2, 'asc'))?.indexOnPage + ).toBe(2); + expect( + (await findRegisterEntryLocation(reader, account.name, 'posting', 0, 'asc'))?.indexOnPage + ).toBe(3); + expect( + (await findRegisterEntryLocation(reader, account.name, 'entry', 0, 'asc'))?.indexOnPage + ).toBe(0); + expect( + (await findRegisterEntryLocation(reader, account.name, 'entry', 1, 'asc'))?.indexOnPage + ).toBe(1); + expect(await findRegisterEntryLocation(reader, account.name, 'posting', 3, 'asc')).toBeNull(); expect(await readAccountInvestmentActivityCount(reader, account)).toBe(59); const first = await readAccountInvestmentActivityPage(pageReader, account, { order: 'desc', @@ -1144,7 +1123,7 @@ it('retains uncertain original cash actions and numbers the full visible entry b }); }); -it('enforces account membership, access, summaries and bounded posting page options', async () => { +it('enforces account membership, access and saved posting summaries', async () => { const database = await createDatabase(); const account = { id: 'cash0001', ...ready() }; const empty = { id: 'empty001', ...ready('assets:empty', 0) }; @@ -1195,9 +1174,6 @@ it('enforces account membership, access, summaries and bounded posting page opti await expect( readAccountInvestmentActivityPage(database, wrongAccount, options) ).rejects.toThrow(); - await expect( - readAccountInvestmentActivityPage(database, account, { ...options, offset: -1 }) - ).rejects.toThrow('Invalid account page.'); await database .deleteFrom('account_activity_summaries') .where('account_name', '=', account.name) diff --git a/packages/db/src/reports/queries.ts b/packages/db/src/reports/queries.ts index e59210c..11e5276 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -1,7 +1,6 @@ import type { PreparedAccountRow } from '@hledger-reports/hledger'; import { decodeNativeTransaction, prepareTransaction } from '@hledger-reports/hledger/transactions'; import { sql, type Kysely } from 'kysely'; -import { registerPageSize } from '../register-page.js'; import type { ReportDatabase } from '../schema.js'; import { hasAccountActivitySummary, @@ -16,8 +15,6 @@ import { type StoredReportData } from './data.js'; import { - assertRegisterPageOptions, - findOldestFirstRegisterRowOffsetForEntry, readRegisterRowReferencePage, type RegisterPageOptions } from './prepared-register-rows.js'; @@ -29,10 +26,6 @@ export interface AccountActivityPage { summary: AccountActivitySummary; } -export interface FocusedAccountActivityPage extends AccountActivityPage { - pageNumber: number; -} - export interface AccountInvestmentActivityPage { rows: { row: PreparedAccountRow; @@ -400,92 +393,53 @@ async function readAccountEntriesByOrdinal( return entriesByAccountOrdinal; } -async function readCashRegisterPageRows( +export async function readCashRegisterPage( database: Kysely, - accountName: string, - rowCount: number, - options: RegisterPageOptions -): Promise { + account: StoredAccount, + pageOrder: RegisterPageOptions['order'], + pageOffset: number +): Promise { + const context = await readAccountPageContext(database, account); + if (!context) return null; + const { rowCount, summary } = context; const orderedReferences = await readRegisterRowReferencePage( database, - accountName, + account.name, 'entry', rowCount, - options + { order: pageOrder, offset: pageOffset } ); const entriesByAccountOrdinal = await readAccountEntriesByOrdinal( database, - accountName, + account.name, rowCount, orderedReferences.map(({ accountOrdinal }) => accountOrdinal) ); - return orderedReferences.map(({ accountOrdinal, display_date }) => { + const rows = orderedReferences.map(({ accountOrdinal, display_date }) => { const row = entriesByAccountOrdinal.get(accountOrdinal); if (!row || row.accountDate !== display_date) throw new Error('Invalid account data.'); return row; }); -} - -export async function readAccountActivityPage( - database: Kysely, - account: StoredAccount, - options: RegisterPageOptions -): Promise { - assertRegisterPageOptions(options); - const context = await readAccountPageContext(database, account); - if (!context) return null; - const { rowCount, summary } = context; - const rows = await readCashRegisterPageRows(database, account.name, rowCount, options); return { rows, summary }; } -async function findCashFocusRowPosition( +export async function findAccountEntryOrdinal( database: Kysely, - accountName: string, - nativeEntryIndex: number + account: StoredAccount, + nativeTransactionIndex: number ): Promise { - const rowPosition = await findOldestFirstRegisterRowOffsetForEntry( - database, - accountName, - 'entry', - nativeEntryIndex - ); - if (rowPosition !== null) return rowPosition; - const entry = await database .selectFrom('account_activity') .select('ordinal') - .where('account_name', '=', accountName) - .where('native_transaction_index', '=', nativeEntryIndex) + .where('account_name', '=', account.name) + .where('native_transaction_index', '=', nativeTransactionIndex) .executeTakeFirst(); - if (entry) throw new Error('Missing prepared Cash row.'); - return null; -} + if (entry) return entry.ordinal; -export async function readFocusedAccountActivityPage( - database: Kysely, - account: StoredAccount, - nativeEntryIndex: number -): Promise { + // A miss skips the page reader, so check account readability here. const context = await readAccountPageContext(database, account); if (!context) throw new Error('Account activity is unavailable.'); - const { rowCount, summary } = context; - const targetRowPosition = await findCashFocusRowPosition( - database, - account.name, - nativeEntryIndex - ); - if (targetRowPosition === null) return null; - - const pageNumber = Math.floor(targetRowPosition / registerPageSize) + 1; - const pageStart = (pageNumber - 1) * registerPageSize; - const rows = await readCashRegisterPageRows(database, account.name, rowCount, { - order: 'asc', - offset: pageStart - }); - const targetRow = rows[targetRowPosition - pageStart]; - if (targetRow?.transaction.index !== nativeEntryIndex) throw new Error('Invalid account data.'); - return { pageNumber, rows, summary }; + return null; } function requireSavedInvestmentPostingCount( @@ -553,7 +507,6 @@ export async function readAccountInvestmentActivityPage( account: StoredAccount, options: RegisterPageOptions ): Promise { - assertRegisterPageOptions(options); const context = await readAccountPageContext(database, account); if (!context) return null; const { rowCount: entryCount, postingRowCount, summary } = context; diff --git a/packages/snapshots/src/index.ts b/packages/snapshots/src/index.ts index 79adc26..0d59808 100644 --- a/packages/snapshots/src/index.ts +++ b/packages/snapshots/src/index.ts @@ -9,13 +9,16 @@ export { readInvestmentActivityPage, readAccountTransaction } from './reports/publication.js'; -export type { ReportPublication, ReportStage } from './reports/publication.js'; +export type { + FocusedAccountActivityPage, + ReportPublication, + ReportStage +} from './reports/publication.js'; export type { StoredAccount, AccountActivitySummary, AccountActivityPage, - AccountInvestmentActivityPage, - FocusedAccountActivityPage + AccountInvestmentActivityPage } 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 4c069cf..5ebe6c7 100644 --- a/packages/snapshots/src/reports/publication.test.ts +++ b/packages/snapshots/src/reports/publication.test.ts @@ -352,7 +352,9 @@ it('locates and reads the ordinary Cash page on the same checked connection', as const ordinaryPage = await readAccountPage(pinned, id, { order: 'asc', offset: 50 }); expect(ordinaryPage?.rows).toEqual([targetRow, lastRow]); expect(ordinaryPage?.summary.hasMultipleCommodities).toBe(true); - expect(await readFocusedAccountPage(pinned, id, 9999)).toBeNull(); + const newestFirst = await readFocusedAccountPage(pinned, id, target, 'desc'); + expect(newestFirst?.pageNumber).toBe(1); + expect(newestFirst?.rows.slice(0, 2)).toEqual([lastRow, targetRow]); const readKey = reports.readPublicationRequest; const next = { ...fixture(), preparedAt: 'replacement during read' }; @@ -364,14 +366,28 @@ it('locates and reads the ordinary Cash page on the same checked connection', as await stage.publish(next, [ready()], journal); return key; }); - const focusedPage = await readFocusedAccountPage(pinned, id, target); + const focusedPage = await readFocusedAccountPage(pinned, id, target, 'asc'); expect(focusedPage).toEqual({ ...ordinaryPage, pageNumber: 2 }); expect(await readOverview(snapshots)).toEqual(next); - await expect(readFocusedAccountPage(pinned, id, target)).rejects.toSatisfy( + await expect(readFocusedAccountPage(pinned, id, target, 'asc')).rejects.toSatisfy( safeError('Unable to read account transactions') ); }); +it('rejects focus when the saved entry has lost its prepared Cash row', async () => { + await publish(); + const publication = await selected(); + const id = publication.accounts[0].id; + withReportFile((database) => + database.prepare("DELETE FROM prepared_register_rows WHERE row_kind = 'entry'").run() + ); + + await expect(readFocusedAccountPage(publication, id, 1, 'desc')).rejects.toSatisfy( + safeError('Unable to read account transactions') + ); + expect(await readAccountTransaction(publication, id, 1)).toEqual(rows()[0]); +}); + it('stores only the intended overview fields and preserves absent history and null values', async () => { const investment: PreparedInvestmentOverview = { investmentAccountNames: ['assets:cash'], @@ -960,9 +976,6 @@ it('rejects unsafe and uncatalogued account IDs before opening financial data', await expect(readAccountTransaction(publication, 'cash0001', 0)).rejects.toSatisfy( safeError('Unable to read account transactions') ); - await expect(readFocusedAccountPage(publication, 'cash0001', 0)).rejects.toSatisfy( - safeError('Unable to read account transactions') - ); await expect(readInvestmentActivityCount(publication, '../escape')).rejects.toSatisfy( safeError('Unable to read account activity') ); diff --git a/packages/snapshots/src/reports/publication.ts b/packages/snapshots/src/reports/publication.ts index a4943f0..2587176 100644 --- a/packages/snapshots/src/reports/publication.ts +++ b/packages/snapshots/src/reports/publication.ts @@ -19,8 +19,9 @@ import { isAccountCatalog, isAccountId, isAccountSummary, - readAccountActivityPage, - readFocusedAccountActivityPage, + findAccountEntryOrdinal, + findRegisterEntryLocation, + readCashRegisterPage, readAccountActivityDetail, readAccountInvestmentActivityCount, readAccountInvestmentActivityPage, @@ -36,7 +37,6 @@ import { type AccountActivitySummary, type AccountActivityPage, type AccountInvestmentActivityPage, - type FocusedAccountActivityPage, type RegisterPageOptions, type StoredAccount, type StoredReportData @@ -68,6 +68,10 @@ export interface ReportPublication extends StoredReportData { publicationKey: string; } +export interface FocusedAccountActivityPage extends AccountActivityPage { + pageNumber: number; +} + export interface ReportStage { transactions: PreparationTransactions; writeRows(name: string, rows: readonly PreparedAccountRow[]): Promise; @@ -192,7 +196,7 @@ export async function readAccountPage( const account = publication.accounts.find((entry) => entry.id === id); if (!account) throw new Error(); return await readFromSelectedPublication(publication, (database) => - readAccountActivityPage(database, account, options) + readCashRegisterPage(database, account, options.order, options.offset) ); } catch { throw new Error('Unable to read account transactions'); @@ -202,16 +206,35 @@ export async function readAccountPage( export async function readFocusedAccountPage( publication: ReportPublication, id: string, - nativeEntryIndex: number + nativeTransactionIndex: number, + order: RegisterPageOptions['order'] ): Promise { try { - if (!isAccountId(id) || !Number.isSafeInteger(nativeEntryIndex) || nativeEntryIndex <= 0) - throw new Error(); const account = publication.accounts.find((entry) => entry.id === id); - if (!account) throw new Error(); - return await readFromSelectedPublication(publication, (database) => - readFocusedAccountActivityPage(database, account, nativeEntryIndex) - ); + if (account?.access !== 'ready') throw new Error('Account activity is unavailable.'); + return await readFromSelectedPublication(publication, async (database) => { + const entryOrdinal = await findAccountEntryOrdinal(database, account, nativeTransactionIndex); + if (entryOrdinal === null) return null; + const location = await findRegisterEntryLocation( + database, + account.name, + 'entry', + entryOrdinal, + order + ); + if (!location) throw new Error('Missing prepared Cash row.'); + + const page = await readCashRegisterPage( + database, + account, + location.pageOrder, + location.pageOffset + ); + const targetRow = page?.rows[location.indexOnPage]; + if (!page || targetRow?.transaction.index !== nativeTransactionIndex) + throw new Error('Invalid account data.'); + return { ...page, pageNumber: location.pageNumber }; + }); } catch { throw new Error('Unable to read account transactions'); } -- 2.54.1 From bcd4c12eecb4d66e6ace6ea0215f93108d7ff24a Mon Sep 17 00:00:00 2001 From: eleith Date: Thu, 3 Dec 2026 11:30:08 -0800 Subject: [PATCH 15/19] feat(web): focus a saved Investment register posting --- .changeset/focus-saved-register-row.md | 2 +- apps/web/e2e/investment-register.e2e.ts | 47 +++++++++++- .../lib/registers/RegisterPageError.svelte | 13 ++++ apps/web/src/lib/registers/cash/data.ts | 7 -- .../lib/registers/cash/row-batch-request.ts | 2 +- .../cash/transaction-details-request.ts | 2 +- .../investment/InvestmentRegister.svelte | 8 +- .../investment/activity-batch-request.ts | 2 +- apps/web/src/lib/registers/investment/data.ts | 1 + .../investment/register-page-request.ts | 44 ----------- .../investment/request-validation.ts | 13 ---- .../investment/table/CellContent.svelte | 1 + .../investment/table/VirtualTable.svelte | 3 +- .../lib/registers/investment/table/table.css | 8 ++ .../register-page-request.test.ts | 12 +-- .../{cash => }/register-page-request.ts | 20 +++-- .../{cash => }/request-validation.ts | 4 +- .../src/lib/server/registers/cash/register.ts | 2 +- .../server/registers/investment/projection.ts | 2 +- .../registers/investment/register.test.ts | 1 + .../server/registers/investment/register.ts | 47 +++++++++++- .../registers/cash/[accountId]/+error.svelte | 19 ++--- .../cash/[accountId]/+page.server.ts | 4 +- .../investments/[accountId]/+error.svelte | 13 ++++ .../investments/[accountId]/+page.server.ts | 4 +- .../[accountId]/page.server.test.ts | 47 ++++++++++-- packages/db/src/reports/index.ts | 3 +- .../db/src/reports/prepared-register-rows.ts | 12 ++- packages/db/src/reports/queries.test.ts | 52 +++++++++---- packages/db/src/reports/queries.ts | 37 +++++++-- packages/snapshots/src/index.ts | 1 + .../snapshots/src/reports/publication.test.ts | 75 +++++++++++++++++++ packages/snapshots/src/reports/publication.ts | 46 ++++++++++-- 33 files changed, 409 insertions(+), 145 deletions(-) create mode 100644 apps/web/src/lib/registers/RegisterPageError.svelte delete mode 100644 apps/web/src/lib/registers/investment/register-page-request.ts delete mode 100644 apps/web/src/lib/registers/investment/request-validation.ts rename apps/web/src/lib/registers/{investment => }/register-page-request.test.ts (76%) rename apps/web/src/lib/registers/{cash => }/register-page-request.ts (79%) rename apps/web/src/lib/registers/{cash => }/request-validation.ts (72%) create mode 100644 apps/web/src/routes/(protected)/registers/investments/[accountId]/+error.svelte diff --git a/.changeset/focus-saved-register-row.md b/.changeset/focus-saved-register-row.md index 094803b..04be665 100644 --- a/.changeset/focus-saved-register-row.md +++ b/.changeset/focus-saved-register-row.md @@ -2,4 +2,4 @@ '@hledger-reports/web': patch --- -Use `?focus=` to open and mark a transaction in the ordinary Cash register. Changing sort keeps focus on the same transaction. If the target is missing, use **Open register** to keep browsing. Links may not find the same transaction after re-preparation. +Use `?focus=` to open the normal page containing a transaction in the Cash or Investment register. Investment marks the transaction’s first visible posting in the chosen date order. Changing sort keeps focus on the same transaction. If the target is missing, use **Open register** to keep browsing. Links may not find the same transaction after re-preparation. diff --git a/apps/web/e2e/investment-register.e2e.ts b/apps/web/e2e/investment-register.e2e.ts index 3fada05..f160ec0 100644 --- a/apps/web/e2e/investment-register.e2e.ts +++ b/apps/web/e2e/investment-register.e2e.ts @@ -22,6 +22,10 @@ async function openInvestment(page: Page, account: 'Brokerage' | 'retirement' = ).toBeVisible(); } +// The two-security purchase is entry 4 in the fictional base journal. +const twoStockPurchaseFocus = 'focus=4'; +const vtiPurchase = 'Open investment activity: Buy VTI on 2026-04-04'; + test('stock actions keep focused details and associated cash without duplicating the shared debit', async ({ page }) => { @@ -112,6 +116,27 @@ test('stock actions keep focused details and associated cash without duplicating ); }); +test('sorting Investment activity keeps focus on the same saved entry', async ({ page }) => { + await page.setViewportSize({ width: 1440, height: 900 }); + await openInvestment(page); + const activity = page.getByRole('region', { name: 'Investment activity', exact: true }); + const accountURL = new URL(page.url()); + accountURL.search = twoStockPurchaseFocus; + await page.goto(accountURL.href); + const current = activity.locator('button[aria-current="true"]'); + const firstDate = activity.locator('[data-row-position="0"][data-column="date"] time'); + await expect(firstDate).toHaveAttribute('datetime', '2026-04-04'); + await expect(current).toHaveAccessibleName(vtiPurchase); + await expect(current).toBeEnabled(); + await expect(page.getByRole('dialog', { name: 'Activity details' })).toHaveCount(0); + await activity + .getByRole('link', { name: 'Date: oldest first; show newest first', exact: true }) + .click(); + await expect(page).toHaveURL(/\?order=desc&focus=4$/); + await expect(firstDate).toHaveAttribute('datetime', '2026-04-16'); + await expect(current).toHaveAccessibleName(vtiPurchase); +}); + test('phone activity keeps the selected stock focused while retaining cash context and standalone deposits', async ({ page }) => { @@ -327,11 +352,12 @@ test.describe('without JavaScript', () => { await prepareReports(page); } }); - test('investment posting activity and date navigation remain ordinary saved HTML', async ({ + test('investment posting activity, date navigation and focus remain readable in saved HTML', async ({ page }) => { await page.setViewportSize({ width: 1440, height: 900 }); await openInvestment(page); + const accountURL = page.url(); const activity = page.getByRole('region', { name: 'Investment activity', exact: true }); await expect(activity.locator('td[data-column="security"]').first()).toHaveText('VTI', { useInnerText: true @@ -349,5 +375,24 @@ test.describe('without JavaScript', () => { await expect( page.locator('main').getByRole('link', { name: 'Holdings', exact: true }) ).toHaveAttribute('href', /\/holdings\?accountId=[a-z0-9]{8}$/); + + await page.goto(`${accountURL}?${twoStockPurchaseFocus}`); + const table = activity.getByRole('table', { name: 'Activity for Brokerage', exact: true }); + const current = table.locator('button[aria-current="true"]'); + await expect(current).toHaveAccessibleName(vtiPurchase); + await expect(current).toBeDisabled(); + await expect( + table.getByRole('button', { name: 'Open investment activity: Buy BND on 2026-04-04' }) + ).toBeVisible(); + await expect( + table.getByRole('button', { name: 'Open investment activity: Buy VTI on 2026-04-05' }) + ).toBeVisible(); + + const missing = await page.goto(`${accountURL}?focus=9007199254740991`); + expect(missing?.status()).toBe(404); + await page.getByRole('link', { name: 'Open register', exact: true }).click(); + await expect(page).toHaveURL(accountURL); + await expect(table).toBeVisible(); + await expect(current).toHaveCount(0); }); }); diff --git a/apps/web/src/lib/registers/RegisterPageError.svelte b/apps/web/src/lib/registers/RegisterPageError.svelte new file mode 100644 index 0000000..52f0e6a --- /dev/null +++ b/apps/web/src/lib/registers/RegisterPageError.svelte @@ -0,0 +1,13 @@ + + +
+

{page.status}

+

{page.error?.message}

+ {#if page.error?.code === 'REGISTER_FOCUS_NOT_FOUND' && registerHref} +

Open register

+ {/if} +
diff --git a/apps/web/src/lib/registers/cash/data.ts b/apps/web/src/lib/registers/cash/data.ts index d062d56..7defc86 100644 --- a/apps/web/src/lib/registers/cash/data.ts +++ b/apps/web/src/lib/registers/cash/data.ts @@ -15,13 +15,6 @@ export interface RegisterRow { export { registerPageSize as rowBatchSize } from '@hledger-reports/snapshots/register-page'; -export interface RegisterPageRequest { - accountId: string; - order: RegisterPageData['order']; - page: number | null; - focusTransactionIndex?: number; -} - export interface RowBatchRequest { accountId: string; order: RegisterPageData['order']; diff --git a/apps/web/src/lib/registers/cash/row-batch-request.ts b/apps/web/src/lib/registers/cash/row-batch-request.ts index 1a072b6..ddebe47 100644 --- a/apps/web/src/lib/registers/cash/row-batch-request.ts +++ b/apps/web/src/lib/registers/cash/row-batch-request.ts @@ -1,6 +1,6 @@ import { error } from '@sveltejs/kit'; import { rowBatchSize, type RowBatchRequest } from './data.js'; -import { isAccountId, isDateOrder } from './request-validation.js'; +import { isAccountId, isDateOrder } from '../request-validation.js'; export function parseRowBatchRequest(input: unknown): RowBatchRequest { if (!hasRowBatchRequestShape(input)) error(400, 'A valid row batch is required.'); diff --git a/apps/web/src/lib/registers/cash/transaction-details-request.ts b/apps/web/src/lib/registers/cash/transaction-details-request.ts index 3844a5e..c7dd1ef 100644 --- a/apps/web/src/lib/registers/cash/transaction-details-request.ts +++ b/apps/web/src/lib/registers/cash/transaction-details-request.ts @@ -1,6 +1,6 @@ import { error } from '@sveltejs/kit'; import type { TransactionDetailsRequest } from './data.js'; -import { isAccountId, isPositiveSafeInteger } from './request-validation.js'; +import { isAccountId, isPositiveSafeInteger } from '../request-validation.js'; export function parseTransactionDetailsRequest(input: unknown): TransactionDetailsRequest { if (!hasTransactionDetailsRequestShape(input)) { diff --git a/apps/web/src/lib/registers/investment/InvestmentRegister.svelte b/apps/web/src/lib/registers/investment/InvestmentRegister.svelte index 64c1574..132e385 100644 --- a/apps/web/src/lib/registers/investment/InvestmentRegister.svelte +++ b/apps/web/src/lib/registers/investment/InvestmentRegister.svelte @@ -42,9 +42,11 @@ let tableFocusTarget = $state(null); let virtualTable = $state<{ scrollToRow: (rowPosition: number) => void }>(); let selectedActivity = $state.raw(null); - const orderHref = $derived( - `?${new URLSearchParams({ order: data.order === 'asc' ? 'desc' : 'asc' })}` - ); + const orderHref = $derived.by(() => { + const order = data.order === 'asc' ? 'desc' : 'asc'; + const focusedActivity = data.activities.find((activity) => activity.isFocusTarget); + return `?${new URLSearchParams(focusedActivity ? { order, focus: String(focusedActivity.transactionIndex) } : { order })}`; + }); let neededBatchStarts = $derived( requiredRemoteBatchStarts( diff --git a/apps/web/src/lib/registers/investment/activity-batch-request.ts b/apps/web/src/lib/registers/investment/activity-batch-request.ts index d199a37..d3b57de 100644 --- a/apps/web/src/lib/registers/investment/activity-batch-request.ts +++ b/apps/web/src/lib/registers/investment/activity-batch-request.ts @@ -1,6 +1,6 @@ import { error } from '@sveltejs/kit'; import { activityBatchSize, type ActivityBatchRequest } from './data.js'; -import { isAccountId, isDateOrder } from './request-validation.js'; +import { isAccountId, isDateOrder } from '../request-validation.js'; export function parseActivityBatchRequest(input: unknown): ActivityBatchRequest { if (!hasActivityBatchRequestShape(input)) error(400, 'A valid activity batch is required.'); diff --git a/apps/web/src/lib/registers/investment/data.ts b/apps/web/src/lib/registers/investment/data.ts index 642d26c..000f645 100644 --- a/apps/web/src/lib/registers/investment/data.ts +++ b/apps/web/src/lib/registers/investment/data.ts @@ -64,6 +64,7 @@ export interface InvestmentActivity { /** Native selected-account balance after the whole entry, only on its final activity. */ cashBalance: { amounts: ReportedAmount[]; unclassifiedAmounts: ReportedAmount[] } | null; issues: InvestmentIssue[]; + isFocusTarget?: true; } export interface InvestmentRegisterData { diff --git a/apps/web/src/lib/registers/investment/register-page-request.ts b/apps/web/src/lib/registers/investment/register-page-request.ts deleted file mode 100644 index 2bd5e45..0000000 --- a/apps/web/src/lib/registers/investment/register-page-request.ts +++ /dev/null @@ -1,44 +0,0 @@ -import { error } from '@sveltejs/kit'; -import type { InvestmentRegisterData } from './data.js'; -import { isAccountId, isDateOrder, isPositiveSafeInteger } from './request-validation.js'; - -export interface RegisterPageRequest { - accountId: string; - order: InvestmentRegisterData['order']; - page: number | null; -} - -export function parseRegisterPageRequest( - accountId: string, - parameters: URLSearchParams -): RegisterPageRequest { - if (!isAccountId(accountId)) error(400, 'A valid account ID is required.'); - for (const key of parameters.keys()) { - if (key !== 'order' && key !== 'page') error(400, 'Unsupported register parameter.'); - } - const order = parseOrder(parameters); - const page = parsePage(parameters); - return { accountId, order, page }; -} - -function parseOrder(parameters: URLSearchParams): RegisterPageRequest['order'] { - const orders = parameters.getAll('order'); - const order = orders[0] ?? 'asc'; - if (orders.length > 1 || !isDateOrder(order)) error(400, 'A valid date order is required.'); - return order; -} - -function parsePage(parameters: URLSearchParams): RegisterPageRequest['page'] { - const pages = parameters.getAll('page'); - if (pages.length > 1) error(400, 'A valid page number is required.'); - const pageText = pages[0]; - if (pageText === undefined) return null; - if (!isCanonicalPageNumberText(pageText)) error(400, 'A valid page number is required.'); - const page = Number(pageText); - if (!isPositiveSafeInteger(page)) error(400, 'A valid page number is required.'); - return page; -} - -function isCanonicalPageNumberText(value: string): boolean { - return /^[1-9][0-9]*(?![\s\S])/.test(value); -} diff --git a/apps/web/src/lib/registers/investment/request-validation.ts b/apps/web/src/lib/registers/investment/request-validation.ts deleted file mode 100644 index 890e5f5..0000000 --- a/apps/web/src/lib/registers/investment/request-validation.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { InvestmentRegisterData } from './data.js'; - -export function isAccountId(value: unknown): value is string { - return typeof value === 'string' && value.length === 8 && !/[^a-z0-9]/.test(value); -} - -export function isDateOrder(value: unknown): value is InvestmentRegisterData['order'] { - return value === 'asc' || value === 'desc'; -} - -export function isPositiveSafeInteger(value: unknown): value is number { - return typeof value === 'number' && Number.isSafeInteger(value) && value > 0; -} diff --git a/apps/web/src/lib/registers/investment/table/CellContent.svelte b/apps/web/src/lib/registers/investment/table/CellContent.svelte index 5c3857e..0917da3 100644 --- a/apps/web/src/lib/registers/investment/table/CellContent.svelte +++ b/apps/web/src/lib/registers/investment/table/CellContent.svelte @@ -63,6 +63,7 @@ data-investment-details disabled={!onOpenActivity} aria-haspopup="dialog" + aria-current={activity.isFocusTarget} title="View activity details" onclick={(event) => onOpenActivity?.(rowPosition, event.currentTarget)} > diff --git a/apps/web/src/lib/registers/investment/table/VirtualTable.svelte b/apps/web/src/lib/registers/investment/table/VirtualTable.svelte index 2282b14..84d4880 100644 --- a/apps/web/src/lib/registers/investment/table/VirtualTable.svelte +++ b/apps/web/src/lib/registers/investment/table/VirtualTable.svelte @@ -238,7 +238,8 @@
{ - expect(parseRegisterPageRequest(accountId, new URLSearchParams())).toEqual({ +it('uses the caller’s default direction and preserves explicit date/page choices', () => { + expect(parseRegisterPageRequest(accountId, new URLSearchParams(), 'asc')).toEqual({ accountId, order: 'asc', page: null }); - expect(parseRegisterPageRequest(accountId, new URLSearchParams('order=desc&page=2'))).toEqual({ + expect( + parseRegisterPageRequest(accountId, new URLSearchParams('order=desc&page=2'), 'asc') + ).toEqual({ accountId, order: 'desc', page: 2 @@ -30,11 +32,11 @@ it('rejects unsupported, repeated and invalid view parameters without echoing in 'page=1.5', 'page=9007199254740992' ]) { - expect(() => parseRegisterPageRequest(accountId, new URLSearchParams(query))).toThrow( + expect(() => parseRegisterPageRequest(accountId, new URLSearchParams(query), 'asc')).toThrow( expect.objectContaining({ status: 400 }) ); } - expect(() => parseRegisterPageRequest('../PRIVATE', new URLSearchParams())).toThrow( + expect(() => parseRegisterPageRequest('../PRIVATE', new URLSearchParams(), 'asc')).toThrow( expect.objectContaining({ status: 400, body: expect.objectContaining({ message: 'A valid account ID is required.' }) diff --git a/apps/web/src/lib/registers/cash/register-page-request.ts b/apps/web/src/lib/registers/register-page-request.ts similarity index 79% rename from apps/web/src/lib/registers/cash/register-page-request.ts rename to apps/web/src/lib/registers/register-page-request.ts index b62f728..350f599 100644 --- a/apps/web/src/lib/registers/cash/register-page-request.ts +++ b/apps/web/src/lib/registers/register-page-request.ts @@ -1,14 +1,21 @@ import { error } from '@sveltejs/kit'; -import type { RegisterPageRequest } from './data.js'; import { isAccountId, isDateOrder, isPositiveSafeInteger } from './request-validation.js'; +export interface RegisterPageRequest { + accountId: string; + order: 'asc' | 'desc'; + page: number | null; + focusTransactionIndex?: number; +} + export function parseRegisterPageRequest( accountId: string, - parameters: URLSearchParams + parameters: URLSearchParams, + defaultOrder: RegisterPageRequest['order'] ): RegisterPageRequest { if (!isAccountId(accountId)) error(400, 'A valid account ID is required.'); requireSupportedParameters(parameters); - const order = parseOrder(parameters); + const order = parseOrder(parameters, defaultOrder); const focusTransactionIndex = parsePositiveIntegerParameter( parameters, 'focus', @@ -33,9 +40,12 @@ function requireSupportedParameters(parameters: URLSearchParams): void { } } -function parseOrder(parameters: URLSearchParams): RegisterPageRequest['order'] { +function parseOrder( + parameters: URLSearchParams, + defaultOrder: RegisterPageRequest['order'] +): RegisterPageRequest['order'] { const orders = parameters.getAll('order'); - const order = orders[0] ?? 'desc'; + const order = orders[0] ?? defaultOrder; if (orders.length > 1 || !isDateOrder(order)) error(400, 'A valid date order is required.'); return order; } diff --git a/apps/web/src/lib/registers/cash/request-validation.ts b/apps/web/src/lib/registers/request-validation.ts similarity index 72% rename from apps/web/src/lib/registers/cash/request-validation.ts rename to apps/web/src/lib/registers/request-validation.ts index 105710f..0eff2be 100644 --- a/apps/web/src/lib/registers/cash/request-validation.ts +++ b/apps/web/src/lib/registers/request-validation.ts @@ -1,10 +1,8 @@ -import type { RegisterPageData } from './data.js'; - export function isAccountId(value: unknown): value is string { return typeof value === 'string' && value.length === 8 && !/[^a-z0-9]/.test(value); } -export function isDateOrder(value: unknown): value is RegisterPageData['order'] { +export function isDateOrder(value: unknown): value is 'asc' | 'desc' { return value === 'asc' || value === 'desc'; } diff --git a/apps/web/src/lib/server/registers/cash/register.ts b/apps/web/src/lib/server/registers/cash/register.ts index 9b5cd17..e9af4d3 100644 --- a/apps/web/src/lib/server/registers/cash/register.ts +++ b/apps/web/src/lib/server/registers/cash/register.ts @@ -9,12 +9,12 @@ import { error } from '@sveltejs/kit'; import { rowBatchSize, type RegisterPageData, - type RegisterPageRequest, type RowBatch, type RowBatchRequest, type TransactionDetails, type TransactionDetailsRequest } from '#lib/registers/cash/data.js'; +import type { RegisterPageRequest } from '#lib/registers/register-page-request.js'; import type { ReadableAccount } from '../prepared-account.js'; import { projectActivityPage, projectTransactionDetails } from './projection.js'; import { diff --git a/apps/web/src/lib/server/registers/investment/projection.ts b/apps/web/src/lib/server/registers/investment/projection.ts index 7543a92..82b5fdf 100644 --- a/apps/web/src/lib/server/registers/investment/projection.ts +++ b/apps/web/src/lib/server/registers/investment/projection.ts @@ -111,7 +111,7 @@ function projectInvestmentActivity( } export function projectInvestmentActivityPage( - { rows, summary }: AccountInvestmentActivityPage, + { rows, summary }: Pick, accountName: string ): Pick { // Several stock actions can share one native entry cash effect; never allocate it. diff --git a/apps/web/src/lib/server/registers/investment/register.test.ts b/apps/web/src/lib/server/registers/investment/register.test.ts index 7560fbd..a0f9c2e 100644 --- a/apps/web/src/lib/server/registers/investment/register.test.ts +++ b/apps/web/src/lib/server/registers/investment/register.test.ts @@ -43,6 +43,7 @@ row.transaction.postings = [ row.investment.cashPostingIndexes = [...row.accountPostingIndexes]; row.investment.expensePostingIndexes = [55, 56]; const page: AccountInvestmentActivityPage = { + activityCount: row.accountPostingIndexes.length, rows: row.accountPostingIndexes.slice(50).map((postingIndex) => ({ row, postingIndex, diff --git a/apps/web/src/lib/server/registers/investment/register.ts b/apps/web/src/lib/server/registers/investment/register.ts index 90c8779..fef4784 100644 --- a/apps/web/src/lib/server/registers/investment/register.ts +++ b/apps/web/src/lib/server/registers/investment/register.ts @@ -1,6 +1,7 @@ import { readInvestmentActivityCount, readInvestmentActivityPage, + readFocusedInvestmentActivityPage, type AccountInvestmentActivityPage } from '@hledger-reports/snapshots'; import { error } from '@sveltejs/kit'; @@ -11,7 +12,7 @@ import { type InvestmentAccountPageData, type InvestmentRegisterData } from '#lib/registers/investment/data.js'; -import type { RegisterPageRequest } from '#lib/registers/investment/register-page-request.js'; +import type { RegisterPageRequest } from '#lib/registers/register-page-request.js'; import type { ReadableAccount } from '../prepared-account.js'; import { selectRegisterPageAccount, @@ -32,7 +33,12 @@ export async function loadRegisterPage( preparedAt: account.publication.overview.preparedAt }; if (account.access === 'ambiguous') return { ...metadata, readFailed: false, register: null }; - return { ...metadata, ...(await readInitialRegisterPage(account, request)) }; + const { order, focusTransactionIndex } = request; + const initialPage = + focusTransactionIndex === undefined + ? await readInitialRegisterPage(account, request) + : await readFocusedRegisterPage(account, order, focusTransactionIndex); + return { ...metadata, ...initialPage }; } export async function readActivityBatch( @@ -111,6 +117,43 @@ async function readInitialRegisterPage( } } +async function readFocusedRegisterPage( + account: ReadableAccount, + order: InvestmentRegisterData['order'], + transactionIndex: number +): Promise> { + try { + const saved = await readFocusedInvestmentActivityPage( + account.publication, + account.id, + transactionIndex, + order + ); + if (saved) { + const projected = projectInvestmentActivityPage(saved, account.name); + projected.activities[saved.indexOnPage].isFocusTarget = true; + return { + register: { + accountId: account.id, + accountName: account.name, + order, + page: saved.pageNumber, + pageCount: Math.ceil(saved.activityCount / activityBatchSize), + activityCount: saved.activityCount, + ...projected + }, + readFailed: false + }; + } + } catch { + return { register: null, readFailed: true }; + } + error(404, { + message: 'Transaction not found in this saved register.', + code: 'REGISTER_FOCUS_NOT_FOUND' + }); +} + async function readSavedActivityPage( account: ReadableAccount, order: InvestmentRegisterData['order'], diff --git a/apps/web/src/routes/(protected)/registers/cash/[accountId]/+error.svelte b/apps/web/src/routes/(protected)/registers/cash/[accountId]/+error.svelte index bd54a64..a3e931e 100644 --- a/apps/web/src/routes/(protected)/registers/cash/[accountId]/+error.svelte +++ b/apps/web/src/routes/(protected)/registers/cash/[accountId]/+error.svelte @@ -1,18 +1,11 @@ -
-

{page.status}

-

{page.error?.message}

- {#if page.error?.code === 'REGISTER_FOCUS_NOT_FOUND' && page.params.accountId} -

- Open register -

- {/if} -
+ diff --git a/apps/web/src/routes/(protected)/registers/cash/[accountId]/+page.server.ts b/apps/web/src/routes/(protected)/registers/cash/[accountId]/+page.server.ts index 85083a5..f1f1e0c 100644 --- a/apps/web/src/routes/(protected)/registers/cash/[accountId]/+page.server.ts +++ b/apps/web/src/routes/(protected)/registers/cash/[accountId]/+page.server.ts @@ -1,9 +1,9 @@ -import { parseRegisterPageRequest } from '#lib/registers/cash/register-page-request.js'; +import { parseRegisterPageRequest } from '#lib/registers/register-page-request.js'; import { loadRegisterPage } from '#lib/server/registers/cash/register.js'; import type { PageServerLoad } from './$types'; export const load = (async (event) => { event.setHeaders({ 'cache-control': 'no-store' }); - const request = parseRegisterPageRequest(event.params.accountId, event.url.searchParams); + const request = parseRegisterPageRequest(event.params.accountId, event.url.searchParams, 'desc'); return loadRegisterPage(event, request); }) satisfies PageServerLoad; diff --git a/apps/web/src/routes/(protected)/registers/investments/[accountId]/+error.svelte b/apps/web/src/routes/(protected)/registers/investments/[accountId]/+error.svelte new file mode 100644 index 0000000..b843453 --- /dev/null +++ b/apps/web/src/routes/(protected)/registers/investments/[accountId]/+error.svelte @@ -0,0 +1,13 @@ + + + diff --git a/apps/web/src/routes/(protected)/registers/investments/[accountId]/+page.server.ts b/apps/web/src/routes/(protected)/registers/investments/[accountId]/+page.server.ts index ea18487..a357896 100644 --- a/apps/web/src/routes/(protected)/registers/investments/[accountId]/+page.server.ts +++ b/apps/web/src/routes/(protected)/registers/investments/[accountId]/+page.server.ts @@ -1,9 +1,9 @@ -import { parseRegisterPageRequest } from '#lib/registers/investment/register-page-request.js'; +import { parseRegisterPageRequest } from '#lib/registers/register-page-request.js'; import { loadRegisterPage } from '#lib/server/registers/investment/register.js'; import type { PageServerLoad } from './$types'; export const load = (async (event) => { event.setHeaders({ 'cache-control': 'no-store' }); - const request = parseRegisterPageRequest(event.params.accountId, event.url.searchParams); + const request = parseRegisterPageRequest(event.params.accountId, event.url.searchParams, 'asc'); return loadRegisterPage(event, request); }) satisfies PageServerLoad; diff --git a/apps/web/src/routes/(protected)/registers/investments/[accountId]/page.server.test.ts b/apps/web/src/routes/(protected)/registers/investments/[accountId]/page.server.test.ts index 6f13dfa..a593402 100644 --- a/apps/web/src/routes/(protected)/registers/investments/[accountId]/page.server.test.ts +++ b/apps/web/src/routes/(protected)/registers/investments/[accountId]/page.server.test.ts @@ -6,8 +6,10 @@ import { readReportPublication, readInvestmentActivityCount, readInvestmentActivityPage, + readFocusedInvestmentActivityPage, type AccountInvestmentActivityPage } from '@hledger-reports/snapshots'; +import { investmentRegisterFixture } from '#lib/registers/investment/investment-register.fixture.js'; import type { ApplicationContext } from '#lib/server/application.js'; import { projectInvestmentActivityPage } from '#lib/server/registers/investment/projection.js'; import { savedReportFixture } from '#lib/server/reports.fixture.js'; @@ -16,7 +18,8 @@ import { load } from './+page.server.js'; vi.mock('@hledger-reports/snapshots', () => ({ readReportPublication: vi.fn(), readInvestmentActivityCount: vi.fn(), - readInvestmentActivityPage: vi.fn() + readInvestmentActivityPage: vi.fn(), + readFocusedInvestmentActivityPage: vi.fn() })); vi.mock('#lib/server/registers/investment/projection.js', () => ({ projectInvestmentActivityPage: vi.fn() @@ -31,6 +34,7 @@ const publication = savedReportFixture({ accounts: [{ id, name, access: 'ready', rowCount: 1, summary: { status: 'undated' } }] }); const activityPage: AccountInvestmentActivityPage = { + activityCount: 51, rows: preparedAccountRows().map((row) => ({ row, postingIndex: 0, @@ -123,25 +127,58 @@ it('pages by the saved posting count in one publication, not the enclosing entry expect(request.setHeaders).toHaveBeenCalledWith({ 'cache-control': 'no-store' }); }); -it.each(['count', 'page'] as const)( +it('marks only the located posting on the saved containing page', async () => { + const [firstBuy, secondBuy, otherActivity] = investmentRegisterFixture().activities; + const focusedPage = { ...activityPage, activityCount: 53, pageNumber: 2, indexOnPage: 1 }; + vi.mocked(readFocusedInvestmentActivityPage).mockResolvedValue(focusedPage); + vi.mocked(projectInvestmentActivityPage).mockReturnValue({ + ...projection, + activities: [otherActivity, firstBuy, secondBuy] + }); + const result = await load(event('order=desc&focus=1')); + expect(readFocusedInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith( + publication, + id, + 1, + 'desc' + ); + expect(readInvestmentActivityCount).not.toHaveBeenCalled(); + expect(result.register).toMatchObject({ + page: 2, + pageCount: 2, + activityCount: 53, + order: 'desc' + }); + expect(result.register?.activities.filter((activity) => activity.isFocusTarget)).toEqual([ + { ...firstBuy, isFocusTarget: true } + ]); +}); + +it.each(['count', 'page', 'focus'] as const)( 'returns a safe read failure when the saved %s cannot be read', async (operation) => { if (operation === 'count') vi.mocked(readInvestmentActivityCount).mockRejectedValue( new Error('PRIVATE saved count diagnostic') ); - else + else if (operation === 'page') vi.mocked(readInvestmentActivityPage).mockRejectedValue( new Error('PRIVATE saved body diagnostic') ); - const request = event(); + else + vi.mocked(readFocusedInvestmentActivityPage).mockRejectedValue( + new Error('PRIVATE focused page diagnostic') + ); + const request = event(operation === 'focus' ? 'focus=1' : ''); const queue = vi.spyOn(request.locals.application!, 'jobsClient', 'get'); - expect(await load(request)).toMatchObject({ + const result = await load(request); + expect(result).toMatchObject({ readFailed: true, accountName: name, access: 'ready', register: null }); + expect(JSON.stringify(result)).not.toContain('PRIVATE'); expect(projectInvestmentActivityPage).not.toHaveBeenCalled(); expect(queue).not.toHaveBeenCalled(); } diff --git a/packages/db/src/reports/index.ts b/packages/db/src/reports/index.ts index 34f43e5..4d2f5a5 100644 --- a/packages/db/src/reports/index.ts +++ b/packages/db/src/reports/index.ts @@ -18,7 +18,7 @@ export { readPublicationRequest, readPublicationInvestmentJson, readCashRegisterPage, - findAccountEntryOrdinal, + findRegisterFocusLocation, readAccountActivityDetail, readAccountInvestmentActivityCount, readAccountInvestmentActivityPage @@ -26,7 +26,6 @@ export { export type { AccountActivityPage, AccountInvestmentActivityPage } from './queries.js'; export { writeRegisterRowsAndPostingCount, - findRegisterEntryLocation, type RegisterPageOptions } from './prepared-register-rows.js'; export { AccountActivitySummaryBuilder } 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 c335516..92d83a9 100644 --- a/packages/db/src/reports/prepared-register-rows.ts +++ b/packages/db/src/reports/prepared-register-rows.ts @@ -15,7 +15,7 @@ export interface RegisterPageOptions { offset: number; } -type RegisterRowKind = ReportDatabase['prepared_register_rows']['row_kind']; +export type RegisterRowKind = ReportDatabase['prepared_register_rows']['row_kind']; export async function readRegisterRowReferencePage( database: Kysely, @@ -60,14 +60,20 @@ export async function findRegisterEntryLocation( } | null> { const dateOrder = pageOrder === 'asc' ? sql`asc` : sql`desc`; const precedingDate = pageOrder === 'asc' ? sql`<` : sql`>`; - // Select the entry's references before sorting, so SQLite can seek by entry ordinal. + // Seek this entry first. Unique positions bounded by entry_row_count expose missing siblings. const { rows } = await sql<{ offset: number }>` with target_entry_rows as materialized ( - select account_name, row_kind, display_date, entry_ordinal, position_in_entry + select account_name, row_kind, display_date, entry_ordinal, position_in_entry, + posting_ordinal, entry_row_count 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 ), first_visible_row as ( select * from target_entry_rows + where (select has_all_siblings and has_unique_postings 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 9c4e7f5..bd807fe 100644 --- a/packages/db/src/reports/queries.test.ts +++ b/packages/db/src/reports/queries.test.ts @@ -11,7 +11,7 @@ import { type ReportDatabase } from '../index.js'; import { - findAccountEntryOrdinal, + findRegisterFocusLocation, readCashRegisterPage, readAccountActivityDetail, readAccountInvestmentActivityCount, @@ -353,20 +353,28 @@ it('reads date-ordered pages with native ties and exact account scope', async () expect(await readPage('asc', 53)).toEqual([]); expect(Math.max(...resultRowCounts)).toBe(50); - const targetEntryOrdinal = rows.indexOf(ascending[50]); + const targetIndex = ascending[50].transaction.index; + expect(await findRegisterFocusLocation(database, account, 'entry', targetIndex, 'asc')).toEqual({ + pageOrder: 'asc', + pageOffset: 50, + pageNumber: 2, + indexOnPage: 0 + }); + const sharedOrdinalIndex = rows[0].transaction.index; expect( - await findRegisterEntryLocation(database, account.name, 'entry', targetEntryOrdinal, 'asc') - ).toEqual({ pageOrder: 'asc', pageOffset: 50, pageNumber: 2, indexOnPage: 0 }); - expect(await findRegisterEntryLocation(database, account.name, 'entry', 0, 'asc')).toEqual({ + await findRegisterFocusLocation(database, account, 'entry', sharedOrdinalIndex, 'asc') + ).toEqual({ pageOrder: 'asc', pageOffset: 0, pageNumber: 1, indexOnPage: 27 }); - const sharedOrdinalIndex = rows[0].transaction.index; - expect(await findAccountEntryOrdinal(database, account, sharedOrdinalIndex)).toBe(0); - expect(await findAccountEntryOrdinal(database, other, sharedOrdinalIndex)).toBeNull(); - expect(await findRegisterEntryLocation(database, account.name, 'entry', 51, 'desc')).toEqual({ + expect( + await findRegisterFocusLocation(database, other, 'entry', sharedOrdinalIndex, 'asc') + ).toBeNull(); + expect( + await findRegisterFocusLocation(database, account, 'entry', rows[51].transaction.index, 'desc') + ).toEqual({ pageOrder: 'desc', pageOffset: 50, pageNumber: 2, @@ -556,7 +564,7 @@ it('rejects missing summaries and malformed native bags rather than inferring fr .where('account_name', '=', account.name) .execute(); await expect(readPage()).rejects.toThrow('Missing account activity summary.'); - await expect(findAccountEntryOrdinal(database, account, 2)).rejects.toThrow( + await expect(findRegisterFocusLocation(database, account, 'entry', 2, 'asc')).rejects.toThrow( 'Missing account activity summary.' ); }); @@ -707,8 +715,12 @@ it('pages original selected-account postings across a shared security group and order: 'desc', offset: 50 }); - expect(first).toEqual({ rows: descending.slice(0, 50), summary: preparedActivitySummary(rows) }); - expect(last).toEqual({ rows: descending.slice(50), summary: first?.summary }); + expect(first).toEqual({ + activityCount: 59, + rows: descending.slice(0, 50), + summary: preparedActivitySummary(rows) + }); + expect(last).toEqual({ activityCount: 59, rows: descending.slice(50), summary: first?.summary }); expect(first?.rows[0].row).toBe(first?.rows[49].row); expect(canonicalBatches).toEqual([1, 3]); expect( @@ -985,7 +997,11 @@ it('keeps security anchors and standalone activities while retaining supporting order: 'asc', offset: 0 }); - expect(page).toEqual({ rows: expected, summary: preparedActivitySummary([rows[index]]) }); + expect(page).toEqual({ + rows: expected, + summary: preparedActivitySummary([rows[index]]), + activityCount: expected.length + }); if (expected.length > 1) expect(page?.rows[0].row).toBe(page?.rows[1].row); } @@ -1156,6 +1172,7 @@ it('enforces account membership, access and saved posting summaries', async () = const options = { order: 'asc', offset: 0 } as const; expect(await readAccountInvestmentActivityCount(database, empty)).toBe(0); expect(await readAccountInvestmentActivityPage(database, empty, options)).toEqual({ + activityCount: 0, rows: [], summary: preparedActivitySummary() }); @@ -1169,6 +1186,14 @@ it('enforces account membership, access and saved posting summaries', async () = ); expect(await readAccountInvestmentActivityCount(database, unavailable)).toBeNull(); expect(await readAccountInvestmentActivityPage(database, unavailable, options)).toBeNull(); + await database + .updateTable('account_activity_summaries') + .set({ posting_row_count: 2 }) + .where('account_name', '=', account.name) + .execute(); + await expect(findRegisterFocusLocation(database, account, 'posting', 2, 'asc')).rejects.toThrow( + 'Invalid prepared register rows.' + ); const wrongAccount = { ...account, name: empty.name }; await expect(readAccountInvestmentActivityCount(database, wrongAccount)).rejects.toThrow(); await expect( @@ -1211,6 +1236,7 @@ it('rejects damaged selected Investment references and canonical entries', async const readPage = () => readAccountInvestmentActivityPage(database, account, { order: 'asc', offset: 0 }); expect(await readPage()).toEqual({ + activityCount: 1, rows: [ { row: rows[0], diff --git a/packages/db/src/reports/queries.ts b/packages/db/src/reports/queries.ts index 11e5276..cc765f3 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -15,8 +15,10 @@ import { type StoredReportData } from './data.js'; import { + findRegisterEntryLocation, readRegisterRowReferencePage, - type RegisterPageOptions + type RegisterPageOptions, + type RegisterRowKind } from './prepared-register-rows.js'; const insertBatchSize = 50; @@ -27,6 +29,7 @@ export interface AccountActivityPage { } export interface AccountInvestmentActivityPage { + activityCount: number; rows: { row: PreparedAccountRow; postingIndex: number; @@ -423,22 +426,42 @@ export async function readCashRegisterPage( return { rows, summary }; } -export async function findAccountEntryOrdinal( +export async function findRegisterFocusLocation( database: Kysely, account: StoredAccount, - nativeTransactionIndex: number -): Promise { + rowKind: RegisterRowKind, + nativeTransactionIndex: number, + order: RegisterPageOptions['order'] +) { const entry = await database .selectFrom('account_activity') .select('ordinal') .where('account_name', '=', account.name) .where('native_transaction_index', '=', nativeTransactionIndex) .executeTakeFirst(); - if (entry) return entry.ordinal; + if (entry) { + const location = await findRegisterEntryLocation( + database, + account.name, + rowKind, + entry.ordinal, + order + ); + if (!location) throw new Error('Missing or invalid prepared register rows.'); + return location; + } - // A miss skips the page reader, so check account readability here. + // A miss skips the page reader. Check the saved context and one page of references. const context = await readAccountPageContext(database, account); if (!context) throw new Error('Account activity is unavailable.'); + const savedRowCount = + rowKind === 'entry' + ? context.rowCount + : requireSavedInvestmentPostingCount(context.postingRowCount, context.rowCount); + await readRegisterRowReferencePage(database, account.name, rowKind, savedRowCount, { + order, + offset: 0 + }); return null; } @@ -534,5 +557,5 @@ export async function readAccountInvestmentActivityPage( selectedPostingKeys.add(postingKey); return activity; }); - return { rows, summary }; + return { rows, summary, activityCount }; } diff --git a/packages/snapshots/src/index.ts b/packages/snapshots/src/index.ts index 0d59808..2e0ffb6 100644 --- a/packages/snapshots/src/index.ts +++ b/packages/snapshots/src/index.ts @@ -7,6 +7,7 @@ export { readFocusedAccountPage, readInvestmentActivityCount, readInvestmentActivityPage, + readFocusedInvestmentActivityPage, readAccountTransaction } from './reports/publication.js'; export type { diff --git a/packages/snapshots/src/reports/publication.test.ts b/packages/snapshots/src/reports/publication.test.ts index 5ebe6c7..9fb4903 100644 --- a/packages/snapshots/src/reports/publication.test.ts +++ b/packages/snapshots/src/reports/publication.test.ts @@ -14,6 +14,7 @@ import { createReportStage, readAccountPage, readFocusedAccountPage, + readFocusedInvestmentActivityPage, readAccountTransaction, readInvestmentActivityPage, readInvestmentOverview, @@ -388,6 +389,80 @@ it('rejects focus when the saved entry has lost its prepared Cash row', async () expect(await readAccountTransaction(publication, id, 1)).toEqual(rows()[0]); }); +it('opens the page containing the first visible Investment posting in either sort order', async () => { + const stage = await createReportStage(snapshots, older); + const exports = accountTransactionExportsFixture(52).map(({ originalJson }, index) => { + if (index === 0) return { originalJson, transactedJson: originalJson }; + const newer = JSON.parse(originalJson); + newer.tpostings[0].pdate = '2026-05-03'; + const json = JSON.stringify(newer); + return { originalJson: json, transactedJson: json }; + }); + const target = JSON.parse(exports[0].originalJson); + const cash = { ...target.tpostings[0], pdate: '2026-03-31' }; + const security = { + ...cash, + pamount: cash.pamount.map((amount: object) => ({ ...amount, acommodity: 'STOCK' })) + }; + target.tdate = '2026-05-02'; + target.tpostings = [cash, { ...security, pdate: '2026-05-01' }, { ...security, pdate: null }]; + const targetJson = JSON.stringify(target); + exports[0] = { originalJson: targetJson, transactedJson: targetJson }; + const accountRows = preparedAccountRowsFromExports(exports); + const targetRow = accountRows[0]; + targetRow.accountPostingIndexes = [0, 1, 2]; + targetRow.investment.securities = [ + { + commodity: 'STOCK', + action: 'buy', + change: [{ commodity: 'STOCK', quantity: '2.00' }], + postingIndexes: [1, 2], + prices: [], + transactedAmounts: [] + } + ]; + for (const pair of exports) { + await stage.transactions.insertOriginal(pair.originalJson); + await stage.transactions.attachTransacted(pair.transactedJson); + } + await stage.writeRows('assets:cash', accountRows); + await stage.publish(fixture(), [ready('assets:cash', accountRows.length)], journal); + const publication = await selected(); + const id = publication.accounts[0].id; + + for (const [order, offset, pageNumber, indexOnPage, postingIndex, displayDate] of [ + ['asc', 0, 1, 0, 1, '2026-05-01'], + ['desc', 50, 2, 1, 2, '2026-05-02'] + ] as const) { + const page = await readFocusedInvestmentActivityPage(publication, id, 1, order); + const ordinary = await readInvestmentActivityPage(publication, id, { order, offset }); + expect(page).toEqual({ ...ordinary, pageNumber, indexOnPage }); + expect(page?.activityCount).toBe(53); + expect(page?.rows[indexOnPage]).toMatchObject({ postingIndex, displayDate }); + } + + const readMissingFocus = () => readFocusedInvestmentActivityPage(publication, id, 53, 'asc'); + const unreadable = safeError('Unable to read account activity'); + await expect(readMissingFocus()).resolves.toBeNull(); + withReportFile((database) => + database.exec('UPDATE account_activity_summaries SET posting_row_count = NULL') + ); + await expect(readMissingFocus()).rejects.toSatisfy(unreadable); + withReportFile((database) => + database.exec(` + UPDATE account_activity_summaries SET posting_row_count = 53; + DELETE FROM prepared_register_rows WHERE row_kind = 'posting' AND entry_ordinal = 0 AND posting_ordinal = 1; + `) + ); + const stillFull = await readInvestmentActivityPage(publication, id, { order: 'asc', offset: 0 }); + expect(stillFull?.rows).toHaveLength(50); + await expect(readFocusedInvestmentActivityPage(publication, id, 1, 'asc')).rejects.toSatisfy( + unreadable + ); + withReportFile((database) => database.exec('DROP TABLE prepared_register_rows')); + await expect(readMissingFocus()).rejects.toSatisfy(unreadable); +}); + it('stores only the intended overview fields and preserves absent history and null values', async () => { const investment: PreparedInvestmentOverview = { investmentAccountNames: ['assets:cash'], diff --git a/packages/snapshots/src/reports/publication.ts b/packages/snapshots/src/reports/publication.ts index 2587176..19ebbe6 100644 --- a/packages/snapshots/src/reports/publication.ts +++ b/packages/snapshots/src/reports/publication.ts @@ -19,8 +19,7 @@ import { isAccountCatalog, isAccountId, isAccountSummary, - findAccountEntryOrdinal, - findRegisterEntryLocation, + findRegisterFocusLocation, readCashRegisterPage, readAccountActivityDetail, readAccountInvestmentActivityCount, @@ -213,16 +212,14 @@ export async function readFocusedAccountPage( 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) => { - const entryOrdinal = await findAccountEntryOrdinal(database, account, nativeTransactionIndex); - if (entryOrdinal === null) return null; - const location = await findRegisterEntryLocation( + const location = await findRegisterFocusLocation( database, - account.name, + account, 'entry', - entryOrdinal, + nativeTransactionIndex, order ); - if (!location) throw new Error('Missing prepared Cash row.'); + if (!location) return null; const page = await readCashRegisterPage( database, @@ -273,6 +270,39 @@ export async function readInvestmentActivityPage( } } +export async function readFocusedInvestmentActivityPage( + publication: ReportPublication, + id: string, + nativeTransactionIndex: number, + order: RegisterPageOptions['order'] +): Promise<(AccountInvestmentActivityPage & { pageNumber: number; indexOnPage: number }) | null> { + 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) => { + const location = await findRegisterFocusLocation( + database, + account, + 'posting', + nativeTransactionIndex, + order + ); + if (!location) return null; + + const page = await readAccountInvestmentActivityPage(database, account, { + order: location.pageOrder, + offset: location.pageOffset + }); + const target = page?.rows[location.indexOnPage]; + if (!page || target?.row.transaction.index !== nativeTransactionIndex) + throw new Error('Invalid account posting data.'); + return { ...page, pageNumber: location.pageNumber, indexOnPage: location.indexOnPage }; + }); + } catch { + throw new Error('Unable to read account activity'); + } +} + export async function readAccountTransaction( publication: ReportPublication, id: string, -- 2.54.1 From 0a4eb62fa75eaf65f7ebf08439dbb6e1a7446dd4 Mon Sep 17 00:00:00 2001 From: eleith Date: Thu, 3 Dec 2026 11:49:59 -0800 Subject: [PATCH 16/19] test(web): separate register URL grammar from route reads --- .../registers/register-page-request.test.ts | 44 ++++++++++++++----- .../cash/[accountId]/page.server.test.ts | 15 ++----- 2 files changed, 36 insertions(+), 23 deletions(-) diff --git a/apps/web/src/lib/registers/register-page-request.test.ts b/apps/web/src/lib/registers/register-page-request.test.ts index e74e7e6..62bf37c 100644 --- a/apps/web/src/lib/registers/register-page-request.test.ts +++ b/apps/web/src/lib/registers/register-page-request.test.ts @@ -18,11 +18,19 @@ it('uses the caller’s default direction and preserves explicit date/page choic }); }); -it('rejects unsupported, repeated and invalid view parameters without echoing input', () => { +it('parses a focus link without selecting a page', () => { + expect(parseRegisterPageRequest(accountId, new URLSearchParams('focus=42'), 'desc')).toEqual({ + accountId, + order: 'desc', + page: null, + focusTransactionIndex: 42 + }); +}); + +it('rejects unsupported, repeated, conflicting and invalid view parameters', () => { for (const query of [ - 'source=PRIVATE', 'order=asc&order=desc', - 'order=PRIVATE', + 'order=sideways', 'page=1&page=2', 'page=0', 'page=01', @@ -30,16 +38,28 @@ it('rejects unsupported, repeated and invalid view parameters without echoing in 'page=+1', 'page=1e2', 'page=1.5', - 'page=9007199254740992' + 'page=9007199254740992', + 'focus=9007199254740992', + 'focus=1&focus=2', + 'focus=1&page=1' ]) { - expect(() => parseRegisterPageRequest(accountId, new URLSearchParams(query), 'asc')).toThrow( - expect.objectContaining({ status: 400 }) + expect( + () => parseRegisterPageRequest(accountId, new URLSearchParams(query), 'asc'), + query + ).toThrow(expect.objectContaining({ status: 400 })); + } +}); + +it('rejects an invalid account ID or an unknown query parameter without echoing input', () => { + for (const [id, query] of [ + ['../PRIVATE', ''], + [accountId, 'PRIVATE_KEY=PRIVATE_VALUE'] + ]) { + expect(() => parseRegisterPageRequest(id, new URLSearchParams(query), 'asc')).toThrow( + expect.objectContaining({ + status: 400, + body: expect.objectContaining({ message: expect.not.stringContaining('PRIVATE') }) + }) ); } - expect(() => parseRegisterPageRequest('../PRIVATE', new URLSearchParams(), 'asc')).toThrow( - expect.objectContaining({ - status: 400, - body: expect.objectContaining({ message: 'A valid account ID is required.' }) - }) - ); }); diff --git a/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts b/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts index 22769fa..8c1eb70 100644 --- a/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts +++ b/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts @@ -136,9 +136,8 @@ it('returns a safe read failure when a focused page is unreadable', async () => expect(JSON.stringify(unreadable)).not.toContain('PRIVATE'); }); -it('rejects malformed and conflicting focus URLs before reading a report', async () => { - for (const query of ['focus=9007199254740992', 'focus=1&focus=2', 'focus=1&page=1']) - await expect(load(event(query))).rejects.toMatchObject({ status: 400 }); +it('rejects a focus URL with a page number before reading a report', async () => { + await expect(load(event('focus=1&page=1'))).rejects.toMatchObject({ status: 400 }); expect(readReportPublication).not.toHaveBeenCalled(); expect(readFocusedAccountPage).not.toHaveBeenCalled(); }); @@ -255,14 +254,8 @@ it('rejects a wrong-kind member before reading its body', async () => { expect(readReportPublication).toHaveBeenCalledTimes(1); expect(readAccountPage).not.toHaveBeenCalled(); }); -it('rejects invalid page syntax before IO and out-of-range pages before body reads', async () => { - await expect(load(event('page=0'))).rejects.toMatchObject({ status: 400 }); - await expect(load(event('order=sideways'))).rejects.toMatchObject({ status: 400 }); - await expect(load(event('page=1&page=2'))).rejects.toMatchObject({ status: 400 }); - await expect(load(event('source=PRIVATE'))).rejects.toMatchObject({ status: 400 }); - expect(readReportPublication).not.toHaveBeenCalled(); +it('rejects an out-of-range page before reading activity', async () => { await expect(load(event('page=3'))).rejects.toMatchObject({ status: 404 }); - expect(readReportPublication).toHaveBeenCalledTimes(1); + expect(readReportPublication).toHaveBeenCalled(); expect(readAccountPage).not.toHaveBeenCalled(); - expect(projectActivityPage).not.toHaveBeenCalled(); }); -- 2.54.1 From 97a87970d94ccedb1ff8595d681b3c6a47ae5784 Mon Sep 17 00:00:00 2001 From: eleith Date: Thu, 3 Dec 2026 14:25:17 -0800 Subject: [PATCH 17/19] refactor(registers): carry the verified focus position --- .../registers/register-page-request.test.ts | 1 - .../lib/registers/register-page-request.ts | 18 +++++++++++---- .../src/lib/server/registers/cash/register.ts | 22 ++++++++----------- .../server/registers/investment/register.ts | 17 +++++++------- .../cash/[accountId]/page.server.test.ts | 7 +++++- .../snapshots/src/reports/publication.test.ts | 20 ++++++++++++----- packages/snapshots/src/reports/publication.ts | 9 +++++--- 7 files changed, 59 insertions(+), 35 deletions(-) diff --git a/apps/web/src/lib/registers/register-page-request.test.ts b/apps/web/src/lib/registers/register-page-request.test.ts index 62bf37c..cfc8da1 100644 --- a/apps/web/src/lib/registers/register-page-request.test.ts +++ b/apps/web/src/lib/registers/register-page-request.test.ts @@ -22,7 +22,6 @@ it('parses a focus link without selecting a page', () => { expect(parseRegisterPageRequest(accountId, new URLSearchParams('focus=42'), 'desc')).toEqual({ accountId, order: 'desc', - page: null, focusTransactionIndex: 42 }); }); diff --git a/apps/web/src/lib/registers/register-page-request.ts b/apps/web/src/lib/registers/register-page-request.ts index 350f599..ef7e4c8 100644 --- a/apps/web/src/lib/registers/register-page-request.ts +++ b/apps/web/src/lib/registers/register-page-request.ts @@ -1,13 +1,23 @@ import { error } from '@sveltejs/kit'; import { isAccountId, isDateOrder, isPositiveSafeInteger } from './request-validation.js'; -export interface RegisterPageRequest { +interface RegisterAccountOrder { accountId: string; order: 'asc' | 'desc'; - page: number | null; - focusTransactionIndex?: number; } +export type PagedRegisterRequest = RegisterAccountOrder & { + page: number | null; + focusTransactionIndex?: never; +}; + +type FocusedRegisterRequest = RegisterAccountOrder & { + page?: never; + focusTransactionIndex: number; +}; + +export type RegisterPageRequest = PagedRegisterRequest | FocusedRegisterRequest; + export function parseRegisterPageRequest( accountId: string, parameters: URLSearchParams, @@ -23,7 +33,7 @@ export function parseRegisterPageRequest( ); if (focusTransactionIndex !== null) { if (parameters.has('page')) error(400, 'Focus links cannot include a page number.'); - return { accountId, order, page: null, focusTransactionIndex }; + return { accountId, order, focusTransactionIndex }; } const page = parsePositiveIntegerParameter( parameters, diff --git a/apps/web/src/lib/server/registers/cash/register.ts b/apps/web/src/lib/server/registers/cash/register.ts index e9af4d3..495dc1f 100644 --- a/apps/web/src/lib/server/registers/cash/register.ts +++ b/apps/web/src/lib/server/registers/cash/register.ts @@ -83,8 +83,13 @@ async function readInitialActivity( account: ReadableAccount, request: RegisterPageRequest ): Promise { - const { order, focusTransactionIndex } = request; - const pagination = resolvePagination(account.rowCount, request); + const { order, page: requestedPage, focusTransactionIndex } = request; + const { rowCount } = account; + const pageCount = Math.max(1, Math.ceil(rowCount / rowBatchSize)); + if (requestedPage != null && requestedPage > pageCount) + error(404, 'Page not found in the prepared report.'); + const fallbackPage = requestedPage ?? (order === 'asc' ? pageCount : 1); + const pagination = { rowCount, page: fallbackPage, pageCount }; try { if (focusTransactionIndex === undefined) { const page = await readSavedActivityPage( @@ -102,26 +107,17 @@ async function readInitialActivity( ); if (focusedPage) { const activity = projectActivityPage(focusedPage); - const targetRow = activity.rows.find((row) => row.transactionIndex === focusTransactionIndex); - if (targetRow) targetRow.isFocusTarget = true; + activity.rows[focusedPage.indexOnPage].isFocusTarget = true; return { ...pagination, page: focusedPage.pageNumber, ...activity, readFailed: false }; } } catch { return { ...pagination, rows: [], endingBalance: null, readFailed: true }; } - error(404, { - message: 'Transaction not found in this saved register.', + error(404, 'Transaction not found in this saved register.', { code: 'REGISTER_FOCUS_NOT_FOUND' }); } -function resolvePagination(rowCount: number, { order, page }: RegisterPageRequest) { - const pageCount = Math.max(1, Math.ceil(rowCount / rowBatchSize)); - const selectedPage = page ?? (order === 'asc' ? pageCount : 1); - if (selectedPage > pageCount) error(404, 'Page not found in the prepared report.'); - return { rowCount, page: selectedPage, pageCount }; -} - function requireBatchPosition(batchStart: number, rowCount: number): void { const available = rowCount === 0 ? batchStart === 0 : batchStart < rowCount; if (!available) error(404, 'History position not found.'); diff --git a/apps/web/src/lib/server/registers/investment/register.ts b/apps/web/src/lib/server/registers/investment/register.ts index fef4784..c82ed83 100644 --- a/apps/web/src/lib/server/registers/investment/register.ts +++ b/apps/web/src/lib/server/registers/investment/register.ts @@ -12,7 +12,10 @@ import { type InvestmentAccountPageData, type InvestmentRegisterData } from '#lib/registers/investment/data.js'; -import type { RegisterPageRequest } from '#lib/registers/register-page-request.js'; +import type { + PagedRegisterRequest, + RegisterPageRequest +} from '#lib/registers/register-page-request.js'; import type { ReadableAccount } from '../prepared-account.js'; import { selectRegisterPageAccount, @@ -33,11 +36,10 @@ export async function loadRegisterPage( preparedAt: account.publication.overview.preparedAt }; if (account.access === 'ambiguous') return { ...metadata, readFailed: false, register: null }; - const { order, focusTransactionIndex } = request; const initialPage = - focusTransactionIndex === undefined + request.focusTransactionIndex === undefined ? await readInitialRegisterPage(account, request) - : await readFocusedRegisterPage(account, order, focusTransactionIndex); + : await readFocusedRegisterPage(account, request.order, request.focusTransactionIndex); return { ...metadata, ...initialPage }; } @@ -70,7 +72,7 @@ async function readSavedActivityCount(account: ReadableAccount): Promise } function selectInitialPage( - request: RegisterPageRequest, + request: PagedRegisterRequest, activityCount: number ): Pick { const pageCount = Math.max(1, Math.ceil(activityCount / activityBatchSize)); @@ -81,7 +83,7 @@ function selectInitialPage( async function readInitialRegisterPage( account: ReadableAccount, - request: RegisterPageRequest + request: PagedRegisterRequest ): Promise> { let activityCount: number; try { @@ -148,8 +150,7 @@ async function readFocusedRegisterPage( } catch { return { register: null, readFailed: true }; } - error(404, { - message: 'Transaction not found in this saved register.', + error(404, 'Transaction not found in this saved register.', { code: 'REGISTER_FOCUS_NOT_FOUND' }); } diff --git a/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts b/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts index 8c1eb70..ed100e0 100644 --- a/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts +++ b/apps/web/src/routes/(protected)/registers/cash/[accountId]/page.server.test.ts @@ -113,7 +113,12 @@ it('loads a member from one pinned publication and delegates its requested page' expect(request.setHeaders).toHaveBeenCalledWith({ 'cache-control': 'no-store' }); }); it('marks only the target on the saved Cash page in the requested order', async () => { - const focusedPage = { ...accountPage, rows: preparedAccountRows(2), pageNumber: 1 }; + const focusedPage = { + ...accountPage, + rows: preparedAccountRows(2), + pageNumber: 1, + indexOnPage: 1 + }; const [other, target] = focusedPage.rows.map((row) => row.transaction.index); const actual = await vi.importActual( '#lib/server/registers/cash/projection.js' diff --git a/packages/snapshots/src/reports/publication.test.ts b/packages/snapshots/src/reports/publication.test.ts index 9fb4903..6f20dc3 100644 --- a/packages/snapshots/src/reports/publication.test.ts +++ b/packages/snapshots/src/reports/publication.test.ts @@ -354,21 +354,31 @@ it('locates and reads the ordinary Cash page on the same checked connection', as expect(ordinaryPage?.rows).toEqual([targetRow, lastRow]); expect(ordinaryPage?.summary.hasMultipleCommodities).toBe(true); const newestFirst = await readFocusedAccountPage(pinned, id, target, 'desc'); - expect(newestFirst?.pageNumber).toBe(1); + expect(newestFirst).toMatchObject({ pageNumber: 1, indexOnPage: 1 }); expect(newestFirst?.rows.slice(0, 2)).toEqual([lastRow, targetRow]); + vi.spyOn(reports, 'findRegisterFocusLocation').mockResolvedValueOnce({ + pageOrder: 'desc', + pageOffset: 0, + pageNumber: 1, + indexOnPage: 0 + }); + await expect(readFocusedAccountPage(pinned, id, target, 'desc')).rejects.toSatisfy( + safeError('Unable to read account transactions') + ); + const readKey = reports.readPublicationRequest; const next = { ...fixture(), preparedAt: 'replacement during read' }; const stage = await createReportStage(snapshots, newer, pinned.accounts); - await importNativeExports(stage, 1, 'new rows'); - await stage.writeRows('assets:cash', rows(1, 'new rows')); + await importNativeExports(stage, originalRows.length, 'new rows'); + await stage.writeRows('assets:cash', rows(originalRows.length, 'new rows')); vi.spyOn(reports, 'readPublicationRequest').mockImplementationOnce(async (database) => { const key = await readKey(database); - await stage.publish(next, [ready()], journal); + await stage.publish(next, [ready('assets:cash', originalRows.length)], journal); return key; }); const focusedPage = await readFocusedAccountPage(pinned, id, target, 'asc'); - expect(focusedPage).toEqual({ ...ordinaryPage, pageNumber: 2 }); + expect(focusedPage).toEqual({ ...ordinaryPage, pageNumber: 2, indexOnPage: 0 }); expect(await readOverview(snapshots)).toEqual(next); await expect(readFocusedAccountPage(pinned, id, target, 'asc')).rejects.toSatisfy( safeError('Unable to read account transactions') diff --git a/packages/snapshots/src/reports/publication.ts b/packages/snapshots/src/reports/publication.ts index 19ebbe6..8e0d815 100644 --- a/packages/snapshots/src/reports/publication.ts +++ b/packages/snapshots/src/reports/publication.ts @@ -67,10 +67,13 @@ export interface ReportPublication extends StoredReportData { publicationKey: string; } -export interface FocusedAccountActivityPage extends AccountActivityPage { +interface RegisterFocusPosition { pageNumber: number; + indexOnPage: number; } +export type FocusedAccountActivityPage = AccountActivityPage & RegisterFocusPosition; + export interface ReportStage { transactions: PreparationTransactions; writeRows(name: string, rows: readonly PreparedAccountRow[]): Promise; @@ -230,7 +233,7 @@ export async function readFocusedAccountPage( const targetRow = page?.rows[location.indexOnPage]; if (!page || targetRow?.transaction.index !== nativeTransactionIndex) throw new Error('Invalid account data.'); - return { ...page, pageNumber: location.pageNumber }; + return { ...page, pageNumber: location.pageNumber, indexOnPage: location.indexOnPage }; }); } catch { throw new Error('Unable to read account transactions'); @@ -275,7 +278,7 @@ export async function readFocusedInvestmentActivityPage( id: string, nativeTransactionIndex: number, order: RegisterPageOptions['order'] -): Promise<(AccountInvestmentActivityPage & { pageNumber: number; indexOnPage: number }) | null> { +): Promise<(AccountInvestmentActivityPage & RegisterFocusPosition) | null> { try { const account = publication.accounts.find((entry) => entry.id === id); if (account?.access !== 'ready') throw new Error('Account activity is unavailable.'); -- 2.54.1 From 9535b8a514a2b9811fd8af3e09c610832b129c5c Mon Sep 17 00:00:00 2001 From: eleith Date: Thu, 3 Dec 2026 15:01:09 -0800 Subject: [PATCH 18/19] refactor(registers): share batch request validation --- apps/web/src/lib/registers/cash/README.md | 2 +- .../lib/registers/cash/RowBatchLoader.svelte | 4 +- apps/web/src/lib/registers/cash/data.ts | 6 -- .../src/lib/registers/cash/register.remote.ts | 8 +-- .../registers/cash/row-batch-request.test.ts | 24 -------- .../investment/ActivityBatchLoader.svelte | 4 +- .../investment/activity-batch-request.test.ts | 53 ----------------- .../investment/activity-batch-request.ts | 33 ----------- apps/web/src/lib/registers/investment/data.ts | 6 -- .../registers/investment/register.remote.ts | 7 +-- .../registers/register-batch-request.test.ts | 59 +++++++++++++++++++ ...h-request.ts => register-batch-request.ts} | 18 ++++-- .../lib/server/registers/batch-position.ts | 6 ++ .../server/registers/cash/register.test.ts | 2 +- .../src/lib/server/registers/cash/register.ts | 12 ++-- .../registers/investment/register.test.ts | 11 +++- .../server/registers/investment/register.ts | 15 +++-- 17 files changed, 111 insertions(+), 159 deletions(-) delete mode 100644 apps/web/src/lib/registers/cash/row-batch-request.test.ts delete mode 100644 apps/web/src/lib/registers/investment/activity-batch-request.test.ts delete mode 100644 apps/web/src/lib/registers/investment/activity-batch-request.ts create mode 100644 apps/web/src/lib/registers/register-batch-request.test.ts rename apps/web/src/lib/registers/{cash/row-batch-request.ts => register-batch-request.ts} (65%) create mode 100644 apps/web/src/lib/server/registers/batch-position.ts diff --git a/apps/web/src/lib/registers/cash/README.md b/apps/web/src/lib/registers/cash/README.md index e3c9d07..1704f95 100644 --- a/apps/web/src/lib/registers/cash/README.md +++ b/apps/web/src/lib/registers/cash/README.md @@ -35,7 +35,7 @@ The request and data names follow the same operations: ```text page parseRegisterPageRequest → loadRegisterPage -row query parseRowBatchRequest → getRowBatch → readRowBatch +row query getRowBatch → parseRegisterBatchRequest → readRowBatch details query parseTransactionDetailsRequest → getTransactionDetails → readTransactionDetails ``` diff --git a/apps/web/src/lib/registers/cash/RowBatchLoader.svelte b/apps/web/src/lib/registers/cash/RowBatchLoader.svelte index b1f3c0f..8d4aa11 100644 --- a/apps/web/src/lib/registers/cash/RowBatchLoader.svelte +++ b/apps/web/src/lib/registers/cash/RowBatchLoader.svelte @@ -1,6 +1,6 @@ + +{#if missingTransactionIndex !== undefined} +

Transaction {missingTransactionIndex} was not found in this saved register.

+{/if} + + diff --git a/apps/web/src/lib/registers/RegisterPageError.svelte b/apps/web/src/lib/registers/RegisterPageError.svelte deleted file mode 100644 index 52f0e6a..0000000 --- a/apps/web/src/lib/registers/RegisterPageError.svelte +++ /dev/null @@ -1,13 +0,0 @@ - - -
-

{page.status}

-

{page.error?.message}

- {#if page.error?.code === 'REGISTER_FOCUS_NOT_FOUND' && registerHref} -

Open register

- {/if} -
diff --git a/apps/web/src/lib/registers/cash/data.ts b/apps/web/src/lib/registers/cash/data.ts index 2cdb10c..4967a43 100644 --- a/apps/web/src/lib/registers/cash/data.ts +++ b/apps/web/src/lib/registers/cash/data.ts @@ -52,6 +52,7 @@ export interface TransactionDetails { export interface RegisterPageData { readFailed: boolean; + missingFocusTransactionIndex?: number; accountId: string; accountName: string; /** Ambiguous: hledger could not uniquely select this exact account, so no amounts are shown. */ diff --git a/apps/web/src/lib/registers/investment/data.ts b/apps/web/src/lib/registers/investment/data.ts index 0af8d02..e56fb0b 100644 --- a/apps/web/src/lib/registers/investment/data.ts +++ b/apps/web/src/lib/registers/investment/data.ts @@ -75,6 +75,7 @@ export interface InvestmentRegisterData { export interface InvestmentAccountPageData { readFailed: boolean; + missingFocusTransactionIndex?: number; preparedAt: string; accountName: string; access: 'ready' | 'ambiguous'; diff --git a/apps/web/src/lib/server/registers/cash/register.ts b/apps/web/src/lib/server/registers/cash/register.ts index a45cc4f..cb486d9 100644 --- a/apps/web/src/lib/server/registers/cash/register.ts +++ b/apps/web/src/lib/server/registers/cash/register.ts @@ -27,7 +27,13 @@ import { type RegisterActivity = Pick< RegisterPageData, - 'rowCount' | 'page' | 'pageCount' | 'rows' | 'endingBalance' | 'readFailed' + | 'rowCount' + | 'page' + | 'pageCount' + | 'rows' + | 'endingBalance' + | 'readFailed' + | 'missingFocusTransactionIndex' >; export async function loadRegisterPage( @@ -92,31 +98,27 @@ async function readInitialActivity( const fallbackPage = requestedPage ?? (order === 'asc' ? pageCount : 1); const pagination = { rowCount, page: fallbackPage, pageCount }; try { - if (focusTransactionIndex === undefined) { - const page = await readSavedActivityPage( - account, - order, - (pagination.page - 1) * rowBatchSize + if (focusTransactionIndex !== undefined) { + const focusedPage = await readFocusedAccountPage( + account.publication, + account.id, + focusTransactionIndex, + order ); - return { ...pagination, ...projectActivityPage(page), readFailed: false }; - } - const focusedPage = await readFocusedAccountPage( - account.publication, - account.id, - focusTransactionIndex, - order - ); - if (focusedPage) { - const activity = projectActivityPage(focusedPage); - activity.rows[focusedPage.indexOnPage].isFocusTarget = true; - return { ...pagination, page: focusedPage.pageNumber, ...activity, readFailed: false }; + if (focusedPage) { + const activity = projectActivityPage(focusedPage); + activity.rows[focusedPage.indexOnPage].isFocusTarget = true; + return { ...pagination, page: focusedPage.pageNumber, ...activity, readFailed: false }; + } } + const page = await readSavedActivityPage(account, order, (fallbackPage - 1) * rowBatchSize); + const activity = { ...pagination, ...projectActivityPage(page), readFailed: false }; + return focusTransactionIndex === undefined + ? activity + : { ...activity, missingFocusTransactionIndex: focusTransactionIndex }; } catch { return { ...pagination, rows: [], endingBalance: null, readFailed: true }; } - error(404, 'Transaction not found in this saved register.', { - code: 'REGISTER_FOCUS_NOT_FOUND' - }); } async function readSavedActivityPage( diff --git a/apps/web/src/lib/server/registers/investment/register.ts b/apps/web/src/lib/server/registers/investment/register.ts index 5729003..ba42f3b 100644 --- a/apps/web/src/lib/server/registers/investment/register.ts +++ b/apps/web/src/lib/server/registers/investment/register.ts @@ -12,10 +12,7 @@ import { type InvestmentRegisterData } from '#lib/registers/investment/data.js'; import type { RegisterBatchRequest } from '#lib/registers/register-batch-request.js'; -import type { - PagedRegisterRequest, - RegisterPageRequest -} from '#lib/registers/register-page-request.js'; +import type { RegisterPageRequest } from '#lib/registers/register-page-request.js'; import { requireRegisterBatchPosition } from '../batch-position.js'; import type { ReadableAccount } from '../prepared-account.js'; import { @@ -37,10 +34,14 @@ export async function loadRegisterPage( preparedAt: account.publication.overview.preparedAt }; if (account.access === 'ambiguous') return { ...metadata, readFailed: false, register: null }; - const initialPage = - request.focusTransactionIndex === undefined - ? await readInitialRegisterPage(account, request) - : await readFocusedRegisterPage(account, request.order, request.focusTransactionIndex); + const { order, focusTransactionIndex } = request; + if (focusTransactionIndex !== undefined) { + const focusResult = await readFocusedRegisterPage(account, order, focusTransactionIndex); + if (focusResult !== null) return { ...metadata, ...focusResult }; + } + const initialPage = await readInitialRegisterPage(account, order, request.page ?? null); + if (focusTransactionIndex !== undefined && !initialPage.readFailed) + return { ...metadata, ...initialPage, missingFocusTransactionIndex: focusTransactionIndex }; return { ...metadata, ...initialPage }; } @@ -74,19 +75,10 @@ async function readSavedActivityCount(account: ReadableAccount): Promise return activityCount; } -function selectInitialPage( - request: PagedRegisterRequest, - activityCount: number -): Pick { - const pageCount = Math.max(1, Math.ceil(activityCount / activityBatchSize)); - const page = request.page ?? (request.order === 'asc' ? pageCount : 1); - if (page > pageCount) error(404, 'Page not found in the prepared report.'); - return { page, pageCount }; -} - async function readInitialRegisterPage( account: ReadableAccount, - request: PagedRegisterRequest + order: InvestmentRegisterData['order'], + requestedPage: number | null ): Promise> { let activityCount: number; try { @@ -94,7 +86,9 @@ async function readInitialRegisterPage( } catch { return { register: null, readFailed: true }; } - const { page, pageCount } = selectInitialPage(request, activityCount); + const pageCount = Math.max(1, Math.ceil(activityCount / activityBatchSize)); + const page = requestedPage ?? (order === 'asc' ? pageCount : 1); + if (page > pageCount) error(404, 'Page not found in the prepared report.'); const register: InvestmentRegisterData = { accountId: account.id, accountName: account.name, @@ -102,17 +96,13 @@ async function readInitialRegisterPage( activityCount, page, pageCount, - order: request.order, + order, endingCash: [], unclassifiedEndingCash: [] }; if (activityCount === 0) return { register, readFailed: false }; try { - const saved = await readSavedActivityPage( - account, - request.order, - (page - 1) * activityBatchSize - ); + const saved = await readSavedActivityPage(account, order, (page - 1) * activityBatchSize); return { register: { ...register, ...projectInvestmentActivityPage(saved, account.name) }, readFailed: false @@ -126,7 +116,7 @@ async function readFocusedRegisterPage( account: ReadableAccount, order: InvestmentRegisterData['order'], transactionIndex: number -): Promise> { +): Promise | null> { try { const saved = await readFocusedInvestmentActivityPage( account.publication, @@ -153,9 +143,7 @@ async function readFocusedRegisterPage( } catch { return { register: null, readFailed: true }; } - error(404, 'Transaction not found in this saved register.', { - code: 'REGISTER_FOCUS_NOT_FOUND' - }); + return null; } async function readSavedActivityPage( diff --git a/apps/web/src/lib/styles/theme.css b/apps/web/src/lib/styles/theme.css index 963f5a3..0efeeed 100644 --- a/apps/web/src/lib/styles/theme.css +++ b/apps/web/src/lib/styles/theme.css @@ -6,6 +6,8 @@ --color-muted: #50615b; --color-accent: #225e4b; --color-negative: #b42318; + --color-error-background: #fee4e2; + --color-error-text: #912018; --color-border: #cbd4ce; --color-border-strong: var(--color-muted); --color-on-accent: #ffffff; @@ -51,6 +53,8 @@ --color-muted: #acbfb1; --color-accent: #8adbb4; --color-negative: #fda29b; + --color-error-background: #4b221f; + --color-error-text: #ffd4d1; --color-border: #3a5343; --color-on-accent: #0b1310; --color-chart-expense: #fdba74; diff --git a/apps/web/src/routes/(protected)/+layout.svelte b/apps/web/src/routes/(protected)/+layout.svelte index 1e73dfa..156f0c3 100644 --- a/apps/web/src/routes/(protected)/+layout.svelte +++ b/apps/web/src/routes/(protected)/+layout.svelte @@ -4,6 +4,7 @@ import { formatDate } from '#lib/dates.js'; import AccountSidebar from '#lib/navigation/AccountSidebar.svelte'; import AppHeader from '#lib/navigation/AppHeader.svelte'; + import SkipToContent from '#lib/navigation/SkipToContent.svelte'; import type { LayoutProps } from './$types'; let { children, data }: Pick = $props(); @@ -15,6 +16,7 @@ } +
- import { resolve } from '$app/paths'; - import { page } from '$app/state'; - import RegisterPageError from '#lib/registers/RegisterPageError.svelte'; - - - diff --git a/apps/web/src/routes/(protected)/registers/cash/[accountId]/+page.svelte b/apps/web/src/routes/(protected)/registers/cash/[accountId]/+page.svelte index 3f15b39..a905326 100644 --- a/apps/web/src/routes/(protected)/registers/cash/[accountId]/+page.svelte +++ b/apps/web/src/routes/(protected)/registers/cash/[accountId]/+page.svelte @@ -1,6 +1,7 @@ - - diff --git a/apps/web/src/routes/(protected)/registers/investments/[accountId]/+page.svelte b/apps/web/src/routes/(protected)/registers/investments/[accountId]/+page.svelte index 67cbaca..628f4bd 100644 --- a/apps/web/src/routes/(protected)/registers/investments/[accountId]/+page.svelte +++ b/apps/web/src/routes/(protected)/registers/investments/[accountId]/+page.svelte @@ -1,6 +1,7 @@ + + +{@render children()} diff --git a/apps/web/src/routes/+error.svelte b/apps/web/src/routes/+error.svelte new file mode 100644 index 0000000..af854e6 --- /dev/null +++ b/apps/web/src/routes/+error.svelte @@ -0,0 +1,29 @@ + + + + {page.status} — hledger reports + + +
+
+

{page.status}

+

{page.error?.message}

+
+
+ + diff --git a/apps/web/src/routes/+layout.svelte b/apps/web/src/routes/+layout.svelte index 559f1ed..a15c550 100644 --- a/apps/web/src/routes/+layout.svelte +++ b/apps/web/src/routes/+layout.svelte @@ -27,7 +27,6 @@
- {@render children()}
@@ -36,18 +35,4 @@ min-height: 100vh; min-height: 100dvh; } - - .skip-link { - position: absolute; - top: 0; - left: var(--space-small); - padding: var(--space-small); - transform: translateY(var(--skip-hidden-offset)); - background: var(--color-surface); - color: var(--color-accent); - } - - .skip-link:focus { - transform: translateY(0); - } -- 2.54.1