diff --git a/src/viewer/app/adp-sources.test.ts b/src/viewer/app/adp-sources.test.ts index 60a0abf..1059b21 100644 --- a/src/viewer/app/adp-sources.test.ts +++ b/src/viewer/app/adp-sources.test.ts @@ -1,7 +1,8 @@ /// /// import { expect, test } from 'bun:test'; -import { adpRows, adpShown, allSources, asAdpHidden, onlySource, sourceChip, taxSlices, toggleSource } from './adp-sources'; +import { adpRows, adpShown, asAdpHidden, flipPart, onlySource, partOn, partOnly, pickPart, sourceChip, taxSlices, toggleSource } from './adp-sources'; +import { LEAF_401K, buildTree, fidelityLeaf } from './scope-tree'; // made-up rows, no real amounts const ROWS = [ @@ -19,13 +20,11 @@ test('each row has one chip: Roth, Pre-tax, the employer (match or non-elective) expect(sourceChip({ kind: 'contribution', source: '' })).toBe('other'); }); -test('checkboxes toggle one chip, a click shows only it, All sources shows all or none', () => { +test('checkboxes toggle one chip, a click shows only it', () => { expect(toggleSource([], 'employer')).toEqual(['employer']); expect(toggleSource(['other', 'roth'], 'pretax')).toEqual(['roth', 'pretax', 'other']); expect(toggleSource(['roth', 'other'], 'roth')).toEqual(['other']); expect(onlySource('pretax')).toEqual(['roth', 'employer', 'other']); - expect(allSources([])).toEqual(['roth', 'pretax', 'employer', 'other']); - expect(allSources(['roth'])).toEqual([]); }); test('only the rows of the shown chips stay; a stored list is cleaned', () => { @@ -46,3 +45,36 @@ test('the 401k history rows: the newest day first whatever the stored order, a d const tx = (date: string, net: number) => ({ date, payDate: '', fund: 'F', type: 'x', kind: 'contribution' as const, source: 'roth' as const, quantity: 1, price: 1, net }); expect(adpRows([tx('2026-01-15', 1), tx('2026-02-15', 2), tx('2025-12-15', 3), tx('2026-02-15', 4)]).map((r) => r.net)).toEqual([4, 2, 1, 3]); }); + +// the money sources as part chips under the 401k chip of the strip (moved here with the strip of the ADP pages) +const tree = buildTree({ fidelity: [{ number: 'A1', name: 'Joint', group: 'Investment' }], k401: true }); +const K = LEAF_401K; +const A1 = fidelityLeaf('A1'); +const arr = (s: ReadonlySet) => Array.from(s); + +test('a part is on while the 401k is ticked and the part shown; framed when it alone is on', () => { + expect(partOn(new Set([K]), [], 'roth')).toBe(true); + expect(partOn(new Set([K]), ['roth'], 'roth')).toBe(false); + // nothing ticked shows everything, yet the boxes stay clear like every other box of the strip + expect(partOn(new Set(), [], 'roth')).toBe(false); + expect(partOnly(new Set([K]), ['pretax', 'employer', 'other'], 'roth')).toBe(true); + expect(partOnly(new Set([K]), ['pretax'], 'roth')).toBe(false); +}); + +test('the box of a part: ticks the 401k with only it, flips it, the last one off takes the 401k away', () => { + // the 401k not ticked: it is ticked with only this part, the ticked accounts stay + const a = flipPart(tree, new Set([A1]), [], 'roth'); + expect([arr(a.ticked), a.hidden]).toEqual([[A1, K], ['pretax', 'employer', 'other']]); + // ticked: the part flips + const b = flipPart(tree, new Set([K]), ['other'], 'roth'); + expect([arr(b.ticked), b.hidden]).toEqual([[K], ['roth', 'other']]); + // the last part switched off: the 401k goes, every part shown for the next time + const c = flipPart(tree, new Set([A1, K]), ['pretax', 'employer', 'other'], 'roth'); + expect([arr(c.ticked), c.hidden]).toEqual([[A1], []]); +}); + +test('a click on a part: the 401k ticked with only that part, the rest of the scope stays', () => { + const a = pickPart(tree, new Set(), 'employer'); + expect([arr(a.ticked), a.hidden]).toEqual([[K], ['roth', 'pretax', 'other']]); + expect(arr(pickPart(tree, new Set([A1, K]), 'other').ticked)).toEqual([A1, K]); +}); diff --git a/src/viewer/app/adp-sources.ts b/src/viewer/app/adp-sources.ts index ad60009..302234e 100644 --- a/src/viewer/app/adp-sources.ts +++ b/src/viewer/app/adp-sources.ts @@ -4,6 +4,7 @@ // rows with no source (dividends and earnings, transfers, fees) form one more chip, so any set can be shown. The choice // is a list of the switched-off chips in the prefs (`adpHidden`), so a source seen for the first time shows import type { AdpTxn } from '../../shared/adp/mykplan'; +import { LEAF_401K, scopeOf, type ScopeNode } from './scope-tree'; export const ADP_SOURCES = ['roth', 'pretax', 'employer', 'other'] as const; export type AdpSourceChip = (typeof ADP_SOURCES)[number]; @@ -15,7 +16,6 @@ export function sourceChip(r: Pick): AdpSourceChip { return r.source === '' ? 'other' : 'employer'; } - export const asAdpHidden = (x: unknown): AdpSourceChip[] => Array.isArray(x) ? ADP_SOURCES.filter((s) => x.indexOf(s) >= 0) : []; @@ -23,12 +23,39 @@ export const asAdpHidden = (x: unknown): AdpSourceChip[] => export const toggleSource = (hidden: readonly AdpSourceChip[], s: AdpSourceChip): AdpSourceChip[] => hidden.indexOf(s) >= 0 ? hidden.filter((x) => x !== s) : ADP_SOURCES.filter((x) => x === s || hidden.indexOf(x) >= 0); -/** a click on a chip: only it is shown (as an account chip of Fidelity) */ +/** a click on a part chip: only it is shown (as an account chip of Fidelity) */ export const onlySource = (s: AdpSourceChip): AdpSourceChip[] => ADP_SOURCES.filter((x) => x !== s); -/** the All sources checkbox: every chip shown, or (when all are shown) none. The strip always has every chip, rows or - * not (owner 2026-11-30: "we should see all the controls no matter if there are some elements or not") */ -export const allSources = (hidden: readonly AdpSourceChip[]): AdpSourceChip[] => (hidden.length ? [] : ADP_SOURCES.slice()); +// The money sources as `part` chips under the 401k chip of the scope strip (the scope tree plan, 2026-12-03: "Roth, +// Pre-tax, Employer, Earnings stay a filter of the 401k rows, never split the balance"). A part is on while the 401k is +// ticked and the part is not hidden; the rules below keep the ticked leaves and `adpHidden` together + +/** a part chip's checkbox: on while the 401k is ticked and the part is shown */ +export const partOn = (ticked: ReadonlySet, hidden: readonly AdpSourceChip[], s: AdpSourceChip): boolean => ticked.has(LEAF_401K) && hidden.indexOf(s) < 0; + +/** a part chip framed as the choice: it alone is on */ +export const partOnly = (ticked: ReadonlySet, hidden: readonly AdpSourceChip[], s: AdpSourceChip): boolean => partOn(ticked, hidden, s) && onlySource(s).every((x) => hidden.indexOf(x) >= 0); + +/** what a part chip changes: the ticked leaves and the hidden parts */ +export interface PartChange { ticked: Set; hidden: AdpSourceChip[] } + +/** + * The checkbox of a part: with the 401k not ticked it ticks the 401k with only this part; else it flips the part, and + * the last part switched off takes the 401k away (every part shown again for the next time) + */ +export function flipPart(root: ScopeNode, ticked: ReadonlySet, hidden: readonly AdpSourceChip[], s: AdpSourceChip): PartChange { + const now = scopeOf(root, ticked); + if (now.indexOf(LEAF_401K) < 0) return { ticked: new Set(now.concat(LEAF_401K)), hidden: onlySource(s) }; + const next = toggleSource(hidden, s); + if (next.length === ADP_SOURCES.length) return { ticked: new Set(now.filter((x) => x !== LEAF_401K)), hidden: [] }; + return { ticked: new Set(now), hidden: next }; +} + +/** a click on a part chip: the 401k ticked (the other ticked leaves stay) with only this part shown */ +export function pickPart(root: ScopeNode, ticked: ReadonlySet, s: AdpSourceChip): PartChange { + const now = scopeOf(root, ticked); + return { ticked: new Set(now.indexOf(LEAF_401K) < 0 ? now.concat(LEAF_401K) : now), hidden: onlySource(s) }; +} /** the rows of the shown chips */ export const adpShown = >(rows: readonly T[], hidden: readonly AdpSourceChip[]): T[] => diff --git a/src/viewer/app/derive.test.ts b/src/viewer/app/derive.test.ts index 88f0f58..bde6efa 100644 --- a/src/viewer/app/derive.test.ts +++ b/src/viewer/app/derive.test.ts @@ -6,17 +6,12 @@ import { ROWS, SIDEBAR } from '../../shared/fixtures/grid'; import type { Account, Position } from '../../shared/model'; import { buildDataset } from '../../shared/parse'; import { sortPositions } from './position-columns'; -import { median, incomeMedian, dripMin, asKind, ALL_FOLD, toggleFold, moveAccount, moveGroup, stepMove, orderAccounts, sortAccounts, scopeOf, toggleAccount, accountsIn, allocation, groupsOf, movers, near52, positionsIn, rangeRows, payoutParts, payDatesIn, securitiesBySymbol, incomeFacts, kindOf, ofKind, toggleKind, kindOn, addMonths, localToday, incomeIn, periodBounds, rangePos, totalsOf, upcomingDividends, payoutTotal, weightedRate, adjustedDrip, rowDripAdj, rowDripAdjUsd, yieldNote, sortDividends, toggleDivSort, asDivSorts, divChips, divSizeOf, toggleDivChip, setDivSize, asDivSize, validScope, dripGap, perPayment, windowEnd, asDivWindow, symbolDrip, dripToBuy, scopeTitle, dripMinAdj, dripMinAdjUsd, framedChips, toggleGroup } from './derive'; +import { median, incomeMedian, dripMin, asKind, moveChip, moveAccount, moveGroup, stepMove, orderAccounts, sortAccounts, allocation, groupsOf, movers, near52, positionsIn, rangeRows, payoutParts, payDatesIn, securitiesBySymbol, incomeFacts, kindOf, ofKind, toggleKind, kindOn, addMonths, localToday, incomeIn, periodBounds, rangePos, totalsOf, upcomingDividends, payoutTotal, weightedRate, adjustedDrip, rowDripAdj, rowDripAdjUsd, yieldNote, sortDividends, toggleDivSort, asDivSorts, divChips, divSizeOf, toggleDivChip, setDivSize, asDivSize, dripGap, perPayment, windowEnd, asDivWindow, symbolDrip, dripToBuy, dripMinAdj, dripMinAdjUsd } from './derive'; const ds = buildDataset({ rows: ROWS, sidebar: SIDEBAR, asOf: null, builtAt: 't' }); -test('scopes: all, a group, an account; an unknown scope falls back to all', () => { +test('groups in the site\'s order with their balances', () => { expect(groupsOf(ds).map((g) => [g.name, g.accounts.length, g.balance])).toEqual([['Investment', 1, 1525.5], ['Retirement', 1, 800]]); - expect(accountsIn(ds, 'all')).toHaveLength(2); - expect(accountsIn(ds, 'group:Retirement').map((a) => a.number)).toEqual(['200000002']); - expect(accountsIn(ds, 'account:X10000001').map((a) => a.name)).toEqual(['Joint']); - expect(validScope(ds, 'account:gone')).toBe('all'); - expect(validScope(ds, 'group:Investment')).toBe('group:Investment'); }); test('totals and movers', () => { @@ -56,25 +51,6 @@ test('allocation, dividends, 52-week, sort and search', () => { expect(sortPositions(rs, 'high52', 1).map((p) => p.symbol)).toEqual(['LOW', 'MID', 'TOP', 'NONE']); }); -test('any set of accounts: checkbox toggles, the shortest scope name', () => { - const three = { ...ds, accounts: ds.accounts.concat({ number: 'X3', name: 'Kid', group: 'Investment', asOf: 't' }) }; - expect(scopeOf(three, ['X10000001', '200000002', 'X3'])).toBe('all'); - expect(scopeOf(three, ['X10000001', 'X3'])).toBe('group:Investment'); - expect(scopeOf(three, ['200000002'])).toBe('account:200000002'); - expect(scopeOf(three, ['X3', '200000002'])).toBe('set:200000002,X3'); - expect(accountsIn(three, 'set:200000002,X3').map((a) => a.number)).toEqual(['200000002', 'X3']); - // from one account, tick another: a set; untick it again: back to one; untick from all: the rest - expect(toggleAccount(three, 'account:X3', '200000002')).toBe('set:200000002,X3'); - expect(toggleAccount(three, 'set:200000002,X3', '200000002')).toBe('account:X3'); - expect(toggleAccount(three, 'all', '200000002')).toBe('group:Investment'); - // the All accounts checkbox can clear everything; then single accounts are ticked one by one - expect(scopeOf(three, [])).toBe('none'); - expect(accountsIn(three, 'none')).toEqual([]); - expect(toggleAccount(three, 'none', 'X3')).toBe('account:X3'); - expect(validScope(three, 'none')).toBe('none'); - expect(validScope(three, 'set:gone')).toBe('all'); -}); - test('movers by % or $: the worst loser last; accounts sorted by the chosen measure', () => { const p = (symbol: string, todayGl: number, todayGlPct: number) => ({ account: 'A', kind: 'position' as const, symbol, description: '', todayGl, todayGlPct, fields: {} }); const ps = [p('BIGUSD', 50, 1), p('BIGPCT', 2, 30), p('LOSS1', -1, -9), p('LOSS2', -20, -2), p('MID', 5, 5)]; @@ -91,49 +67,6 @@ test('movers by % or $: the worst loser last; accounts sorted by the chosen meas expect(sortAccounts(accs, 'totalPct').map((a) => a.number)).toEqual(['2', '1']); }); -test('the frame goes on the highest chip chosen whole: All accounts, a group, else each account', () => { - const acc = (number: string, group: string) => ({ number, name: number, group, asOf: 't' }); - const d = { ...ds, accounts: [acc('A', 'Investment'), acc('B', 'Investment'), acc('C', 'Investment'), acc('R1', 'Retirement'), acc('R2', 'Retirement'), acc('K', 'Other')] }; - const framed = (...n: string[]) => Array.from(framedChips(d, new Set(n))).sort(); - // everything: only All accounts, not its groups and accounts - expect(framed('A', 'B', 'C', 'R1', 'R2', 'K')).toEqual(['all']); - // a whole group: the group - expect(framed('R1', 'R2')).toEqual(['group:Retirement']); - // a group of one account chosen: the group - expect(framed('K')).toEqual(['group:Other']); - // one account of a bigger group: that account - expect(framed('B')).toEqual(['account:B']); - // two of one group: both accounts - expect(framed('A', 'B')).toEqual(['account:A', 'account:B']); - // three accounts of two groups: all three - expect(framed('A', 'B', 'R1')).toEqual(['account:A', 'account:B', 'account:R1']); - // a whole group and an account of another: the group and the account - expect(framed('A', 'B', 'C', 'R2')).toEqual(['account:R2', 'group:Investment']); - // nothing chosen, or numbers that are not accounts: no frame - expect(framed()).toEqual([]); - expect(framed('X')).toEqual([]); -}); - -test('the group checkbox keeps only its group when every account is chosen, else adds or takes the group', () => { - const acc = (number: string, group: string) => ({ number, name: number, group, asOf: 't' }); - const d = { ...ds, accounts: [acc('A', 'Investment'), acc('B', 'Investment'), acc('R1', 'Retirement'), acc('R2', 'Retirement'), acc('K', 'Other')] }; - const pick = (group: string, ...n: string[]) => toggleGroup(d, new Set(n), group); - // all chosen: only Investment, and the frame then goes on the group - const only = pick('Investment', 'A', 'B', 'R1', 'R2', 'K'); - expect(accountsIn(d, only).map((a) => a.number)).toEqual(['A', 'B']); - expect(Array.from(framedChips(d, new Set(['A', 'B'])))).toEqual(['group:Investment']); - // some chosen, the group whole: taken away - expect(accountsIn(d, pick('Investment', 'A', 'B', 'K')).map((a) => a.number)).toEqual(['K']); - // some chosen, the group partly or not at all: added - expect(accountsIn(d, pick('Retirement', 'A', 'R1')).map((a) => a.number)).toEqual(['A', 'R1', 'R2']); - expect(accountsIn(d, pick('Other', 'A')).map((a) => a.number)).toEqual(['A', 'K']); - // nothing chosen: the group; the only group taken away: nothing - expect(accountsIn(d, pick('Other')).map((a) => a.number)).toEqual(['K']); - expect(pick('Other', 'K')).toBe('none'); - // a group that is not there changes nothing - expect(accountsIn(d, pick('Nope', 'A')).map((a) => a.number)).toEqual(['A']); -}); - test('my order of accounts: moved within the bar, groups stay put', () => { const acc = (number: string, group: string) => ({ number, name: number, group, asOf: 't' }); const d = { ...ds, accounts: [acc('A', 'Investment'), acc('B', 'Investment'), acc('C', 'Investment'), acc('R1', 'Retirement'), acc('R2', 'Retirement')] }; @@ -180,20 +113,6 @@ test('ETFs and Stocks boxes switch on their own; both or none is all', () => { expect(ofKind([{ ...p, securityType: 'Mutual Fund' }], 'none')).toHaveLength(1); }); -describe('toggleFold', () => { - test('a group folds and unfolds only itself', () => { - expect(toggleFold([], 'Investment')).toEqual(['Investment']); - expect(toggleFold(['Investment', 'Retirement'], 'Investment')).toEqual(['Retirement']); - }); - test('All accounts folds everything when all is open', () => { - expect(toggleFold([], ALL_FOLD)).toEqual([ALL_FOLD]); - }); - test('All accounts unfolds everything when anything is folded', () => { - expect(toggleFold([ALL_FOLD], ALL_FOLD)).toEqual([]); - expect(toggleFold(['Retirement'], ALL_FOLD)).toEqual([]); - }); -}); - test('localToday is the date in local time, not UTC', () => { expect(localToday(new Date(2026, 10, 30, 21, 30))).toBe('2026-11-30'); expect(localToday(new Date(2026, 0, 5, 0, 10))).toBe('2026-01-05'); @@ -359,18 +278,6 @@ test('DRIP of a merged Positions line: every account\'s own number added up, plu expect(Object.is(symbolDrip([{ drip: { shares: 0.1, usd: 5 } }, { drip: { shares: -0.1, usd: -5 } }], 'all')!.shares, 0)).toBe(true); }); -test('the name of what is shown: All accounts, a group, up to three accounts by name, else a count', () => { - const acct = (number: string, name: string): Account => ({ number, name, group: 'G', asOf: '' }); - const words = { all: 'All accounts', count: (n: number) => `${n} accounts` }; - const [a, b, c, d] = [acct('1', 'One'), acct('2', 'Two'), acct('3', 'Two ROTH IRA'), acct('4', 'Four')]; - expect(scopeTitle('all', [a!, b!, c!, d!], words)).toBe('All accounts'); - expect(scopeTitle('none', [], words)).toBe('All accounts'); - expect(scopeTitle('group:Retirement', [c!], words)).toBe('Retirement'); - expect(scopeTitle('account:1', [a!], words)).toBe('One'); - expect(scopeTitle('set:1,2,3', [a!, b!, c!], words)).toBe('One + Two + Two ROTH IRA'); - expect(scopeTitle('set:1,2,3,4', [a!, b!, c!, d!], words)).toBe('4 accounts'); -}); - // the pay dates as incomeIn built them before payDatesIn: every step up to two years each way, then the ones inside const STEPS: Record = { Monthly: 1, Quarterly: 3, 'Semi-annually': 6, Annually: 12 }; const allPayDates = (payDate: string, step: number | undefined, from: string, to: string): string[] => @@ -603,16 +510,9 @@ test('median of a month, quarter or year: the periods from the one of the first expect([median([3, 1, 2]), median([1, 4]), median([1.005, 2])]).toEqual([2, 2.5, 1.5]); }); -test('the strip on the scope tree, kept in today\'s words: ticked leaves, folds, moves', async () => { - const { leavesOfScope, scopeOfLeaves, foldKey, moveChip } = await import('./derive'); +test('a chip moved on the strip as the owner\'s order: accounts within their group, groups whole', () => { const acc = (number: string, group: string) => ({ number, name: number, group, asOf: 't' }); const d = { ...ds, accounts: [acc('A', 'Investment'), acc('B', 'Investment'), acc('R1', 'Retirement')] }; - expect(Array.from(leavesOfScope(d, 'group:Investment'))).toEqual(['fidelity:A', 'fidelity:B']); - expect(Array.from(leavesOfScope(d, 'none'))).toEqual([]); - expect(scopeOfLeaves(d, new Set(['fidelity:R1']))).toBe('account:R1'); - expect(scopeOfLeaves(d, new Set(['fidelity:A', 'fidelity:B', 'fidelity:R1']))).toBe('all'); - expect(scopeOfLeaves(d, new Set(['fidelity:gone']))).toBe('none'); - expect([foldKey('all'), foldKey('group:fidelity/Retirement')]).toEqual([ALL_FOLD, 'Retirement']); expect(moveChip(d, 'fidelity:B', 'fidelity:A')).toEqual({ accountOrder: ['B', 'A', 'R1'] }); expect(moveChip(d, 'group:fidelity/Retirement', 'group:fidelity/Investment')).toEqual({ groupOrder: ['Retirement', 'Investment'] }); expect(moveChip(d, 'fidelity:A', 'group:fidelity/Retirement')).toBeNull(); diff --git a/src/viewer/app/derive.ts b/src/viewer/app/derive.ts index 26f606e..58f6d2a 100644 --- a/src/viewer/app/derive.ts +++ b/src/viewer/app/derive.ts @@ -4,8 +4,7 @@ import { pairOn, togglePair } from './pair'; import type { Account, Dataset, Position } from '../../shared/model'; import { incomeReceived, isIncome, type TxnStore } from '../../shared/transactions'; import { incomeTax, type IncomeTax } from './income-tax'; -import type { Scope } from './prefs'; -import { FIDELITY, ROOT, buildTree, fidelityLeaf, framedNodes, groupAccounts, groupId, scopeOf as leavesShown, toggleLeaf, toggleNode, type ScopeNode } from './scope-tree'; +import { FIDELITY, fidelityLeaf, groupAccounts, groupId } from './scope-tree'; import { addDays, addMonths } from '../../shared/dates'; import { perYear } from '../../shared/typed-columns'; @@ -18,26 +17,9 @@ export function groupsOf(ds: Dataset): Group[] { return groupAccounts(ds.accounts).map((g) => ({ ...g, balance: g.accounts.reduce((s, a) => s + (a.balance ?? 0), 0) })); } -// The scope rules run on the scope tree (app/scope-tree.ts); until the 401k joins it the tree holds the Fidelity accounts -// alone, and the scope is kept in today's words ('all', 'group:', 'account:', 'set:'). One tree per dataset -const trees = new WeakMap(); -export function fidelityTree(ds: Dataset): ScopeNode { - let tree = trees.get(ds); - if (!tree) { tree = buildTree({ fidelity: ds.accounts }); trees.set(ds, tree); } - return tree; -} -const leafSet = (numbers: Iterable): Set => new Set(Array.from(numbers).map(fidelityLeaf)); -const numbersOf = (tree: ScopeNode, leaves: ReadonlySet): string[] => leavesShown(tree, leaves).map((id) => id.slice(fidelityLeaf('').length)); -// a node of the tree as the key of its chip in today's strip: all, group:, account: +// the key of a group chip in the scope tree ('group:fidelity/'), for the owner's order of groups const GROUP_KEY = groupId(FIDELITY, ''); -const chipKey = (id: string): string => (id.startsWith(GROUP_KEY) ? `group:${id.slice(GROUP_KEY.length)}` : id.startsWith(fidelityLeaf('')) ? `account:${id.slice(fidelityLeaf('').length)}` : id); - -/** the scope kept in today's words as the ticked leaves of the tree ('none': nothing ticked, 'all': every leaf) */ -export const leavesOfScope = (ds: Dataset, scope: Scope): Set => leafSet(accountsIn(ds, scope).map((a) => a.number)); -/** the ticked leaves of the strip as the scope kept in today's words */ -export const scopeOfLeaves = (ds: Dataset, leaves: ReadonlySet): Scope => scopeOf(ds, numbersOf(fidelityTree(ds), leaves)); -/** a chip of the strip as its mark in `Prefs.collapsed`: ALL_FOLD for the root, the name of a group */ -export const foldKey = (id: string): string => (id === ROOT ? ALL_FOLD : id.startsWith(GROUP_KEY) ? id.slice(GROUP_KEY.length) : id); + /** * A chip dropped before another of its parent (a drag or Alt+arrows on the strip) as the owner's order to keep: accounts * within their group (`accountOrder`), groups as a whole (`groupOrder`); null for chips that do not move together @@ -94,84 +76,6 @@ export function stepMove(order: string[], id: string, step: -1 | 1): [moved: str return step < 0 ? [id, other] : [other, id]; } -/** the folded mark of All accounts in `Prefs.collapsed`; group names mark folded groups */ -export const ALL_FOLD = '*'; - -/** - * A click on All accounts or a group chip as a button (owner 2026-11-24): folds or unfolds it, the selection stays. - * All accounts unfolds everything (every group open again) or folds everything; a group folds only its accounts - */ -export function toggleFold(collapsed: string[], name: string): string[] { - if (name === ALL_FOLD) return collapsed.includes(ALL_FOLD) || collapsed.length ? [] : [ALL_FOLD]; - return collapsed.includes(name) ? collapsed.filter((g) => g !== name) : collapsed.concat(name); -} - -export function accountsIn(ds: Dataset, scope: Scope): Account[] { - if (scope.startsWith('group:')) return ds.accounts.filter((a) => a.group === scope.slice(6)); - if (scope.startsWith('account:')) return ds.accounts.filter((a) => a.number === scope.slice(8)); - if (scope.startsWith('set:')) { const set = new Set(scope.slice(4).split(',')); return ds.accounts.filter((a) => set.has(a.number)); } - if (scope === 'none') return []; - return ds.accounts; -} - -/** - * The name of what is shown, the Balance card's title (owner 2026-11-24: "All accounts" when all are chosen, any other - * choice named by its accounts, "Elena + Ameliia + Elena ROTH IRA"): nothing or all = `all`, a whole group = its name, up to - * three accounts = their names joined by " + ", more = `count(n)` - */ -export function scopeTitle(scope: Scope, accounts: Account[], words: { all: string; count: (n: number) => string }): string { - if (scope === 'none' || scope === 'all') return words.all; - if (scope.startsWith('group:')) return scope.slice(6); - return accounts.length <= 3 ? accounts.map((a) => a.name).join(' + ') : words.count(accounts.length); -} - -/** any set of accounts as the shortest scope: none = 'none', all of them = 'all', exactly a group = 'group:', one = 'account:' */ -export function scopeOf(ds: Dataset, numbers: string[]): Scope { - const set = new Set(numbers.filter((n) => ds.accounts.some((a) => a.number === n))); - if (!set.size) return 'none'; - if (set.size === ds.accounts.length) return 'all'; - if (set.size === 1) return `account:${Array.from(set)[0]}`; - const group = groupsOf(ds).find((g) => g.accounts.length === set.size && g.accounts.every((a) => set.has(a.number))); - if (group) return `group:${group.name}`; - return `set:${ds.accounts.filter((a) => set.has(a.number)).map((a) => a.number).join(',')}`; -} - -/** - * The chips framed as chosen (owner 2026-12-03: "All accounts no needs to select all groups and individual accs, we want to - * select most responsible group"): the highest chip whose accounts are all shown and whose parent is not. Every account - * shown: only All accounts; a whole group: the group, not its accounts; the rest: each shown account, so Elena and Ameliia - * of one group, or three accounts of two groups, are framed one by one. Keys as in `data-scope`: `all`, `group:`, - * `account:` - */ -export function framedChips(ds: Dataset, shown: ReadonlySet): Set { - const out = new Set(); - framedNodes(fidelityTree(ds), leafSet(Array.from(shown))).forEach((id) => out.add(chipKey(id))); - return out; -} - -/** - * The group checkbox: with every account chosen it keeps only that group (owner 2026-12-03: "I selected Investments group - * but its not highlights", asked: only this group), so the frame goes on it (framedChips); otherwise it adds the group's - * accounts, or takes them away when the whole group is chosen - */ -export function toggleGroup(ds: Dataset, shown: ReadonlySet, group: string): Scope { - const tree = fidelityTree(ds); - return scopeOf(ds, numbersOf(tree, toggleNode(tree, leafSet(Array.from(shown)), groupId(FIDELITY, group)))); -} - -/** the account checkbox (owner 2026-11-23: "only Elena and Elena ROTH IRA"): adds or removes one account */ -export function toggleAccount(ds: Dataset, scope: Scope, number: string): Scope { - const tree = fidelityTree(ds); - return scopeOf(ds, numbersOf(tree, toggleLeaf(tree, leafSet(accountsIn(ds, scope).map((a) => a.number)), fidelityLeaf(number)))); -} - -/** a scope that no longer exists (account closed, other data) falls back to all accounts */ -export function validScope(ds: Dataset | null, scope: Scope): Scope { - if (!ds || scope === 'all') return 'all'; - if (scope === 'none') return 'none'; - return accountsIn(ds, scope).length ? scope : 'all'; -} - export interface Totals { balance: number; todayGl: number; todayGlPct: number | null; totalGl: number; totalGlPct: number | null; costBasis: number; estAnnualIncome: number; cash: number; pending: number } const sum = (xs: T[], f: (x: T) => number | undefined) => xs.reduce((s, x) => s + (f(x) ?? 0), 0); diff --git a/src/viewer/app/i18n/ru.ts b/src/viewer/app/i18n/ru.ts index 913825d..30c0135 100644 --- a/src/viewer/app/i18n/ru.ts +++ b/src/viewer/app/i18n/ru.ts @@ -870,4 +870,28 @@ export const RU: Record = { 'Federal: the standard deduction of {year} is {amount}, or your itemized total. Default standard': 'Федеральный: стандартный вычет {year} года {amount} или ваша постатейная сумма. По умолчанию стандартный', 'Itemized total': 'Постатейная сумма', 'Mortgage interest, state and property taxes up to the cap, gifts to charity: the total of Schedule A': 'Проценты по ипотеке, налоги штата и на недвижимость до лимита, пожертвования: итог Schedule A', + // the scope tree, the site map and the reference copies (the scope tree plan, 2026-12-03) + 'Fidelity': 'Fidelity', + 'ADP': 'ADP', + 'ADP mykplan 401k': 'ADP mykplan 401k', + '401k': '401k', + 'ADP Workforce': 'ADP Workforce', + 'Work': 'Работа', + '{name}: click to show only it': '{name}: нажмите, чтобы показать только его', + 'Fold or unfold the money sources': 'Свернуть или развернуть источники денег', + '{hint}. A filter of the 401k rows; the balance is never split': '{hint}. Фильтр строк 401k; баланс не делится', + 'Site map': 'Карта сайта', + 'Every page, and the pages as they were before the new navigation': 'Все страницы и страницы в том виде, какими они были до новой навигации', + 'Shown for any account: the balance, the accounts and the cards of what is ticked': 'Есть для любого счёта: баланс, счета и карточки отмеченного', + 'Shown for Fidelity accounts: the positions held': 'Есть для счетов Fidelity: позиции', + 'Shown for Fidelity transactions or the 401k history': 'Есть для операций Fidelity или истории 401k', + 'Shown for Fidelity accounts: Watchlist, Investments, Dividends, DRIPs': 'Есть для счетов Fidelity: Watchlist, Investments, Dividends, DRIPs', + 'Shown for a taxable Fidelity account once its tax summary is read': 'Есть для налогооблагаемого счёта Fidelity, когда прочитана его налоговая сводка', + 'Shown for ADP Workforce, once it is read': 'Есть для ADP Workforce, когда он прочитан', + 'Reference copies': 'Эталонные копии', + 'The pages as they were before the new navigation, kept to compare the numbers of the new pages with them': 'Страницы в том виде, какими они были до новой навигации: сохранены, чтобы сверять с ними числа новых страниц', + 'compare with': 'сравнить с', + 'no data read yet': 'данные ещё не прочитаны', + 'Reference copy of {page}: the page as it was before the new navigation': 'Эталонная копия {page}: страница в том виде, какой она была до новой навигации', + 'Open the new page': 'Открыть новую страницу', }; diff --git a/src/viewer/app/merge.ts b/src/viewer/app/merge.ts index 55cb810..c99a0c5 100644 --- a/src/viewer/app/merge.ts +++ b/src/viewer/app/merge.ts @@ -17,7 +17,6 @@ import type { Account, Position } from '../../shared/model'; import { adjustedDrip, dripGap, symbolDrip, type Drip } from './derive'; import { FIELD_COLUMNS } from './position-columns'; -import type { MainTab } from './prefs'; export type MergeKind = 'sum' | 'static' | 'recomputed' | 'agree' | 'any' | 'blank'; export const MERGE_KINDS: readonly MergeKind[] = ['sum', 'static', 'recomputed', 'agree', 'any', 'blank']; @@ -67,7 +66,7 @@ export const mergeOn = (merge: boolean, shownAccounts: number): boolean => merge * merged (owner 2026-11-27: "if we click on that while we are sitting on Summary we will switch to Positions page with * merge mode enabled"), never unmerged */ -export const toggleMerge = (p: { merge: boolean; tab?: MainTab }): { merge: boolean; tab: MainTab } => ({ merge: p.tab !== undefined && p.tab !== 'positions' ? true : !p.merge, tab: 'positions' }); +export const toggleMerge = (p: { merge: boolean; tab?: string }): { merge: boolean; tab: 'positions' } => ({ merge: p.tab !== undefined && p.tab !== 'positions' ? true : !p.merge, tab: 'positions' }); type Value = string | number | boolean; const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); diff --git a/src/viewer/app/pages.test.ts b/src/viewer/app/pages.test.ts index 2ce6e74..87baac3 100644 --- a/src/viewer/app/pages.test.ts +++ b/src/viewer/app/pages.test.ts @@ -3,8 +3,7 @@ /// // The pages table: which pages a scope shows, which one opens, today's seven tabs. Account numbers here are made up import { expect, test } from 'bun:test'; -import { LEAF_401K, LEAF_PAY, PAGES, REFERENCE_PAGES, openPage, pageFacts, pageName, referenceName, referenceSource, referenceTabs, visiblePages } from './pages'; -import { MAIN_TABS } from './prefs'; +import { LEAF_401K, LEAF_PAY, PAGES, REFERENCE_PAGES, REFERENCE_TABS as MAIN_TABS, oldestRead, openPage, pageFacts, pageName, referenceName, referenceSource, referenceTabs, shownPages, visiblePages } from './pages'; const taxable = { id: 'fidelity:X1', shelter: null }; const roth = { id: 'fidelity:R1', shelter: 'free' as const }; @@ -57,9 +56,25 @@ test('today\'s seven pages, in today\'s order, each with its source and its new expect(REFERENCE_PAGES.map((r) => r.page)).toEqual(['summary', 'positions', 'activity', 'reports', 'taxes', 'summary', 'activity']); }); -test('today\'s tabs: the ADP pages once the 401k is read, Fidelity Taxes once a tax year is read', () => { - expect(referenceTabs({ adp: false, taxYears: false })).toEqual(['summary', 'positions', 'activity', 'reports']); - expect(referenceTabs({ adp: true, taxYears: false })).toEqual(['summary', 'positions', 'activity', 'reports', 'adpSummary', 'adpActivity']); - expect(referenceTabs({ adp: false, taxYears: true })).toEqual(['summary', 'positions', 'activity', 'reports', 'taxes']); - expect(referenceTabs({ adp: true, taxYears: true })).toEqual(MAIN_TABS.slice()); +test('today\'s tabs: the ADP pages once the 401k is read, the Fidelity ones once Fidelity is, Fidelity Taxes once a tax year is read', () => { + expect(referenceTabs({ fidelity: true, adp: false, taxYears: false })).toEqual(['summary', 'positions', 'activity', 'reports']); + expect(referenceTabs({ fidelity: true, adp: true, taxYears: false })).toEqual(['summary', 'positions', 'activity', 'reports', 'adpSummary', 'adpActivity']); + expect(referenceTabs({ fidelity: true, adp: false, taxYears: true })).toEqual(['summary', 'positions', 'activity', 'reports', 'taxes']); + expect(referenceTabs({ fidelity: true, adp: true, taxYears: true })).toEqual(MAIN_TABS.slice()); + expect(referenceTabs({ fidelity: false, adp: true, taxYears: true })).toEqual(['adpSummary', 'adpActivity']); +}); + +test('the tabs drawn now: Taxes is the Fidelity Taxes page (a taxable account and a tax year read), no Salary yet', () => { + const tabs = (have: boolean, ...leaves: Array<{ id: string; shelter?: 'free' | 'deferred' | null }>) => shownPages(pageFacts(leaves), { taxYears: have }); + expect(tabs(true, taxable, roth, k401, pay)).toEqual(['summary', 'positions', 'activity', 'reports', 'taxes']); + expect(tabs(false, taxable, k401)).toEqual(['summary', 'positions', 'activity', 'reports']); + expect(tabs(true, k401)).toEqual(['summary', 'activity']); + expect(tabs(true, roth)).toEqual(['summary', 'positions', 'activity', 'reports']); + expect(tabs(true, pay)).toEqual([]); +}); + +test('As of: the oldest read among the sources shown', () => { + expect(oldestRead([{ name: 'Fidelity', at: '2026-12-03T17:04:00Z' }, { name: 'ADP 401k', at: '2026-12-02T23:10:00Z' }])).toEqual({ name: 'ADP 401k', at: '2026-12-02T23:10:00Z' }); + expect(oldestRead([{ name: 'Fidelity', at: '2026-12-03T17:04:00Z' }])!.name).toBe('Fidelity'); + expect(oldestRead([])).toBeNull(); }); diff --git a/src/viewer/app/pages.ts b/src/viewer/app/pages.ts index 919fc1a..637962e 100644 --- a/src/viewer/app/pages.ts +++ b/src/viewer/app/pages.ts @@ -5,10 +5,9 @@ // and ADP subgroup we would not need [the page prefixes]"); a page is shown only where the scope has data for it // - REFERENCE_PAGES: the seven pages of today (Fidelity Summary ... ADP Activity), kept as they are for comparing the new // numbers with them (owner 2026-12-03: "requirement for site map and having previous pages versions backup in this -// sitemap should remain"); until the scope tree takes over they are the tabs the app draws +// sitemap should remain"): reached from the site map at their own addresses, never saved as the page to open import type { Shelter } from '../../shared/tax'; import { t } from './i18n'; -import type { MainTab } from './prefs'; export const PAGES = ['summary', 'positions', 'activity', 'reports', 'taxes', 'salary'] as const; export type Page = (typeof PAGES)[number]; @@ -57,8 +56,22 @@ export function openPage(wanted: T, visible: readonly T[]): T return visible.indexOf(wanted) >= 0 ? wanted : visible[0] ?? null; } +/** + * Taxes is the Fidelity Taxes page for now (the tax added by the taxable accounts): it shows while the scope has a taxable + * Fidelity account and Fidelity's tax summary has a year; the 401k and the pay sections come later (the plan, PR 9). + * Salary waits for the ADP Workforce read. The other pages as visiblePages says + */ +export function shownPages(f: PageFacts, have: { taxYears: boolean }): Page[] { + return visiblePages(f).filter((p) => (p === 'taxes' ? have.taxYears && f.taxable : p !== 'salary')); +} + +// the pages of before the tree, in their order (owner 2026-11-29: the pages of one source carry its name, the ADP 401k +// ones after Fidelity's) +export const REFERENCE_TABS = ['summary', 'positions', 'activity', 'reports', 'taxes', 'adpSummary', 'adpActivity'] as const; +export type RefTab = (typeof REFERENCE_TABS)[number]; + /** a page of today, kept for comparing: its tab, the source it shows and the new page it becomes */ -export interface ReferencePage { tab: MainTab; source: 'fidelity' | 'adp'; page: Page } +export interface ReferencePage { tab: RefTab; source: 'fidelity' | 'adp'; page: Page } // the order of today's tabs (owner 2026-11-29: the pages of one source carry its name, the ADP 401k ones after Fidelity's) export const REFERENCE_PAGES: readonly ReferencePage[] = [ @@ -72,15 +85,23 @@ export const REFERENCE_PAGES: readonly ReferencePage[] = [ ]; /** the name of a page of today, its source first (owner 2026-11-29: "Fidelity Summary, Fidelity Positions and Fidelity Activity") */ -export const referenceName = (tab: MainTab): string => ({ summary: t('Fidelity Summary'), positions: t('Fidelity Positions'), activity: t('Fidelity Activity'), reports: t('Fidelity Reports'), taxes: t('Fidelity Taxes'), adpSummary: t('ADP Summary'), adpActivity: t('ADP Activity') })[tab]; +export const referenceName = (tab: RefTab): string => ({ summary: t('Fidelity Summary'), positions: t('Fidelity Positions'), activity: t('Fidelity Activity'), reports: t('Fidelity Reports'), taxes: t('Fidelity Taxes'), adpSummary: t('ADP Summary'), adpActivity: t('ADP Activity') })[tab]; /** the source of a page of today: the ADP pages show the 401k's money sources in the strip, the rest the Fidelity accounts */ -export const referenceSource = (tab: MainTab): 'fidelity' | 'adp' => REFERENCE_PAGES.find((r) => r.tab === tab)?.source ?? 'fidelity'; +export const referenceSource = (tab: RefTab): 'fidelity' | 'adp' => REFERENCE_PAGES.find((r) => r.tab === tab)?.source ?? 'fidelity'; /** - * Today's tabs with data: the ADP pages once the 401k history is there (owner 2026-11-30), Fidelity Taxes once Fidelity's - * tax summary has a year (owner 2026-12-03); the rest always + * Today's tabs with data: the ADP pages once the 401k history is there (owner 2026-11-30), the Fidelity ones once + * Fidelity is read, Fidelity Taxes once its tax summary has a year (owner 2026-12-03) */ -export function referenceTabs(have: { adp: boolean; taxYears: boolean }): MainTab[] { - return REFERENCE_PAGES.filter((r) => (r.tab === 'taxes' ? have.taxYears : r.source === 'adp' ? have.adp : true)).map((r) => r.tab); +export function referenceTabs(have: { fidelity: boolean; adp: boolean; taxYears: boolean }): RefTab[] { + return REFERENCE_PAGES.filter((r) => (r.source === 'adp' ? have.adp : have.fidelity && (r.tab !== 'taxes' || have.taxYears))).map((r) => r.tab); } + +/** a source's last read: its name and the ISO time */ +export interface Read { name: string; at: string } +/** + * The "As of" right of the tabs (the scope tree plan, 2026-12-03): the oldest read among the sources shown, so no number + * on the page is newer than it says; null when nothing is shown + */ +export const oldestRead = (reads: readonly Read[]): Read | null => reads.reduce((old, r) => (!old || r.at < old.at ? r : old), null); diff --git a/src/viewer/app/prefs.test.ts b/src/viewer/app/prefs.test.ts index df6d323..116f3a0 100644 --- a/src/viewer/app/prefs.test.ts +++ b/src/viewer/app/prefs.test.ts @@ -2,7 +2,7 @@ /// /// import { expect, test } from 'bun:test'; -import { COLUMNS_V, DEFAULT_PREFS, SORT_DEFAULT_V, loadPrefs, withFirstColumns } from './prefs'; +import { COLUMNS_V, DEFAULT_PREFS, NAV_V, SORT_DEFAULT_V, loadPrefs, migrateNav, withFirstColumns } from './prefs'; import { NEW_COLUMNS_BY_V, NEW_COLUMN_KEYS } from './position-columns'; const load = (json: string | null) => loadPrefs({ getItem: () => json }); @@ -12,11 +12,29 @@ test('no saved value or broken JSON gives the defaults', () => { expect(load('{broken')).toEqual(DEFAULT_PREFS); }); -test('scope and search must be strings', () => { +test('scope ids and search must be strings', () => { const p = load('{"scope":5,"search":null}'); - expect(p.scope).toBe('all'); + expect(p.scope).toEqual(['all']); expect(p.search).toBe(''); - expect(load('{"scope":"account:X1","search":"abc"}').scope).toBe('account:X1'); + expect(load('{"navV":2,"scope":["fidelity:X1",3],"search":"abc"}').scope).toEqual(['fidelity:X1']); +}); + +test('the navigation of before the tree is moved over once (owner 2026-12-03: one scope tree, pages without a prefix)', () => { + // the ADP pages: the same page of the tree with the scope ADP + expect(migrateNav({ tab: 'adpSummary', scope: 'group:Investment' })).toEqual({ navV: NAV_V, tab: 'summary', scope: ['adp'], collapsed: [] }); + expect(migrateNav({ tab: 'adpActivity' })).toEqual({ navV: NAV_V, tab: 'activity', scope: ['adp'], collapsed: [] }); + // a Fidelity page keeps its page; the scope in its old words as ids; the folds as node ids + expect(migrateNav({ tab: 'positions', scope: 'account:X1', collapsed: ['*', 'Retirement'] })).toEqual({ navV: NAV_V, tab: 'positions', scope: ['fidelity:X1'], collapsed: ['all', 'group:fidelity/Retirement'] }); + expect(migrateNav({ tab: 'taxes', scope: 'group:Investment' }).scope).toEqual(['group:fidelity/Investment']); + expect(migrateNav({ scope: 'set:X1,X2' }).scope).toEqual(['fidelity:X1', 'fidelity:X2']); + expect(migrateNav({ scope: 'all' }).scope).toEqual(['all']); + expect(migrateNav({ scope: 'none' }).scope).toEqual([]); + // moved once: a kept tree navigation stays as it is (a node id named 'all' is not a group) + expect(migrateNav({ navV: NAV_V, tab: 'reports', scope: ['adp:401k'], collapsed: ['all', 'adp:401k'] })).toEqual({ navV: NAV_V, tab: 'reports', scope: ['adp:401k'], collapsed: ['all', 'adp:401k'] }); + expect(migrateNav({ navV: NAV_V, tab: 'adpSummary', scope: 'x' })).toEqual({ navV: NAV_V, tab: 'summary', scope: ['all'], collapsed: [] }); + // through the store: an old saved choice loads as the new one + const p = load('{"tab":"adpSummary","scope":"all","collapsed":["Investment"]}'); + expect([p.tab, p.scope, p.collapsed, p.navV]).toEqual(['summary', ['adp'], ['group:fidelity/Investment'], NAV_V]); }); test('period aliases and junk', () => { diff --git a/src/viewer/app/prefs.ts b/src/viewer/app/prefs.ts index 023b20d..d650042 100644 --- a/src/viewer/app/prefs.ts +++ b/src/viewer/app/prefs.ts @@ -13,22 +13,22 @@ import { DEFAULT_HIDDEN, FIRST_COLUMNS_BY_V, NEW_COLUMNS_BY_V } from './position import { asActivityPeriod, type ActivityPeriod } from './activity'; import { asAdpHidden, type AdpSourceChip } from './adp-sources'; import { INCOME_SPANS, SPANS, asSpans, type Span } from './spans'; +import { PAGES, type Page } from './pages'; +import { ADP, ROOT, migrateFolded, oldScopeIds } from './scope-tree'; import { ACCOUNT_SORTS, DEFAULT_DIV_SORTS, asDivSize, asDivSorts, asDivWhen, asDivWindow, asKind, asPastWindow, type AccountSort, type DivSize, type DivSort, type DivWhen, type DivWindow, type Kind, type PastWindow } from './derive'; -// the pages, the Fidelity ones first; the ADP 401k page shows once its history is there (owner 2026-11-30), Fidelity -// Taxes once Fidelity's tax summary has a year (owner 2026-12-03) -export const MAIN_TABS = ['summary', 'positions', 'activity', 'reports', 'taxes', 'adpSummary', 'adpActivity'] as const; -export type MainTab = (typeof MAIN_TABS)[number]; // the reports of the Fidelity Reports page (owner 2026-12-01: Watchlist, then Dividends) export const REPORTS = ['watchlist', 'investments', 'dividends', 'drips'] as const; export type Report = (typeof REPORTS)[number]; -// 'all', 'none', 'group:', 'account:' or 'set:,' -export type Scope = string; +// the ticked leaves of the scope tree (app/scope-tree.ts tickedOf): 'fidelity:', 'adp:401k'; a node id ('all', +// 'fidelity', 'adp', 'group:fidelity/') stands for its leaves until the next tick writes them +export type Scope = string[]; export interface Prefs { scope: Scope; - tab: MainTab; + tab: Page; // the wanted page: drawn while the scope has data for it (app/pages.ts openPage) + navV: number; // the navigation kept: 2 = the scope tree (NAV_V); a lower one is moved over once (migrateNav) sort: { key: string; dir: 1 | -1 }; search: string; // the filter of the Symbol column (symbol or name) filters: Record; // the filters of the other positions columns, by column key (src/shared/typed-columns.ts) @@ -58,7 +58,7 @@ export interface Prefs { accountSort: AccountSort; // the Accounts card order accountOrder: string[]; // the owner's own order of accounts (dragged in the accounts bar) groupOrder: string[]; // the owner's own order of groups (dragged as a whole) - collapsed: string[]; // folded groups in the accounts bar, '*' = All accounts folded + collapsed: string[]; // the folded chips of the strip by node id ('all' = everything folded, 'adp:401k' its money sources) merge: boolean; // Positions of several accounts as one line per ticker (app/merge.ts) adpHidden: AdpSourceChip[]; // the money-source chips of the ADP pages switched off (app/adp-sources.ts) // the time spans each ADP Summary card shows, its own choice (owner 2026-12-01, app/spans.ts) @@ -80,9 +80,27 @@ export interface Prefs { taxYear: string; } -export const DEFAULT_PREFS: Prefs = { scope: 'all', tab: 'summary', sort: { key: 'marketCap', dir: -1 }, search: '', filters: {}, types: {}, hidden: DEFAULT_HIDDEN.slice(), columnsV: 9, columns: [], period: '1Y', views: {}, moversBy: 'pct', moversOf: 'all', incomeOf: 'all', incomeSpans: INCOME_SPANS.slice(), dividendsOf: 'all', activityPeriod: 'All', dividendsSort: DEFAULT_DIV_SORTS.slice(), dividendsSize: 'payout', dividendsWindow: 'DTM', dividendsWhen: 'upcoming', dividendsPastWindow: 'MTD', accountSort: 'mine', accountOrder: [], groupOrder: [], collapsed: [], merge: false, reportOf: { watchlist: 'all', investments: 'all', dividends: 'all', drips: 'all' }, reportTax: { watchlist: 'all', investments: 'all', dividends: 'all', drips: 'all' }, report: 'watchlist', adpHidden: [], adpContribSpans: SPANS.slice(), adpIncomeSpans: SPANS.slice(), adpPeriod: '1Y', adpActivityPeriod: asActivityPeriod(undefined), fundamentalsView: 'page', fundamentalsIntervals: ['D'], fundamentalsBefore: [], fundamentalsSplit: {}, noticesAt: 'top-right', fundamentalsOpen: '', taxYear: '' }; +export const DEFAULT_PREFS: Prefs = { scope: [ROOT], tab: 'summary', navV: 2, sort: { key: 'marketCap', dir: -1 }, search: '', filters: {}, types: {}, hidden: DEFAULT_HIDDEN.slice(), columnsV: 9, columns: [], period: '1Y', views: {}, moversBy: 'pct', moversOf: 'all', incomeOf: 'all', incomeSpans: INCOME_SPANS.slice(), dividendsOf: 'all', activityPeriod: 'All', dividendsSort: DEFAULT_DIV_SORTS.slice(), dividendsSize: 'payout', dividendsWindow: 'DTM', dividendsWhen: 'upcoming', dividendsPastWindow: 'MTD', accountSort: 'mine', accountOrder: [], groupOrder: [], collapsed: [], merge: false, reportOf: { watchlist: 'all', investments: 'all', dividends: 'all', drips: 'all' }, reportTax: { watchlist: 'all', investments: 'all', dividends: 'all', drips: 'all' }, report: 'watchlist', adpHidden: [], adpContribSpans: SPANS.slice(), adpIncomeSpans: SPANS.slice(), adpPeriod: '1Y', adpActivityPeriod: asActivityPeriod(undefined), fundamentalsView: 'page', fundamentalsIntervals: ['D'], fundamentalsBefore: [], fundamentalsSplit: {}, noticesAt: 'top-right', fundamentalsOpen: '', taxYear: '' }; const KEY = 'accounts.prefs'; +/** the navigation of the scope tree (owner 2026-12-03); prefs kept before it are moved over once */ +export const NAV_V = 2; +const strings = (x: unknown): string[] => (Array.isArray(x) ? x.filter((v): v is string => typeof v === 'string') : []); +/** + * The navigation kept before the tree, moved over once: the ADP pages become the pages of the tree with the scope ADP + * (`adpSummary` -> Summary, `adpActivity` -> Activity), the Fidelity ones keep their page; the scope in its old words + * ('all', 'group:Investment', 'account:', 'set:,') as node and leaf ids; the folded chips as node ids. Kept + * after the move: tab, scope and folds as they are, cleaned + */ +export function migrateNav(p: { navV?: unknown; tab?: unknown; scope?: unknown; collapsed?: unknown }): Pick { + const page = (x: unknown): Page => ((PAGES as readonly unknown[]).indexOf(x) >= 0 ? (x as Page) : 'summary'); + if (p.navV === NAV_V) return { navV: NAV_V, tab: page(p.tab), scope: Array.isArray(p.scope) ? strings(p.scope) : DEFAULT_PREFS.scope.slice(), collapsed: strings(p.collapsed) }; + const adp = p.tab === 'adpSummary' || p.tab === 'adpActivity'; + const tab = p.tab === 'adpSummary' ? 'summary' : p.tab === 'adpActivity' ? 'activity' : page(p.tab); + const scope = adp ? [ADP] : typeof p.scope === 'string' ? oldScopeIds(p.scope) : DEFAULT_PREFS.scope.slice(); + return { navV: NAV_V, tab, scope, collapsed: migrateFolded(strings(p.collapsed)) }; +} + export function loadPrefs(storage: Pick | undefined = globalThis.localStorage): Prefs { try { const raw = storage?.getItem(KEY); @@ -90,11 +108,10 @@ export function loadPrefs(storage: Pick | undefined = global return { ...DEFAULT_PREFS, ...p, - scope: typeof p.scope === 'string' ? p.scope : 'all', + ...migrateNav(p), search: typeof p.search === 'string' ? p.search : '', filters: cleanFilters(p.filters), types: cleanTypes(p.types), - tab: (MAIN_TABS as readonly string[]).indexOf(String(p.tab)) >= 0 ? (p.tab as MainTab) : 'summary', // the columns added later start hidden once, for a choice saved before them (owner 2026-11-24: all of Fidelity's // columns, the table keeps the owner's view) // no choice saved at all: the defaults of a new browser @@ -121,7 +138,6 @@ export function loadPrefs(storage: Pick | undefined = global accountSort: (ACCOUNT_SORTS as readonly string[]).indexOf(String(p.accountSort)) >= 0 ? (p.accountSort as AccountSort) : 'mine', accountOrder: Array.isArray(p.accountOrder) ? p.accountOrder.filter((x): x is string => typeof x === 'string') : [], groupOrder: Array.isArray(p.groupOrder) ? p.groupOrder.filter((x): x is string => typeof x === 'string') : [], - collapsed: Array.isArray(p.collapsed) ? p.collapsed.filter((x): x is string => typeof x === 'string') : [], merge: p.merge === true, adpHidden: asAdpHidden(p.adpHidden), adpContribSpans: asSpans(p.adpContribSpans), diff --git a/src/viewer/app/route.test.ts b/src/viewer/app/route.test.ts index 02439b3..3d54e0d 100644 --- a/src/viewer/app/route.test.ts +++ b/src/viewer/app/route.test.ts @@ -3,9 +3,8 @@ /// // The page in the address: today's pages, the pages of the tree, the site map; never an account number or a group name import { expect, test } from 'bun:test'; -import { PAGES } from './pages'; -import { MAIN_TABS } from './prefs'; -import { REFERENCE_HASH, ROUTE_SCOPES, hashOf, hashToWrite, parseHash, tabOfHash, type Route } from './route'; +import { PAGES, REFERENCE_TABS as MAIN_TABS } from './pages'; +import { REFERENCE_HASH, ROUTE_SCOPES, hashOf, hashStep, parseHash, routeOf, scopeIdOf, type Route } from './route'; test('today\'s seven pages have their own addresses, read back to the same page', () => { expect(MAIN_TABS.map((tab) => hashOf({ kind: 'reference', tab }))).toEqual(['#fidelity-summary', '#fidelity-positions', '#fidelity-activity', '#fidelity-reports', '#fidelity-taxes', '#adp-summary', '#adp-activity']); @@ -37,13 +36,21 @@ test('an address holds only fixed words, never an account number or a group name expect(Object.values(REFERENCE_HASH).every((h) => !/\d/.test(h))).toBe(true); }); -test('while today\'s pages are drawn, only their addresses choose a page; the saved page is written back', () => { - expect(tabOfHash('#adp-activity')).toBe('adpActivity'); - expect(tabOfHash('#summary')).toBeNull(); - expect(tabOfHash('#sitemap')).toBeNull(); - expect(tabOfHash('')).toBeNull(); - expect(hashToWrite('', 'summary')).toBe('#fidelity-summary'); - expect(hashToWrite('#fidelity-summary', 'positions')).toBe('#fidelity-positions'); - expect(hashToWrite('#adp-summary', 'adpSummary')).toBeNull(); - expect(hashToWrite('#sitemap', 'taxes')).toBe('#fidelity-taxes'); +test('the address of what is drawn: the wanted page with its scope word, a reference copy, the site map', () => { + expect(hashOf(routeOf({ kind: 'page' }, 'positions', 'fidelity'))).toBe('#positions/fidelity'); + expect(hashOf(routeOf({ kind: 'page' }, 'summary', null))).toBe('#summary'); + expect(hashOf(routeOf({ kind: 'reference', tab: 'adpActivity' }, 'summary', 'all'))).toBe('#adp-activity'); + expect(hashOf(routeOf({ kind: 'sitemap' }, 'summary', 'all'))).toBe('#sitemap'); + expect(ROUTE_SCOPES.map(scopeIdOf)).toEqual(['all', 'fidelity', 'adp']); +}); + +test('another page adds a step to the history, the same page under another scope writes over it', () => { + const page = (p: 'summary' | 'activity', scope: 'all' | 'adp' | null = null): Route => ({ kind: 'page', page: p, scope }); + expect(hashStep(null, page('summary'))).toBe('replace'); + expect(hashStep(page('summary'), page('activity'))).toBe('push'); + expect(hashStep(page('summary', 'all'), page('summary', 'adp'))).toBe('replace'); + expect(hashStep(page('summary'), { kind: 'sitemap' })).toBe('push'); + expect(hashStep({ kind: 'reference', tab: 'summary' }, { kind: 'reference', tab: 'adpSummary' })).toBe('push'); + expect(hashStep({ kind: 'reference', tab: 'summary' }, { kind: 'reference', tab: 'summary' })).toBe('replace'); + expect(hashStep({ kind: 'sitemap' }, page('summary'))).toBe('push'); }); diff --git a/src/viewer/app/route.ts b/src/viewer/app/route.ts index 110875c..51de571 100644 --- a/src/viewer/app/route.ts +++ b/src/viewer/app/route.ts @@ -2,14 +2,15 @@ // The page in the address (owner 2026-12-03, the scope tree plan: "a hash wins on load, a page click writes it"), so a page // can be bookmarked and Back goes to the page before. Three kinds of address: // - today's seven pages, kept forever as the addresses of the reference copies: #fidelity-summary ... #adp-activity -// - the pages of the scope tree: # or #/ (drawn once the tree takes over) -// - #sitemap, reserved for the site map of every page +// - the pages of the scope tree: # or #/ +// - #sitemap, the site map of every page // Never an account number or a group name: only these fixed words ever go into an address -import { PAGES, type Page } from './pages'; -import type { MainTab } from './prefs'; +import { createStore } from '../../shared/store'; +import { PAGES, type Page, type RefTab } from './pages'; +import { ADP, FIDELITY, ROOT, type ScopeWord } from './scope-tree'; /** the address of each page of today */ -export const REFERENCE_HASH: Readonly> = { +export const REFERENCE_HASH: Readonly> = { summary: 'fidelity-summary', positions: 'fidelity-positions', activity: 'fidelity-activity', @@ -20,10 +21,10 @@ export const REFERENCE_HASH: Readonly> = { }; export const SITEMAP_HASH = 'sitemap'; export const ROUTE_SCOPES = ['all', 'fidelity', 'adp'] as const; -export type RouteScope = (typeof ROUTE_SCOPES)[number]; +export type RouteScope = ScopeWord; export type Route = - | { kind: 'reference'; tab: MainTab } + | { kind: 'reference'; tab: RefTab } | { kind: 'page'; page: Page; scope: RouteScope | null } | { kind: 'sitemap' }; @@ -32,7 +33,7 @@ export function parseHash(hash: string): Route | null { const h = decodeURIComponent(hash.replace(/^#\/?/, '')).trim().toLowerCase(); if (!h) return null; if (h === SITEMAP_HASH) return { kind: 'sitemap' }; - const tab = (Object.keys(REFERENCE_HASH) as MainTab[]).find((k) => REFERENCE_HASH[k] === h); + const tab = (Object.keys(REFERENCE_HASH) as RefTab[]).find((k) => REFERENCE_HASH[k] === h); if (tab) return { kind: 'reference', tab }; const [page, scope, ...rest] = h.split('/'); if (rest.length || (PAGES as readonly string[]).indexOf(page!) < 0) return null; @@ -47,17 +48,26 @@ export function hashOf(route: Route): string { return `#${route.page}${route.scope ? `/${route.scope}` : ''}`; } +/** what the app draws: a page of the tree (the saved page), a reference copy, or the site map */ +export type View = { kind: 'page' } | { kind: 'reference'; tab: RefTab } | { kind: 'sitemap' }; +/** the view of this visit: never saved, so a reference copy or the site map is never the page the app opens on */ +export const routeView = createStore({ kind: 'page' }); + +/** the address of what is drawn: the reference copy, the site map, or the wanted page with the scope word when there is one */ +export function routeOf(view: View, page: Page, scope: RouteScope | null): Route { + return view.kind === 'page' ? { kind: 'page', page, scope } : view; +} + +/** the scope word of an address as the kept scope: the node it names */ +export const scopeIdOf = (w: RouteScope): string => (w === 'all' ? ROOT : w === 'fidelity' ? FIDELITY : ADP); + /** - * What the address does to the saved page while the app draws today's pages: the page of today it names, or null (none, - * unknown, or an address of a page that is not drawn yet: the saved page stays and the address follows it) + * How the address follows a change: another page, reference copy or the site map adds a step to the history, so Back + * walks them; the same page under another scope (or the data coming in) writes over the step in place; the first one too */ -export const tabOfHash = (hash: string): MainTab | null => { - const r = parseHash(hash); - return r && r.kind === 'reference' ? r.tab : null; -}; - -/** the address to write for the saved page, or null when the address already says it */ -export function hashToWrite(current: string, tab: MainTab): string | null { - const want = hashOf({ kind: 'reference', tab }); - return current === want ? null : want; +export function hashStep(prev: Route | null, next: Route): 'push' | 'replace' { + if (!prev || prev.kind !== next.kind) return prev ? 'push' : 'replace'; + if (prev.kind === 'page' && next.kind === 'page') return prev.page === next.page ? 'replace' : 'push'; + if (prev.kind === 'reference' && next.kind === 'reference') return prev.tab === next.tab ? 'replace' : 'push'; + return 'replace'; } diff --git a/src/viewer/app/scope-tree.test.ts b/src/viewer/app/scope-tree.test.ts index 7a00678..b10993b 100644 --- a/src/viewer/app/scope-tree.test.ts +++ b/src/viewer/app/scope-tree.test.ts @@ -4,7 +4,7 @@ // The scope tree: the plan's traces (owner 2026-12-03) and the rules of the strip. Names and numbers are made up import { expect, test } from 'bun:test'; import { pageFacts, visiblePages } from './pages'; -import { ADP, FIDELITY, LEAF_401K, LEAF_PAY, ROOT, buildTree, checkState, chipKids, chipLabel, fidelityLeaf, framedNodes, groupAccounts, groupId, leavesOf, migrateFolded, migrateScope, nodeOf, onlyNode, pathTo, scopeOf, scopeTitle, shownLeaves, toggleLeaf, toggleNode, validScope, type ScopeNode } from './scope-tree'; +import { ADP, FIDELITY, LEAF_401K, LEAF_PAY, ROOT, buildTree, checkState, chipKids, chipLabel, fidelityLeaf, framedNodes, groupAccounts, groupId, leavesOf, leafNodes, migrateFolded, migrateScope, nodeOf, oldScopeIds, scopeWord, tickedOf, toggleFolded, treeWords, onlyNode, pathTo, scopeOf, scopeTitle, shownLeaves, toggleLeaf, toggleNode, validScope, type ScopeNode } from './scope-tree'; const acct = (number: string, name: string, group: string, type?: string) => ({ number, name, group, type }); // Fidelity = Investment {A1, A2}, Retirement {R1}; ADP = {K} (the plan's traces) @@ -138,6 +138,41 @@ test('a kept scope: only the leaves still there; the scope of before the tree as expect(migrateFolded(['*', 'Retirement'])).toEqual([ROOT, RET]); }); +test('the kept scope: leaf ids, a node id standing for its leaves; unknown ids left out', () => { + expect(Array.from(tickedOf(tree, [FIDELITY]))).toEqual([A1, A2, R1]); + expect(Array.from(tickedOf(tree, [ADP, A1]))).toEqual([A1, K]); + expect(Array.from(tickedOf(tree, [ROOT]))).toEqual(ALL); + expect(Array.from(tickedOf(tree, ['fidelity:closed', 'group:fidelity/Gone']))).toEqual([]); + expect(oldScopeIds('all')).toEqual([ROOT]); + expect(oldScopeIds('none')).toEqual([]); + expect(oldScopeIds('group:Investment')).toEqual([INV]); + expect(oldScopeIds('set:A2,R1')).toEqual([A2, R1]); + expect(leafNodes(tree, [R1, 'nope']).map((n) => [n.id, n.shelter])).toEqual([[R1, 'free']]); +}); + +test('the scope as an address word: all, one whole source, else none (never a number or a group name)', () => { + expect([scopeWord(tree, []), scopeWord(tree, [ROOT]), scopeWord(tree, ALL)]).toEqual(['all', 'all', 'all']); + expect([scopeWord(tree, [FIDELITY]), scopeWord(tree, [A1, A2, R1]), scopeWord(tree, [ADP]), scopeWord(tree, [K])]).toEqual(['fidelity', 'fidelity', 'adp', 'adp']); + expect([scopeWord(tree, [INV]), scopeWord(tree, [A1, K])]).toEqual([null, null]); + // a kept word says itself before the tree is read + expect(scopeWord(buildTree({ fidelity: [] }), [FIDELITY])).toBe('fidelity'); +}); + +test('a click on a chip folds it; the root folds everything or opens everything', () => { + expect(toggleFolded([], INV)).toEqual([INV]); + expect(toggleFolded([INV, RET], INV)).toEqual([RET]); + expect(toggleFolded([], ROOT)).toEqual([ROOT]); + expect(toggleFolded([ROOT], ROOT)).toEqual([]); + expect(toggleFolded([RET, K], ROOT)).toEqual([]); +}); + +test('the strip\'s words: the short labels and the full names', () => { + const w = treeWords(); + expect([w.all, w.allShort, w.k401, w.k401Short, w.payShort]).toEqual(['All accounts', 'All', 'ADP mykplan 401k', '401k', 'Work']); + const t = buildTree({ fidelity: FID, k401: true }, w); + expect([chipLabel(t, ROOT), chipLabel(t, K), nodeOf(t, K)!.name]).toEqual(['All', 'ADP 401k', 'ADP mykplan 401k']); +}); + test('nothing here changes the tree or the set it is given', () => { const before = JSON.stringify(tree); const shown = set(A1, A2); diff --git a/src/viewer/app/scope-tree.ts b/src/viewer/app/scope-tree.ts index 922e9cb..5da3155 100644 --- a/src/viewer/app/scope-tree.ts +++ b/src/viewer/app/scope-tree.ts @@ -6,6 +6,7 @@ // The scope is the set of ticked leaves; nothing ticked shows the same as everything ticked (owner 2026-11-24). Every // function here is pure and never changes the tree or the set it is given import { shelterOf, type Shelter } from '../../shared/tax'; +import { t } from './i18n'; import { FIDELITY_LEAF, LEAF_401K, LEAF_PAY } from './pages'; export { FIDELITY_LEAF, LEAF_401K, LEAF_PAY }; @@ -38,6 +39,11 @@ export function groupAccounts(accounts: readonly T[ export interface TreeWords { all: string; allShort?: string; fidelity: string; adp: string; k401: string; k401Short: string; pay: string; payShort: string } export const TREE_WORDS: TreeWords = { all: 'All accounts', fidelity: 'Fidelity', adp: 'ADP', k401: 'ADP mykplan 401k', k401Short: '401k', pay: 'ADP Workforce', payShort: 'Work' }; +/** + * The words of the strip in the chosen language: short labels on the chips (owner 2026-12-03: the root "All", "All -> + * ADP: 401k and Work"), the full names in the tooltips, for a screen reader and on the cards + */ +export const treeWords = (): TreeWords => ({ all: t('All accounts'), allShort: t('All'), fidelity: t('Fidelity'), adp: t('ADP'), k401: t('ADP mykplan 401k'), k401Short: t('401k'), pay: t('ADP Workforce'), payShort: t('Work') }); /** * The tree of what has data: the Fidelity accounts (in the owner's order) by their groups, the ADP 401k and the ADP pay @@ -177,16 +183,59 @@ export function chipLabel(root: ScopeNode, id: string): string { export const validScope = (root: ScopeNode, shown: ReadonlySet): Set => new Set(scopeOf(root, shown)); /** - * The scope kept before the tree (`Prefs.scope`: 'all', 'none', 'group:', 'account:', 'set:,') as - * ticked leaves: 'all' ticks every leaf, 'none' none, a group its accounts, an account itself + * The kept scope (`Prefs.scope`) as ticked leaves. It holds leaf ids; a node id there stands for all its leaves (an + * address `#summary/fidelity` or a choice kept before the tree names a node before its leaves are read), so the next + * tick writes leaves. Ids not in the tree (an account closed, a source not read here) are left out */ -export function migrateScope(root: ScopeNode, scope: string): Set { - if (scope === 'all') return new Set(leavesOf(root)); - if (scope.startsWith('group:')) { const g = nodeOf(root, groupId(FIDELITY, scope.slice(6))); return new Set(g ? leavesOf(g) : []); } - if (scope.startsWith('account:')) return new Set(scopeOf(root, new Set([fidelityLeaf(scope.slice(8))]))); - if (scope.startsWith('set:')) return new Set(scopeOf(root, new Set(scope.slice(4).split(',').map(fidelityLeaf)))); - return new Set(); +export function tickedOf(root: ScopeNode, ids: readonly string[]): Set { + const want = new Set(); + ids.forEach((id) => { const n = nodeOf(root, id); if (n) leavesOf(n).forEach((l) => want.add(l)); }); + return new Set(scopeOf(root, want)); } +/** + * The scope kept before the tree ('all', 'none', 'group:', 'account:', 'set:,') as node ids for + * tickedOf: 'all' the root, 'none' nothing, a group its node, an account or a set their leaves + */ +export function oldScopeIds(scope: string): string[] { + if (scope === 'all') return [ROOT]; + if (scope.startsWith('group:')) return [groupId(FIDELITY, scope.slice(6))]; + if (scope.startsWith('account:')) return [fidelityLeaf(scope.slice(8))]; + if (scope.startsWith('set:')) return scope.slice(4).split(',').filter(Boolean).map(fidelityLeaf); + return []; +} + +/** the scope kept before the tree as ticked leaves: 'all' ticks every leaf, 'none' none, a group its accounts, an account itself */ +export const migrateScope = (root: ScopeNode, scope: string): Set => tickedOf(root, oldScopeIds(scope)); + /** the folded chips kept before the tree (`Prefs.collapsed`: '*' for All, Fidelity's group names) as node ids */ export const migrateFolded = (collapsed: readonly string[]): string[] => collapsed.map((c) => (c === '*' ? ROOT : c.startsWith('group:') ? c : groupId(FIDELITY, c))); + +/** + * A click on the root or a group chip as a button (owner 2026-11-24): folds or unfolds it, the selection stays. The root + * unfolds everything (every chip open again) or folds everything; another chip folds only its own children + */ +export function toggleFolded(collapsed: readonly string[], id: string): string[] { + if (id === ROOT) return collapsed.length ? [] : [ROOT]; + return collapsed.indexOf(id) >= 0 ? collapsed.filter((c) => c !== id) : collapsed.concat(id); +} + +/** the scope words an address may carry (app/route.ts): All, one whole source */ +export type ScopeWord = 'all' | 'fidelity' | 'adp'; +/** + * The scope as an address word: 'all' for nothing or every leaf ticked, a source's id when exactly its leaves are ticked, + * else null (a custom choice stays out of the address: never an account number or a group name). A kept scope that is + * one such word already says it before the tree is read + */ +export function scopeWord(root: ScopeNode, ids: readonly string[]): ScopeWord | null { + if (!ids.length || (ids.length === 1 && ids[0] === ROOT)) return 'all'; + if (ids.length === 1 && (ids[0] === FIDELITY || ids[0] === ADP)) return ids[0]; + const ticked = scopeOf(root, tickedOf(root, ids)); + const all = leavesOf(root); + if (ticked.length === all.length) return 'all'; + const exactly = (id: string) => { const n = nodeOf(root, id); const l = n ? leavesOf(n) : []; return l.length === ticked.length && l.every((x, i) => x === ticked[i]); }; + return exactly(FIDELITY) ? 'fidelity' : exactly(ADP) ? 'adp' : null; +} + +/** the shown leaves as their nodes (id and shelter), for the facts of the pages (app/pages.ts pageFacts) */ +export const leafNodes = (root: ScopeNode, ids: readonly string[]): ScopeNode[] => ids.map((id) => nodeOf(root, id)).filter((n): n is ScopeNode => !!n); diff --git a/src/viewer/app/sitemap.test.ts b/src/viewer/app/sitemap.test.ts new file mode 100644 index 0000000..10a6c67 --- /dev/null +++ b/src/viewer/app/sitemap.test.ts @@ -0,0 +1,32 @@ +/// +/// +/// +// The site map: the pages of the tree with their scopes, the reference copies of before the tree. Names are made up +import { expect, test } from 'bun:test'; +import { mapPages, mapReferences } from './sitemap'; +import { buildTree } from './scope-tree'; + +const FID = [{ number: 'A1', name: 'Joint', group: 'Investment', type: 'Brokerage' }, { number: 'R1', name: 'Kid ROTH IRA', group: 'Retirement', type: 'ROTH IRA' }]; + +test('the pages of the tree with the scopes they have data under', () => { + const both = buildTree({ fidelity: FID, k401: true }); + expect(mapPages(both, { taxYears: true })).toEqual([ + { page: 'summary', scopes: ['all', 'fidelity', 'adp'] }, + { page: 'positions', scopes: ['all', 'fidelity'] }, + { page: 'activity', scopes: ['all', 'fidelity', 'adp'] }, + { page: 'reports', scopes: ['all', 'fidelity'] }, + { page: 'taxes', scopes: ['all', 'fidelity'] }, + ]); + // no tax year read: no Taxes; only the 401k read: its two pages under All and ADP + expect(mapPages(both, { taxYears: false }).map((p) => p.page)).toEqual(['summary', 'positions', 'activity', 'reports']); + expect(mapPages(buildTree({ fidelity: [], k401: true }), { taxYears: true })).toEqual([{ page: 'summary', scopes: ['all', 'adp'] }, { page: 'activity', scopes: ['all', 'adp'] }]); + expect(mapPages(buildTree({ fidelity: [] }), { taxYears: true })).toEqual([]); +}); + +test('every reference copy in today\'s order, greyed without data, each with the new page to compare it with', () => { + const refs = mapReferences({ fidelity: true, adp: false, taxYears: false }); + expect(refs.map((r) => [r.tab, r.has, r.page, r.scope])).toEqual([ + ['summary', true, 'summary', 'fidelity'], ['positions', true, 'positions', 'fidelity'], ['activity', true, 'activity', 'fidelity'], ['reports', true, 'reports', 'fidelity'], + ['taxes', false, 'taxes', 'fidelity'], ['adpSummary', false, 'summary', 'adp'], ['adpActivity', false, 'activity', 'adp'], + ]); +}); diff --git a/src/viewer/app/sitemap.ts b/src/viewer/app/sitemap.ts new file mode 100644 index 0000000..1699f4d --- /dev/null +++ b/src/viewer/app/sitemap.ts @@ -0,0 +1,27 @@ +/// +// The site map (owner 2026-12-03: "requirement for site map and having previous pages versions backup in this sitemap +// should remain, just in case we will want to check and compare your new calculations with our newly created pages"): +// every page of the tree with the scopes it has data under, and the reference copies of the pages of before the tree. +// Pure: ui/SiteMap.tsx draws it +import { PAGES, REFERENCE_PAGES, pageFacts, referenceTabs, shownPages, type Page, type RefTab } from './pages'; +import { scopeIdOf } from './route'; +import { ADP, FIDELITY, leafNodes, nodeOf, shownLeaves, tickedOf, type ScopeNode, type ScopeWord } from './scope-tree'; + +/** a page of the tree and the scope words it has data under (All first, then each source read) */ +export interface MapPage { page: Page; scopes: ScopeWord[] } + +/** the pages of the tree with their scopes; a page with no data under any scope is left out */ +export function mapPages(root: ScopeNode, have: { taxYears: boolean }): MapPage[] { + const words: ScopeWord[] = (['all', 'fidelity', 'adp'] as const).filter((w) => w === 'all' || !!nodeOf(root, w === 'fidelity' ? FIDELITY : ADP)); + const shown = new Map(words.map((w) => [w, shownPages(pageFacts(leafNodes(root, shownLeaves(root, tickedOf(root, [scopeIdOf(w)])))), have)] as [ScopeWord, Page[]])); + return PAGES.map((page) => ({ page, scopes: words.filter((w) => shown.get(w)!.indexOf(page) >= 0) })).filter((p) => p.scopes.length > 0); +} + +/** a reference copy: its tab, whether it has data here, and the page of the tree with the scope to compare it with */ +export interface MapReference { tab: RefTab; has: boolean; page: Page; scope: ScopeWord } + +/** every reference copy in today's order, each with data or not (a page with none is listed, greyed) */ +export function mapReferences(have: { fidelity: boolean; adp: boolean; taxYears: boolean }): MapReference[] { + const on = referenceTabs(have); + return REFERENCE_PAGES.map((r) => ({ tab: r.tab, has: on.indexOf(r.tab) >= 0, page: r.page, scope: r.source })); +} diff --git a/src/viewer/ui/AdpSourceChips.tsx b/src/viewer/ui/AdpSourceChips.tsx deleted file mode 100644 index 4c3d7d4..0000000 --- a/src/viewer/ui/AdpSourceChips.tsx +++ /dev/null @@ -1,37 +0,0 @@ -/// -import { ADP_SOURCES, allSources, onlySource, toggleSource, type AdpSourceChip } from '../app/adp-sources'; -import { t } from '../app/i18n'; -import { Chip } from './Chip'; - -// The navbar strip of the ADP pages (owner 2026-11-30): the money sources of the 401k in place of the Fidelity accounts, -// with the look and the keys of the accounts strip (ui/Chip.tsx). A click on a source shows only it, its checkbox adds or removes it, All -// sources shows every one or none (rules in app/adp-sources.ts) -const NAME = (): Record => ({ roth: t('Roth'), pretax: t('Pre-tax'), employer: t('Employer'), other: t('Earnings and other') }); -const HINT = (): Record => ({ - roth: t('Your Roth contributions: taxed now, tax-free later'), - pretax: t('Your pre-tax contributions: taxed when taken out'), - employer: t('The employer match and other employer money'), - other: t('Dividends and earnings, transfers and fees: the rows with no source'), -}); - -// every chip always, rows or not (owner 2026-11-30: controls always shown, so the strip never jumps) -export function AdpSourceChips({ hidden, className, onChange }: { hidden: readonly AdpSourceChip[]; className?: string; onChange: (hidden: AdpSourceChip[]) => void }) { - const present = ADP_SOURCES; - const shown = present.filter((s) => hidden.indexOf(s) < 0); - const name = NAME(); - const hint = HINT(); - return ( -
- onChange([])} data-source="all" - check={{ checked: shown.length === present.length, mixed: shown.length > 0, label: t('Show {name}', { name: t('All sources') }), onChange: () => onChange(allSources(hidden)) }} /> - {present.map((s) => { - const only = onlySource(s); - const isOnly = only.every((x) => hidden.indexOf(x) >= 0) && hidden.indexOf(s) < 0; - return ( - onChange(only)} data-source={s} - check={{ checked: hidden.indexOf(s) < 0, label: t('Show {name}', { name: name[s] }), onChange: () => onChange(toggleSource(hidden, s)) }} /> - ); - })} -
- ); -} diff --git a/src/viewer/ui/App.tsx b/src/viewer/ui/App.tsx index 464888b..6c99e14 100644 --- a/src/viewer/ui/App.tsx +++ b/src/viewer/ui/App.tsx @@ -1,13 +1,14 @@ /// import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import type { Account } from '../../shared/model'; -import { accountsIn, foldKey, leavesOfScope, localToday, moveChip, orderAccounts, scopeOfLeaves, scopeTitle, toggleFold, validScope } from '../app/derive'; -import { TREE_WORDS, buildTree } from '../app/scope-tree'; +import { localToday, moveChip, orderAccounts } from '../app/derive'; +import { ADP_SOURCES } from '../app/adp-sources'; +import { FIDELITY_LEAF, LEAF_401K, ROOT, buildTree, leafNodes, scopeOf, scopeTitle, scopeWord, shownLeaves, tickedOf, toggleFolded, treeWords } from '../app/scope-tree'; import { adpHistory, autoWatch, dataset, loginSaved, sheetPin, transactions, watchChosen, watching } from '../app/data'; import { connectGoogle, sheets } from '../app/google'; import { lang, t } from '../app/i18n'; -import { prefs, setPrefs, type MainTab } from '../app/prefs'; -import { referenceName, referenceSource, referenceTabs } from '../app/pages'; +import { prefs, setPrefs } from '../app/prefs'; +import { REFERENCE_PAGES, oldestRead, openPage, pageFacts, pageName, referenceName, referenceSource, referenceTabs, shownPages, type Page, type Read, type RefTab } from '../app/pages'; import { USERSCRIPT_ATTR, userscriptVersion } from '../app/status'; import { rovingIndex } from '../app/focus'; import { squashed } from '../app/squash'; @@ -16,7 +17,6 @@ import { APP_VERSION, isOlder } from '../app/version'; import { loadConfig } from '../../shared/sheets/gis'; import { Activity } from './Activity'; import { AdpActivity } from './AdpActivity'; -import { AdpSourceChips } from './AdpSourceChips'; import { Reports } from './Reports'; import { AdpSummary } from './AdpSummary'; import { LangButton, MergeButton, ThemeButton, WatchButton } from './IconButtons'; @@ -37,7 +37,9 @@ import { Taxes } from './Taxes'; import { animate } from './animate'; import { readTime } from './format'; import { GutterScrollbars } from './GutterScrollbars'; -import { useRoute } from './useRoute'; +import { ScopeSummary } from './ScopeSummary'; +import { ReferenceNote, SiteMap } from './SiteMap'; +import { goPage, goReference, useRoute } from './useRoute'; import { useStore } from './useStore'; import { useTheme } from './useTheme'; import { PHONE_QUERY, useMedia } from './useMedia'; @@ -49,6 +51,8 @@ const PANEL_KEY = 'accounts-panel-settings'; const panelOpen = (): boolean => { try { return localStorage.getItem(PANEL_KEY) === 'open'; } catch { return false; } }; // one empty list for no data, so the screens below see the same accounts from draw to draw const NO_ACCOUNTS: Account[] = []; +/** the Fidelity accounts among some leaves, in the owner's order (no leaf of Fidelity: none) */ +const accountsOf = (accounts: Account[], leaves: ReadonlySet): Account[] => accounts.filter((a) => leaves.has(`${FIDELITY_LEAF}${a.number}`)); export function App() { const theme = useTheme(); @@ -57,18 +61,34 @@ export function App() { const { ds: rawDs, error } = useStore(dataset); const txns = useStore(transactions); const adp = useStore(adpHistory); - // the ADP page only once its history is there (owner 2026-11-30), Fidelity Taxes only once Fidelity's tax summary has a - // year (owner 2026-12-03: "if there are no data then we have nothing to show and we should not"); a page saved but not - // shown falls back to Summary + // Fidelity Taxes only once Fidelity's tax summary has a year (owner 2026-12-03: "if there are no data then we have + // nothing to show and we should not") const taxYearsRead = taxYears(rawDs?.taxSummary).length > 0; - const tabs = useMemo(() => referenceTabs({ adp: !!adp, taxYears: taxYearsRead }), [adp, taxYearsRead]); - // the page in the address (app/route.ts): a hash wins on load, a page click writes it, so Back works - useRoute(pr.tab); - const openTab: MainTab = tabs.indexOf(pr.tab) >= 0 ? pr.tab : 'summary'; - // the pages of the ADP 401k show its money sources in the strip, the rest the Fidelity accounts (app/pages.ts) - const adpPage = referenceSource(openTab) === 'adp'; // the owner's own order of accounts applies everywhere: the bar, Positions, the Accounts card const ds = useMemo(() => (rawDs ? orderAccounts(rawDs, pr.accountOrder, pr.groupOrder) : null), [rawDs, pr.accountOrder, pr.groupOrder]); + // a browser with only the 401k read shows it too (the scope tree plan: "a 401k-only browser works") + const have = !!ds || !!adp; + // the scope tree of what is read (owner 2026-12-03: "All group ... two other sub groups: Fidelity and ADP"), the strip's + // words in the chosen language; the kept scope as ticked leaves (app/scope-tree.ts) + const words = useMemo(() => treeWords(), [language]); + const k401 = !!adp; + const tree = useMemo(() => buildTree({ fidelity: ds?.accounts ?? NO_ACCOUNTS, k401 }, words), [ds, k401, words]); + const ticked = useMemo(() => tickedOf(tree, pr.scope), [tree, pr.scope]); + const leaves = useMemo(() => shownLeaves(tree, ticked), [tree, ticked]); + const leafKey = leaves.join(','); + // the pages with data under the scope, in the table's order (app/pages.ts; owner 2026-12-03: "we will show only + // available pages for certain acc"); the saved page is the wanted one, drawn while it has data, else the first one + const facts = useMemo(() => pageFacts(leafNodes(tree, leaves)), [tree, leafKey]); + const tabs = useMemo(() => shownPages(facts, { taxYears: taxYearsRead }), [facts, taxYearsRead]); + // the page in the address (app/route.ts): a hash wins on load, a page click writes it, so Back works; a reference copy of + // a page of before the tree and the site map are drawn by their address only, never saved + const view = useRoute(pr.tab, scopeWord(tree, pr.scope)); + const refTabs = useMemo(() => referenceTabs({ fidelity: !!ds?.accounts.length, adp: k401, taxYears: taxYearsRead }), [ds, k401, taxYearsRead]); + const reference: RefTab | null = view.kind === 'reference' ? view.tab : null; + const page: Page | null = view.kind === 'page' ? openPage(pr.tab, tabs) : null; + // what the tabs and the phone's line of pages show: the reference copies on a reference copy, else the pages of the tree + const open: string | null = reference ?? page; + const adpRef = !!reference && referenceSource(reference) === 'adp'; const g = useStore(sheets); useStore(loginSaved); const watch = useStore(watching); @@ -136,15 +156,15 @@ export function App() { }; // another page starts open - useEffect(() => { setAsked(false); setHeld(false); }, [pr.tab]); + useEffect(() => { setAsked(false); setHeld(false); }, [open]); const flat = squashed({ phone, settings: showSettings, asked, held }); // The phone's Summary (owner 2026-11-27: "content is clashing ... should push it upper as I scroll", "squash should // happen smoothly and ... next panel below must be absolutely visible in full"): the whole page scrolls there, so the // navbar and the tabs panel go up with the cards, pushed by them, and nothing slides under anything. The line of the // pages lies over the top of the page once the tabs panel has gone under it: at that moment the first card stands one // gutter below the line, whole - const flow = phone && openTab !== 'positions' && !!ds; - const page = useRef(null); + const flow = phone && open !== 'positions' && have; + const pageBox = useRef(null); const scrollBox = useRef(null); const tabsBox = useRef(null); const [past, setPast] = useState(false); @@ -152,7 +172,7 @@ export function App() { const el = tabsBox.current; if (!flow || !el || typeof IntersectionObserver === 'undefined') { setPast(false); return undefined; } // the line's strip is 30 px tall: the tabs panel is "gone" when its bottom is above the strip's bottom - const io = new IntersectionObserver((seen) => setPast(!seen[seen.length - 1]!.isIntersecting), { root: page.current, rootMargin: '-30px 0px 0px 0px' }); + const io = new IntersectionObserver((seen) => setPast(!seen[seen.length - 1]!.isIntersecting), { root: pageBox.current, rootMargin: '-30px 0px 0px 0px' }); io.observe(el); return () => io.disconnect(); }, [flow]); @@ -163,38 +183,64 @@ export function App() { const timer = setTimeout(() => setClip(false), 380); return () => clearTimeout(timer); }, [flat]); - const scope = validScope(ds, pr.scope); // nothing ticked shows the same as everything ticked (owner 2026-11-24): the boxes stay clear, the numbers are all. // Kept from draw to draw: App draws again on every status message of the script and every Sheets log line, and a new // list made Summary and Positions work every number out again - const accounts = useMemo(() => (ds ? (scope === 'none' ? ds.accounts : accountsIn(ds, scope)) : NO_ACCOUNTS), [ds, scope]); - const one = accounts.length === 1 ? accounts[0] : null; - // the strip draws the scope tree of the Fidelity accounts (app/scope-tree.ts); the scope is kept in today's words - const tree = useMemo(() => (ds ? buildTree({ fidelity: ds.accounts }, { ...TREE_WORDS, all: t('All accounts') }) : null), [ds, language]); - const ticked = useMemo(() => (ds ? leavesOfScope(ds, scope) : new Set()), [ds, scope]); + const shownSet = useMemo(() => new Set(leaves), [leafKey]); + const accounts = useMemo(() => (ds ? accountsOf(ds.accounts, shownSet) : NO_ACCOUNTS), [ds, shownSet]); + // a reference copy of a Fidelity page has its own strip of today: the Fidelity accounts only, the Fidelity part of the + // same scope (the rest of the scope stays as it is) + const fidTree = useMemo(() => buildTree({ fidelity: ds?.accounts ?? NO_ACCOUNTS }, { ...words, allShort: undefined }), [ds, words]); + const fidTicked = useMemo(() => new Set(scopeOf(fidTree, ticked)), [fidTree, ticked]); + const refAccounts = useMemo(() => (ds ? (fidTicked.size ? accountsOf(ds.accounts, fidTicked) : ds.accounts) : NO_ACCOUNTS), [ds, fidTicked]); + // the reference copies of the ADP pages keep their strip of today: All sources and the money sources of the 401k + const adpTree = useMemo(() => buildTree({ fidelity: NO_ACCOUNTS, k401: true }, { ...words, all: t('All sources'), allShort: undefined }), [words]); + const adpTicked = useMemo(() => new Set(pr.adpHidden.length < ADP_SOURCES.length ? [LEAF_401K] : []), [pr.adpHidden]); + const shownAccounts = reference ? refAccounts : accounts; + const one = shownAccounts.length === 1 ? shownAccounts[0] : null; // the name of what is shown titles the Balance card (owner 2026-11-24), the right of the tabs keeps only the time - const title = !ds ? '' : scopeTitle(scope, accounts, { all: t('All accounts'), count: (n) => t('{n} accounts', { n }) }); + const count = (n: number) => t('{n} accounts', { n }); + const title = scopeTitle(tree, ticked, count); + const fidelityTitle = scopeTitle(tree, new Set(accounts.map((a) => `${FIDELITY_LEAF}${a.number}`)), count); + const refTitle = scopeTitle(fidTree, fidTicked, count); + // As of: the oldest read among the sources shown, each one's own in the tooltip (the scope tree plan, 2026-12-03) + const reads: Read[] = []; + const fidelityShown = reference ? !adpRef : view.kind === 'sitemap' || facts.fidelity; + const adpShown = reference ? adpRef : view.kind === 'sitemap' || facts.k401; + if (fidelityShown && ds) reads.push({ name: 'Fidelity', at: ds.builtAt }); + if (adpShown && adp) reads.push({ name: t('ADP 401k'), at: adp.at }); + const asOf = oldestRead(reads); const year = new Date().getFullYear(); const googleTitle = loadConfig().clientId ? t('Connect Google Sheets') : t('Google Sheets: set the Client ID first (🚀 Get started)'); + // the tabs: the pages of the tree, or the reference copies while one of them is drawn (with their names of today) + const tabList: readonly string[] = reference ? refTabs : tabs; + const tabName = (tab: string): string => (reference ? referenceName(tab as RefTab) : pageName(tab as Page)); + const pick = (tab: string): void => (reference ? goReference(tab as RefTab) : goPage(tab as Page)); const onTabKey = (e: React.KeyboardEvent) => { - const to = rovingIndex(tabs.length, tabs.indexOf(openTab), e.key); + const to = rovingIndex(tabList.length, Math.max(0, tabList.indexOf(open ?? '')), e.key); if (to === null) return; e.preventDefault(); - const tab = tabs[to]!; - setPrefs({ tab }); + const tab = tabList[to]!; + pick(tab); document.getElementById(`tab-${tab}`)?.focus(); }; + const onFold = (id: string) => setPrefs({ collapsed: toggleFolded(prefs.get().collapsed, id) }); + const folded = (id: string) => pr.collapsed.indexOf(id) >= 0; + const onMove = (moved: string, target: string) => { const order = ds && moveChip(ds, moved, target); if (order) animate(() => setPrefs(order)); }; + const stripClass = 'order-last w-full max-sm:mt-2 lg:order-none lg:w-auto lg:flex-1 lg:basis-0'; + const refPage = reference ? REFERENCE_PAGES.find((r) => r.tab === reference)! : null; const today = localToday(); + const hintOf = (a: Account | null | undefined): string | undefined => (a ? [a.type, a.number].filter(Boolean).join(': ') : undefined); return ( // the page is exactly one screen tall (owner 2026-11-23: the footer must always be visible): the navbar on top, the // footer in the bottom gutter, and only the part between them scrolls -
+
{/* the line of the pages over the scrolled Summary of a phone: it takes no room, so its coming moves nothing */} {flow && (
- (tab === pr.tab ? page.current?.scrollTo({ top: 0, behavior: 'smooth' }) : setPrefs({ tab }))} /> + (tab === open ? pageBox.current?.scrollTo({ top: 0, behavior: 'smooth' }) : pick(tab))} />
)} @@ -210,18 +256,22 @@ export function App() { {/* a phone (owner 2026-11-27): ☰, the logo, the theme button; the icon buttons wait folded under them */} setMenuOpen((v) => !v)} label={menuOpen ? t('Hide the buttons') : t('Show the buttons')} />

- +

{phone && } {/* the accounts strip lives in the navbar between the logo and the buttons (owner 2026-11-24); below lg it takes its own full row under them */} - {/* the ADP pages show the 401k's money sources there instead of the Fidelity accounts (owner 2026-11-30) */} - {ds && adpPage && adp &&