diff --git a/.changeset/focus-saved-register-row.md b/.changeset/focus-saved-register-row.md new file mode 100644 index 0000000..7018226 --- /dev/null +++ b/.changeset/focus-saved-register-row.md @@ -0,0 +1,5 @@ +--- +'@hledger-reports/web': patch +--- + +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, the register opens normally and shows a notice instead. Links may not find the same transaction after re-preparation. 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/apps/web/e2e/cash-register.e2e.ts b/apps/web/e2e/cash-register.e2e.ts index 5939284..963f503 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,11 @@ 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 and missing-target notices remain readable in HTML', 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 +32,37 @@ 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(200); + expect(missing?.request().redirectedFrom()).toBeNull(); + await expect(page.getByRole('main').getByRole('status')).toContainText( + /Transaction 9007199254740991\b.*was not found/ + ); + await expect(activity.locator('[data-column="date"] time').first()).toHaveAttribute( + 'datetime', + '2026-04-15' + ); + await expect(activity.locator('button[aria-current="true"]')).toHaveCount(0); + await expect( + activity.getByRole('link', { name: 'Date: newest first; show oldest first', exact: true }) + ).toHaveAttribute('href', '?order=asc'); + const skipLink = page.getByRole('link', { name: 'Skip to content', exact: true }); + await expect(skipLink).toHaveAttribute('href', '#main'); + + const malformed = await page.goto(`${accountURL}?focus=invalid`); + expect(malformed?.status()).toBe(400); + expect(malformed?.request().redirectedFrom()).toBeNull(); + const main = page.getByRole('main'); + await expect(main.getByText(/valid transaction index/i)).toBeVisible(); + await expect( + page.getByRole('navigation', { name: 'Primary', exact: true, includeHidden: true }) + ).toHaveCount(0); + await expect(skipLink).toHaveCount(0); }); }); @@ -147,12 +183,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/e2e/investment-register.e2e.ts b/apps/web/e2e/investment-register.e2e.ts index 3fada05..48d04ec 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,33 @@ 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"]'); + const notice = page.getByRole('main').getByRole('status'); + await expect(notice).toHaveCount(0); + 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&order=desc`); + expect(missing?.status()).toBe(200); + expect(missing?.request().redirectedFrom()).toBeNull(); + await expect(notice).toContainText(/Transaction 9007199254740991\b.*was not found/); + const firstDate = table.locator('td[data-column="date"] time').first(); + await expect(firstDate).toHaveAttribute('datetime', '2026-04-16'); + await expect(current).toHaveCount(0); + await table + .getByRole('link', { name: 'Date: newest first; show oldest first', exact: true }) + .click(); + await expect(page).toHaveURL(/\?order=asc$/); + await expect(firstDate).toHaveAttribute('datetime', '2026-04-04'); + await expect(notice).toHaveCount(0); }); }); diff --git a/apps/web/src/lib/navigation/SkipToContent.svelte b/apps/web/src/lib/navigation/SkipToContent.svelte new file mode 100644 index 0000000..8fce3a8 --- /dev/null +++ b/apps/web/src/lib/navigation/SkipToContent.svelte @@ -0,0 +1,17 @@ + + + diff --git a/apps/web/src/lib/registers/RegisterFocusNotice.svelte b/apps/web/src/lib/registers/RegisterFocusNotice.svelte new file mode 100644 index 0000000..bdc9bad --- /dev/null +++ b/apps/web/src/lib/registers/RegisterFocusNotice.svelte @@ -0,0 +1,23 @@ + + +{#if missingTransactionIndex !== undefined} +

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

