Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 22 additions & 22 deletions src/viewer/app/derive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,25 +5,33 @@ 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, buildTree, fidelityLeaf, framedNodes, groupAccounts, groupId, scopeOf as leavesShown, toggleLeaf, toggleNode, type ScopeNode } from './scope-tree';
import { addDays, addMonths } from '../../shared/dates';
import { perYear } from '../../shared/typed-columns';

export { addMonths };

export interface Group { name: string; accounts: Account[]; balance: number }

/** groups in the site's order (the order the accounts came in) */
/** groups in the site's order (the order the accounts came in), as the scope tree groups them (app/scope-tree.ts) */
export function groupsOf(ds: Dataset): Group[] {
const out: Group[] = [];
ds.accounts.forEach((a) => {
let g = out.find((x) => x.name === a.group);
if (!g) { g = { name: a.group, accounts: [], balance: 0 }; out.push(g); }
g.accounts.push(a);
g.balance += a.balance ?? 0;
});
return out;
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<Dataset, ScopeNode>();
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<string>): Set<string> => new Set(Array.from(numbers).map(fidelityLeaf));
const numbersOf = (tree: ScopeNode, leaves: ReadonlySet<string>): 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:<name>, account:<number>
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 owner's own order (owner 2026-11-24): groups move as a whole with their accounts, accounts move inside their
* group; accounts in `order` come by its index, the rest keep the site's order after them
Expand Down Expand Up @@ -120,12 +128,7 @@ export function scopeOf(ds: Dataset, numbers: string[]): Scope {
*/
export function framedChips(ds: Dataset, shown: ReadonlySet<string>): Set<string> {
const out = new Set<string>();
if (!ds.accounts.length || !ds.accounts.some((a) => shown.has(a.number))) return out;
if (ds.accounts.every((a) => shown.has(a.number))) return out.add('all');
groupsOf(ds).forEach((g) => {
if (g.accounts.every((a) => shown.has(a.number))) out.add(`group:${g.name}`);
else g.accounts.filter((a) => shown.has(a.number)).forEach((a) => out.add(`account:${a.number}`));
});
framedNodes(fidelityTree(ds), leafSet(Array.from(shown))).forEach((id) => out.add(chipKey(id)));
return out;
}

Expand All @@ -135,17 +138,14 @@ export function framedChips(ds: Dataset, shown: ReadonlySet<string>): Set<string
* accounts, or takes them away when the whole group is chosen
*/
export function toggleGroup(ds: Dataset, shown: ReadonlySet<string>, group: string): Scope {
const mine = groupsOf(ds).find((g) => g.name === group)?.accounts.map((a) => a.number) ?? [];
if (!mine.length) return scopeOf(ds, Array.from(shown));
if (ds.accounts.every((a) => shown.has(a.number))) return scopeOf(ds, mine);
const others = Array.from(shown).filter((n) => mine.indexOf(n) < 0);
return scopeOf(ds, mine.every((n) => shown.has(n)) ? others : others.concat(mine));
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 now = accountsIn(ds, scope).map((a) => a.number);
return scopeOf(ds, now.includes(number) ? now.filter((n) => n !== number) : now.concat(number));
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 */
Expand Down
147 changes: 147 additions & 0 deletions src/viewer/app/scope-tree.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
/// <reference types="bun" />
/// <reference types="node" />
/// <reference lib="esnext" />
// 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';

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)
const FID = [acct('A1', 'Joint', 'Investment', 'Brokerage'), acct('A2', 'Kids', 'Investment', 'Brokerage'), acct('R1', 'Max ROTH IRA', 'Retirement', 'ROTH IRA')];
const tree = buildTree({ fidelity: FID, k401: true });
const [A1, A2, R1] = ['A1', 'A2', 'R1'].map(fidelityLeaf) as [string, string, string];
const K = LEAF_401K;
const INV = groupId(FIDELITY, 'Investment');
const RET = groupId(FIDELITY, 'Retirement');
const set = (...ids: string[]) => new Set(ids);
const sorted = (s: ReadonlySet<string>) => Array.from(s).sort();
const ALL = [A1, A2, R1, K];

test('the tree: All -> source -> group -> account; a source with nothing read is left out', () => {
expect(tree.kids!.map((k) => k.id)).toEqual([FIDELITY, ADP]);
expect(nodeOf(tree, FIDELITY)!.kids!.map((g) => [g.id, g.kids!.map((a) => a.id)])).toEqual([[INV, [A1, A2]], [RET, [R1]]]);
expect(leavesOf(tree)).toEqual(ALL);
expect(nodeOf(tree, R1)!.shelter).toBe('free');
expect(nodeOf(tree, A1)!.shelter).toBeNull();
expect(buildTree({ fidelity: [] , k401: true }).kids!.map((k) => k.id)).toEqual([ADP]);
expect(buildTree({ fidelity: FID }).kids!.map((k) => k.id)).toEqual([FIDELITY]);
expect(leavesOf(buildTree({ fidelity: [] }))).toEqual([]);
expect(pathTo(tree, A2)!.map((n) => n.id)).toEqual([ROOT, FIDELITY, INV, A2]);
expect(pathTo(tree, 'nope')).toBeNull();
expect(groupAccounts([acct('1', 'a', 'G'), acct('2', 'b', 'H'), acct('3', 'c', 'G')]).map((g) => [g.name, g.accounts.map((a) => a.number)])).toEqual([['G', ['1', '3']], ['H', ['2']]]);
});

test('leaf ids of the 401k and the pay, in tree-only use', () => {
const both = buildTree({ fidelity: FID, k401: true, pay: true });
expect(nodeOf(both, ADP)!.kids!.map((k) => k.id)).toEqual(['adp:401k', 'adp:pay']);
expect(LEAF_PAY).toBe('adp:pay');
// the pages of only the pay: Taxes and Salary
expect(visiblePages(pageFacts(shownLeaves(both, set(LEAF_PAY)).map((id) => ({ id, shelter: nodeOf(both, id)!.shelter }))))).toEqual(['taxes', 'salary']);
// the ADP source: the 401k pages and the salary and taxes pages
const adp = toggleNode(both, set(), ADP);
expect(sorted(adp)).toEqual(['adp:401k', 'adp:pay']);
expect(visiblePages(pageFacts(shownLeaves(both, adp).map((id) => ({ id, shelter: nodeOf(both, id)!.shelter }))))).toEqual(['summary', 'activity', 'taxes', 'salary']);
});

test('the five traces of the plan', () => {
// All + tick Investment -> {A1, A2}
expect(sorted(toggleNode(tree, set(...ALL), INV))).toEqual([A1, A2].sort());
// Fidelity only + tick Investment -> {A1, A2}
expect(sorted(toggleNode(tree, set(A1, A2, R1), INV))).toEqual([A1, A2].sort());
// {A1, A2, K} + tick Retirement -> {A1, A2, R1, K}
expect(sorted(toggleNode(tree, set(A1, A2, K), RET))).toEqual(ALL.slice().sort());
// {A1, A2} + tick Investment -> none (= everything)
expect(sorted(toggleNode(tree, set(A1, A2), INV))).toEqual([]);
expect(shownLeaves(tree, set())).toEqual(ALL);
// All + tick ADP -> {K}, then tick Fidelity -> All
const adp = toggleNode(tree, set(...ALL), ADP);
expect(sorted(adp)).toEqual([K]);
const back = toggleNode(tree, adp, FIDELITY);
expect(sorted(back)).toEqual(ALL.slice().sort());
expect(sorted(framedNodes(tree, back))).toEqual([ROOT]);
});

test('the All checkbox: everything ticked -> nothing, else everything; an unknown node changes nothing', () => {
expect(sorted(toggleNode(tree, set(...ALL), ROOT))).toEqual([]);
expect(sorted(toggleNode(tree, set(A1), ROOT))).toEqual(ALL.slice().sort());
expect(sorted(toggleNode(tree, set(), ROOT))).toEqual(ALL.slice().sort());
expect(sorted(toggleNode(tree, set(A1, 'gone'), 'nope'))).toEqual([A1]);
});

test('an account checkbox adds or removes only it; a click on a chip shows only its leaves', () => {
expect(sorted(toggleLeaf(tree, set(A1), K))).toEqual([A1, K].sort());
expect(sorted(toggleLeaf(tree, set(A1, K), A1))).toEqual([K]);
expect(sorted(toggleLeaf(tree, set(A1), 'fidelity:gone'))).toEqual([A1]);
expect(sorted(onlyNode(tree, INV))).toEqual([A1, A2].sort());
expect(sorted(onlyNode(tree, K))).toEqual([K]);
expect(sorted(onlyNode(tree, 'nope'))).toEqual([]);
});

test('the frame: the highest node chosen whole whose parent is not', () => {
expect(sorted(framedNodes(tree, set(...ALL)))).toEqual([ROOT]);
expect(sorted(framedNodes(tree, set(A1, A2, R1)))).toEqual([FIDELITY]);
expect(sorted(framedNodes(tree, set(A1, A2, K)))).toEqual([ADP, INV].sort());
expect(sorted(framedNodes(tree, set(A1, R1)))).toEqual([A1, RET].sort());
expect(sorted(framedNodes(tree, set()))).toEqual([]);
expect(sorted(framedNodes(tree, set('gone')))).toEqual([]);
});

test('checkbox states: ticked, partly, clear', () => {
expect(checkState(tree, set(...ALL))).toEqual({ checked: true, mixed: false });
expect(checkState(tree, set(A1))).toEqual({ checked: false, mixed: true });
expect(checkState(nodeOf(tree, INV)!, set(R1))).toEqual({ checked: false, mixed: false });
expect(checkState(nodeOf(tree, K)!, set(K))).toEqual({ checked: true, mixed: false });
expect(checkState(buildTree({ fidelity: [] }), set())).toEqual({ checked: false, mixed: false });
});

test('the title: All, one account, a whole source or group, up to three names, else a count', () => {
const count = (n: number) => `${n} accounts`;
expect(scopeTitle(tree, set(), count)).toBe('All accounts');
expect(scopeTitle(tree, set(...ALL), count)).toBe('All accounts');
expect(scopeTitle(tree, set(R1), count)).toBe('Max ROTH IRA');
expect(scopeTitle(tree, set(A1, A2), count)).toBe('Investment');
expect(scopeTitle(tree, set(A1, A2, R1), count)).toBe('Fidelity');
expect(scopeTitle(tree, set(A1, R1), count)).toBe('Joint + Max ROTH IRA');
expect(scopeTitle(tree, set(A1, A2, K), count)).toBe('Joint + Kids + ADP mykplan 401k');
const five = buildTree({ fidelity: FID.concat(acct('A3', 'Three', 'Investment'), acct('A4', 'Four', 'Investment')), k401: true });
expect(scopeTitle(five, set(fidelityLeaf('A3'), fidelityLeaf('A4'), A1, R1), count)).toBe('4 accounts');
});

test('a level with one child is one chip: the 401k alone in ADP is drawn as "ADP 401k"; with the pay, ADP -> 401k, Work', () => {
const kids = (t: ScopeNode, id: string) => chipKids(t, nodeOf(t, id)!).map((k) => k.id);
// All with Fidelity and ADP: the sources; ADP with the 401k alone is drawn as the 401k
expect(kids(tree, ROOT)).toEqual([FIDELITY, K]);
expect(chipLabel(tree, K)).toBe('ADP 401k');
const both = buildTree({ fidelity: FID, k401: true, pay: true });
expect(kids(both, ROOT)).toEqual([FIDELITY, ADP]);
expect(kids(both, ADP)).toEqual([K, LEAF_PAY]);
expect([chipLabel(both, K), chipLabel(both, LEAF_PAY), chipLabel(both, ADP)]).toEqual(['401k', 'Work', 'ADP']);
// Fidelity alone (today's strip): All draws the groups itself, as today
const fid = buildTree({ fidelity: FID });
expect(kids(fid, ROOT)).toEqual([INV, RET]);
expect(kids(fid, INV)).toEqual([A1, A2]);
expect([chipLabel(fid, ROOT), chipLabel(fid, INV), chipLabel(fid, A1)]).toEqual(['All accounts', 'Investment', 'Joint']);
expect(chipLabel(fid, 'nope')).toBe('nope');
});

test('a kept scope: only the leaves still there; the scope of before the tree as leaves', () => {
expect(sorted(validScope(tree, set(A1, 'fidelity:closed')))).toEqual([A1]);
expect(sorted(validScope(tree, set('fidelity:closed')))).toEqual([]);
expect(scopeOf(tree, set(K, A2, A1))).toEqual([A1, A2, K]);
expect(sorted(migrateScope(tree, 'all'))).toEqual(ALL.slice().sort());
expect(sorted(migrateScope(tree, 'none'))).toEqual([]);
expect(sorted(migrateScope(tree, 'group:Investment'))).toEqual([A1, A2].sort());
expect(sorted(migrateScope(tree, 'group:Gone'))).toEqual([]);
expect(sorted(migrateScope(tree, 'account:R1'))).toEqual([R1]);
expect(sorted(migrateScope(tree, 'set:A2,R1,closed'))).toEqual([A2, R1].sort());
expect(migrateFolded(['*', 'Retirement'])).toEqual([ROOT, RET]);
});

test('nothing here changes the tree or the set it is given', () => {
const before = JSON.stringify(tree);
const shown = set(A1, A2);
toggleNode(tree, shown, INV); toggleNode(tree, shown, ROOT); toggleLeaf(tree, shown, K); framedNodes(tree, shown); onlyNode(tree, RET); migrateScope(tree, 'all');
expect(JSON.stringify(tree)).toBe(before);
expect(sorted(shown)).toEqual([A1, A2].sort());
});
Loading