Focus a saved register row #83

Merged
eleith merged 19 commits from feat/focus-register-row into main 2026-12-04 13:58:00 +00:00
67 changed files with 2146 additions and 952 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
'@hledger-reports/web': patch
---
Use `?focus=<entry index>` 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.
+5
View File
@@ -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.
+57 -5
View File
@@ -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<string> {
const href = await page
.getByRole('complementary', { name: 'Accounts', exact: true, includeHidden: true })
@@ -13,10 +17,11 @@ async function checkingAccountHref(page: Page): Promise<string> {
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');
});
+55 -1
View File
@@ -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);
});
});
@@ -0,0 +1,17 @@
<a class="skip-link" href="#main">Skip to content</a>
<style>
.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);
}
</style>
@@ -0,0 +1,23 @@
<script lang="ts">
let { missingTransactionIndex }: { missingTransactionIndex?: number } = $props();
</script>
{#if missingTransactionIndex !== undefined}
<p role="status">Transaction {missingTransactionIndex} was not found in this saved register.</p>
{/if}
<style>
p {
align-self: center;
flex-shrink: 0;
max-inline-size: min(var(--content-width), calc(100% - 2 * var(--space-medium)));
margin: 0;
padding: var(--space-tight) var(--space-small);
border: var(--border-width) solid var(--color-error-background);
border-radius: var(--radius-control);
background: var(--color-error-background);
color: var(--color-error-text);
text-align: center;
overflow-wrap: anywhere;
}
</style>
+1 -1
View File
@@ -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
```
@@ -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;
@@ -1,6 +1,6 @@
<script lang="ts">
import { untrack } from 'svelte';
import type { RowBatchRequest } from './data.js';
import type { RegisterBatchRequest } from '../register-batch-request.js';
import type { RowBatchResult } from './batches.js';
import { getRowBatch } from './register.remote.js';
@@ -10,7 +10,7 @@
reserveRetrySlot,
canRetry
}: {
request: RowBatchRequest;
request: RegisterBatchRequest;
onResult: (result: RowBatchResult) => void;
reserveRetrySlot: (batchStart: number) => boolean;
canRetry: boolean;
+3 -13
View File
@@ -10,21 +10,10 @@ export interface RegisterRow {
statuses: string[];
change: ReportedAmount[];
balance: ReportedAmount[];
isFocusTarget?: true;
}
export const rowBatchSize = 50;
export interface RegisterPageRequest {
accountId: string;
order: RegisterPageData['order'];
page: number | null;
}
export interface RowBatchRequest {
accountId: string;
order: RegisterPageData['order'];
batchStart: number;
}
export { registerPageSize as rowBatchSize } from '@hledger-reports/snapshots/register-page';
export interface RowBatch {
batchStart: number;
@@ -63,6 +52,7 @@ export interface TransactionDetails {
export interface RegisterPageData {
readFailed: boolean;
missingFocusTransactionIndex?: number;
accountId: string;
accountName: string;
/** Ambiguous: hledger could not uniquely select this exact account, so no amounts are shown. */
@@ -1,42 +0,0 @@
import { error } from '@sveltejs/kit';
import type { RegisterPageRequest } from './data.js';
import { isAccountId, isDateOrder, isPositiveSafeInteger } from './request-validation.js';
export function parseRegisterPageRequest(
accountId: string,
parameters: URLSearchParams
): RegisterPageRequest {
if (!isAccountId(accountId)) error(400, 'A valid account ID is required.');
requireSupportedParameters(parameters);
const order = parseOrder(parameters);
const page = parsePage(parameters);
return { accountId, order, page };
}
function requireSupportedParameters(parameters: URLSearchParams): void {
for (const key of parameters.keys()) {
if (key !== 'order' && key !== 'page') error(400, 'Unsupported register parameter.');
}
}
function parseOrder(parameters: URLSearchParams): RegisterPageRequest['order'] {
const orders = parameters.getAll('order');
const order = orders[0] ?? 'desc';
if (orders.length > 1 || !isDateOrder(order)) error(400, 'A valid date order is required.');
return order;
}
function parsePage(parameters: URLSearchParams): RegisterPageRequest['page'] {
const pages = parameters.getAll('page');
if (pages.length > 1) error(400, 'A valid page number is required.');
const pageText = pages[0];
if (pageText === undefined) return null;
if (!isPageNumberText(pageText)) error(400, 'A valid page number is required.');
const page = Number(pageText);
if (!isPositiveSafeInteger(page)) error(400, 'A valid page number is required.');
return page;
}
function isPageNumberText(value: string): boolean {
return /^[1-9]/.test(value) && !/[^0-9]/.test(value);
}
@@ -1,7 +1,7 @@
import { getRequestEvent, query } from '$app/server';
import type { TransactionDetailsRequest, RowBatchRequest } from './data.js';
import { parseRegisterBatchRequest, type RegisterBatchRequest } from '../register-batch-request.js';
import type { TransactionDetailsRequest } from './data.js';
import { parseTransactionDetailsRequest } from './transaction-details-request.js';
import { parseRowBatchRequest } from './row-batch-request.js';
import { readRowBatch, readTransactionDetails } from '#lib/server/registers/cash/register.js';
export const getTransactionDetails = query(
@@ -13,7 +13,7 @@ export const getTransactionDetails = query(
}
);
export const getRowBatch = query('unchecked', async (input: RowBatchRequest) => {
const request = parseRowBatchRequest(input);
export const getRowBatch = query('unchecked', async (input: RegisterBatchRequest) => {
const request = parseRegisterBatchRequest(input);
return readRowBatch(getRequestEvent().locals, request);
});
@@ -1,23 +0,0 @@
import { expect, it } from 'vitest';
import { parseRowBatchRequest } from './row-batch-request.js';
it('accepts an account/date row batch at an aligned boundary', () => {
const request = { accountId: 'abcd1234', order: 'desc', batchStart: 150 };
expect(parseRowBatchRequest(request)).toEqual(request);
});
it.each([
null,
{ accountId: '../PRIVATE', order: 'desc', batchStart: 0 },
{ accountId: 'abcd1234', order: 'desc', batchStart: 1 },
{ accountId: 'abcd1234', order: 'desc', batchStart: Number.MAX_SAFE_INTEGER + 1 },
{ accountId: 'abcd1234', order: 'desc', batchStart: 0, limit: 1000000 }
])('rejects malformed row batch inputs before reads: %j', (input) => {
try {
parseRowBatchRequest(input);
expect.unreachable();
} catch (error) {
expect(error).toMatchObject({ status: 400 });
expect(JSON.stringify(error)).not.toContain('PRIVATE');
}
});
@@ -1,33 +0,0 @@
import { error } from '@sveltejs/kit';
import { rowBatchSize, type RowBatchRequest } from './data.js';
import { isAccountId, isDateOrder } from './request-validation.js';
export function parseRowBatchRequest(input: unknown): RowBatchRequest {
if (!hasRowBatchRequestShape(input)) error(400, 'A valid row batch is required.');
const { accountId, order, batchStart } = input;
if (!isAccountId(accountId)) error(400, 'A valid account ID is required.');
if (!isDateOrder(order)) error(400, 'A valid date order is required.');
if (!isBatchStart(batchStart)) error(400, 'A valid history position is required.');
return { accountId, order, batchStart };
}
function hasRowBatchRequestShape(
input: unknown
): input is { accountId: unknown; order: unknown; batchStart: unknown } {
if (input === null || typeof input !== 'object' || Array.isArray(input)) return false;
const prototype = Object.getPrototypeOf(input);
if (prototype !== Object.prototype && prototype !== null) return false;
return (
Reflect.ownKeys(input).length === 3 &&
['accountId', 'order', 'batchStart'].every((key) => Object.hasOwn(input, key))
);
}
function isBatchStart(value: unknown): value is number {
return (
typeof value === 'number' &&
Number.isSafeInteger(value) &&
value >= 0 &&
value % rowBatchSize === 0
);
}
@@ -23,6 +23,7 @@
<div
class="cash-value"
class:striped={rowPosition % 2 === 1}
class:focused-row-cell={row?.isFocusTarget}
class:money={isMoneyColumn(column)}
data-row-position={rowPosition}
data-column={column}
@@ -49,6 +50,7 @@
data-cash-details
disabled={!onOpenTransaction}
aria-haspopup="dialog"
aria-current={row.isFocusTarget}
aria-label={`View transaction details: ${row.payee || 'Transaction'} on ${row.date}`}
onclick={(event) => onOpenTransaction?.(rowPosition, event.currentTarget)}
>{row.payee || 'Transaction'}</button
@@ -46,6 +46,14 @@
border-bottom: 0;
background: transparent;
}
.cash-register .cash-table tr:has(.focused-row-cell),
.cash-register [role='row'] .focused-row-cell {
background: color-mix(in srgb, var(--color-accent) 12%, var(--color-surface));
}
.cash-register .cash-table td[data-column='date']:has(.focused-row-cell),
.cash-register [role='row'] .focused-row-cell[data-column='date'] {
box-shadow: inset 3px 0 var(--color-accent);
}
.cash-register [role='row']:hover .cash-value:not(.cash-heading),
.cash-register [role='row']:focus-within .cash-value:not(.cash-heading) {
background: color-mix(in srgb, var(--color-accent) 20%, var(--color-surface));
@@ -1,6 +1,6 @@
import { error } from '@sveltejs/kit';
import type { TransactionDetailsRequest } from './data.js';
import { isAccountId, isPositiveSafeInteger } from './request-validation.js';
import { isAccountId, isPositiveSafeInteger } from '../request-validation.js';
export function parseTransactionDetailsRequest(input: unknown): TransactionDetailsRequest {
if (!hasTransactionDetailsRequestShape(input)) {
@@ -1,6 +1,6 @@
<script lang="ts">
import { untrack } from 'svelte';
import type { ActivityBatchRequest } from './data.js';
import type { RegisterBatchRequest } from '../register-batch-request.js';
import type { ActivityBatchResult } from './activity-batches.js';
import { prepareBatchTableRows } from './activity-table-rows.js';
import { getActivityBatch } from './register.remote.js';
@@ -11,7 +11,7 @@
reserveRetrySlot,
canRetry
}: {
request: ActivityBatchRequest;
request: RegisterBatchRequest;
onResult: (result: ActivityBatchResult) => void;
reserveRetrySlot: (batchStart: number) => boolean;
canRetry: boolean;
@@ -42,9 +42,11 @@
let tableFocusTarget = $state<HTMLElement | null>(null);
let virtualTable = $state<{ scrollToRow: (rowPosition: number) => void }>();
let selectedActivity = $state.raw<InvestmentActivity | null>(null);
const orderHref = $derived(
`?${new URLSearchParams({ order: data.order === 'asc' ? 'desc' : 'asc' })}`
);
const orderHref = $derived.by(() => {
const order = data.order === 'asc' ? 'desc' : 'asc';
const focusedActivity = data.activities.find((activity) => activity.isFocusTarget);
return `?${new URLSearchParams(focusedActivity ? { order, focus: String(focusedActivity.transactionIndex) } : { order })}`;
});
let neededBatchStarts = $derived(
requiredRemoteBatchStarts(
@@ -1,53 +0,0 @@
import { expect, it } from 'vitest';
import { parseActivityBatchRequest } from './activity-batch-request.js';
const request = { accountId: 'abcd1234', order: 'desc', batchStart: 150 };
it('accepts only the bounded investment request, including a null-prototype object', () => {
expect(parseActivityBatchRequest(request)).toEqual(request);
expect(parseActivityBatchRequest(Object.assign(Object.create(null), request))).toEqual(request);
expect(parseActivityBatchRequest({ ...request, order: 'asc', batchStart: 0 })).toEqual({
...request,
order: 'asc',
batchStart: 0
});
});
it('rejects non-records, missing or extra keys, inherited fields and symbol keys', () => {
for (const input of [
null,
[],
new Date(),
Object.create(request),
{ accountId: request.accountId, order: request.order },
{ ...request, limit: 1000000 },
{ ...request, [Symbol('PRIVATE')]: true }
]) {
expect(() => parseActivityBatchRequest(input)).toThrow(
expect.objectContaining({
status: 400,
body: expect.objectContaining({ message: 'A valid activity batch is required.' })
})
);
}
});
it('rejects invalid native IDs, orders and unsafe or unaligned positions with safe errors', () => {
for (const input of [
{ ...request, accountId: '../PRIVATE' },
{ ...request, accountId: 'abcd1234\n' },
{ ...request, order: 'PRIVATE' },
...[1, -50, 1.5, NaN, Infinity, Number.MAX_SAFE_INTEGER + 1, '50'].map((batchStart) => ({
...request,
batchStart
}))
]) {
try {
parseActivityBatchRequest(input);
expect.unreachable();
} catch (error) {
expect(error).toMatchObject({ status: 400 });
expect(JSON.stringify(error)).not.toContain('PRIVATE');
}
}
});
@@ -5,13 +5,7 @@ import type {
ReportedAmount
} from '@hledger-reports/hledger';
export const activityBatchSize = 50;
export interface ActivityBatchRequest {
accountId: string;
order: InvestmentRegisterData['order'];
batchStart: number;
}
export { registerPageSize as activityBatchSize } from '@hledger-reports/snapshots/register-page';
export interface ActivityBatch {
batchStart: number;
@@ -64,6 +58,7 @@ export interface InvestmentActivity {
/** Native selected-account balance after the whole entry, only on its final activity. */
cashBalance: { amounts: ReportedAmount[]; unclassifiedAmounts: ReportedAmount[] } | null;
issues: InvestmentIssue[];
isFocusTarget?: true;
}
export interface InvestmentRegisterData {
@@ -80,6 +75,7 @@ export interface InvestmentRegisterData {
export interface InvestmentAccountPageData {
readFailed: boolean;
missingFocusTransactionIndex?: number;
preparedAt: string;
accountName: string;
access: 'ready' | 'ambiguous';
@@ -1,43 +0,0 @@
import { expect, it } from 'vitest';
import { parseRegisterPageRequest } from './register-page-request.js';
const accountId = 'abcd1234';
it('defaults to ascending with no specified page and preserves explicit date/page choices', () => {
expect(parseRegisterPageRequest(accountId, new URLSearchParams())).toEqual({
accountId,
order: 'asc',
page: null
});
expect(parseRegisterPageRequest(accountId, new URLSearchParams('order=desc&page=2'))).toEqual({
accountId,
order: 'desc',
page: 2
});
});
it('rejects unsupported, repeated and invalid view parameters without echoing input', () => {
for (const query of [
'source=PRIVATE',
'order=asc&order=desc',
'order=PRIVATE',
'page=1&page=2',
'page=0',
'page=01',
'page=1%0A',
'page=+1',
'page=1e2',
'page=1.5',
'page=9007199254740992'
]) {
expect(() => parseRegisterPageRequest(accountId, new URLSearchParams(query))).toThrow(
expect.objectContaining({ status: 400 })
);
}
expect(() => parseRegisterPageRequest('../PRIVATE', new URLSearchParams())).toThrow(
expect.objectContaining({
status: 400,
body: expect.objectContaining({ message: 'A valid account ID is required.' })
})
);
});
@@ -1,44 +0,0 @@
import { error } from '@sveltejs/kit';
import type { InvestmentRegisterData } from './data.js';
import { isAccountId, isDateOrder, isPositiveSafeInteger } from './request-validation.js';
export interface RegisterPageRequest {
accountId: string;
order: InvestmentRegisterData['order'];
page: number | null;
}
export function parseRegisterPageRequest(
accountId: string,
parameters: URLSearchParams
): RegisterPageRequest {
if (!isAccountId(accountId)) error(400, 'A valid account ID is required.');
for (const key of parameters.keys()) {
if (key !== 'order' && key !== 'page') error(400, 'Unsupported register parameter.');
}
const order = parseOrder(parameters);
const page = parsePage(parameters);
return { accountId, order, page };
}
function parseOrder(parameters: URLSearchParams): RegisterPageRequest['order'] {
const orders = parameters.getAll('order');
const order = orders[0] ?? 'asc';
if (orders.length > 1 || !isDateOrder(order)) error(400, 'A valid date order is required.');
return order;
}
function parsePage(parameters: URLSearchParams): RegisterPageRequest['page'] {
const pages = parameters.getAll('page');
if (pages.length > 1) error(400, 'A valid page number is required.');
const pageText = pages[0];
if (pageText === undefined) return null;
if (!isCanonicalPageNumberText(pageText)) error(400, 'A valid page number is required.');
const page = Number(pageText);
if (!isPositiveSafeInteger(page)) error(400, 'A valid page number is required.');
return page;
}
function isCanonicalPageNumberText(value: string): boolean {
return /^[1-9][0-9]*(?![\s\S])/.test(value);
}
@@ -1,9 +1,8 @@
import { getRequestEvent, query } from '$app/server';
import type { ActivityBatchRequest } from './data.js';
import { parseActivityBatchRequest } from './activity-batch-request.js';
import { parseRegisterBatchRequest, type RegisterBatchRequest } from '../register-batch-request.js';
import { readActivityBatch } from '#lib/server/registers/investment/register.js';
export const getActivityBatch = query('unchecked', async (input: ActivityBatchRequest) => {
const request = parseActivityBatchRequest(input);
export const getActivityBatch = query('unchecked', async (input: RegisterBatchRequest) => {
const request = parseRegisterBatchRequest(input);
return readActivityBatch(getRequestEvent().locals, request);
});
@@ -1,13 +0,0 @@
import type { InvestmentRegisterData } from './data.js';
export function isAccountId(value: unknown): value is string {
return typeof value === 'string' && value.length === 8 && !/[^a-z0-9]/.test(value);
}
export function isDateOrder(value: unknown): value is InvestmentRegisterData['order'] {
return value === 'asc' || value === 'desc';
}
export function isPositiveSafeInteger(value: unknown): value is number {
return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
}
@@ -63,6 +63,7 @@
data-investment-details
disabled={!onOpenActivity}
aria-haspopup="dialog"
aria-current={activity.isFocusTarget}
title="View activity details"
onclick={(event) => onOpenActivity?.(rowPosition, event.currentTarget)}
>
@@ -238,7 +238,8 @@
<div
class="investment-cell"
inert={isRetainedActivityOffscreen(rowPosition)}
class:striped={rowPosition % 2 === 1}
class:striped={rowPosition % 2 === 1 && !row?.activity.isFocusTarget}
class:focused-row-cell={row?.activity.isFocusTarget}
class:money={isMoneyColumn(column.key)}
class:status={column.key === 'status'}
data-row-position={rowPosition}
@@ -41,6 +41,14 @@
.investment-table .activity-row:nth-child(even) {
background: var(--color-background);
}
.investment-table .activity-row:has([aria-current='true']),
.investment-table .investment-cell.focused-row-cell {
background: color-mix(in srgb, var(--color-accent) 12%, var(--color-surface));
}
.investment-table td[data-column='date']:has([aria-current='true']),
.investment-table .focused-row-cell[data-column='date'] {
box-shadow: inset 3px 0 var(--color-accent);
}
.investment-table .activity-row:hover,
.investment-table .activity-row:focus-within {
background: color-mix(in srgb, var(--color-accent) 20%, var(--color-surface));
@@ -0,0 +1,59 @@
import { expect, it } from 'vitest';
import { parseRegisterBatchRequest } from './register-batch-request.js';
const request = { accountId: 'abcd1234', order: 'desc', batchStart: 150 };
it('parses aligned register requests, including a null-prototype object', () => {
expect(parseRegisterBatchRequest(request)).toEqual(request);
expect(parseRegisterBatchRequest(Object.assign(Object.create(null), request))).toEqual(request);
expect(parseRegisterBatchRequest({ ...request, order: 'asc', batchStart: 0 })).toEqual({
...request,
order: 'asc',
batchStart: 0
});
});
it('rejects non-records, missing or extra keys, inherited fields and symbol keys', () => {
for (const input of [
null,
[],
new Date(),
Object.create(request),
{ accountId: request.accountId, order: request.order },
{ ...request, [Symbol('extra')]: true }
]) {
expect(() => parseRegisterBatchRequest(input)).toThrow(
expect.objectContaining({ status: 400 })
);
}
});
it('rejects invalid account IDs, orders and unsafe or unaligned positions', () => {
const unsafeAlignedStart = 9_007_199_254_741_000;
for (const input of [
{ ...request, accountId: 'abcd1234\n' },
{ ...request, order: 'sideways' },
...[1, -50, 1.5, NaN, Infinity, unsafeAlignedStart, '50'].map((batchStart) => ({
...request,
batchStart
}))
]) {
expect(() => parseRegisterBatchRequest(input)).toThrow(
expect.objectContaining({ status: 400 })
);
}
});
it('rejects extra fields and malformed values without echoing private input', () => {
for (const input of [
{ ...request, limit: 'PRIVATE' },
{ ...request, accountId: '../PRIVATE' }
]) {
expect(() => parseRegisterBatchRequest(input)).toThrow(
expect.objectContaining({
status: 400,
body: expect.objectContaining({ message: expect.not.stringContaining('PRIVATE') })
})
);
}
});
@@ -1,9 +1,15 @@
import { registerPageSize } from '@hledger-reports/snapshots/register-page';
import { error } from '@sveltejs/kit';
import { activityBatchSize, type ActivityBatchRequest } from './data.js';
import { isAccountId, isDateOrder } from './request-validation.js';
export function parseActivityBatchRequest(input: unknown): ActivityBatchRequest {
if (!hasActivityBatchRequestShape(input)) error(400, 'A valid activity batch is required.');
export interface RegisterBatchRequest {
accountId: string;
order: 'asc' | 'desc';
batchStart: number;
}
export function parseRegisterBatchRequest(input: unknown): RegisterBatchRequest {
if (!hasRegisterBatchRequestShape(input)) error(400, 'A valid register batch is required.');
const { accountId, order, batchStart } = input;
if (!isAccountId(accountId)) error(400, 'A valid account ID is required.');
if (!isDateOrder(order)) error(400, 'A valid date order is required.');
@@ -11,7 +17,7 @@ export function parseActivityBatchRequest(input: unknown): ActivityBatchRequest
return { accountId, order, batchStart };
}
function hasActivityBatchRequestShape(
function hasRegisterBatchRequestShape(
input: unknown
): input is { accountId: unknown; order: unknown; batchStart: unknown } {
if (input === null || typeof input !== 'object' || Array.isArray(input)) return false;
@@ -28,6 +34,6 @@ function isBatchStart(value: unknown): value is number {
typeof value === 'number' &&
Number.isSafeInteger(value) &&
value >= 0 &&
value % activityBatchSize === 0
value % registerPageSize === 0
);
}
@@ -0,0 +1,64 @@
import { expect, it } from 'vitest';
import { parseRegisterPageRequest } from './register-page-request.js';
const accountId = 'abcd1234';
it('uses the caller’s default direction and preserves explicit date/page choices', () => {
expect(parseRegisterPageRequest(accountId, new URLSearchParams(), 'asc')).toEqual({
accountId,
order: 'asc',
page: null
});
expect(
parseRegisterPageRequest(accountId, new URLSearchParams('order=desc&page=2'), 'asc')
).toEqual({
accountId,
order: 'desc',
page: 2
});
});
it('parses a focus link without selecting a page', () => {
expect(parseRegisterPageRequest(accountId, new URLSearchParams('focus=42'), 'desc')).toEqual({
accountId,
order: 'desc',
focusTransactionIndex: 42
});
});
it('rejects unsupported, repeated, conflicting and invalid view parameters', () => {
for (const query of [
'order=asc&order=desc',
'order=sideways',
'page=1&page=2',
'page=0',
'page=01',
'page=1%0A',
'page=+1',
'page=1e2',
'page=1.5',
'page=9007199254740992',
'focus=9007199254740992',
'focus=1&focus=2',
'focus=1&page=1'
]) {
expect(
() => parseRegisterPageRequest(accountId, new URLSearchParams(query), 'asc'),
query
).toThrow(expect.objectContaining({ status: 400 }));
}
});
it('rejects an invalid account ID or an unknown query parameter without echoing input', () => {
for (const [id, query] of [
['../PRIVATE', ''],
[accountId, 'PRIVATE_KEY=PRIVATE_VALUE']
]) {
expect(() => parseRegisterPageRequest(id, new URLSearchParams(query), 'asc')).toThrow(
expect.objectContaining({
status: 400,
body: expect.objectContaining({ message: expect.not.stringContaining('PRIVATE') })
})
);
}
});
@@ -0,0 +1,76 @@
import { error } from '@sveltejs/kit';
import { isAccountId, isDateOrder, isPositiveSafeInteger } from './request-validation.js';
interface RegisterAccountOrder {
accountId: string;
order: 'asc' | 'desc';
}
export type PagedRegisterRequest = RegisterAccountOrder & {
page: number | null;
focusTransactionIndex?: never;
};
type FocusedRegisterRequest = RegisterAccountOrder & {
page?: never;
focusTransactionIndex: number;
};
export type RegisterPageRequest = PagedRegisterRequest | FocusedRegisterRequest;
export function parseRegisterPageRequest(
accountId: string,
parameters: URLSearchParams,
defaultOrder: RegisterPageRequest['order']
): RegisterPageRequest {
if (!isAccountId(accountId)) error(400, 'A valid account ID is required.');
requireSupportedParameters(parameters);
const order = parseOrder(parameters, defaultOrder);
const focusTransactionIndex = parsePositiveIntegerParameter(
parameters,
'focus',
'A valid transaction index is required.'
);
if (focusTransactionIndex !== null) {
if (parameters.has('page')) error(400, 'Focus links cannot include a page number.');
return { accountId, order, focusTransactionIndex };
}
const page = parsePositiveIntegerParameter(
parameters,
'page',
'A valid page number is required.'
);
return { accountId, order, page };
}
function requireSupportedParameters(parameters: URLSearchParams): void {
for (const key of parameters.keys()) {
if (key !== 'order' && key !== 'page' && key !== 'focus')
error(400, 'Unsupported register parameter.');
}
}
function parseOrder(
parameters: URLSearchParams,
defaultOrder: RegisterPageRequest['order']
): RegisterPageRequest['order'] {
const orders = parameters.getAll('order');
const order = orders[0] ?? defaultOrder;
if (orders.length > 1 || !isDateOrder(order)) error(400, 'A valid date order is required.');
return order;
}
function parsePositiveIntegerParameter(
parameters: URLSearchParams,
key: 'page' | 'focus',
message: string
): number | null {
const [text, extra] = parameters.getAll(key);
if (text === undefined) return null;
if (extra !== undefined) error(400, message);
const isCanonicalPositiveIntegerText = /^[1-9]/.test(text) && !/[^0-9]/.test(text);
if (!isCanonicalPositiveIntegerText) error(400, message);
const value = Number(text);
if (!isPositiveSafeInteger(value)) error(400, message);
return value;
}
@@ -1,10 +1,8 @@
import type { RegisterPageData } from './data.js';
export function isAccountId(value: unknown): value is string {
return typeof value === 'string' && value.length === 8 && !/[^a-z0-9]/.test(value);
}
export function isDateOrder(value: unknown): value is RegisterPageData['order'] {
export function isDateOrder(value: unknown): value is 'asc' | 'desc' {
return value === 'asc' || value === 'desc';
}
@@ -0,0 +1,6 @@
import { error } from '@sveltejs/kit';
export function requireRegisterBatchPosition(batchStart: number, savedRowCount: number): void {
const available = savedRowCount === 0 ? batchStart === 0 : batchStart < savedRowCount;
if (!available) error(404, 'History position not found.');
}
@@ -123,7 +123,7 @@ it('rejects accounts outside the configured cash register and native-ready catal
{ account: name, register: 'investment' },
{ account: 'assets:other', register: 'cash' }
]),
batchRequest
{ ...batchRequest, batchStart: 0 }
)
).rejects.toMatchObject({ status: 404 });
vi.mocked(readReportPublication).mockResolvedValue({
@@ -174,8 +174,7 @@ it('reads a bounded batch and returns only public rows', async () => {
const result = await readRowBatch(locals(), batchRequest);
expect(readAccountPage).toHaveBeenCalledExactlyOnceWith(batchPublication, accountId, {
order: 'desc',
offset: 250,
limit: 50
offset: 250
});
expect(result).toMatchObject({
batchStart: 250,
@@ -2,18 +2,20 @@ import type { PreparedAccountRow } from '@hledger-reports/hledger';
import {
readAccountPage,
readAccountTransaction,
readFocusedAccountPage,
type AccountActivityPage
} from '@hledger-reports/snapshots';
import { error } from '@sveltejs/kit';
import {
rowBatchSize,
type RegisterPageData,
type RegisterPageRequest,
type RowBatch,
type RowBatchRequest,
type TransactionDetails,
type TransactionDetailsRequest
} from '#lib/registers/cash/data.js';
import type { RegisterBatchRequest } from '#lib/registers/register-batch-request.js';
import type { RegisterPageRequest } from '#lib/registers/register-page-request.js';
import { requireRegisterBatchPosition } from '../batch-position.js';
import type { ReadableAccount } from '../prepared-account.js';
import { projectActivityPage, projectTransactionDetails } from './projection.js';
import {
@@ -25,7 +27,13 @@ import {
type RegisterActivity = Pick<
RegisterPageData,
'rowCount' | 'page' | 'pageCount' | 'rows' | 'endingBalance' | 'readFailed'
| 'rowCount'
| 'page'
| 'pageCount'
| 'rows'
| 'endingBalance'
| 'readFailed'
| 'missingFocusTransactionIndex'
>;
export async function loadRegisterPage(
@@ -57,10 +65,10 @@ export async function loadRegisterPage(
export async function readRowBatch(
locals: RegisterLocals,
request: RowBatchRequest
request: RegisterBatchRequest
): Promise<RowBatch> {
const account = await requireAuthenticatedReadableAccount(locals, 'cash', request.accountId);
requireBatchPosition(request.batchStart, account.rowCount);
requireRegisterBatchPosition(request.batchStart, account.rowCount);
try {
const page = await readSavedActivityPage(account, request.order, request.batchStart);
return { batchStart: request.batchStart, rows: projectActivityPage(page).rows };
@@ -82,36 +90,35 @@ async function readInitialActivity(
account: ReadableAccount,
request: RegisterPageRequest
): Promise<RegisterActivity> {
const pagination = resolvePagination(account.rowCount, request);
const activity: RegisterActivity = {
...pagination,
rows: [],
endingBalance: null,
readFailed: false
};
if (account.rowCount === 0) return { ...activity, endingBalance: [] };
try {
const page = await readSavedActivityPage(
account,
request.order,
(pagination.page - 1) * rowBatchSize
);
return { ...activity, ...projectActivityPage(page) };
} catch {
return { ...activity, readFailed: true };
}
}
function resolvePagination(rowCount: number, { order, page }: RegisterPageRequest) {
const { order, page: requestedPage, focusTransactionIndex } = request;
const { rowCount } = account;
const pageCount = Math.max(1, Math.ceil(rowCount / rowBatchSize));
const selectedPage = page ?? (order === 'asc' ? pageCount : 1);
if (selectedPage > pageCount) error(404, 'Page not found in the prepared report.');
return { rowCount, page: selectedPage, pageCount };
}
function requireBatchPosition(batchStart: number, rowCount: number): void {
const available = rowCount === 0 ? batchStart === 0 : batchStart < rowCount;
if (!available) error(404, 'History position not found.');
if (requestedPage != null && requestedPage > pageCount)
error(404, 'Page not found in the prepared report.');
const fallbackPage = requestedPage ?? (order === 'asc' ? pageCount : 1);
const pagination = { rowCount, page: fallbackPage, pageCount };
try {
if (focusTransactionIndex !== undefined) {
const focusedPage = await readFocusedAccountPage(
account.publication,
account.id,
focusTransactionIndex,
order
);
if (focusedPage) {
const activity = projectActivityPage(focusedPage);
activity.rows[focusedPage.indexOnPage].isFocusTarget = true;
return { ...pagination, page: focusedPage.pageNumber, ...activity, readFailed: false };
}
}
const page = await readSavedActivityPage(account, order, (fallbackPage - 1) * rowBatchSize);
const activity = { ...pagination, ...projectActivityPage(page), readFailed: false };
return focusTransactionIndex === undefined
? activity
: { ...activity, missingFocusTransactionIndex: focusTransactionIndex };
} catch {
return { ...pagination, rows: [], endingBalance: null, readFailed: true };
}
}
async function readSavedActivityPage(
@@ -121,8 +128,7 @@ async function readSavedActivityPage(
): Promise<AccountActivityPage> {
const page = await readAccountPage(account.publication, account.id, {
order,
offset: batchStart,
limit: rowBatchSize
offset: batchStart
});
if (!page) throw new Error('Prepared account rows unavailable.');
return page;
@@ -110,6 +110,7 @@ function page(record: PreparedAccountRow, indexes = [0, 1], entryOrder = [0, 1])
rows: indexes.map((postingIndex) => ({
row: record,
postingIndex,
displayDate: record.transaction.postings[postingIndex].date ?? record.transaction.date,
entryActivityPosition: entryOrder.indexOf(postingIndex) + 1,
entryActivityCount: entryOrder.length
})),
@@ -53,6 +53,7 @@ function projectInvestmentActivity(
{
row: accountRow,
postingIndex,
displayDate,
entryActivityPosition,
entryActivityCount
}: AccountInvestmentActivityPage['rows'][number],
@@ -92,7 +93,7 @@ function projectInvestmentActivity(
)
]
: [],
date: posting.date ?? transaction.date,
date: displayDate,
statuses: [posting.effectiveStatus],
payee: transaction.payee,
notes,
@@ -110,7 +111,7 @@ function projectInvestmentActivity(
}
export function projectInvestmentActivityPage(
{ rows, summary }: AccountInvestmentActivityPage,
{ rows, summary }: Pick<AccountInvestmentActivityPage, 'rows' | 'summary'>,
accountName: string
): Pick<InvestmentRegisterData, 'activities' | 'endingCash' | 'unclassifiedEndingCash'> {
// Several stock actions can share one native entry cash effect; never allocate it.
@@ -1,6 +1,6 @@
import type { AccountConfig } from '@hledger-reports/config';
import {
countInvestmentActivities,
readInvestmentActivityCount,
readInvestmentActivityPage,
readReportPublication,
type AccountInvestmentActivityPage
@@ -17,7 +17,7 @@ import { loadRegisterPage, readActivityBatch } from './register.js';
vi.mock('@hledger-reports/snapshots', () => ({
readReportPublication: vi.fn(),
countInvestmentActivities: vi.fn(),
readInvestmentActivityCount: vi.fn(),
readInvestmentActivityPage: vi.fn()
}));
vi.mock('@hledger-reports/hledger', () => {
@@ -43,9 +43,11 @@ row.transaction.postings = [
row.investment.cashPostingIndexes = [...row.accountPostingIndexes];
row.investment.expensePostingIndexes = [55, 56];
const page: AccountInvestmentActivityPage = {
activityCount: row.accountPostingIndexes.length,
rows: row.accountPostingIndexes.slice(50).map((postingIndex) => ({
row,
postingIndex,
displayDate: selectedPosting.date ?? row.transaction.date,
entryActivityPosition: postingIndex + 1,
entryActivityCount: 55
})),
@@ -90,10 +92,9 @@ it('reads one pinned publication at fixed size without separately recounting and
expect(readReportPublication).toHaveBeenCalledOnce();
expect(readInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(publication, accountId, {
order: 'desc',
offset: 50,
limit: 50
offset: 50
});
expect(countInvestmentActivities).not.toHaveBeenCalled();
expect(readInvestmentActivityCount).not.toHaveBeenCalled();
expect(Object.keys(result)).toEqual(['batchStart', 'activities']);
expect(result.batchStart).toBe(50);
expect(result.activities).toHaveLength(5);
@@ -160,28 +161,35 @@ it('requires configured investment membership and a native-ready selected accoun
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
});
it('uses the integrity-verified empty result for out-of-range positions, not the transaction count', async () => {
it('rejects a start past the saved posting count without another count read', async () => {
vi.mocked(readInvestmentActivityPage).mockResolvedValue({ ...page, rows: [] });
await expect(readActivityBatch(locals(), request)).rejects.toMatchObject({
await expect(readActivityBatch(locals(), { ...request, batchStart: 100 })).rejects.toMatchObject({
status: 404,
body: { message: 'History position not found.' }
});
expect(readInvestmentActivityPage).toHaveBeenCalledOnce();
expect(countInvestmentActivities).not.toHaveBeenCalled();
expect(readInvestmentActivityCount).not.toHaveBeenCalled();
});
it('permits only batch zero for declared-empty accounts without reading a body', async () => {
it('permits only batch zero for empty accounts and checks the saved page', async () => {
vi.mocked(readReportPublication).mockResolvedValue({
...publication,
accounts: publication.accounts.map((account) => ({ ...account, rowCount: 0 }))
});
expect(await readActivityBatch(locals(), { ...request, batchStart: 0 })).toEqual({
batchStart: 0,
activities: []
vi.mocked(readInvestmentActivityPage).mockResolvedValue({
...page,
activityCount: 0,
rows: [],
summary: { ...page.summary, endingCash: [] }
});
const batchZero = { ...request, batchStart: 0 };
expect(await readActivityBatch(locals(), batchZero)).toEqual({ batchStart: 0, activities: [] });
await expect(readActivityBatch(locals(), request)).rejects.toMatchObject({ status: 404 });
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
expect(countInvestmentActivities).not.toHaveBeenCalled();
expect(readInvestmentActivityPage).toHaveBeenCalledOnce();
vi.mocked(readInvestmentActivityPage).mockRejectedValue(
new Error('Unable to read account activity')
);
await expect(readActivityBatch(locals(), batchZero)).rejects.toMatchObject({ status: 503 });
});
it('sanitizes missing, foreign and unreadable publications before activity reads', async () => {
@@ -200,27 +208,29 @@ it('sanitizes missing, foreign and unreadable publications before activity reads
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
});
it.each([null, 0, -1, 1.5, Number.MAX_SAFE_INTEGER + 1])(
'rejects an unreadable initial activity count (%s) before reading a saved body',
async (activityCount) => {
vi.mocked(countInvestmentActivities).mockResolvedValue(activityCount);
const result = await loadRegisterPage(
{ locals: locals(), parent: async () => ({}) },
{ accountId, order: 'asc', page: null }
);
expect(result).toMatchObject({
readFailed: true,
accountName: name,
access: 'ready',
register: null
});
expect(countInvestmentActivities).toHaveBeenCalledExactlyOnceWith(publication, accountId);
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
}
);
it('reports a saved count read failure for a declared-empty account', async () => {
vi.mocked(readReportPublication).mockResolvedValue({
...publication,
accounts: publication.accounts.map((account) => ({ ...account, rowCount: 0 }))
});
vi.mocked(readInvestmentActivityCount).mockRejectedValue(
new Error('Unable to read account activity')
);
const result = await loadRegisterPage(
{ locals: locals(), parent: async () => ({}) },
{ accountId, order: 'asc', page: null }
);
expect(result).toMatchObject({
readFailed: true,
accountName: name,
access: 'ready',
register: null
});
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
});
it('returns an SSR read failure when a counted initial page cannot be projected', async () => {
vi.mocked(countInvestmentActivities).mockResolvedValue(55);
vi.mocked(readInvestmentActivityCount).mockResolvedValue(55);
vi.mocked(readInvestmentActivityPage).mockResolvedValue({
...page,
rows: [{ ...page.rows[0], postingIndex: 999 }]
@@ -232,8 +242,7 @@ it('returns an SSR read failure when a counted initial page cannot be projected'
expect(result).toMatchObject({ readFailed: true, register: null });
expect(readInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(publication, accountId, {
order: 'asc',
offset: 50,
limit: 50
offset: 50
});
expect(JSON.stringify(result)).not.toContain('PRIVATE');
});
@@ -1,17 +1,19 @@
import {
countInvestmentActivities,
readInvestmentActivityCount,
readInvestmentActivityPage,
readFocusedInvestmentActivityPage,
type AccountInvestmentActivityPage
} from '@hledger-reports/snapshots';
import { error } from '@sveltejs/kit';
import {
activityBatchSize,
type ActivityBatch,
type ActivityBatchRequest,
type InvestmentAccountPageData,
type InvestmentRegisterData
} from '#lib/registers/investment/data.js';
import type { RegisterPageRequest } from '#lib/registers/investment/register-page-request.js';
import type { RegisterBatchRequest } from '#lib/registers/register-batch-request.js';
import type { RegisterPageRequest } from '#lib/registers/register-page-request.js';
import { requireRegisterBatchPosition } from '../batch-position.js';
import type { ReadableAccount } from '../prepared-account.js';
import {
selectRegisterPageAccount,
@@ -32,64 +34,61 @@ export async function loadRegisterPage(
preparedAt: account.publication.overview.preparedAt
};
if (account.access === 'ambiguous') return { ...metadata, readFailed: false, register: null };
return { ...metadata, ...(await readInitialRegisterPage(account, request)) };
const { order, focusTransactionIndex } = request;
if (focusTransactionIndex !== undefined) {
const focusResult = await readFocusedRegisterPage(account, order, focusTransactionIndex);
if (focusResult !== null) return { ...metadata, ...focusResult };
}
const initialPage = await readInitialRegisterPage(account, order, request.page ?? null);
if (focusTransactionIndex !== undefined && !initialPage.readFailed)
return { ...metadata, ...initialPage, missingFocusTransactionIndex: focusTransactionIndex };
return { ...metadata, ...initialPage };
}
export async function readActivityBatch(
locals: RegisterLocals,
request: ActivityBatchRequest
request: RegisterBatchRequest
): Promise<ActivityBatch> {
const account = await requireAuthenticatedReadableAccount(
locals,
'investment',
request.accountId
);
if (account.rowCount === 0) {
if (request.batchStart !== 0) error(404, 'History position not found.');
return { batchStart: 0, activities: [] };
}
const { order, batchStart } = request;
const { rowCount: savedEntryCount } = account;
if (savedEntryCount === 0) requireRegisterBatchPosition(batchStart, savedEntryCount);
let page: AccountInvestmentActivityPage;
let activities: ActivityBatch['activities'];
try {
page = await readSavedActivityPage(account, request.order, request.batchStart);
page = await readSavedActivityPage(account, order, batchStart);
activities = projectInvestmentActivityPage(page, account.name).activities;
} catch {
error(503, 'Prepared history could not be read.');
}
// The saved reader already verifies the visible count and the exact page length.
if (page.rows.length === 0) error(404, 'History position not found.');
return { batchStart: request.batchStart, activities };
requireRegisterBatchPosition(batchStart, page.activityCount);
return { batchStart, activities };
}
async function countReadableActivities(account: ReadableAccount): Promise<number> {
if (account.rowCount === 0) return 0;
const activityCount = await countInvestmentActivities(account.publication, account.id);
if (activityCount === null || !Number.isSafeInteger(activityCount) || activityCount < 1)
throw new Error('Prepared activity count unavailable.');
async function readSavedActivityCount(account: ReadableAccount): Promise<number> {
const activityCount = await readInvestmentActivityCount(account.publication, account.id);
if (activityCount === null) throw new Error('Prepared activity count unavailable.');
return activityCount;
}
function selectInitialPage(
request: RegisterPageRequest,
activityCount: number
): Pick<InvestmentRegisterData, 'page' | 'pageCount'> {
const pageCount = Math.max(1, Math.ceil(activityCount / activityBatchSize));
const page = request.page ?? (request.order === 'asc' ? pageCount : 1);
if (page > pageCount) error(404, 'Page not found in the prepared report.');
return { page, pageCount };
}
async function readInitialRegisterPage(
account: ReadableAccount,
request: RegisterPageRequest
order: InvestmentRegisterData['order'],
requestedPage: number | null
): Promise<Pick<InvestmentAccountPageData, 'register' | 'readFailed'>> {
let activityCount: number;
try {
activityCount = await countReadableActivities(account);
activityCount = await readSavedActivityCount(account);
} catch {
return { register: null, readFailed: true };
}
const { page, pageCount } = selectInitialPage(request, activityCount);
const pageCount = Math.max(1, Math.ceil(activityCount / activityBatchSize));
const page = requestedPage ?? (order === 'asc' ? pageCount : 1);
if (page > pageCount) error(404, 'Page not found in the prepared report.');
const register: InvestmentRegisterData = {
accountId: account.id,
accountName: account.name,
@@ -97,17 +96,13 @@ async function readInitialRegisterPage(
activityCount,
page,
pageCount,
order: request.order,
order,
endingCash: [],
unclassifiedEndingCash: []
};
if (activityCount === 0) return { register, readFailed: false };
try {
const saved = await readSavedActivityPage(
account,
request.order,
(page - 1) * activityBatchSize
);
const saved = await readSavedActivityPage(account, order, (page - 1) * activityBatchSize);
return {
register: { ...register, ...projectInvestmentActivityPage(saved, account.name) },
readFailed: false
@@ -117,6 +112,40 @@ async function readInitialRegisterPage(
}
}
async function readFocusedRegisterPage(
account: ReadableAccount,
order: InvestmentRegisterData['order'],
transactionIndex: number
): Promise<Pick<InvestmentAccountPageData, 'register' | 'readFailed'> | null> {
try {
const saved = await readFocusedInvestmentActivityPage(
account.publication,
account.id,
transactionIndex,
order
);
if (saved) {
const projected = projectInvestmentActivityPage(saved, account.name);
projected.activities[saved.indexOnPage].isFocusTarget = true;
return {
register: {
accountId: account.id,
accountName: account.name,
order,
page: saved.pageNumber,
pageCount: Math.ceil(saved.activityCount / activityBatchSize),
activityCount: saved.activityCount,
...projected
},
readFailed: false
};
}
} catch {
return { register: null, readFailed: true };
}
return null;
}
async function readSavedActivityPage(
account: ReadableAccount,
order: InvestmentRegisterData['order'],
@@ -124,8 +153,7 @@ async function readSavedActivityPage(
): Promise<AccountInvestmentActivityPage> {
const page = await readInvestmentActivityPage(account.publication, account.id, {
order,
offset: batchStart,
limit: activityBatchSize
offset: batchStart
});
if (!page) throw new Error('Prepared account rows unavailable.');
return page;
+4
View File
@@ -6,6 +6,8 @@
--color-muted: #50615b;
--color-accent: #225e4b;
--color-negative: #b42318;
--color-error-background: #fee4e2;
--color-error-text: #912018;
--color-border: #cbd4ce;
--color-border-strong: var(--color-muted);
--color-on-accent: #ffffff;
@@ -51,6 +53,8 @@
--color-muted: #acbfb1;
--color-accent: #8adbb4;
--color-negative: #fda29b;
--color-error-background: #4b221f;
--color-error-text: #ffd4d1;
--color-border: #3a5343;
--color-on-accent: #0b1310;
--color-chart-expense: #fdba74;
@@ -4,6 +4,7 @@
import { formatDate } from '#lib/dates.js';
import AccountSidebar from '#lib/navigation/AccountSidebar.svelte';
import AppHeader from '#lib/navigation/AppHeader.svelte';
import SkipToContent from '#lib/navigation/SkipToContent.svelte';
import type { LayoutProps } from './$types';
let { children, data }: Pick<LayoutProps, 'children' | 'data'> = $props();
@@ -15,6 +16,7 @@
}
</script>
<SkipToContent />
<div
class="app-shell"
class:desktop-accounts-visible={data.accountSidebar !== null && desktopAccountsVisible}
@@ -1,9 +1,9 @@
import { parseRegisterPageRequest } from '#lib/registers/cash/register-page-request.js';
import { parseRegisterPageRequest } from '#lib/registers/register-page-request.js';
import { loadRegisterPage } from '#lib/server/registers/cash/register.js';
import type { PageServerLoad } from './$types';
export const load = (async (event) => {
event.setHeaders({ 'cache-control': 'no-store' });
const request = parseRegisterPageRequest(event.params.accountId, event.url.searchParams);
const request = parseRegisterPageRequest(event.params.accountId, event.url.searchParams, 'desc');
return loadRegisterPage(event, request);
}) satisfies PageServerLoad;
@@ -1,6 +1,7 @@
<script lang="ts">
import { resolve } from '$app/paths';
import Register from '#lib/registers/cash/Register.svelte';
import RegisterFocusNotice from '#lib/registers/RegisterFocusNotice.svelte';
import { accountLabel } from '#lib/accounts.js';
import { formatAmount } from '#lib/amounts.js';
import { isNegativeAmount } from '#lib/registers/cash/amount-sign.js';
@@ -53,6 +54,7 @@
are shown.
</p>
{:else}
<RegisterFocusNotice missingTransactionIndex={data.missingFocusTransactionIndex} />
{#key data}
<Register {data} labels={data.accountLabels} />
{/key}
@@ -5,6 +5,7 @@ import { beforeEach, expect, it, vi } from 'vitest';
import {
readReportPublication,
readAccountPage,
readFocusedAccountPage,
type AccountActivityPage
} from '@hledger-reports/snapshots';
import type { ApplicationContext } from '#lib/server/application.js';
@@ -15,6 +16,7 @@ import { load } from './+page.server.js';
vi.mock('@hledger-reports/snapshots', () => ({
readReportPublication: vi.fn(),
readAccountPage: vi.fn(),
readFocusedAccountPage: vi.fn(),
readAccountTransaction: vi.fn()
}));
vi.mock('#lib/server/registers/cash/projection.js', () => ({
@@ -104,13 +106,62 @@ it('loads a member from one pinned publication and delegates its requested page'
expect(readReportPublication).toHaveBeenCalledOnce();
expect(readAccountPage).toHaveBeenCalledExactlyOnceWith(publication, id, {
order: 'desc',
offset: 50,
limit: 50
offset: 50
});
expect(projectActivityPage).toHaveBeenCalledExactlyOnceWith(accountPage);
expect(request.parent).toHaveBeenCalledOnce();
expect(request.setHeaders).toHaveBeenCalledWith({ 'cache-control': 'no-store' });
});
it('marks only the target on the saved Cash page in the requested order', async () => {
const focusedPage = {
...accountPage,
rows: preparedAccountRows(2),
pageNumber: 1,
indexOnPage: 1
};
const [other, target] = focusedPage.rows.map((row) => row.transaction.index);
const actual = await vi.importActual<typeof import('#lib/server/registers/cash/projection.js')>(
'#lib/server/registers/cash/projection.js'
);
vi.mocked(projectActivityPage).mockImplementationOnce(actual.projectActivityPage);
vi.mocked(readFocusedAccountPage).mockResolvedValue(focusedPage);
const result = await load(event(`focus=${target}&order=asc`));
expect(result).toMatchObject({ page: 1, order: 'asc', readFailed: false });
expect(result.rows[0]).toMatchObject({ transactionIndex: other });
expect(result.rows[0]).not.toHaveProperty('isFocusTarget');
expect(result.rows[1]).toMatchObject({ transactionIndex: target, isFocusTarget: true });
expect(readFocusedAccountPage).toHaveBeenCalledExactlyOnceWith(publication, id, target, 'asc');
expect(readAccountPage).not.toHaveBeenCalled();
});
it('returns the ordinary Cash page in the requested order when the target is absent', async () => {
vi.mocked(readFocusedAccountPage).mockResolvedValue(null);
const result = await load(event('focus=99&order=asc'));
expect(readAccountPage).toHaveBeenCalledWith(publication, id, { order: 'asc', offset: 50 });
expect(result).toMatchObject({
readFailed: false,
page: 2,
order: 'asc',
missingFocusTransactionIndex: 99,
...projection
});
});
it('returns a safe read failure when a focused page is unreadable', async () => {
vi.mocked(readFocusedAccountPage).mockRejectedValue(new Error('PRIVATE diagnostic'));
const unreadable = await load(event('focus=100'));
expect(unreadable).toMatchObject({ readFailed: true, rows: [], endingBalance: null });
expect(unreadable).not.toHaveProperty('missingFocusTransactionIndex');
expect(readAccountPage).not.toHaveBeenCalled();
expect(JSON.stringify(unreadable)).not.toContain('PRIVATE');
});
it('rejects a focus URL with a page number before reading a report', async () => {
await expect(load(event('focus=1&page=1'))).rejects.toMatchObject({ status: 400 });
expect(readReportPublication).not.toHaveBeenCalled();
expect(readFocusedAccountPage).not.toHaveBeenCalled();
});
it('requires an application without reading reports or parent data', async () => {
const request = event();
request.locals.application = null;
@@ -130,11 +181,12 @@ it.each(['missing', 'unreadable', 'journal-changed'] as const)(
expect(projectActivityPage).not.toHaveBeenCalled();
}
);
it('returns a safe read failure when the saved body cannot be read', async () => {
it('returns a safe read failure when the fallback page cannot be read after a focus miss', async () => {
vi.mocked(readFocusedAccountPage).mockResolvedValue(null);
vi.mocked(readAccountPage).mockRejectedValue(
new Error('PRIVATE /books/included.journal:12 database diagnostic')
);
const request = event();
const request = event('focus=99');
const queue = vi.spyOn(request.locals.application!, 'jobsClient', 'get');
const result = await load(request);
expect(result).toEqual({
@@ -152,8 +204,7 @@ it('returns a safe read failure when the saved body cannot be read', async () =>
});
expect(readAccountPage).toHaveBeenCalledExactlyOnceWith(publication, id, {
order: 'desc',
offset: 0,
limit: 50
offset: 0
});
expect(projectActivityPage).not.toHaveBeenCalled();
expect(queue).not.toHaveBeenCalled();
@@ -164,8 +215,7 @@ it('opens the newest recorded activity on the first descending page by default',
await load(event());
expect(readAccountPage).toHaveBeenCalledExactlyOnceWith(publication, id, {
order: 'desc',
offset: 0,
limit: 50
offset: 0
});
expect(projectActivityPage).toHaveBeenCalledExactlyOnceWith(firstPage);
});
@@ -173,8 +223,7 @@ it('opens the last page when ascending order is requested', async () => {
await load(event('order=asc'));
expect(readAccountPage).toHaveBeenCalledExactlyOnceWith(publication, id, {
order: 'asc',
offset: 50,
limit: 50
offset: 50
});
expect(projectActivityPage).toHaveBeenCalledExactlyOnceWith(accountPage);
});
@@ -183,33 +232,30 @@ it('rejects a disabled register before IO', async () => {
expect(readReportPublication).not.toHaveBeenCalled();
expect(readAccountPage).not.toHaveBeenCalled();
});
it('does not read or project ambiguous or empty account activity', async () => {
it('does not read or project activity for an ambiguous account', async () => {
vi.mocked(readReportPublication).mockResolvedValue({
...publication,
accounts: [{ id, name, access: 'ambiguous', rowCount: null, summary: { status: 'ambiguous' } }]
});
expect(await load(event())).toMatchObject({
expect(await load(event('focus=1'))).toMatchObject({
readFailed: false,
access: 'ambiguous',
rows: [],
rowCount: null,
endingBalance: null
});
expect(readAccountPage).not.toHaveBeenCalled();
expect(readFocusedAccountPage).not.toHaveBeenCalled();
expect(projectActivityPage).not.toHaveBeenCalled();
});
it('reports unreadable activity even if the catalog says the account is empty', async () => {
vi.mocked(readReportPublication).mockResolvedValue({
...publication,
accounts: [{ id, name, access: 'ready', rowCount: 0, summary: { status: 'undated' } }]
});
expect(await load(event())).toMatchObject({
readFailed: false,
access: 'ready',
rows: [],
rowCount: 0,
page: 1,
pageCount: 1,
endingBalance: []
});
expect(readAccountPage).not.toHaveBeenCalled();
expect(projectActivityPage).not.toHaveBeenCalled();
vi.mocked(readAccountPage).mockRejectedValue(new Error('Unable to read account transactions'));
expect(await load(event())).toMatchObject({ readFailed: true, rows: [], endingBalance: null });
});
it('rejects an unknown member before reading activity', async () => {
const request = event();
@@ -229,14 +275,8 @@ it('rejects a wrong-kind member before reading its body', async () => {
expect(readReportPublication).toHaveBeenCalledTimes(1);
expect(readAccountPage).not.toHaveBeenCalled();
});
it('rejects invalid page syntax before IO and out-of-range pages before body reads', async () => {
await expect(load(event('page=0'))).rejects.toMatchObject({ status: 400 });
await expect(load(event('order=sideways'))).rejects.toMatchObject({ status: 400 });
await expect(load(event('page=1&page=2'))).rejects.toMatchObject({ status: 400 });
await expect(load(event('source=PRIVATE'))).rejects.toMatchObject({ status: 400 });
expect(readReportPublication).not.toHaveBeenCalled();
it('rejects an out-of-range page before reading activity', async () => {
await expect(load(event('page=3'))).rejects.toMatchObject({ status: 404 });
expect(readReportPublication).toHaveBeenCalledTimes(1);
expect(readReportPublication).toHaveBeenCalled();
expect(readAccountPage).not.toHaveBeenCalled();
expect(projectActivityPage).not.toHaveBeenCalled();
});
@@ -1,9 +1,9 @@
import { parseRegisterPageRequest } from '#lib/registers/investment/register-page-request.js';
import { parseRegisterPageRequest } from '#lib/registers/register-page-request.js';
import { loadRegisterPage } from '#lib/server/registers/investment/register.js';
import type { PageServerLoad } from './$types';
export const load = (async (event) => {
event.setHeaders({ 'cache-control': 'no-store' });
const request = parseRegisterPageRequest(event.params.accountId, event.url.searchParams);
const request = parseRegisterPageRequest(event.params.accountId, event.url.searchParams, 'asc');
return loadRegisterPage(event, request);
}) satisfies PageServerLoad;
@@ -1,6 +1,7 @@
<script lang="ts">
import { resolve } from '$app/paths';
import InvestmentRegister from '#lib/registers/investment/InvestmentRegister.svelte';
import RegisterFocusNotice from '#lib/registers/RegisterFocusNotice.svelte';
import { accountLabel } from '#lib/accounts.js';
import { formatAmount } from '#lib/amounts.js';
import type { PageData } from './$types';
@@ -68,6 +69,7 @@
are shown.
</p>
{:else if register}
<RegisterFocusNotice missingTransactionIndex={data.missingFocusTransactionIndex} />
{#key data}
<InvestmentRegister data={register} labels={data.accountLabels} />
{/key}
@@ -4,10 +4,12 @@ import { testConfig } from '#lib/server/application.fixture.js';
import { beforeEach, expect, it, vi } from 'vitest';
import {
readReportPublication,
countInvestmentActivities,
readInvestmentActivityCount,
readInvestmentActivityPage,
readFocusedInvestmentActivityPage,
type AccountInvestmentActivityPage
} from '@hledger-reports/snapshots';
import { investmentRegisterFixture } from '#lib/registers/investment/investment-register.fixture.js';
import type { ApplicationContext } from '#lib/server/application.js';
import { projectInvestmentActivityPage } from '#lib/server/registers/investment/projection.js';
import { savedReportFixture } from '#lib/server/reports.fixture.js';
@@ -15,8 +17,9 @@ import { load } from './+page.server.js';
vi.mock('@hledger-reports/snapshots', () => ({
readReportPublication: vi.fn(),
countInvestmentActivities: vi.fn(),
readInvestmentActivityPage: vi.fn()
readInvestmentActivityCount: vi.fn(),
readInvestmentActivityPage: vi.fn(),
readFocusedInvestmentActivityPage: vi.fn()
}));
vi.mock('#lib/server/registers/investment/projection.js', () => ({
projectInvestmentActivityPage: vi.fn()
@@ -31,9 +34,11 @@ const publication = savedReportFixture({
accounts: [{ id, name, access: 'ready', rowCount: 1, summary: { status: 'undated' } }]
});
const activityPage: AccountInvestmentActivityPage = {
activityCount: 51,
rows: preparedAccountRows().map((row) => ({
row,
postingIndex: 0,
displayDate: row.transaction.postings[0].date ?? row.transaction.date,
entryActivityPosition: 1,
entryActivityCount: 1
})),
@@ -84,13 +89,13 @@ function event(
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(readReportPublication).mockResolvedValue(publication);
vi.mocked(countInvestmentActivities).mockResolvedValue(51);
vi.mocked(readInvestmentActivityCount).mockResolvedValue(51);
vi.mocked(readInvestmentActivityPage).mockResolvedValue(activityPage);
vi.mocked(projectInvestmentActivityPage).mockReturnValue(projection);
});
it('counts and pages original activities in one publication, not the enclosing transaction count', async () => {
vi.mocked(countInvestmentActivities).mockImplementation(async (pinned) => {
it('pages by the saved posting count in one publication, not the enclosing entry count', async () => {
vi.mocked(readInvestmentActivityCount).mockImplementation(async (pinned) => {
expect(pinned).toBe(publication);
vi.mocked(readReportPublication).mockResolvedValue(null);
return 51;
@@ -113,35 +118,83 @@ it('counts and pages original activities in one publication, not the enclosing t
}
});
expect(readReportPublication).toHaveBeenCalledOnce();
expect(countInvestmentActivities).toHaveBeenCalledExactlyOnceWith(publication, id);
expect(readInvestmentActivityCount).toHaveBeenCalledExactlyOnceWith(publication, id);
expect(readInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(publication, id, {
order: 'desc',
offset: 50,
limit: 50
offset: 50
});
expect(projectInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(activityPage, name);
expect(request.setHeaders).toHaveBeenCalledWith({ 'cache-control': 'no-store' });
});
it.each(['count', 'page'] as const)(
it('marks only the located posting on the saved containing page', async () => {
const [firstBuy, secondBuy, otherActivity] = investmentRegisterFixture().activities;
const focusedPage = { ...activityPage, activityCount: 53, pageNumber: 2, indexOnPage: 1 };
vi.mocked(readFocusedInvestmentActivityPage).mockResolvedValue(focusedPage);
vi.mocked(projectInvestmentActivityPage).mockReturnValue({
...projection,
activities: [otherActivity, firstBuy, secondBuy]
});
const result = await load(event('order=desc&focus=1'));
expect(readFocusedInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(
publication,
id,
1,
'desc'
);
expect(readInvestmentActivityCount).not.toHaveBeenCalled();
expect(result.register).toMatchObject({
page: 2,
pageCount: 2,
activityCount: 53,
order: 'desc'
});
expect(result.register?.activities.filter((activity) => activity.isFocusTarget)).toEqual([
{ ...firstBuy, isFocusTarget: true }
]);
});
it('returns the ordinary Investment page and missing index when the target is absent', async () => {
vi.mocked(readFocusedInvestmentActivityPage).mockResolvedValue(null);
const result = await load(event('focus=99'));
expect(readInvestmentActivityPage).toHaveBeenCalledWith(publication, id, {
order: 'asc',
offset: 50
});
expect(result).toMatchObject({
readFailed: false,
missingFocusTransactionIndex: 99,
register: { page: 2, order: 'asc', ...projection }
});
});
it.each(['count', 'fallback page', 'focus'] as const)(
'returns a safe read failure when the saved %s cannot be read',
async (operation) => {
if (operation === 'count')
vi.mocked(countInvestmentActivities).mockRejectedValue(
new Error('PRIVATE native count diagnostic')
vi.mocked(readInvestmentActivityCount).mockRejectedValue(
new Error('PRIVATE saved count diagnostic')
);
else
else if (operation === 'fallback page') {
vi.mocked(readFocusedInvestmentActivityPage).mockResolvedValue(null);
vi.mocked(readInvestmentActivityPage).mockRejectedValue(
new Error('PRIVATE saved body diagnostic')
);
const request = event();
} else
vi.mocked(readFocusedInvestmentActivityPage).mockRejectedValue(
new Error('PRIVATE focused page diagnostic')
);
const request = event(operation === 'count' ? '' : 'focus=1');
const queue = vi.spyOn(request.locals.application!, 'jobsClient', 'get');
expect(await load(request)).toMatchObject({
const result = await load(request);
expect(result).toMatchObject({
readFailed: true,
accountName: name,
access: 'ready',
register: null
});
expect(result).not.toHaveProperty('missingFocusTransactionIndex');
expect(JSON.stringify(result)).not.toContain('PRIVATE');
expect(projectInvestmentActivityPage).not.toHaveBeenCalled();
expect(queue).not.toHaveBeenCalled();
}
@@ -151,14 +204,12 @@ it('defaults descending to the first activity page and ascending to the last', a
await load(event('order=desc'));
expect(readInvestmentActivityPage).toHaveBeenLastCalledWith(publication, id, {
order: 'desc',
offset: 0,
limit: 50
offset: 0
});
await load(event());
expect(readInvestmentActivityPage).toHaveBeenLastCalledWith(publication, id, {
order: 'asc',
offset: 50,
limit: 50
offset: 50
});
});
@@ -172,20 +223,29 @@ it('rejects disabled and wrong-kind members without activity reads', async () =>
])
)
).rejects.toMatchObject({ status: 404 });
expect(countInvestmentActivities).not.toHaveBeenCalled();
expect(readInvestmentActivityCount).not.toHaveBeenCalled();
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
});
it('does not count, read or project ambiguous or declared-empty accounts', async () => {
it('does not count or read activity for an ambiguous account', async () => {
vi.mocked(readReportPublication).mockResolvedValue({
...publication,
accounts: [{ id, name, access: 'ambiguous', rowCount: null, summary: { status: 'ambiguous' } }]
});
expect(await load(event())).toMatchObject({ access: 'ambiguous', register: null });
const result = await load(event('focus=1'));
expect(result).toMatchObject({ access: 'ambiguous', register: null });
expect(result).not.toHaveProperty('missingFocusTransactionIndex');
expect(readFocusedInvestmentActivityPage).not.toHaveBeenCalled();
expect(readInvestmentActivityCount).not.toHaveBeenCalled();
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
});
it('uses the saved posting count for a readable empty account', async () => {
vi.mocked(readReportPublication).mockResolvedValue({
...publication,
accounts: [{ id, name, access: 'ready', rowCount: 0, summary: { status: 'undated' } }]
});
vi.mocked(readInvestmentActivityCount).mockResolvedValue(0);
expect(await load(event())).toMatchObject({
readFailed: false,
register: {
@@ -197,7 +257,7 @@ it('does not count, read or project ambiguous or declared-empty accounts', async
unclassifiedEndingCash: []
}
});
expect(countInvestmentActivities).not.toHaveBeenCalled();
expect(readInvestmentActivityCount).toHaveBeenCalledOnce();
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
expect(projectInvestmentActivityPage).not.toHaveBeenCalled();
});
@@ -206,13 +266,13 @@ it('rejects unknown accounts before activity IO', async () => {
const request = event();
request.params.accountId = 'unknown1';
await expect(load(request)).rejects.toMatchObject({ status: 404 });
expect(countInvestmentActivities).not.toHaveBeenCalled();
expect(readInvestmentActivityCount).not.toHaveBeenCalled();
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
});
it('rejects pages outside the activity count before reading canonical activity bodies', async () => {
await expect(load(event('page=3'))).rejects.toMatchObject({ status: 404 });
expect(countInvestmentActivities).toHaveBeenCalledOnce();
expect(readInvestmentActivityCount).toHaveBeenCalledOnce();
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
});
@@ -232,17 +292,16 @@ it('waits for the parent layout before using the request-pinned publication', as
expect(await Promise.race([loading, nextTurn])).toBe(pending);
expect(parent).toHaveBeenCalledOnce();
expect(readReportPublication).not.toHaveBeenCalled();
expect(countInvestmentActivities).not.toHaveBeenCalled();
expect(readInvestmentActivityCount).not.toHaveBeenCalled();
} finally {
releaseParent.resolve();
await loading;
}
expect(readReportPublication).not.toHaveBeenCalled();
expect(countInvestmentActivities).toHaveBeenCalledExactlyOnceWith(publication, id);
expect(readInvestmentActivityCount).toHaveBeenCalledExactlyOnceWith(publication, id);
expect(readInvestmentActivityPage).toHaveBeenCalledExactlyOnceWith(publication, id, {
order: 'asc',
offset: 50,
limit: 50
offset: 50
});
});
@@ -252,7 +311,7 @@ it('requires an application without reading reports or parent data', async () =>
await expect(load(request)).rejects.toMatchObject({ status: 503 });
expect(request.parent).not.toHaveBeenCalled();
expect(readReportPublication).not.toHaveBeenCalled();
expect(countInvestmentActivities).not.toHaveBeenCalled();
expect(readInvestmentActivityCount).not.toHaveBeenCalled();
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
});
@@ -263,7 +322,7 @@ it.each(['missing', 'unreadable', 'journal-changed'] as const)(
request.locals.savedReports = Promise.resolve({ status });
await expect(load(request)).rejects.toMatchObject({ status: 503 });
expect(readReportPublication).not.toHaveBeenCalled();
expect(countInvestmentActivities).not.toHaveBeenCalled();
expect(readInvestmentActivityCount).not.toHaveBeenCalled();
expect(readInvestmentActivityPage).not.toHaveBeenCalled();
}
);
@@ -0,0 +1,9 @@
<script lang="ts">
import SkipToContent from '#lib/navigation/SkipToContent.svelte';
import type { LayoutProps } from './$types';
let { children }: Pick<LayoutProps, 'children'> = $props();
</script>
<SkipToContent />
{@render children()}
+29
View File
@@ -0,0 +1,29 @@
<script lang="ts">
import { page } from '$app/state';
</script>
<svelte:head>
<title>{page.status} — hledger reports</title>
</svelte:head>
<main id="main" tabindex="-1">
<div class="message">
<h1 class="page-title">{page.status}</h1>
<p>{page.error?.message}</p>
</div>
</main>
<style>
main {
display: grid;
place-items: center;
min-height: 100vh;
min-height: 100dvh;
padding: var(--space-medium);
text-align: center;
}
.message {
max-inline-size: var(--content-width);
overflow-wrap: anywhere;
}
</style>
-15
View File
@@ -27,7 +27,6 @@
</svelte:head>
<div class="workspace">
<a class="skip-link" href="#main">Skip to content</a>
{@render children()}
</div>
@@ -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);
}
</style>
@@ -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);
+5
View File
@@ -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",
+3 -1
View File
@@ -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<ReportDatabase>): Promise<void> {
@@ -21,7 +22,8 @@ export async function runMigrations(database: Kysely<ReportDatabase>): Promise<v
'004_native_transactions': nativeTransactions,
'005_shared_account_transactions': sharedAccountTransactions,
'006_transaction_dates': transactionDates,
'007_single_saved_report': singleSavedReport
'007_single_saved_report': singleSavedReport,
'008_prepared_register_rows': preparedRegisterRows
};
}
}
@@ -0,0 +1,42 @@
import { sql, type Kysely } from 'kysely';
import type { ReportDatabase } from '../schema.js';
export async function up(database: Kysely<ReportDatabase>): Promise<void> {
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);
}
+1
View File
@@ -0,0 +1 @@
export const registerPageSize = 50;
+8 -7
View File
@@ -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';
@@ -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<ReportDatabase>,
accountName: string,
expectedEntryCount: number
): Promise<void> {
const counts = await readPostingReferenceCounts(database, accountName);
validatePostingReferenceCounts(counts, expectedEntryCount);
}
async function readPostingReferenceCounts(
database: Kysely<ReportDatabase>,
accountName: string
): Promise<PostingReferenceCounts> {
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<PostingReferenceCounts>`
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
)
)`;
}
@@ -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<ReportDatabase>,
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<ReportDatabase>,
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.');
}
+420 -166
View File
@@ -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.');
});
+175 -210
View File
@@ -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<ReportDatabase>,
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<ReportDatabase>,
accountName: string,
totalAccountEntryCount: number,
pageAccountOrdinals: readonly number[]
): Promise<Map<number, PreparedAccountRow>> {
const entriesByAccountOrdinal = new Map<number, PreparedAccountRow>();
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<ReportDatabase>,
account: StoredAccount,
options: AccountActivityPageOptions
pageOrder: RegisterPageOptions['order'],
pageOffset: number
): Promise<AccountActivityPage | null> {
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<ReportDatabase>,
account: StoredAccount,
rowCount: number
): Promise<number> {
// 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<ReportDatabase>,
account: StoredAccount
): Promise<number | null> {
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<ReturnType<typeof readRegisterRowReferencePage>>[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<ReportDatabase>,
account: StoredAccount,
options: AccountActivityPageOptions
options: RegisterPageOptions
): Promise<AccountInvestmentActivityPage | null> {
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<number, PreparedAccountRow>();
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<string>();
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 };
}
+13 -1
View File
@@ -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;
+5
View File
@@ -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": [
+8 -3
View File
@@ -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 {
+1
View File
@@ -0,0 +1 @@
export { registerPageSize } from '@hledger-reports/db/register-page';
@@ -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(
+93 -8
View File
@@ -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<void>;
@@ -182,21 +191,56 @@ async function readFromSelectedPublication<Result>(
export async function readAccountPage(
publication: ReportPublication,
id: string,
options: AccountActivityPageOptions
options: RegisterPageOptions
): Promise<AccountActivityPage | null> {
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<FocusedAccountActivityPage | 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,
'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<number | null> {
@@ -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<AccountInvestmentActivityPage | null> {
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<T>(action: () => Promise<T>): Promise<T> {
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(