+{/if} + + 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/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/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 @@ +
{ 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/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 @@ + + +{@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); - } 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/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/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); + 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 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/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/index.ts b/packages/db/src/reports/index.ts index 9dba059..4d2f5a5 100644 --- a/packages/db/src/reports/index.ts +++ b/packages/db/src/reports/index.ts @@ -17,15 +17,16 @@ export { readReportData, readPublicationRequest, readPublicationInvestmentJson, - readAccountActivityPage, + readCashRegisterPage, + findRegisterFocusLocation, readAccountActivityDetail, - countAccountInvestmentActivities, + readAccountInvestmentActivityCount, readAccountInvestmentActivityPage } from './queries.js'; -export type { - AccountActivityPage, - AccountActivityPageOptions, - AccountInvestmentActivityPage -} from './queries.js'; +export type { AccountActivityPage, AccountInvestmentActivityPage } from './queries.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/investment-posting-rows.ts b/packages/db/src/reports/investment-posting-rows.ts new file mode 100644 index 0000000..5ffa4c6 --- /dev/null +++ b/packages/db/src/reports/investment-posting-rows.ts @@ -0,0 +1,149 @@ +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)`; + +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 fromVisibleInvestmentPostings(accountName: string) { + return sql`${fromRawAccountPostingReferences(accountName)} + and ${isVisibleInvestmentActivity()}`; +} + +interface PostingReferenceCounts { + activity_count: number; + first_ordinal: number | null; + last_ordinal: number | null; + posting_count: number; + distinct_posting_count: number; + invalid_count: number | null; +} + +export async function validateRawAccountPostingReferences( + database: Kysely, + accountName: string, + expectedEntryCount: number +): Promise { + const counts = await readPostingReferenceCounts(database, accountName); + validatePostingReferenceCounts(counts, expectedEntryCount); +} + +async function readPostingReferenceCounts( + database: Kysely, + accountName: string +): 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, + 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()}`; +} + +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/prepared-register-rows.ts b/packages/db/src/reports/prepared-register-rows.ts new file mode 100644 index 0000000..92d83a9 --- /dev/null +++ b/packages/db/src/reports/prepared-register-rows.ts @@ -0,0 +1,131 @@ +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, + fromVisibleInvestmentPostings, + postingCountInEntry, + postingPositionInOriginalOrder, + validateRawAccountPostingReferences +} from './investment-posting-rows.js'; + +export interface RegisterPageOptions { + order: 'asc' | 'desc'; + offset: number; +} + +export type RegisterRowKind = ReportDatabase['prepared_register_rows']['row_kind']; + +export async function readRegisterRowReferencePage( + database: Kysely, + accountName: string, + rowKind: RegisterRowKind, + savedTotalRowCount: number, + { order, offset }: RegisterPageOptions +) { + const references = await database + .selectFrom('prepared_register_rows') + .where('account_name', '=', accountName) + .where('row_kind', '=', rowKind) + .select([ + 'display_date', + 'entry_ordinal as accountOrdinal', + 'posting_ordinal', + 'position_in_entry', + 'entry_row_count' + ]) + .orderBy('display_date', order) + .orderBy('entry_ordinal', 'asc') + .orderBy('position_in_entry', 'asc') + .offset(offset) + .limit(registerPageSize) + .execute(); + const expectedPageLength = Math.min(registerPageSize, Math.max(0, savedTotalRowCount - offset)); + if (references.length !== expectedPageLength) throw new Error('Invalid prepared register rows.'); + return references; +} + +export async function findRegisterEntryLocation( + database: Kysely, + accountName: string, + rowKind: RegisterRowKind, + 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`>`; + // 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, + 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 ( + 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 ${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); + 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( + database: ReportTransaction, + accountName: string, + expectedEntryCount: number +) { + await validateRawAccountPostingReferences(database, accountName, expectedEntryCount); + + 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); + + 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 + ) + select activity.account_name, 'posting', ${displayedPostingDate}, activity.ordinal, posting.posting_ordinal, + ${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 115ab22..bd807fe 100644 --- a/packages/db/src/reports/queries.test.ts +++ b/packages/db/src/reports/queries.test.ts @@ -11,9 +11,10 @@ import { type ReportDatabase } from '../index.js'; import { - readAccountActivityPage, + findRegisterFocusLocation, + readCashRegisterPage, readAccountActivityDetail, - countAccountInvestmentActivities, + readAccountInvestmentActivityCount, readAccountInvestmentActivityPage, readReportData, writeAccountRows, @@ -21,6 +22,12 @@ import { writeReportData as writePublicationData } from './queries.js'; import type { ReportTransaction } from '../database.js'; +import { validateRawAccountPostingReferences } from './investment-posting-rows.js'; +import { + findRegisterEntryLocation, + readRegisterRowReferencePage, + writeRegisterRowsAndPostingCount +} 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'; @@ -163,6 +170,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) @@ -174,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, limit: 50 } 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 ); @@ -245,6 +251,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) @@ -270,9 +278,8 @@ 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; - 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]); @@ -299,6 +306,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(); @@ -318,6 +326,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) @@ -335,42 +345,75 @@ 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 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)); expect(await readPage('desc', 50)).toEqual(rows.slice(50)); expect(await readPage('asc', 53)).toEqual([]); expect(Math.max(...resultRowCounts)).toBe(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 readAccountActivityPage(database, other, { order: 'asc', offset: 0, limit: 50 }) - ).toEqual({ rows: otherRows, summary: preparedActivitySummary(otherRows) }); + await findRegisterFocusLocation(database, account, 'entry', sharedOrdinalIndex, 'asc') + ).toEqual({ + pageOrder: 'asc', + pageOffset: 0, + pageNumber: 1, + indexOnPage: 27 + }); + 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, + indexOnPage: 1 + }); + + 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, 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 }) - ).rejects.toThrow(); + await expect(readCashRegisterPage(database, mismatchedAccount, 'asc', 0)).rejects.toThrow(); 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(); + await expect(readPage('asc', 50)).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, @@ -380,6 +423,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) @@ -391,15 +435,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 { @@ -409,15 +453,14 @@ 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) }); - await expect( - readAccountActivityPage(reader, account, { order: 'asc', offset: 1, limit: 1 }) - ).rejects.toThrow(); + expect(await readCashRegisterPage(reader, account, 'asc', 0)).toEqual({ + rows: rows.slice(0, 50), + summary: preparedActivitySummary(rows) + }); + await expect(readCashRegisterPage(reader, account, 'asc', 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); @@ -435,6 +478,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) @@ -442,10 +486,34 @@ 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) => readCashRegisterPage(reader, account, '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( @@ -453,24 +521,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 () => { @@ -478,31 +537,36 @@ 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 = () => readCashRegisterPage(database, account, 'asc', 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.'); + await expect(findRegisterFocusLocation(database, account, 'entry', 2, 'asc')).rejects.toThrow( + 'Missing account activity summary.' + ); }); it('does not create missing storage or replace an existing report file', async () => { @@ -548,7 +612,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: [ @@ -595,6 +660,7 @@ it('pages original selected-account postings across a shared security group and transaction, new Map([[account.name, preparedActivitySummary(rows)]]) ); + await writeRegisterRowsAndPostingCount(transaction, account.name, rows.length); await transaction.commit().execute(); } finally { if (!transaction.isCommitted && !transaction.isRolledBack) @@ -617,33 +683,51 @@ it('pages original selected-account postings across a shared security group and const reference = (ordinal: number, postingIndex: number) => ({ row: rows[ordinal], postingIndex, + 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)]; - expect(await countAccountInvestmentActivities(reader, account)).toBe(59); + 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 ordinal 2 starts at its second original posting, after both postings of ordinal 1. + expect( + (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', - 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 }); + 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( ( await readAccountInvestmentActivityPage(reader, account, { order: 'asc', - offset: 0, - limit: 50 + offset: 0 }) )?.rows ).toEqual(ascending.slice(0, 50)); @@ -651,8 +735,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)); @@ -660,13 +743,176 @@ 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 () => { + const database = await createDatabase(); + 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 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(writeRegisterRowsAndPostingCount(transaction, account.name, 1)).rejects.toThrow( + 'Invalid account posting data.' + ); + const { rows: partialRows } = await sql`select 1 from prepared_register_rows`.execute( + transaction + ); + expect(partialRows).toEqual([]); + + await transaction + .deleteFrom('account_activity') + .where('account_name', '=', account.name) + .execute(); + await writeAccountRows(transaction, account.name, 0, [row]); + await writeRegisterRowsAndPostingCount(transaction, account.name, 1); + 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 + } + ]); + + 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(); + await expect(readAccountInvestmentActivityCount(database, otherAccount)).rejects.toThrow( + 'Invalid prepared posting count.' + ); + + const entryPage = { order: 'asc', offset: 0 } as const; + 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', 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)).rejects.toThrow( + 'Invalid account data.' + ); }); it('keeps security anchors and standalone activities while retaining supporting cash only as context', async () => { @@ -732,6 +978,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) @@ -741,40 +989,33 @@ 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 })); - expect(await countAccountInvestmentActivities(database, account)).toBe(expected.length); const page = await readAccountInvestmentActivityPage(database, account, { order: 'asc', - offset: 0, - limit: 50 + offset: 0 + }); + expect(page).toEqual({ + rows: expected, + summary: preparedActivitySummary([rows[index]]), + activityCount: expected.length }); - 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') @@ -782,7 +1023,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') @@ -795,14 +1036,9 @@ 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', - offset: 50, - limit: 1 - }) - ).rejects.toThrow(); + validateRawAccountPostingReferences(database, accounts[0].name, 1) + ).rejects.toThrow('Invalid account posting data.'); } }); @@ -870,6 +1106,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) @@ -878,25 +1115,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 })); - 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) { - 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', @@ -909,7 +1139,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) }; @@ -932,38 +1162,54 @@ 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); + 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() }); - expect(await countAccountInvestmentActivities(database, unavailable)).toBeNull(); + 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(); + 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(countAccountInvestmentActivities(database, wrongAccount)).rejects.toThrow(); + await expect(readAccountInvestmentActivityCount(database, wrongAccount)).rejects.toThrow(); 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 database .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(); }); -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(); @@ -981,40 +1227,48 @@ 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(countAccountInvestmentActivities(database, account)).rejects.toThrow(); - 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({ + activityCount: 1, + 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(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(); + + 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 09e1b2d..cc765f3 100644 --- a/packages/db/src/reports/queries.ts +++ b/packages/db/src/reports/queries.ts @@ -14,9 +14,14 @@ import { type StoredAccount, type StoredReportData } from './data.js'; +import { + findRegisterEntryLocation, + readRegisterRowReferencePage, + type RegisterPageOptions, + type RegisterRowKind +} from './prepared-register-rows.js'; const insertBatchSize = 50; -const maxPageRows = 50; export interface AccountActivityPage { rows: PreparedAccountRow[]; @@ -24,21 +29,17 @@ export interface AccountActivityPage { } export interface AccountInvestmentActivityPage { + activityCount: number; rows: { row: PreparedAccountRow; postingIndex: number; + displayDate: string; entryActivityPosition: number; entryActivityCount: number; }[]; summary: AccountActivitySummary; } -export interface AccountActivityPageOptions { - order: 'asc' | 'desc'; - offset: number; - limit: number; -} - type StoredActivityRow = Pick< ReportDatabase['account_activity'], 'ordinal' | 'account_date' | 'native_transaction_index' | 'context_json' @@ -135,6 +136,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), @@ -334,22 +336,14 @@ 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 > maxPageRows - ) - throw new Error('Invalid account page.'); -} - 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') @@ -376,221 +370,192 @@ 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) + }; } -export async function readAccountActivityPage( +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 readCashRegisterPage( database: Kysely, account: StoredAccount, - options: AccountActivityPageOptions + pageOrder: RegisterPageOptions['order'], + pageOffset: number ): Promise { - assertPageOptions(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, + { order: pageOrder, offset: pageOffset } + ); + 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 }; } -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( +export async function findRegisterFocusLocation( 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 - ${accountPostingReferences(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; + 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) { + 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. 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; } -export async function countAccountInvestmentActivities( +function requireSavedInvestmentPostingCount( + visiblePostingCount: number | null, + entryCount: number +): 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( database: Kysely, account: StoredAccount ): Promise { const context = await readAccountPageContext(database, account); - return context - ? countStoredAccountInvestmentActivities(database, account, context.rowCount) - : null; + if (!context) return null; + 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); const context = await readAccountPageContext(database, account); if (!context) return null; - const { rowCount, summary } = context; - const activityCount = await countStoredAccountInvestmentActivities(database, account, rowCount); - const { order, offset, limit } = options; - const { rows: references } = await sql<{ - ordinal: number; - posting_index: number; - entry_activity_position: number; - 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 - ${accountPostingReferences(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 - limit ${limit} offset ${offset} - `.execute(database); - if (references.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( - ({ - ordinal, - posting_index: postingIndex, - entry_activity_position: entryActivityPosition, - entry_activity_count: entryActivityCount - }) => { - const row = parents.get(ordinal); - 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 { rowCount: entryCount, postingRowCount, summary } = context; + const activityCount = requireSavedInvestmentPostingCount(postingRowCount, entryCount); + const orderedReferences = await readRegisterRowReferencePage( + database, + account.name, + 'posting', + activityCount, + options ); - return { rows, summary }; + const entriesByAccountOrdinal = await readAccountEntriesByOrdinal( + database, + account.name, + entryCount, + orderedReferences.map(({ accountOrdinal }) => accountOrdinal) + ); + 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, activityCount }; } diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 3a2e630..a691d42 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,8 +26,19 @@ 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; + posting_row_count: number | null; has_multiple_amounts: 0 | 1; has_multiple_commodities: 0 | 1; ending_balance_json: string; @@ -55,6 +66,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/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/index.ts b/packages/snapshots/src/index.ts index 7504ac3..2e0ffb6 100644 --- a/packages/snapshots/src/index.ts +++ b/packages/snapshots/src/index.ts @@ -4,16 +4,21 @@ export { readReportPublication, readInvestmentOverview, readAccountPage, - countInvestmentActivities, + readFocusedAccountPage, + readInvestmentActivityCount, readInvestmentActivityPage, + readFocusedInvestmentActivityPage, 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, - AccountActivityPageOptions, AccountInvestmentActivityPage } from '@hledger-reports/db/reports'; export { 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'; diff --git a/packages/snapshots/src/reports/publication.test.ts b/packages/snapshots/src/reports/publication.test.ts index b4fd9f9..6f20dc3 100644 --- a/packages/snapshots/src/reports/publication.test.ts +++ b/packages/snapshots/src/reports/publication.test.ts @@ -10,9 +10,11 @@ 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, + readFocusedAccountPage, + readFocusedInvestmentActivityPage, readAccountTransaction, readInvestmentActivityPage, readInvestmentOverview, @@ -24,6 +26,7 @@ import { ambiguous, accountTransactionExportsFixture, preparedOverview as fixture, + preparedAccountRowsFromExports, journal, ready, preparedAccountRows as rows @@ -157,6 +160,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 +175,47 @@ 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 } + ]); + 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(); + } 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()); @@ -177,13 +224,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)); @@ -208,6 +253,55 @@ 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 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); + 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); +}); + it('does not mix two publications from different attempts of the same request', async () => { vi.spyOn(crypto, 'randomUUID') .mockReturnValueOnce('00000000-0000-4000-8000-000000000000') @@ -220,7 +314,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(); @@ -230,7 +324,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)).rejects.toSatisfy( @@ -241,26 +335,142 @@ 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); + const newestFirst = await readFocusedAccountPage(pinned, id, target, 'desc'); + 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 page = await readAccountPage(pinned, pinned.accounts[0].id, { - order: 'asc', - offset: 0, - limit: 50 - }); - expect(page?.rows).toEqual(rows()); + const focusedPage = await readFocusedAccountPage(pinned, id, target, 'asc'); + 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') + ); +}); + +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('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 () => { @@ -360,8 +570,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()); @@ -489,12 +698,24 @@ 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, { order: 'asc', - offset: 0, - limit: 50 + offset: 0 }); expect(page).toEqual( account.access === 'ready' @@ -523,27 +744,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 }); + expect(page?.rows.map(({ transaction }) => transaction.index)).toEqual([nativeIndex]); } }); @@ -770,7 +996,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 { @@ -821,10 +1047,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') @@ -835,11 +1061,11 @@ 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( - 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(); }); @@ -926,16 +1152,30 @@ 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; + ALTER TABLE account_activity_summaries DROP COLUMN posting_row_count; + 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 () => { @@ -973,8 +1213,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 58b8793..8e0d815 100644 --- a/packages/snapshots/src/reports/publication.ts +++ b/packages/snapshots/src/reports/publication.ts @@ -19,9 +19,10 @@ import { isAccountCatalog, isAccountId, isAccountSummary, - readAccountActivityPage, + findRegisterFocusLocation, + readCashRegisterPage, readAccountActivityDetail, - countAccountInvestmentActivities, + readAccountInvestmentActivityCount, readAccountInvestmentActivityPage, readReportData, readPublicationRequest, @@ -31,10 +32,11 @@ import { writeAccountRows, writeAccountActivitySummaries, writeReportData, + writeRegisterRowsAndPostingCount, type AccountActivitySummary, type AccountActivityPage, - type AccountActivityPageOptions, type AccountInvestmentActivityPage, + type RegisterPageOptions, type StoredAccount, type StoredReportData } from '@hledger-reports/db/reports'; @@ -65,6 +67,13 @@ export interface ReportPublication extends StoredReportData { publicationKey: string; } +interface RegisterFocusPosition { + pageNumber: number; + indexOnPage: number; +} + +export type FocusedAccountActivityPage = AccountActivityPage & RegisterFocusPosition; + export interface ReportStage { transactions: PreparationTransactions; writeRows(name: string, rows: readonly PreparedAccountRow[]): Promise; @@ -182,21 +191,56 @@ async function readFromSelectedPublication( export async function readAccountPage( publication: ReportPublication, id: string, - options: AccountActivityPageOptions + options: RegisterPageOptions ): Promise { try { if (!isAccountId(id)) throw new Error(); const account = publication.accounts.find((entry) => entry.id === id); if (!account) throw new Error(); return await readFromSelectedPublication(publication, (database) => - readAccountActivityPage(database, account, options) + readCashRegisterPage(database, account, options.order, options.offset) ); } catch { throw new Error('Unable to read account transactions'); } } -export async function countInvestmentActivities( +export async function readFocusedAccountPage( + publication: ReportPublication, + id: string, + nativeTransactionIndex: number, + order: RegisterPageOptions['order'] +): Promise { + 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, + 'entry', + nativeTransactionIndex, + order + ); + if (!location) return null; + + 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, indexOnPage: location.indexOnPage }; + }); + } catch { + throw new Error('Unable to read account transactions'); + } +} + +export async function readInvestmentActivityCount( publication: ReportPublication, id: string ): Promise { @@ -205,7 +249,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'); @@ -215,7 +259,7 @@ export async function countInvestmentActivities( export async function readInvestmentActivityPage( publication: ReportPublication, id: string, - options: AccountActivityPageOptions + options: RegisterPageOptions ): Promise { try { if (!isAccountId(id)) throw new Error(); @@ -229,6 +273,39 @@ export async function readInvestmentActivityPage( } } +export async function readFocusedInvestmentActivityPage( + publication: ReportPublication, + id: string, + nativeTransactionIndex: number, + order: RegisterPageOptions['order'] +): 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.'); + 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, @@ -316,6 +393,13 @@ export async function createReportStage( { id: string; rowCount: number; summaryBuilder: AccountActivitySummaryBuilder } >(); let currentName: string | undefined; + + async function writePreparedRegisterRows(catalog: readonly StoredAccount[]) { + for (const { name, rowCount: entryCount } of catalog) { + if (entryCount !== null) await writeRegisterRowsAndPostingCount(writer, name, entryCount); + } + } + async function operation(action: () => Promise): Promise { try { if (state !== 'active') throw new Error(); @@ -433,6 +517,7 @@ export async function createReportStage( } ); await writeAccountActivitySummaries(writer, activitySummaries); + await writePreparedRegisterRows(catalog); await writer.commit().execute(); await closeDatabase(); const outcome = await replaceSavedReportIfNewer(