From 1e0829cfc805412354acac41a85dc881ecba1da0 Mon Sep 17 00:00:00 2001 From: Maksim Kostromin Date: Thu, 3 Dec 2026 20:02:18 -0500 Subject: [PATCH] refactor(summary): shared balance card and the combine math --- src/viewer/app/combine.test.ts | 72 ++++++++++++++++++++ src/viewer/app/combine.ts | 117 +++++++++++++++++++++++++++++++++ src/viewer/app/series.test.ts | 74 +++++++++++++++++++++ src/viewer/app/series.ts | 70 ++++++++++++++++++++ src/viewer/ui/AdpSummary.tsx | 31 +++++---- src/viewer/ui/BalanceCard.tsx | 24 +++++++ src/viewer/ui/Summary.tsx | 35 +++++----- 7 files changed, 389 insertions(+), 34 deletions(-) create mode 100644 src/viewer/app/combine.test.ts create mode 100644 src/viewer/app/combine.ts create mode 100644 src/viewer/app/series.test.ts create mode 100644 src/viewer/app/series.ts create mode 100644 src/viewer/ui/BalanceCard.tsx diff --git a/src/viewer/app/combine.test.ts b/src/viewer/app/combine.test.ts new file mode 100644 index 0000000..3953b7e --- /dev/null +++ b/src/viewer/app/combine.test.ts @@ -0,0 +1,72 @@ +/// +/// +/// +// The combine math of a Summary over several sources; every number is made up +import { expect, test } from 'bun:test'; +import { PNL_KINDS, combinedTotals, cut, incomeReceived, pnlByKind, slicesOf, taxTreatment } from './combine'; + +test('combined totals: dollars summed, Total return % = Σ return ÷ Σ put in, Today over the balance before it', () => { + const fid = { balance: 52000.1, putIn: 40000, dividends: 1200.05, today: 84.12 }; + const k401 = { balance: 10000, putIn: 9000, dividends: 300, today: null }; + const c = combinedTotals([fid, k401]); + expect([c.balance, c.putIn, c.dividends, c.total, c.growth, c.today]).toEqual([62000.1, 49000, 1500.05, 13000.1, 11500.05, 84.12]); + expect(c.totalPct).toBeCloseTo((13000.1 / 49000) * 100); + // not the average of the two percents + expect(c.totalPct).not.toBeCloseTo((((52000.1 - 40000) / 40000) * 100 + ((10000 - 9000) / 9000) * 100) / 2); + // the 401k adds $0 to Today, its balance is in the base of the percent + expect(c.todayPct).toBeCloseTo((84.12 / (62000.1 - 84.12)) * 100); + expect(combinedTotals([])).toEqual({ balance: 0, putIn: 0, dividends: 0, total: 0, totalPct: null, growth: 0, today: 0, todayPct: null }); +}); + +test('profit and loss by kind: rows and columns add up to the total return; a kind a source does not have is "--" and $0', () => { + const t = pnlByKind([ + { id: 'investment', putIn: 1000, kinds: { interest: 10, ordinary: 20, qualified: 30, shortTerm: -5, longTerm: 40, unrealized: 100.1 } }, + { id: 'retirement', putIn: 500, kinds: { interest: 1, ordinary: 2, qualified: 3, shortTerm: 0, longTerm: 4, unrealized: 50.2 } }, + { id: 'k401', putIn: 2000, kinds: { earnings: 70, unrealized: 130.3 } }, + ]); + expect(t.rows.map((r) => r.kind)).toEqual(PNL_KINDS.slice()); + expect(t.rows.find((r) => r.kind === 'earnings')!.cells).toEqual([null, null, 70]); + expect(t.rows.find((r) => r.kind === 'qualified')!.cells).toEqual([30, 3, null]); + expect(t.rows.find((r) => r.kind === 'unrealized')!.total).toBe(280.6); + expect(t.columns.map((c) => c.total)).toEqual([195.1, 60.2, 200.3]); + expect(t.total).toBe(455.6); + expect(t.total).toBe(t.rows.reduce((s, r) => Math.round((s + r.total) * 100) / 100, 0)); + expect(t.putIn).toBe(3500); + expect(t.columns[2]!.pct).toBeCloseTo(10.015); + expect(t.pct).toBeCloseTo((455.6 / 3500) * 100); +}); + +test('income received by how it is taxed: qualified + ordinary and interest = taxable; taxable + tax-free + deferred + 401k = the total', () => { + const r = incomeReceived([ + { shelter: null, interest: 1.1, ordinary: 2.2, qualified: 3.3 }, + { shelter: null, interest: 0, ordinary: 0.1, qualified: 0.2 }, + { shelter: 'free', interest: 0.5, ordinary: 1, qualified: 2 }, + { shelter: 'deferred', interest: 0, ordinary: 0, qualified: 4 }, + ], 7.77); + expect(r).toEqual({ total: 22.17, taxable: 6.9, qualified: 3.5, ordinary: 3.4, taxFree: 3.5, deferred: 4, k401: 7.77 }); + expect(incomeReceived([])).toEqual({ total: 0, taxable: 0, qualified: 0, ordinary: 0, taxFree: 0, deferred: 0, k401: 0 }); +}); + +test('slices: dollars of a name summed over the sources, percents from the summed dollars, the largest first', () => { + const s = slicesOf([['ETFs', 100.1], ['Stocks', 50], ['ETFs', 49.9, 'with the 401k fund'], ['Cash', 0], ['Mutual funds', 50]]); + expect(s.map((x) => [x.name, x.value])).toEqual([['ETFs', 150], ['Stocks', 50], ['Mutual funds', 50]]); + expect(s[0]!.note).toBe('with the 401k fund'); + expect(s.map((x) => x.pct)).toEqual([60, 20, 20]); + expect(slicesOf([])).toEqual([]); +}); + +test('an amount cut by shares adds up to the cent, the last part takes the rounding', () => { + const parts = cut(100, { a: 1, b: 1, c: 1 }); + expect(parts).toEqual([['a', 33.33], ['b', 33.33], ['c', 33.34]]); + expect(Math.round(parts.reduce((s, [, v]) => s + v * 100, 0))).toBe(10000); + expect(cut(10, { roth: 0, pretax: 0 })).toEqual([['roth', 0], ['pretax', 10]]); + expect(cut(5, {})).toEqual([]); +}); + +test('tax treatment: taxable, tax-free later (Roth IRAs + the 401k\'s Roth part), taxed when taken out (the rest of the retirement money)', () => { + const s = taxTreatment({ taxable: 1000, roth: 300, deferred: 200, k401: { balance: 1000, putIn: { roth: 250, pretax: 500, employer: 250 } } }); + expect(s.map((x) => [x.name, x.value])).toEqual([['Taxed when taken out', 950], ['Taxable', 1000], ['Tax-free later (Roth)', 550]].sort((a, b) => (b[1] as number) - (a[1] as number))); + expect(s.reduce((x, y) => x + y.value, 0)).toBe(2500); + expect(s.reduce((x, y) => x + y.pct, 0)).toBeCloseTo(100); + expect(taxTreatment({ taxable: 10, roth: 0, deferred: 0 }).map((x) => x.name)).toEqual(['Taxable']); +}); diff --git a/src/viewer/app/combine.ts b/src/viewer/app/combine.ts new file mode 100644 index 0000000..ef5db18 --- /dev/null +++ b/src/viewer/app/combine.ts @@ -0,0 +1,117 @@ +/// +// The math of a Summary over several sources (the scope tree plan, owner 2026-12-03: "mathematically everything should be +// correct"; Fidelity first, then ADP mykplan; where data can be combined a Combined view, below it what cannot). Every +// dollar is summed from cents, every percent is worked out again from the summed dollars, never an average of percents; +// two different things are never summed (Fidelity's cost basis is the cost of the positions held, the 401k's is the money +// put in: the combined card shows Money put in instead). Pure: the UI uses it once the 401k joins the tree +import type { Shelter } from '../../shared/tax'; +import type { Slice } from './derive'; +import { sumUsd } from './series'; + +const pctOf = (part: number, whole: number): number | null => (whole > 0 ? (part / whole) * 100 : null); + +/** one source (or account) of the balance: `today` null where the source has no daily price (the 401k: priced once a day after the close) */ +export interface BalancePart { balance: number; putIn: number; dividends: number; today: number | null } +export interface CombinedTotals { balance: number; putIn: number; dividends: number; total: number; totalPct: number | null; growth: number; today: number; todayPct: number | null } + +/** + * The head of the combined Balance card: balance, money put in and dividends summed; Total return = balance - money put + * in, its percent = Σ return / Σ put in; Growth = Total return - dividends; Today = Σ today of the sources that have one, + * its percent over the balance before it (balance - today), the 401k's balance in that base + */ +export function combinedTotals(parts: readonly BalancePart[]): CombinedTotals { + const balance = sumUsd(parts.map((p) => p.balance)); + const putIn = sumUsd(parts.map((p) => p.putIn)); + const dividends = sumUsd(parts.map((p) => p.dividends)); + const total = sumUsd([balance, -putIn]); + const today = sumUsd(parts.map((p) => p.today ?? 0)); + return { balance, putIn, dividends, total, totalPct: pctOf(total, putIn), growth: sumUsd([total, -dividends]), today, todayPct: pctOf(today, balance - today) }; +} + +/** the owner's sub-levels of a result (2026-12-03): interest and dividends, realized, unrealized; `earnings` is the 401k's one number, not split */ +export const PNL_KINDS = ['interest', 'ordinary', 'qualified', 'earnings', 'shortTerm', 'longTerm', 'unrealized'] as const; +export type PnlKind = (typeof PNL_KINDS)[number]; +/** a column of the table: Investment, Retirement, the 401k...; a kind the source does not have is left out (shown "--", counted as $0) */ +export interface PnlColumn { id: string; kinds: Partial>; putIn: number } +export interface PnlByKind { + rows: Array<{ kind: PnlKind; cells: Array; total: number }>; + columns: Array<{ id: string; total: number; putIn: number; pct: number | null }>; + total: number; putIn: number; pct: number | null; +} + +/** + * Profit and loss by kind: the kinds as rows, the columns as given; the Total column = Σ of the row, the Total return row + * = Σ of the column, Return % = the column's total ÷ its money put in, the last cell Σ return ÷ Σ put in + */ +export function pnlByKind(columns: readonly PnlColumn[]): PnlByKind { + const rows = PNL_KINDS.map((kind) => { + const cells = columns.map((c) => (c.kinds[kind] === undefined ? null : c.kinds[kind]!)); + return { kind, cells, total: sumUsd(cells.map((v) => v ?? 0)) }; + }); + const cols = columns.map((c, i) => { const total = sumUsd(rows.map((r) => r.cells[i] ?? 0)); return { id: c.id, total, putIn: c.putIn, pct: pctOf(total, c.putIn) }; }); + const total = sumUsd(cols.map((c) => c.total)); + const putIn = sumUsd(cols.map((c) => c.putIn)); + return { rows, columns: cols, total, putIn, pct: pctOf(total, putIn) }; +} + +/** what a Fidelity account received in a window, by kind */ +export interface Received { shelter: Shelter | null; interest: number; ordinary: number; qualified: number } +export interface IncomeReceived { total: number; taxable: number; qualified: number; ordinary: number; taxFree: number; deferred: number; k401: number } + +/** + * Income received in one window (MTD, QTD, YTD) by how it is taxed: the dividends and interest paid into the shown Fidelity + * accounts (taxable ones: qualified, and ordinary with the interest; Roth: tax-free; other retirement: tax-deferred) and + * the 401k's dividends and earnings of the same window (not taxed while inside the plan). Only what was received is + * combined: an expected payment needs the pay dates of positions, which only Fidelity has + */ +export function incomeReceived(fidelity: readonly Received[], k401 = 0): IncomeReceived { + const all = (r: Received) => sumUsd([r.interest, r.ordinary, r.qualified]); + const taxable = fidelity.filter((r) => !r.shelter); + const qualified = sumUsd(taxable.map((r) => r.qualified)); + const ordinary = sumUsd(taxable.map((r) => sumUsd([r.ordinary, r.interest]))); + const taxFree = sumUsd(fidelity.filter((r) => r.shelter === 'free').map(all)); + const deferred = sumUsd(fidelity.filter((r) => r.shelter === 'deferred').map(all)); + const taxableSum = sumUsd([qualified, ordinary]); + return { total: sumUsd([taxableSum, taxFree, deferred, k401]), taxable: taxableSum, qualified, ordinary, taxFree, deferred, k401 }; +} + +/** an allocation of several sources: the dollars of a name summed, the percent of each from the summed dollars, the largest first; an empty slice left out */ +export function slicesOf(pairs: ReadonlyArray): Slice[] { + const by = new Map(); + pairs.forEach(([name, value, note]) => { + const s = by.get(name) ?? { name, cents: 0 }; + s.cents += Math.round(value * 100); + if (note && s.note === undefined) s.note = note; + by.set(name, s); + }); + const list = Array.from(by.values()).filter((s) => s.cents !== 0); + const total = list.reduce((x, s) => x + s.cents, 0); + return list.sort((a, b) => b.cents - a.cents).map((s) => ({ name: s.name, value: s.cents / 100, pct: total > 0 ? (s.cents / total) * 100 : 0, ...(s.note ? { note: s.note } : {}) })); +} + +/** an amount cut by shares to the cent: the last part takes what the rounding left, so the parts add up to the amount */ +export function cut(amount: number, shares: Readonly>): Array<[string, number]> { + const keys = Object.keys(shares); + const whole = keys.reduce((s, k) => s + shares[k]!, 0); + const total = Math.round(amount * 100); + let left = total; + return keys.map((k, i) => { + const c = i === keys.length - 1 ? left : whole > 0 ? Math.round((total * shares[k]!) / whole) : 0; + left -= c; + return [k, c / 100]; + }); +} + +/** the balances by how they are taxed later: the Fidelity accounts by shelter, the 401k by the money each of its sources put in */ +export interface TaxTreatmentInput { taxable: number; roth: number; deferred: number; k401?: { balance: number; putIn: { roth: number; pretax: number; employer: number } } } +export const TAX_TREATMENT_WORDS = { taxable: 'Taxable', free: 'Tax-free later (Roth)', deferred: 'Taxed when taken out' }; + +/** + * Tax treatment of the whole scope: taxable accounts; tax-free later = the Roth IRAs + the 401k's Roth part; taxed when + * taken out = the other retirement accounts + the 401k's pre-tax and employer parts. The 401k's balance is cut the way + * its own Tax allocation card cuts it: by the money each source put in, the last part takes the rounding + */ +export function taxTreatment(v: TaxTreatmentInput, words = TAX_TREATMENT_WORDS): Slice[] { + const k = v.k401 ? Object.fromEntries(cut(v.k401.balance, v.k401.putIn)) as Record<'roth' | 'pretax' | 'employer', number> : { roth: 0, pretax: 0, employer: 0 }; + return slicesOf([[words.taxable, v.taxable], [words.free, sumUsd([v.roth, k.roth])], [words.deferred, sumUsd([v.deferred, k.pretax, k.employer])]]); +} diff --git a/src/viewer/app/series.test.ts b/src/viewer/app/series.test.ts new file mode 100644 index 0000000..28fa88f --- /dev/null +++ b/src/viewer/app/series.test.ts @@ -0,0 +1,74 @@ +/// +/// +/// +// Several balance series as one: carried values, the combined line, a period's change per series then summed. Made-up numbers +import { expect, test } from 'bun:test'; +import { mergeSeries, periodChange, pointAt, sumUsd, type Series } from './series'; + +const p = (date: string, value: number) => ({ date, value }); + +test('the last known point at or before a day; nothing before the first', () => { + const pts = [p('2026-10-01', 100), p('2026-10-05', 110), p('2026-10-31', 130)]; + expect(pointAt(pts, '2026-09-30')).toBeNull(); + expect(pointAt(pts, '2026-10-01')).toEqual(p('2026-10-01', 100)); + expect(pointAt(pts, '2026-10-20')).toEqual(p('2026-10-05', 110)); + expect(pointAt(pts, '2026-12-01')).toEqual(p('2026-10-31', 130)); + expect(pointAt([], '2026-10-01')).toBeNull(); +}); + +test('dollars are added as cents: 0.1 + 0.2 is 0.3', () => { + expect(sumUsd([0.1, 0.2])).toBe(0.3); + expect(sumUsd([1000.005, -0.005])).toBe(1000.01); + expect(sumUsd([])).toBe(0); +}); + +test('one line of a daily series and a month-end one: from the first day both have a value, the 401k carried between its points', () => { + const daily: Series = { id: 'f1', flows: [], points: [p('2026-09-29', 90), p('2026-09-30', 95), p('2026-10-01', 100), p('2026-10-02', 101.1), p('2026-10-30', 102.2)] }; + const k: Series = { id: 'k', flows: [], points: [p('2026-09-30', 1000), p('2026-10-31', 1100)] }; + const m = mergeSeries([daily, k]); + expect(m.map((x) => [x.date, x.value])).toEqual([['2026-09-30', 1095], ['2026-10-01', 1100], ['2026-10-02', 1101.1], ['2026-10-30', 1102.2], ['2026-10-31', 1202.2]]); + // a hover says which day each part is from + expect(m[2]!.parts).toEqual([{ id: 'f1', date: '2026-10-02', value: 101.1 }, { id: 'k', date: '2026-09-30', value: 1000 }]); + expect(mergeSeries([])).toEqual([]); + expect(mergeSeries([{ id: 'empty', points: [], flows: [] }, k]).map((x) => x.value)).toEqual([1000, 1100]); +}); + +test('a period: change = end - start, gain = change - money put in, the gain percent the Modified Dietz way', () => { + // $1000 on Oct 1, $500 put in on Oct 6 (half of the 10 days), $1600 on Oct 11: change 600, gain 100 over 1000 + 500 x 0.5 + const s: Series = { id: 'a', points: [p('2026-10-01', 1000), p('2026-10-06', 1550), p('2026-10-11', 1600)], flows: [{ date: '2026-10-06', net: 500 }] }; + const c = periodChange([s], '2026-10-01'); + expect([c.start, c.end, c.flows, c.change, c.gain]).toEqual([1000, 1600, 500, 600, 100]); + expect(c.changePct).toBeCloseTo(60); + expect(c.gainPct).toBeCloseTo(8); + // a flow on the start day is already in the start value: not counted again + expect(periodChange([{ ...s, flows: [{ date: '2026-10-01', net: 500 }] }], '2026-10-01').flows).toBe(0); +}); + +test('per series: its own start (the last point not after the period start, else its first), its own flows; then summed', () => { + const f: Series = { id: 'f', points: [p('2026-08-29', 2000), p('2026-09-02', 2100), p('2026-12-02', 2400)], flows: [{ date: '2026-10-15', net: 200 }] }; + // the 401k: month ends only, so its start for a period from Sep 1 is Aug 31; and its last point is a day older + const k: Series = { id: 'k', points: [p('2026-08-31', 5000), p('2026-11-30', 6000), p('2026-12-01', 6050)], flows: [{ date: '2026-09-15', net: 400 }, { date: '2026-10-15', net: 400 }, { date: '2026-12-02', net: 400 }] }; + const c = periodChange([f, k], '2026-09-01'); + expect(c.rows.map((r) => [r.id, r.from, r.to, r.start, r.end, r.flows])).toEqual([['f', '2026-08-29', '2026-12-02', 2000, 2400, 200], ['k', '2026-08-31', '2026-12-01', 5000, 6050, 800]]); + expect([c.start, c.end, c.flows, c.change, c.gain]).toEqual([7000, 8450, 1000, 1450, 450]); + // the percents come from the summed dollars, never the average of each source's percent + expect(c.changePct).toBeCloseTo((1450 / 7000) * 100); + const average = ((periodChange([f], '2026-09-01').changePct! + periodChange([k], '2026-09-01').changePct!) / 2); + expect(average).toBeCloseTo(20.5); + expect(c.changePct).not.toBeCloseTo(average); +}); + +test('a transfer between two shown accounts nets to zero; with one of them alone it is a deposit or a withdrawal', () => { + const a: Series = { id: 'a', points: [p('2026-10-01', 1000), p('2026-10-31', 520)], flows: [{ date: '2026-10-20', net: -500 }] }; + const b: Series = { id: 'b', points: [p('2026-10-01', 300), p('2026-10-31', 810)], flows: [{ date: '2026-10-20', net: 500 }] }; + const both = periodChange([a, b], '2026-10-01'); + expect([both.flows, both.change, both.gain]).toEqual([0, 30, 30]); + expect(periodChange([b], '2026-10-01').flows).toBe(500); + expect(periodChange([a], '2026-10-01').gain).toBe(20); +}); + +test('nothing to compare: no series, no points, no start', () => { + expect(periodChange([], '2026-10-01')).toEqual({ rows: [], start: 0, end: 0, flows: 0, change: 0, gain: 0, changePct: null, gainPct: null }); + const zero = periodChange([{ id: 'z', points: [p('2026-10-01', 0), p('2026-10-02', 0)], flows: [] }], '2026-10-01'); + expect([zero.changePct, zero.gainPct]).toEqual([null, null]); +}); diff --git a/src/viewer/app/series.ts b/src/viewer/app/series.ts new file mode 100644 index 0000000..8389d65 --- /dev/null +++ b/src/viewer/app/series.ts @@ -0,0 +1,70 @@ +/// +// Balance series of several sources as one (the scope tree plan, owner 2026-12-03: "mathematically everything should be +// correct"): Fidelity accounts have a value every day, the 401k at month ends and its last price day. A series is carried +// at its last known value until its next one; the combined line starts on the first day every series has a value; a +// period's change is worked out per series (its own start, its own deposits and withdrawals) and only then summed, the +// percents from the summed dollars, never an average of percents. Dollars are added as whole cents +import type { Point } from '../../shared/history'; +import type { Flow } from './pnl'; + +/** one source's balance: its points (oldest first) and the money put in (plus) or taken out (minus) by day */ +export interface Series { id: string; points: readonly Point[]; flows: readonly Flow[] } + +const cents = (x: number): number => Math.round(x * 100); +/** dollars summed as cents, so the parts always add up to the cent */ +export const sumUsd = (xs: readonly number[]): number => xs.reduce((s, x) => s + cents(x), 0) / 100; +const dayMs = (iso: string): number => Date.parse(`${iso}T00:00:00Z`); +const daysBetween = (a: string, b: string): number => Math.round((dayMs(b) - dayMs(a)) / 86_400_000); + +/** the last known point at or before a day (the value carried until the next one); null before the first */ +export function pointAt(points: readonly Point[], date: string): Point | null { + let hit: Point | null = null; + for (const p of points) { if (p.date <= date) hit = p; else break; } + return hit; +} + +/** a day of the combined line: the sum, and the point of each series it came from (its date says how old it is) */ +export interface MergedPoint extends Point { parts: Array<{ id: string; date: string; value: number }> } + +/** + * Several series as one line: from the first day every series has a value, each day any series has a point = the sum of + * the last known values. A series with no points is left out + */ +export function mergeSeries(list: readonly Series[]): MergedPoint[] { + const live = list.filter((s) => s.points.length > 0); + if (!live.length) return []; + const start = live.map((s) => s.points[0]!.date).sort().pop()!; + const dates = Array.from(new Set(live.reduce((all, s) => all.concat(s.points.map((p) => p.date)), []))).filter((d) => d >= start).sort(); + return dates.map((date) => { + const parts = live.map((s) => { const p = pointAt(s.points, date)!; return { id: s.id, date: p.date, value: p.value }; }); + return { date, value: sumUsd(parts.map((p) => p.value)), parts }; + }); +} + +/** the change of one series over a period: from its own start to its own last point, its flows in between */ +export interface SeriesChange { id: string; from: string; to: string; start: number; end: number; flows: number; weighted: number } +export interface PeriodChange { rows: SeriesChange[]; start: number; end: number; flows: number; change: number; gain: number; changePct: number | null; gainPct: number | null } + +/** + * The change of a period over several series. Per series: from its last known point at or before `from` (else its first) + * to its last point; its deposits and withdrawals after the first of those points up to the second, each also weighed by + * the share of the span it was in. Then the dollars are summed: change = end - start, gain = change - money put in + * (a transfer between two shown accounts is -X and +X, so it nets to zero); change % over the start, gain % the Modified + * Dietz way: over the start plus each flow times the share of the span it was in + */ +export function periodChange(list: readonly Series[], from: string): PeriodChange { + const rows = list.filter((s) => s.points.length > 0).map((s): SeriesChange => { + const a = pointAt(s.points, from) ?? s.points[0]!; + const b = s.points[s.points.length - 1]!; + const inside = s.flows.filter((f) => f.date > a.date && f.date <= b.date); + const span = Math.max(1, daysBetween(a.date, b.date)); + return { id: s.id, from: a.date, to: b.date, start: a.value, end: b.value, flows: sumUsd(inside.map((f) => f.net)), weighted: inside.reduce((x, f) => x + f.net * (daysBetween(f.date, b.date) / span), 0) }; + }); + const start = sumUsd(rows.map((r) => r.start)); + const end = sumUsd(rows.map((r) => r.end)); + const flows = sumUsd(rows.map((r) => r.flows)); + const change = sumUsd([end, -start]); + const gain = sumUsd([change, -flows]); + const base = start + rows.reduce((x, r) => x + r.weighted, 0); + return { rows, start, end, flows, change, gain, changePct: start > 0 ? (change / start) * 100 : null, gainPct: base > 0 ? (gain / base) * 100 : null }; +} diff --git a/src/viewer/ui/AdpSummary.tsx b/src/viewer/ui/AdpSummary.tsx index d1b6979..b98e148 100644 --- a/src/viewer/ui/AdpSummary.tsx +++ b/src/viewer/ui/AdpSummary.tsx @@ -7,8 +7,9 @@ import { adpRows, adpShown, taxSlices, type AdpRow, type AdpSourceChip } from '. import { t } from '../app/i18n'; import { prefs, setPrefs } from '../app/prefs'; import { shownSpans, spanBounds, type Span } from '../app/spans'; -import { BalanceChart, CARD_CHART_HEIGHT, PnlRows } from './BalanceChart'; -import { BalanceHead, FactRow, ReturnFacts } from './BalanceHead'; +import { CARD_CHART_HEIGHT, PnlRows } from './BalanceChart'; +import { BalanceCard } from './BalanceCard'; +import { FactRow, ReturnFacts } from './BalanceHead'; import { returnFacts } from '../app/pnl'; import { Allocation, AllocationBig, ViewSwitch } from './Allocation'; import { Card } from './Card'; @@ -93,20 +94,18 @@ export const AdpSummary = memo(function AdpSummary({ store, hidden, today }: { s // the chart on top, the rest in two columns or one under it
- }> - {/* the same head as Fidelity Summary (BalanceHead); no Today line: the 401k has month ends and the last price day, - no daily values (owner 2026-11-30: "Today is not applicable for ADP, but for period is"); the period line is the - gain without the money put in during it, the chosen one then YTD and 1Y (PnlRows). The facts are Fidelity's in the - same rows: Total return, Growth, Dividends, Cost basis (what was put in) at the bottom; no Cash or Pending (owner: - "cash is not applicable for 401k"), the read time in the tabs bar */} - } - facts={<> - - {usd(putIn)} - } /> - - + {/* the same card as Fidelity Summary (ui/BalanceCard.tsx); no Today line: the 401k has month ends and the last price + day, no daily values (owner 2026-11-30: "Today is not applicable for ADP, but for period is"); the period line is + the gain without the money put in during it, the chosen one then YTD and 1Y (PnlRows). The facts are Fidelity's in + the same rows: Total return, Growth, Dividends, Cost basis (what was put in) at the bottom; no Cash or Pending + (owner: "cash is not applicable for 401k"), the read time in the tabs bar */} + } + facts={<> + + {usd(putIn)} + } />
diff --git a/src/viewer/ui/BalanceCard.tsx b/src/viewer/ui/BalanceCard.tsx new file mode 100644 index 0000000..4f5a319 --- /dev/null +++ b/src/viewer/ui/BalanceCard.tsx @@ -0,0 +1,24 @@ +/// +import type { ReactNode } from 'react'; +import type { Point } from '../../shared/history'; +import type { PulseMark } from '../app/pulse'; +import { BalanceChart, type Exact, type Flows, type PeriodPref } from './BalanceChart'; +import { BalanceHead } from './BalanceHead'; +import { Card } from './Card'; + +// The balance card of a Summary, one for Fidelity Summary and ADP Summary (owner 2026-11-30: "why we have so different +// balance headers? fix it"; the scope tree plan 2026-12-03: one Balance card for any scope): the head (BalanceHead: the +// balance with its change lines on the left, the facts on the right), the chart with its periods under it, and the +// chart big in the ⤢ window. Each page keeps its own period (`of`) +export function BalanceCard({ id, head, title, titleHint, pulse, value, lines, facts, series, of, flows, exact, empty, tall }: { + id: string; head: string; title: string; titleHint?: string; pulse: PulseMark; + value: string; lines: ReactNode; facts: ReactNode; + series: Point[]; of?: PeriodPref; flows: Flows; exact?: Exact; empty?: string; tall?: number; +}) { + return ( + }> + + + + ); +} diff --git a/src/viewer/ui/Summary.tsx b/src/viewer/ui/Summary.tsx index 3d8fe0a..863452b 100644 --- a/src/viewer/ui/Summary.tsx +++ b/src/viewer/ui/Summary.tsx @@ -3,8 +3,9 @@ import type { Account, Dataset, Position } from '../../shared/model'; import { FundamentalsLink, hasFundamentals } from './Fundamentals'; import { ACCOUNT_SORTS, movers, ofKind, payoutTotal, sortAccounts, sortDividends, yieldNote, DIV_CHIPS, DIV_WINDOWS, DIV_WHEN, PAST_WINDOWS, windowStart, divChips, divSizeOf, setDivSize, toggleDivChip, type AccountSort, type DivChip, type MedianSpan } from '../app/derive'; import { MOVERS_MAX, accountBetas, dividendsView, incomeView, summaryBase } from '../app/summary'; -import { BalanceChart, PnlRows } from './BalanceChart'; -import { BalanceHead, ChangeRow, FactRow, ReturnFacts } from './BalanceHead'; +import { PnlRows } from './BalanceChart'; +import { BalanceCard } from './BalanceCard'; +import { ChangeRow, FactRow, ReturnFacts } from './BalanceHead'; import { fidelityFacts, fidelityFlows, fidelityPnl, paidIn, returnFacts } from '../app/pnl'; import { periodGain } from '../../shared/history'; import { animate } from './animate'; @@ -149,22 +150,20 @@ export const Summary = memo(function Summary({ ds, accounts, title, titleHint, t
{/* the last card of a column keeps its bottom margin; the negative one of this box takes it back, so the page ends at the cards and the footer alone is the gap under them */} - }> - {/* the balance with Today and the P&L lines on the left, the facts on the right (BalanceHead); every P&L sets the - deposits and transfers aside (app/pnl.ts; owner 2026-11-30: "no needs to see a balance change Fidelity") */} - - - - } - facts={<> - - {usd(tot.costBasis)} - {usd(tot.cash)} - {tot.pending !== 0 && {signedUsd(tot.pending)}} - } /> - - + {/* the balance with Today and the P&L lines on the left, the facts on the right (ui/BalanceCard.tsx); every P&L sets + the deposits and transfers aside (app/pnl.ts; owner 2026-11-30: "no needs to see a balance change Fidelity") */} + + + + } + facts={<> + + {usd(tot.costBasis)} + {usd(tot.cash)} + {tot.pending !== 0 && {signedUsd(tot.pending)}} + } /> {/* the ETFs Stocks chips in the middle, the % $ switch by ⤢: a choice of one and a set of chips stand apart, the same on Upcoming dividends (owner 2026-12-01: "separate options and multiselections", "switch these buttons groups") */}