Skip to content
Open
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
40 changes: 36 additions & 4 deletions src/viewer/app/adp-sources.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
/// <reference types="bun" />
/// <reference lib="esnext" />
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 = [
Expand All @@ -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', () => {
Expand All @@ -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<string>) => 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]);
});
37 changes: 32 additions & 5 deletions src/viewer/app/adp-sources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand All @@ -15,20 +16,46 @@ export function sourceChip(r: Pick<AdpTxn, 'kind' | 'source'>): AdpSourceChip {
return r.source === '' ? 'other' : 'employer';
}


export const asAdpHidden = (x: unknown): AdpSourceChip[] =>
Array.isArray(x) ? ADP_SOURCES.filter((s) => x.indexOf(s) >= 0) : [];

/** the checkbox of a chip: on -> off, off -> on */
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<string>, 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<string>, 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<string>; 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<string>, 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<string>, 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 = <T extends Pick<AdpTxn, 'kind' | 'source'>>(rows: readonly T[], hidden: readonly AdpSourceChip[]): T[] =>
Expand Down
106 changes: 3 additions & 103 deletions src/viewer/app/derive.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down Expand Up @@ -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)];
Expand All @@ -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')] };
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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<string, number> = { Monthly: 1, Quarterly: 3, 'Semi-annually': 6, Annually: 12 };
const allPayDates = (payDate: string, step: number | undefined, from: string, to: string): string[] =>
Expand Down Expand Up @@ -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();
Expand Down
Loading