From a62b1f16d291a1ff302f617d64c9b5c2258efd98 Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 04:24:12 +0700 Subject: [PATCH 1/4] [AI] test(currency): assert report charts, crossover, exports and Monte Carlo pots across two clients (CHE-1197) --- .../e2e/currency-sync-helpers.ts | 340 ++++++++++++++ .../e2e/currency-sync-monte-carlo.test.ts | 388 ++++++++++++++++ .../e2e/currency-sync-reports.test.ts | 416 ++++++++++++++++++ .../desktop-client/e2e/currency-sync.test.ts | 241 ++-------- ...e-1197-currency-report-browser-coverage.md | 6 + 5 files changed, 1178 insertions(+), 213 deletions(-) create mode 100644 packages/desktop-client/e2e/currency-sync-helpers.ts create mode 100644 packages/desktop-client/e2e/currency-sync-monte-carlo.test.ts create mode 100644 packages/desktop-client/e2e/currency-sync-reports.test.ts create mode 100644 upcoming-release-notes/che-1197-currency-report-browser-coverage.md diff --git a/packages/desktop-client/e2e/currency-sync-helpers.ts b/packages/desktop-client/e2e/currency-sync-helpers.ts new file mode 100644 index 00000000000..417da2c3b18 --- /dev/null +++ b/packages/desktop-client/e2e/currency-sync-helpers.ts @@ -0,0 +1,340 @@ +import { createHash } from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; + +import type { Browser, Page } from '@playwright/test'; + +import { expect } from './fixtures'; +import { BudgetPage } from './page-models/budget-page'; +import { ConfigurationPage } from './page-models/configuration-page'; + +// Shared by the two-client currency journeys (currency-sync*.test.ts). +// Two isolated browser clients run against a disposable local sync server: +// E2E_SYNC_SERVER_URL=http://127.0.0.1: (a fresh ACTUAL_DATA_DIR) +// E2E_EVIDENCE_DIR= optional: screenshots and observed values +export const SERVER_URL = process.env.E2E_SYNC_SERVER_URL; +export const EVIDENCE_DIR = process.env.E2E_EVIDENCE_DIR; +export const PASSWORD = 'che-1024-disposable'; +export const RATE_HOSTS = /frankfurter|coingecko/; + +// Test mode pins the app clock: every date below is January 2017. +export const MONTH = '2017-01'; +export const EURO_NATIVE = 80; // 100.00 EUR deposit, 20.00 EUR expense +export const POINTS_NATIVE = 1000; // 1,000 pt, a decimals-0 custom unit + +export type TestWindow = Window & { + $send: (method: string, args?: Record) => Promise; + $query: (query: unknown) => Promise<{ data: unknown[] }>; + $q: (table: string) => { + select: (fields: string[]) => unknown; + }; + __navigate: (url: string) => void; + __actionsForMenu: { + saveSyncedPrefs: (payload: { + prefs: Record; + }) => Promise; + downloadBudget: (payload: { cloudFileId: string }) => Promise; + }; +}; + +export type Json = Record; + +// The dev server may reload every open page once when a lazily imported +// dependency is first optimised; wait for the app globals to come back. +export async function appReady(page: Page) { + await page.waitForFunction( + () => + typeof (window as TestWindow).$q === 'function' && + typeof (window as TestWindow).__navigate === 'function', + undefined, + { timeout: 30_000 }, + ); +} + +export async function send( + page: Page, + method: string, + args?: Record, +) { + await appReady(page); + return page.evaluate( + ([name, params]) => + (window as TestWindow).$send(name, params as Record), + [method, args] as const, + ) as Promise; +} + +export async function savePrefs(page: Page, prefs: Record) { + await page.evaluate(async values => { + await (window as TestWindow).__actionsForMenu.saveSyncedPrefs({ + prefs: values, + }); + }, prefs); +} + +export async function connect(page: Page) { + await send(page, 'set-server-url', { url: SERVER_URL }); + // Already bootstrapped by the first client: that error is expected. + await send(page, 'subscribe-bootstrap', { password: PASSWORD }); + const signIn = await send<{ error?: string }>(page, 'subscribe-sign-in', { + password: PASSWORD, + }); + expect(signIn.error).toBeUndefined(); +} + +// Pushes this client's changes and pulls the other client's. fullSync is +// single-flight: a call made while an automatic sync runs joins it and may +// miss the newest change, so the second call guarantees one full round trip. +export async function sync(page: Page) { + for (let round = 0; round < 2; round++) { + const result = await send<{ error?: unknown } | undefined>(page, 'sync'); + expect(result?.error).toBeUndefined(); + } +} + +export async function shoot(page: Page, name: string) { + if (EVIDENCE_DIR) { + fs.mkdirSync(EVIDENCE_DIR, { recursive: true }); + await page.screenshot({ path: path.join(EVIDENCE_DIR, `${name}.png`) }); + } +} + +export const BIDI = /[‪-‮⁦-⁩]/g; + +// Rendered text of the whole app, one ' | ' per line break, without the +// bidi marks the currency formatter wraps amounts in. +export async function pageText(page: Page) { + const raw = await page + .evaluate(() => document.body.innerText) + // A page that is reloading has no text yet: the poll tries again. + .catch(() => ''); + return raw + .replace(BIDI, '') + .replace(/[\u00a0\u202f]/g, ' ') + .replace(/\s*\n+\s*/g, ' | '); +} + +// Right after a prefs sync the router can briefly drop flag-gated routes and +// bounce to /budget, so navigate until the app stays on the requested route. +export async function open(page: Page, route: string) { + await expect + .poll( + async () => { + await appReady(page); + const path = await page.evaluate(() => window.location.pathname); + if (path !== route) { + await page.evaluate( + url => (window as TestWindow).__navigate(url), + route, + ); + await page.waitForTimeout(250); + } + return page.evaluate(() => window.location.pathname); + }, + { message: `open ${route}`, timeout: 30_000 }, + ) + .toBe(route); +} + +export function grab(t: string, re: RegExp): string[] | { unmatched: string } { + const match = re.exec(t); + if (match) { + return match.slice(1); + } + const start = t.indexOf(' | Help | '); + return { unmatched: t.slice(start < 0 ? 0 : start + 10, start + 600) }; +} + +export const sidebarOf = (t: string) => + t.slice(t.indexOf('All accounts'), t.indexOf(' | Add account')); + +export const USD = '(-?\\+?\\$[\\d,]+\\.\\d\\d)'; +export const NOTE = + 'Values in USD\\. Foreign-currency history is an estimate at current rates\\.'; + +export const round2 = (n: number) => Math.round(n * 100) / 100; +export const usd = (n: number) => + `${n < 0 ? '-' : ''}$${Math.abs(n).toLocaleString('en-US', { + minimumFractionDigits: 2, + maximumFractionDigits: 2, + })}`; + +export type Rates = { eur: number; points: number }; + +// Everything a rate pair implies, in Main (USD). On-budget Checking is 500.00 +// income and a 150.00 Rent expense; the foreign accounts are off budget. +export function derive({ eur, points }: Rates) { + const euroNet = round2(EURO_NATIVE * eur); + const euroDeposit = round2(100 * eur); + const euroPayment = round2(-20 * eur); + const pointsNet = round2(POINTS_NATIVE * points); + const off = round2(euroNet + pointsNet); + const all = round2(350 + off); + return { euroNet, euroDeposit, euroPayment, pointsNet, off, all }; +} + +// Disposable fixture on client A: an on-budget USD Checking account (500.00 +// income, a 150.00 Rent expense), an off-budget EUR account and an off-budget +// custom-unit account, a Rent budget of 200.00, all dated January 2017. +export async function createFixture(page: Page) { + return page.evaluate(async m => { + const w = window as TestWindow; + const euro = (await w.$send('account-create', { + name: 'Euro savings', + balance: 100, + offBudget: true, + currency: 'EUR', + })) as string; + const points = (await w.$send('account-create', { + name: 'Loyalty points', + balance: 1000, + offBudget: true, + currency: 'X-POINTS', + })) as string; + const checking = (await w.$send('account-create', { + name: 'Checking', + balance: 500, + offBudget: false, + currency: 'USD', + })) as string; + const groupId = await w.$send('category-group-create', { + name: 'Bills', + }); + const categoryId = (await w.$send('category-create', { + name: 'Rent', + groupId, + })) as string; + const date = `${m}-01`; + await w.$send('transactions-batch-update', { + added: [ + // Aligned with the budget month: spent -150.00 of 200.00. + { + id: w.crypto.randomUUID(), + account: checking, + date, + amount: -15000, + category: categoryId, + }, + { id: w.crypto.randomUUID(), account: euro, date, amount: -2000 }, + ], + }); + await w.$send('budget/budget-amount', { + month: m, + category: categoryId, + amount: 20000, + }); + const pages = (await w.$query(w.$q('dashboard_pages').select(['id']))) + .data as Array<{ id: string }>; + return { euro, points, checking, categoryId, dashboardId: pages[0].id }; + }, MONTH); +} + +export type Fixture = Awaited>; + +export type TwoClients = { + a: Page; + b: Page; + fixture: Fixture; + accountIds: string[]; + rateRequests: string[]; + close: () => Promise; +}; + +// Client A builds the disposable budget and uploads it; client B downloads it +// through the same sync server. browser.newPage() gives each client its own +// storage, so they are two devices. Only the external rate hosts are routed, +// and aborted: no rate is ever fetched. The app calendar is pinned to +// 2017-01-01 by the Playwright user agent (loot-core months.ts), which is what +// makes day-dependent cards deterministic. (page.clock.setFixedTime was tried +// and rejected: with it the dashboard never leaves "Loading reports...".) +export async function bootTwoClients( + browser: Browser, + options: { flags?: Record } = {}, +): Promise { + const a = await browser.newPage(); + const b = await browser.newPage(); + const rateRequests: string[] = []; + for (const page of [a, b]) { + await page.route(RATE_HOSTS, route => { + rateRequests.push(route.request().url()); + return route.abort(); + }); + } + await a.goto('/'); + await new ConfigurationPage(a).startFresh(); + await new ConfigurationPage(a).initializeTestMainCurrency(); + await savePrefs(a, { + 'flags.newSidebarUI': 'false', + hideFraction: 'false', + ...options.flags, + }); + const fixture = await createFixture(a); + await a.reload(); + await new BudgetPage(a).waitFor({ timeout: 90_000 }); + + await connect(a); + const upload = await send<{ error?: unknown }>(a, 'upload-budget'); + expect(upload.error).toBeUndefined(); + const enable = await send<{ error?: unknown }>(a, 'sync-budget'); + expect(enable.error).toBeUndefined(); + const [localBudget] = await send>( + a, + 'get-budgets', + ); + expect(localBudget.cloudFileId).toBeTruthy(); + await b.goto('/'); + await connect(b); + await b.evaluate( + id => + (window as TestWindow).__actionsForMenu.downloadBudget({ + cloudFileId: id, + }), + localBudget.cloudFileId as string, + ); + await new BudgetPage(b).waitFor({ timeout: 90_000 }); + + return { + a, + b, + fixture, + accountIds: [fixture.checking, fixture.euro, fixture.points], + rateRequests, + close: async () => { + await a.close(); + await b.close(); + }, + }; +} + +// What this run says about itself, written at run time. The git and tree ids +// come from the pre-run record through the environment; the source hashes are +// computed here from the files that actually executed. +export function runSelfDescription(files: string[]) { + const hash = (file: string) => + createHash('sha256') + .update(fs.readFileSync(path.join(__dirname, file))) + .digest('hex'); + return { + startedAt: new Date().toISOString(), + gitSha: process.env.E2E_GIT_SHA ?? null, + treeSha: process.env.E2E_TREE_SHA ?? null, + appUrl: process.env.E2E_START_URL ?? null, + syncServerUrl: SERVER_URL ?? null, + node: process.version, + sources: Object.fromEntries( + [...files, 'currency-sync-helpers.ts'].map(file => [file, hash(file)]), + ), + }; +} + +export function writeObserved(file: string, value: unknown) { + if (EVIDENCE_DIR) { + fs.mkdirSync(EVIDENCE_DIR, { recursive: true }); + fs.writeFileSync( + path.join(EVIDENCE_DIR, file), + JSON.stringify(value, null, 2), + ); + } +} + +process.stderr.write(`[step ${new Date().toISOString()}] ${m}\n`); diff --git a/packages/desktop-client/e2e/currency-sync-monte-carlo.test.ts b/packages/desktop-client/e2e/currency-sync-monte-carlo.test.ts new file mode 100644 index 00000000000..c0f86522541 --- /dev/null +++ b/packages/desktop-client/e2e/currency-sync-monte-carlo.test.ts @@ -0,0 +1,388 @@ +import type { Page } from '@playwright/test'; + +import { + BIDI, + SERVER_URL, + bootTwoClients, + open, + pageText, + runSelfDescription, + savePrefs, + send, + shoot, + sync, + writeObserved, +} from './currency-sync-helpers'; +import type { Json, TestWindow } from './currency-sync-helpers'; +import { expect, test } from './fixtures'; +import { BudgetPage } from './page-models/budget-page'; + +// CHE-1197: Monte Carlo on the accumulated candidate, on the real two-client / +// disposable-sync-server design. Client A writes widgets, rates and an account +// deletion; client B reads. Mixed-currency linked pots (EUR, a custom unit and +// USD) must show their balances converted to Main, and a missing rate or a +// deleted linked account must show "Unavailable" - never zero - on the pot +// table, the page and the dashboard card. The simulation is seeded, so the +// same Main balances give identical results whether pots are linked or +// entered by hand: that pins the simulation semantics. No Monte Carlo VRT +// baseline exists; this uses browser assertions and saved screenshots only. +const observed: Record = {}; + +const UNAVAILABLE = + 'Unavailable: a linked account balance cannot be converted to USD. Add an exchange rate in Settings or unlink the pot.'; +const BASE = { + currentAge: 60, + targetAge: 70, + simulationCount: 1000, + spendingPhases: [{ id: 'phase-1', name: 'Phase 1', annualWithdrawal: 4500 }], +}; + +// Stored native balances: 80.00 EUR, 1,000 pt (scale 100), 350.00 USD. +const NATIVE = { euro: 8000, points: 100000, checking: 35000 }; +const mainCents = (eur: number, points: number) => ({ + euro: Math.round(NATIVE.euro * eur), + points: Math.round(NATIVE.points * points), + checking: NATIVE.checking, +}); +const dollars = (cents: number) => + `$${(cents / 100).toLocaleString('en-US', { minimumFractionDigits: 2 })}`; + +const clean = (text: string) => text.replace(BIDI, ''); + +async function widgets(page: Page) { + return page.evaluate(async () => { + const w = window as unknown as TestWindow; + return (await w.$query(w.$q('dashboard').select(['id', 'type', 'meta']))) + .data as Array<{ id: string; type: string; meta: Json }>; + }); +} + +// Results block of the page (success, medians, depletion) as one string. +async function readResults(page: Page) { + await expect + .poll(async () => pageText(page), { timeout: 60_000 }) + .toContain('SUCCESS RATE'); + const text = clean(await pageText(page)); + const from = text.indexOf('SUCCESS RATE'); + return text.slice(from, text.indexOf(' | Portfolio performance', from)); +} + +// Starting balance cell of every pot: a $ amount, or "Unavailable". +async function readPots(page: Page) { + await page.getByText('Investment pots', { exact: true }).first().click(); + await expect(page.getByText('Pot name')).toBeVisible(); + const cells = await page.evaluate(() => + Array.from(document.querySelectorAll('input')).map(input => ({ + label: input.getAttribute('aria-label') ?? '', + value: input.value, + })), + ); + const pots: Record = {}; + let name = ''; + for (const [i, cell] of cells.entries()) { + const value = clean(cell.value); + if (cell.label || cell.value === 'on') { + continue; + } + if (value.startsWith('$')) { + pots[name] = value; + } else { + name = value; + pots[name] = cells[i + 1]?.label ? 'Unavailable' : '?'; + } + } + return pots; +} + +test.describe('Monte Carlo linked pots across two clients', () => { + test.skip(!SERVER_URL, 'needs E2E_SYNC_SERVER_URL (disposable server)'); + test.use({ actionTimeout: 20_000 }); + + test('mixed-currency pots convert to Main and report unavailable, never zero', async ({ + browser, + }) => { + test.setTimeout(900_000); + observed.run = runSelfDescription(['currency-sync-monte-carlo.test.ts']); + const c = await bootTwoClients(browser, { + flags: { 'flags.monteCarloReport': 'true' }, + }); + const { a: author, b: reader, fixture } = c; + const id: Record = {}; + + const linkedPots = [ + { id: 'pot-eur', name: 'Euro pot', accountId: fixture.euro }, + { id: 'pot-pts', name: 'Points pot', accountId: fixture.points }, + { id: 'pot-chk', name: 'Checking pot', accountId: fixture.checking }, + ]; + const twinPots = (eur: number, points: number) => { + const cents = mainCents(eur, points); + return [ + { id: 'pot-eur', name: 'Euro pot', startingBalance: cents.euro }, + { id: 'pot-pts', name: 'Points pot', startingBalance: cents.points }, + { + id: 'pot-chk', + name: 'Checking pot', + startingBalance: cents.checking, + }, + ]; + }; + + // The widget list is cached per page load: a reload picks up edits that + // arrived over sync. + async function reloadReader() { + await open(reader, '/budget'); + await reader.reload(); + await new BudgetPage(reader).waitFor({ timeout: 90_000 }); + } + + async function openPage(widgetId: string) { + await open(reader, `/reports/monte-carlo/${widgetId}`); + await expect + .poll(async () => pageText(reader), { timeout: 60_000 }) + .toContain('Configuration'); + } + + // The dashboard card of one widget: a success percentage, or the notice. + async function readCard(name: string) { + await reloadReader(); + await open(reader, `/reports/${fixture.dashboardId}`); + // Cards far below the fold are not rendered until scrolled into view. + await expect + .poll( + async () => { + await reader.evaluate(() => + document.querySelectorAll('div').forEach(el => { + if (el.scrollHeight > el.clientHeight + 50) { + el.scrollTop = el.scrollHeight; + } + }), + ); + await reader.waitForTimeout(300); + return clean(await pageText(reader)); + }, + { timeout: 60_000 }, + ) + .toContain(name); + const text = clean(await pageText(reader)); + return text.slice(text.indexOf(name), text.indexOf(name) + 260); + } + + async function persisted(widgetId: string) { + const rows = await widgets(reader); + return rows.find(row => row.id === widgetId)?.meta as Json; + } + + try { + await savePrefs(author, { + 'manualRate.EUR.USD': '1.1', + 'customUnit.X-POINTS': JSON.stringify({ + name: 'Points', + symbol: 'pt', + decimals: 0, + }), + 'manualRate.X-POINTS.USD': '0.01', + }); + const add = (meta: Json) => + send(author, 'dashboard-add-widget', { + type: 'monte-carlo-card', + width: 4, + height: 2, + meta, + dashboard_page_id: fixture.dashboardId, + }); + await add({ + ...BASE, + name: 'MC linked', + pots: linkedPots.map(p => ({ + ...p, + startingBalance: + NATIVE[ + p.id === 'pot-eur' + ? 'euro' + : p.id === 'pot-pts' + ? 'points' + : 'checking' + ], + })), + }); + await add({ ...BASE, name: 'MC manual', pots: twinPots(1.1, 0.01) }); + await add({ + ...BASE, + name: 'MC usd only', + pots: [ + { + id: 'pot-chk', + name: 'Checking pot', + startingBalance: NATIVE.checking, + accountId: fixture.checking, + }, + ], + }); + await sync(author); + await sync(reader); + for (const row of await widgets(reader)) { + if (row.type === 'monte-carlo-card') { + id[String((row.meta as Json).name)] = row.id; + } + } + expect(Object.keys(id).sort()).toEqual([ + 'MC linked', + 'MC manual', + 'MC usd only', + ]); + + // A state: pot table, page results and card, for linked, twin, USD. + async function expectState( + label: string, + eur: number, + points: number, + usdOnly: { results?: string }, + ) { + const cents = mainCents(eur, points); + await openPage(id['MC linked']); + const pots = await readPots(reader); + expect(pots, `${label}: linked pot balances`).toEqual({ + 'Euro pot': dollars(cents.euro), + 'Points pot': dollars(cents.points), + 'Checking pot': dollars(cents.checking), + }); + const linked = await readResults(reader); + await shoot(reader, `${label}-linked-page`); + + await openPage(id['MC manual']); + const manualPots = await readPots(reader); + expect(manualPots, `${label}: manual pot balances`).toEqual(pots); + const manual = await readResults(reader); + // Seeded simulation: Main-equivalent balances give identical results. + expect(linked, `${label}: linked == manual Main equivalent`).toBe( + manual, + ); + expect(linked).toMatch(/SUCCESS RATE \| \d+(\.\d)?% \| MEDIAN ENDING/); + + await openPage(id['MC usd only']); + const only = await readResults(reader); + if (usdOnly.results) { + expect(only, `${label}: Main-only pot unchanged`).toBe( + usdOnly.results, + ); + } + const percent = /SUCCESS RATE \| (\d+(?:\.\d)?%)/.exec(linked)?.[1]; + const card = await readCard('MC linked'); + expect(card, `${label}: card`).toContain( + `${percent} | Success rate to age 70`, + ); + observed[label] = { pots, linked, manual, only, card }; + return only; + } + + const s1 = await expectState('step1-eur-1.1', 1.1, 0.01, {}); + + // Saved native configuration: Save widget keeps native balances; a rate + // edit never rewrites them. + await openPage(id['MC linked']); + await reader.getByRole('button', { name: 'Save widget' }).click(); + await expect( + reader.getByText('Dashboard widget successfully saved.'), + ).toBeVisible(); + await sync(reader); + await sync(author); + const saved = await persisted(id['MC linked']); + const savedPots = (saved.pots as Array).map(p => [ + p.id, + p.startingBalance, + p.accountId, + ]); + expect(savedPots).toEqual([ + ['pot-eur', NATIVE.euro, fixture.euro], + ['pot-pts', NATIVE.points, fixture.points], + ['pot-chk', NATIVE.checking, fixture.checking], + ]); + expect(saved).toMatchObject(BASE); + observed.savedNative = saved; + + // Step 2: a rate update on A. Twin balances follow the new Main values. + await savePrefs(author, { + 'manualRate.EUR.USD': '1.25', + 'manualRate.X-POINTS.USD': '0.02', + }); + await send(author, 'dashboard-update-widget', { + id: id['MC manual'], + meta: { ...BASE, name: 'MC manual', pots: twinPots(1.25, 0.02) }, + }); + await sync(author); + await sync(reader); + await reloadReader(); + expect( + await persisted(id['MC linked']), + 'native config after rate edit', + ).toEqual(saved); + await expectState('step2-eur-1.25', 1.25, 0.02, { results: s1 }); + await openPage(id['MC linked']); + await reader.getByRole('button', { name: 'Save widget' }).click(); + await expect( + reader.getByText('Dashboard widget successfully saved.'), + ).toBeVisible(); + await sync(reader); + expect( + await persisted(id['MC linked']), + 'native config after re-save', + ).toEqual(saved); + + // Step 3: EUR rate removed. Euro pot, page and card are unavailable; + // the other pots still convert; the USD-only widget is untouched. + await savePrefs(reader, { 'manualRate.EUR.USD': '' }); + await sync(reader); + await sync(author); + await openPage(id['MC linked']); + const removedPots = await readPots(reader); + expect(removedPots).toEqual({ + 'Euro pot': 'Unavailable', + 'Points pot': dollars(mainCents(1.25, 0.02).points), + 'Checking pot': '$350.00', + }); + await expect + .poll(async () => clean(await pageText(reader))) + .toContain(UNAVAILABLE); + expect(clean(await pageText(reader))).not.toContain('SUCCESS RATE'); + await shoot(reader, 'step3-removed-page'); + expect(await readCard('MC linked')).toContain(UNAVAILABLE); + await openPage(id['MC usd only']); + expect(await readResults(reader)).toBe(s1); + observed['step3-eur-removed'] = { pots: removedPots }; + + // Step 4: EUR back at 1.2, then the linked Loyalty points account is + // deleted on A. Only that pot is unavailable. + await savePrefs(author, { 'manualRate.EUR.USD': '1.2' }); + await send(author, 'account-close', { + id: fixture.points, + forced: true, + }); + await sync(author); + await sync(reader); + await openPage(id['MC linked']); + const deletedPots = await readPots(reader); + expect(deletedPots).toEqual({ + 'Euro pot': dollars(mainCents(1.2, 0.02).euro), + 'Points pot': 'Unavailable', + 'Checking pot': '$350.00', + }); + const text = clean(await pageText(reader)); + expect(text).toContain(UNAVAILABLE); + expect(text).toContain('Unavailable account'); + expect(text).not.toContain('SUCCESS RATE'); + await shoot(reader, 'step4-deleted-account-page'); + expect(await readCard('MC linked')).toContain(UNAVAILABLE); + // The stored link and native balance are kept, not zeroed or rewritten. + expect(await persisted(id['MC linked'])).toEqual(saved); + await openPage(id['MC usd only']); + expect(await readResults(reader)).toBe(s1); + observed['step4-deleted-account'] = { pots: deletedPots }; + + expect(c.rateRequests).toEqual([]); + } finally { + observed.rateRequests = c.rateRequests; + writeObserved('observed-monte-carlo.json', observed); + await c.close(); + } + }); +}); diff --git a/packages/desktop-client/e2e/currency-sync-reports.test.ts b/packages/desktop-client/e2e/currency-sync-reports.test.ts new file mode 100644 index 00000000000..350326d60e6 --- /dev/null +++ b/packages/desktop-client/e2e/currency-sync-reports.test.ts @@ -0,0 +1,416 @@ +import fs from 'node:fs'; + +import type { Page } from '@playwright/test'; + +import { + BIDI, + SERVER_URL, + bootTwoClients, + derive, + open, + pageText, + runSelfDescription, + savePrefs, + send, + shoot, + sync, + usd, + writeObserved, +} from './currency-sync-helpers'; +import type { Rates } from './currency-sync-helpers'; +import { expect, test } from './fixtures'; +import { BudgetPage } from './page-models/budget-page'; + +// CHE-1197: browser values the first journey (currency-sync.test.ts) left +// open, on the same real two-client / disposable-sync-server design. Client A +// writes rates, B receives them over sync, and B's rendered numbers must equal +// the canonical converted model. Unavailable is asserted as unavailable, +// never as zero. Needs E2E_SYNC_SERVER_URL (CI skips it; local runs are the +// evidence). +const observed: Record = {}; + +const REPORT_NAME = (graph: string) => `Chart ${graph}`; +const GRAPHS = [ + ['BarGraph', 'total'], + ['DonutGraph', 'total'], + ['LineGraph', 'time'], + ['AreaGraph', 'time'], + ['StackedBarGraph', 'time'], +] as const; + +const unbidi = (text: string) => text.replace(BIDI, '').replace(/\s+/g, ' '); + +// Hover across the chart and collect every distinct tooltip it shows. Charts +// draw a tooltip only for the point under the pointer, so one sweep reads +// every bar, line point or area column the report has. +async function hoverTooltips(page: Page) { + const chart = page.locator('.recharts-wrapper').first(); + await chart.waitFor({ timeout: 60_000 }); + const box = await chart.boundingBox(); + expect(box, 'chart is drawn').toBeTruthy(); + const { x, y, width, height } = box as NonNullable; + const seen = new Set(); + for (const row of [0.3, 0.6]) { + for (let i = 1; i <= 14; i++) { + await page.mouse.move(x + (width * i) / 15, y + height * row); + await page.waitForTimeout(80); + const text = await page.evaluate(() => + Array.from( + document.querySelectorAll('.recharts-tooltip-wrapper'), + ) + .filter(el => el.style.visibility !== 'hidden') + .map(el => el.innerText.replace(/\s*\n+\s*/g, ' | ')) + .join(' ## '), + ); + if (text.trim()) { + seen.add(unbidi(text)); + } + } + } + return [...seen]; +} + +// The donut draws the hovered slice's name, amount and share as SVG text. +async function donutLabels(page: Page) { + const sectors = page.locator('.recharts-sector'); + const labels: string[] = []; + for (let i = 0; i < (await sectors.count()); i++) { + await sectors.nth(i).hover({ force: true }); + labels.push( + unbidi( + await page.evaluate(() => + Array.from(document.querySelectorAll('.recharts-wrapper svg text')) + .map(node => node.textContent) + .join(' | '), + ), + ), + ); + } + return labels; +} + +const share = (part: number, whole: number) => + `(${((part / whole) * 100).toFixed(2)}%)`; + +// What every chart must show for a rate pair: per-account Net, the whole +// report's Assets/Debts/Net, and the donut shares. +function chartExpectations(rates: Rates) { + const v = derive(rates); + const assets = 500 + v.euroDeposit + v.pointsNet; + return { + bar: [ + `Checking | Assets: | $500.00 | Debts: | -$150.00 | Net: | $350.00`, + `Euro savings | Assets: | ${usd(v.euroDeposit)} | Debts: | -${usd(-v.euroPayment)} | Net: | ${usd(v.euroNet)}`, + `Loyalty points | Assets: | ${usd(v.pointsNet)} | Debts: | $0.00 | Net: | ${usd(v.pointsNet)}`, + ], + series: `Jan '17 | Checking | $350.00 | Euro savings | ${usd(v.euroNet)} | Loyalty points | ${usd(v.pointsNet)} | Total | ${usd(v.all)}`, + area: `Jan '17 | Assets: | ${usd(assets)} | Debts: | -${usd(150 - v.euroPayment)} | Net: | ${usd(v.all)}`, + donut: [ + `Checking | $350.00 | ${share(350, v.all)}`, + `Euro savings | ${usd(v.euroNet)} | ${share(v.euroNet, v.all)}`, + `Loyalty points | ${usd(v.pointsNet)} | ${share(v.pointsNet, v.all)}`, + ], + }; +} + +// Crossover: investment income is round(balance * 4% / 12) cents; the Rent +// category's 150.00 sets expenses and target income; "Life savings" is the +// converted balance of every selected account. +function crossoverTooltip(rates: Rates) { + const { all } = derive(rates); + const income = Math.round((all * 100 * 0.04) / 12) / 100; + return `Monthly investment income: | ${usd(income)} | Monthly expenses: | $150.00 | Target income: | $150.00 | Life savings: | ${usd(all)}`; +} + +const NUM = /^-?\d+(\.\d{1,2})?$/; +const BUDGET_ANALYSIS_ROWS = [ + '2016-08,0,0,0,0', + '2016-09,0,0,0,0', + '2016-10,0,0,0,0', + '2016-11,0,0,0,0', + '2016-12,0,0,0,0', + '2017-01,200,-150,0,50', +]; +const BUDGET_ANALYSIS_HEADER = + 'Month,Budgeted,Spent,Overspending Adjustment,Balance'; + +async function download(page: Page, click: () => Promise) { + const pending = page.waitForEvent('download'); + await click(); + const file = await pending; + const filePath = await file.path(); + return { + name: file.suggestedFilename(), + bytes: fs.readFileSync(filePath), + }; +} + +test.describe('currency report values and exports across two clients', () => { + test.skip(!SERVER_URL, 'needs E2E_SYNC_SERVER_URL (disposable server)'); + test.use({ actionTimeout: 20_000 }); + + test('crossover, charts, summary, budget overview and exports follow the canonical converted model', async ({ + browser, + }) => { + test.setTimeout(900_000); + observed.run = runSelfDescription(['currency-sync-reports.test.ts']); + const c = await bootTwoClients(browser, { + flags: { 'flags.budgetAnalysisReport': 'true' }, + }); + const { b: reader, a: author, fixture } = c; + const reportIds: Record = {}; + let budgetAnalysisId = ''; + + // The reports pages only settle after the dashboard has loaded once on a + // client (observed: a first visit to /reports/crossover spins forever). + let warm = false; + async function readSurface(route: string) { + if (!warm) { + await open(reader, `/reports/${fixture.dashboardId}`); + await expect + .poll(async () => pageText(reader), { timeout: 60_000 }) + .toContain('Budget Overview'); + warm = true; + } + await open(reader, route); + await expect + .poll(async () => !(await pageText(reader)).includes('Loading'), { + timeout: 60_000, + }) + .toBe(true); + } + + async function expectChartsAndCrossover(rates: Rates, step: string) { + const want = chartExpectations(rates); + const seen: Record = {}; + await readSurface('/reports/crossover'); + await expect + .poll( + async () => + (observed[`${step}-crossover-last`] = await hoverTooltips(reader)), + { + message: `${step}: crossover tooltip`, + timeout: 60_000, + }, + ) + .toEqual( + expect.arrayContaining([ + expect.stringContaining(crossoverTooltip(rates)), + ]), + ); + seen.crossover = (await hoverTooltips(reader)).slice(0, 2); + await shoot(reader, `${step}-crossover`); + + for (const [graph] of GRAPHS) { + await readSurface(`/reports/custom/${reportIds[graph]}`); + if (graph === 'DonutGraph') { + await expect + .poll(() => donutLabels(reader), { timeout: 60_000 }) + .toEqual( + expect.arrayContaining( + want.donut.map(label => expect.stringContaining(label)), + ), + ); + seen[graph] = await donutLabels(reader); + } else { + const expected = + graph === 'BarGraph' + ? want.bar + : graph === 'AreaGraph' + ? [want.area] + : [want.series]; + await expect + .poll(() => hoverTooltips(reader), { + message: `${step}: ${graph} tooltips`, + timeout: 60_000, + }) + .toEqual( + expect.arrayContaining( + expected.map(text => expect.stringContaining(text)), + ), + ); + seen[graph] = await hoverTooltips(reader); + } + await shoot(reader, `${step}-${graph}`); + } + observed[`${step}-charts`] = seen; + } + + // Main-only: the summary card's Avg Per Month is the fixture's 150.00 + // expense divided by the elapsed fraction of the pinned month (day 1 of + // 31): 150 * 31 = 4,650.00. Budget Overview prorates the 200.00 budget + // the same way: 150.00 spent - 200.00 * 1/31, rounded = 143.55. Neither + // moves with a rate; foreign accounts are off budget. + const AVG_PER_MONTH = usd((150 * 31) / 1); + const BUDGET_OVERVIEW = `+${usd(Math.round((150 - 200 / 31) * 100) / 100)}`; + async function expectMainOnlyCards(step: string) { + await readSurface(`/reports/${fixture.dashboardId}`); + const avgPerMonth = `Avg Per Month | January 2017 | ${AVG_PER_MONTH} | Avg Per Transaction`; + const overview = `Budget Overview | Compare Jan 2017 to budgeted | ${BUDGET_OVERVIEW} | 3-Month Average`; + for (const [label, expected] of [ + ['Avg Per Month', avgPerMonth], + ['Budget Overview', overview], + ]) { + await expect + .poll(async () => unbidi(await pageText(reader)), { + message: `${step}: ${label}`, + timeout: 60_000, + }) + .toContain(expected); + } + observed[`${step}-main-only-cards`] = { + avgPerMonth: AVG_PER_MONTH, + budgetOverview: BUDGET_OVERVIEW, + appCalendar: 'Jan 2017', + }; + } + + async function exportBudgetAnalysis(step: string) { + await readSurface(`/reports/budget-analysis/${budgetAnalysisId}`); + const file = await download(reader, () => + reader.getByRole('button', { name: 'Export as CSV' }).click(), + ); + expect(file.name, `${step}: file name`).toBe( + 'budget-analysis-2016-08-2017-01.csv', + ); + const lines = file.bytes.toString('utf8').trim().split('\n'); + // Schema unchanged: the same header and one row per month. + expect(lines[0], `${step}: header`).toBe(BUDGET_ANALYSIS_HEADER); + expect(lines.slice(1), `${step}: rows`).toEqual(BUDGET_ANALYSIS_ROWS); + // Machine-readable: plain decimal numbers, no symbol, separator or + // display rounding adjustment. + for (const cell of lines.slice(1).flatMap(l => l.split(',').slice(1))) { + expect(cell, `${step}: cell ${cell}`).toMatch(NUM); + } + // The same canonical numbers the page shows (displayed with $ and .00). + const page = await pageText(reader); + expect(unbidi(page)).toContain( + 'Budgeted: | $200.00 | Spent: | -$150.00 | Overspending adj: | $0.00 | Ending balance: | +$50.00', + ); + observed[`${step}-budget-analysis-csv`] = { + name: file.name, + text: file.bytes.toString('utf8'), + }; + } + + try { + // Rates, a saved report per chart type and a budget analysis widget, + // all written on A. + await savePrefs(author, { + 'manualRate.EUR.USD': '1.1', + 'customUnit.X-POINTS': JSON.stringify({ + name: 'Points', + symbol: 'pt', + decimals: 0, + }), + 'manualRate.X-POINTS.USD': '0.01', + }); + for (const [graph, mode] of GRAPHS) { + reportIds[graph] = await send(author, 'report/create', { + name: REPORT_NAME(graph), + startDate: '2017-01-01', + endDate: '2017-01-31', + isDateStatic: false, + dateRange: 'This month', + mode, + groupBy: 'Account', + interval: 'Monthly', + balanceType: 'Net', + showEmpty: false, + showOffBudget: true, + showHiddenCategories: true, + includeCurrentInterval: true, + showUncategorized: true, + trimIntervals: false, + showTrendLines: false, + graphType: graph, + conditionsOp: 'and', + conditions: [{ field: 'account', op: 'oneOf', value: c.accountIds }], + }); + } + await send(author, 'dashboard-add-widget', { + type: 'budget-analysis-card', + width: 4, + height: 2, + meta: null, + dashboard_page_id: fixture.dashboardId, + }); + await sync(author); + await sync(reader); + budgetAnalysisId = await reader.evaluate(async () => { + const w = window as unknown as { + $query: ( + q: unknown, + ) => Promise<{ data: Array<{ id: string; type: string }> }>; + $q: (t: string) => { select: (f: string[]) => unknown }; + }; + const { data } = await w.$query( + w.$q('dashboard').select(['id', 'type']), + ); + return data.find(d => d.type === 'budget-analysis-card')?.id ?? ''; + }); + expect(budgetAnalysisId).toBeTruthy(); + + // Step 1: EUR 1.1, points 0.01. + const step1: Rates = { eur: 1.1, points: 0.01 }; + await expectChartsAndCrossover(step1, 'step1-eur-1.1'); + await expectMainOnlyCards('step1-eur-1.1'); + await exportBudgetAnalysis('step1-eur-1.1'); + + // Step 2: a rate update on A reaches B; export again. + await savePrefs(author, { + 'manualRate.EUR.USD': '1.25', + 'manualRate.X-POINTS.USD': '0.02', + }); + await sync(author); + await sync(reader); + const step2: Rates = { eur: 1.25, points: 0.02 }; + await expectChartsAndCrossover(step2, 'step2-eur-1.25'); + await expectMainOnlyCards('step2-eur-1.25'); + await exportBudgetAnalysis('step2-eur-1.25'); + + // Step 3: EUR rate removed on B. Rate-dependent charts and crossover + // say unavailable; Main-only cards and the export do not move. + await savePrefs(reader, { 'manualRate.EUR.USD': '' }); + await sync(reader); + await sync(author); + await readSurface('/reports/crossover'); + await expect + .poll(async () => pageText(reader), { timeout: 60_000 }) + .toContain('Crossover point is unavailable.'); + expect(await reader.locator('.recharts-wrapper').count()).toBe(0); + for (const [graph] of GRAPHS) { + await readSurface(`/reports/custom/${reportIds[graph]}`); + await expect + .poll(async () => pageText(reader), { + message: `${graph} unavailable`, + timeout: 60_000, + }) + .toContain('Custom report values are unavailable.'); + expect(await reader.locator('.recharts-wrapper').count()).toBe(0); + } + await expectMainOnlyCards('step3-eur-removed'); + await exportBudgetAnalysis('step3-eur-removed'); + + // Step 4: EUR 1.2 restored on A; after a full reload B renders the + // same numbers from its own storage. + await savePrefs(author, { 'manualRate.EUR.USD': '1.2' }); + await sync(author); + await sync(reader); + await open(reader, '/budget'); + await reader.reload(); + warm = false; + await new BudgetPage(reader).waitFor({ timeout: 90_000 }); + const step4: Rates = { eur: 1.2, points: 0.02 }; + await expectChartsAndCrossover(step4, 'step4-reloaded-eur-1.2'); + await expectMainOnlyCards('step4-reloaded-eur-1.2'); + await exportBudgetAnalysis('step4-reloaded-eur-1.2'); + + expect(c.rateRequests).toEqual([]); + } finally { + observed.rateRequests = c.rateRequests; + writeObserved('observed-reports.json', observed); + await c.close(); + } + }); +}); diff --git a/packages/desktop-client/e2e/currency-sync.test.ts b/packages/desktop-client/e2e/currency-sync.test.ts index 9d484422ce3..2809284589e 100644 --- a/packages/desktop-client/e2e/currency-sync.test.ts +++ b/packages/desktop-client/e2e/currency-sync.test.ts @@ -3,103 +3,41 @@ import path from 'node:path'; import type { Page } from '@playwright/test'; +import { + EURO_NATIVE, + EVIDENCE_DIR, + MONTH, + NOTE, + POINTS_NATIVE, + RATE_HOSTS, + SERVER_URL, + USD, + appReady, + connect, + createFixture, + derive, + grab, + open, + pageText, + round2, + savePrefs, + send, + shoot, + sidebarOf, + sync, + usd, +} from './currency-sync-helpers'; +import type { Json, Rates, TestWindow } from './currency-sync-helpers'; import { expect, test } from './fixtures'; import { BudgetPage } from './page-models/budget-page'; import { ConfigurationPage } from './page-models/configuration-page'; -// Two isolated browser clients against a disposable local sync server: -// E2E_SYNC_SERVER_URL=http://127.0.0.1:5106 (a fresh ACTUAL_DATA_DIR) -// E2E_EVIDENCE_DIR= optional: screenshots and observed values +// Two isolated browser clients against a disposable local sync server (see +// currency-sync-helpers.ts for E2E_SYNC_SERVER_URL / E2E_EVIDENCE_DIR). // Without E2E_SYNC_SERVER_URL the suite is skipped (CI does not run it); it // never touches a real server. -const SERVER_URL = process.env.E2E_SYNC_SERVER_URL; -const EVIDENCE_DIR = process.env.E2E_EVIDENCE_DIR; -const PASSWORD = 'che-1024-disposable'; -const RATE_HOSTS = /frankfurter|coingecko/; - -// Test mode pins the app clock: every date below is January 2017. -const MONTH = '2017-01'; -const EURO_NATIVE = 80; // 100.00 EUR deposit, 20.00 EUR expense -const POINTS_NATIVE = 1000; // 1,000 pt, a decimals-0 custom unit - -type TestWindow = Window & { - $send: (method: string, args?: Record) => Promise; - $query: (query: unknown) => Promise<{ data: unknown[] }>; - $q: (table: string) => { - select: (fields: string[]) => unknown; - }; - __navigate: (url: string) => void; - __actionsForMenu: { - saveSyncedPrefs: (payload: { - prefs: Record; - }) => Promise; - downloadBudget: (payload: { cloudFileId: string }) => Promise; - }; -}; - -type Json = Record; const observed: Record = {}; -// The dev server may reload every open page once when a lazily imported -// dependency is first optimised; wait for the app globals to come back. -async function appReady(page: Page) { - await page.waitForFunction( - () => - typeof (window as TestWindow).$q === 'function' && - typeof (window as TestWindow).__navigate === 'function', - undefined, - { timeout: 30_000 }, - ); -} - -async function send( - page: Page, - method: string, - args?: Record, -) { - await appReady(page); - return page.evaluate( - ([name, params]) => - (window as TestWindow).$send(name, params as Record), - [method, args] as const, - ) as Promise; -} - -async function savePrefs(page: Page, prefs: Record) { - await page.evaluate(async values => { - await (window as TestWindow).__actionsForMenu.saveSyncedPrefs({ - prefs: values, - }); - }, prefs); -} - -async function connect(page: Page) { - await send(page, 'set-server-url', { url: SERVER_URL }); - // Already bootstrapped by the first client: that error is expected. - await send(page, 'subscribe-bootstrap', { password: PASSWORD }); - const signIn = await send<{ error?: string }>(page, 'subscribe-sign-in', { - password: PASSWORD, - }); - expect(signIn.error).toBeUndefined(); -} - -// Pushes this client's changes and pulls the other client's. fullSync is -// single-flight: a call made while an automatic sync runs joins it and may -// miss the newest change, so the second call guarantees one full round trip. -async function sync(page: Page) { - for (let round = 0; round < 2; round++) { - const result = await send<{ error?: unknown } | undefined>(page, 'sync'); - expect(result?.error).toBeUndefined(); - } -} - -async function shoot(page: Page, name: string) { - if (EVIDENCE_DIR) { - fs.mkdirSync(EVIDENCE_DIR, { recursive: true }); - await page.screenshot({ path: path.join(EVIDENCE_DIR, `${name}.png`) }); - } -} - // ---------------------------------------------------------------- budget math const BUDGET_CELL_NAMES = [ @@ -187,80 +125,6 @@ async function expectBudgetMath( // ------------------------------------------------------------ surface reading -const BIDI = /[‪-‮⁦-⁩]/g; - -// Rendered text of the whole app, one ' | ' per line break, without the -// bidi marks the currency formatter wraps amounts in. -async function pageText(page: Page) { - const raw = await page - .evaluate(() => document.body.innerText) - // A page that is reloading has no text yet: the poll tries again. - .catch(() => ''); - return raw - .replace(BIDI, '') - .replace(/[\u00a0\u202f]/g, ' ') - .replace(/\s*\n+\s*/g, ' | '); -} - -// Right after a prefs sync the router can briefly drop flag-gated routes and -// bounce to /budget, so navigate until the app stays on the requested route. -async function open(page: Page, route: string) { - await expect - .poll( - async () => { - await appReady(page); - const path = await page.evaluate(() => window.location.pathname); - if (path !== route) { - await page.evaluate( - url => (window as TestWindow).__navigate(url), - route, - ); - await page.waitForTimeout(250); - } - return page.evaluate(() => window.location.pathname); - }, - { message: `open ${route}`, timeout: 30_000 }, - ) - .toBe(route); -} - -function grab(t: string, re: RegExp): string[] | { unmatched: string } { - const match = re.exec(t); - if (match) { - return match.slice(1); - } - const start = t.indexOf(' | Help | '); - return { unmatched: t.slice(start < 0 ? 0 : start + 10, start + 600) }; -} - -const sidebarOf = (t: string) => - t.slice(t.indexOf('All accounts'), t.indexOf(' | Add account')); - -const USD = '(-?\\+?\\$[\\d,]+\\.\\d\\d)'; -const NOTE = - 'Values in USD\\. Foreign-currency history is an estimate at current rates\\.'; - -const round2 = (n: number) => Math.round(n * 100) / 100; -const usd = (n: number) => - `${n < 0 ? '-' : ''}$${Math.abs(n).toLocaleString('en-US', { - minimumFractionDigits: 2, - maximumFractionDigits: 2, - })}`; - -type Rates = { eur: number; points: number }; - -// Everything a rate pair implies, in Main (USD). On-budget Checking is 500.00 -// income and a 150.00 Rent expense; the foreign accounts are off budget. -function derive({ eur, points }: Rates) { - const euroNet = round2(EURO_NATIVE * eur); - const euroDeposit = round2(100 * eur); - const euroPayment = round2(-20 * eur); - const pointsNet = round2(POINTS_NATIVE * points); - const off = round2(euroNet + pointsNet); - const all = round2(350 + off); - return { euroNet, euroDeposit, euroPayment, pointsNet, off, all }; -} - type Surface = { name: string; route: (ctx: Context) => string; @@ -661,56 +525,7 @@ test.describe('multi-currency persistence across two clients', () => { 'flags.budgetAnalysisReport': 'true', }); - const fixture = await clientA.evaluate(async m => { - const w = window as TestWindow; - const euro = (await w.$send('account-create', { - name: 'Euro savings', - balance: 100, - offBudget: true, - currency: 'EUR', - })) as string; - const points = (await w.$send('account-create', { - name: 'Loyalty points', - balance: 1000, - offBudget: true, - currency: 'X-POINTS', - })) as string; - const checking = (await w.$send('account-create', { - name: 'Checking', - balance: 500, - offBudget: false, - currency: 'USD', - })) as string; - const groupId = await w.$send('category-group-create', { - name: 'Bills', - }); - const categoryId = (await w.$send('category-create', { - name: 'Rent', - groupId, - })) as string; - const date = `${m}-01`; - await w.$send('transactions-batch-update', { - added: [ - // Aligned with the budget month: spent -150.00 of 200.00. - { - id: crypto.randomUUID(), - account: checking, - date, - amount: -15000, - category: categoryId, - }, - { id: crypto.randomUUID(), account: euro, date, amount: -2000 }, - ], - }); - await w.$send('budget/budget-amount', { - month: m, - category: categoryId, - amount: 20000, - }); - const pages = (await w.$query(w.$q('dashboard_pages').select(['id']))) - .data as Array<{ id: string }>; - return { euro, points, checking, categoryId, dashboardId: pages[0].id }; - }, MONTH); + const fixture = await createFixture(clientA); const { categoryId, dashboardId } = fixture; const accountIds = [fixture.checking, fixture.euro, fixture.points]; diff --git a/upcoming-release-notes/che-1197-currency-report-browser-coverage.md b/upcoming-release-notes/che-1197-currency-report-browser-coverage.md new file mode 100644 index 00000000000..f0c41c0151f --- /dev/null +++ b/upcoming-release-notes/che-1197-currency-report-browser-coverage.md @@ -0,0 +1,6 @@ +--- +category: Maintenance +authors: [congvc-dev] +--- + +Add two-client browser coverage for multi-currency report values, report exports and Monte Carlo linked pots From 6403fdf5e260b90737301d29e992dd2025ea5ef1 Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 04:26:05 +0700 Subject: [PATCH 2/4] [AI] test(currency): fix import order and drop stray debug lines in CHE-1197 journeys (CHE-1197) --- .../desktop-client/e2e/currency-sync-helpers.ts | 2 -- .../e2e/currency-sync-monte-carlo.test.ts | 2 +- .../e2e/currency-sync-reports.test.ts | 2 +- packages/desktop-client/e2e/currency-sync.test.ts | 15 +++++++-------- 4 files changed, 9 insertions(+), 12 deletions(-) diff --git a/packages/desktop-client/e2e/currency-sync-helpers.ts b/packages/desktop-client/e2e/currency-sync-helpers.ts index 417da2c3b18..a51e2d067e0 100644 --- a/packages/desktop-client/e2e/currency-sync-helpers.ts +++ b/packages/desktop-client/e2e/currency-sync-helpers.ts @@ -336,5 +336,3 @@ export function writeObserved(file: string, value: unknown) { ); } } - -process.stderr.write(`[step ${new Date().toISOString()}] ${m}\n`); diff --git a/packages/desktop-client/e2e/currency-sync-monte-carlo.test.ts b/packages/desktop-client/e2e/currency-sync-monte-carlo.test.ts index c0f86522541..31abca30a14 100644 --- a/packages/desktop-client/e2e/currency-sync-monte-carlo.test.ts +++ b/packages/desktop-client/e2e/currency-sync-monte-carlo.test.ts @@ -2,13 +2,13 @@ import type { Page } from '@playwright/test'; import { BIDI, - SERVER_URL, bootTwoClients, open, pageText, runSelfDescription, savePrefs, send, + SERVER_URL, shoot, sync, writeObserved, diff --git a/packages/desktop-client/e2e/currency-sync-reports.test.ts b/packages/desktop-client/e2e/currency-sync-reports.test.ts index 350326d60e6..1d6f3b4d879 100644 --- a/packages/desktop-client/e2e/currency-sync-reports.test.ts +++ b/packages/desktop-client/e2e/currency-sync-reports.test.ts @@ -4,7 +4,6 @@ import type { Page } from '@playwright/test'; import { BIDI, - SERVER_URL, bootTwoClients, derive, open, @@ -12,6 +11,7 @@ import { runSelfDescription, savePrefs, send, + SERVER_URL, shoot, sync, usd, diff --git a/packages/desktop-client/e2e/currency-sync.test.ts b/packages/desktop-client/e2e/currency-sync.test.ts index 2809284589e..e83aa47363e 100644 --- a/packages/desktop-client/e2e/currency-sync.test.ts +++ b/packages/desktop-client/e2e/currency-sync.test.ts @@ -4,27 +4,26 @@ import path from 'node:path'; import type { Page } from '@playwright/test'; import { - EURO_NATIVE, - EVIDENCE_DIR, - MONTH, - NOTE, - POINTS_NATIVE, - RATE_HOSTS, - SERVER_URL, - USD, appReady, connect, createFixture, derive, + EVIDENCE_DIR, grab, + MONTH, + NOTE, open, pageText, + POINTS_NATIVE, + RATE_HOSTS, round2, savePrefs, send, + SERVER_URL, shoot, sidebarOf, sync, + USD, usd, } from './currency-sync-helpers'; import type { Json, Rates, TestWindow } from './currency-sync-helpers'; From 259eb93a750bb9fff7d5f333628d87e3bcefa89a Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 04:28:46 +0700 Subject: [PATCH 3/4] [AI] test(currency): match the Monte Carlo unavailable notice on the accumulated head (CHE-1197) --- packages/desktop-client/e2e/currency-sync-monte-carlo.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/desktop-client/e2e/currency-sync-monte-carlo.test.ts b/packages/desktop-client/e2e/currency-sync-monte-carlo.test.ts index 31abca30a14..12052674c65 100644 --- a/packages/desktop-client/e2e/currency-sync-monte-carlo.test.ts +++ b/packages/desktop-client/e2e/currency-sync-monte-carlo.test.ts @@ -29,7 +29,7 @@ import { BudgetPage } from './page-models/budget-page'; const observed: Record = {}; const UNAVAILABLE = - 'Unavailable: a linked account balance cannot be converted to USD. Add an exchange rate in Settings or unlink the pot.'; + 'Unavailable: a linked account balance cannot be converted to USD. Add an exchange rate in Settings, link the pot to another account or remove the pot.'; const BASE = { currentAge: 60, targetAge: 70, From cdcfb8ec14945ec8298ba63898e0dc9580e2299b Mon Sep 17 00:00:00 2001 From: "congvc-bot[bot]" <3634010+congvc-bot[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 04:39:18 +0700 Subject: [PATCH 4/4] [AI] test(currency): retry the donut slice hover while the chart animates in (CHE-1197) --- packages/desktop-client/e2e/currency-sync-reports.test.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/desktop-client/e2e/currency-sync-reports.test.ts b/packages/desktop-client/e2e/currency-sync-reports.test.ts index 1d6f3b4d879..bb5eb64bf2f 100644 --- a/packages/desktop-client/e2e/currency-sync-reports.test.ts +++ b/packages/desktop-client/e2e/currency-sync-reports.test.ts @@ -75,7 +75,13 @@ async function donutLabels(page: Page) { const sectors = page.locator('.recharts-sector'); const labels: string[] = []; for (let i = 0; i < (await sectors.count()); i++) { - await sectors.nth(i).hover({ force: true }); + // The donut animates in: a slice that is not hoverable yet is skipped and + // the caller's poll tries again. + try { + await sectors.nth(i).hover({ force: true, timeout: 5_000 }); + } catch { + continue; + } labels.push( unbidi( await page.evaluate(() =>