From 69ea13b9ab85f00bae2505981763ba98debab815 Mon Sep 17 00:00:00 2001 From: Maksim Kostromin Date: Thu, 3 Dec 2026 18:44:39 -0500 Subject: [PATCH] feat(taxes): fidelity taxes page with the household settings --- src/viewer/app/i18n/ru.ts | 84 +++++++++++ src/viewer/app/prefs.test.ts | 7 + src/viewer/app/prefs.ts | 10 +- src/viewer/app/tax-household.test.ts | 55 ++++++++ src/viewer/app/tax-household.ts | 54 +++++++ src/viewer/app/taxes-page.test.ts | 102 ++++++++++++++ src/viewer/app/taxes-page.ts | 104 ++++++++++++++ src/viewer/app/transfer.test.ts | 1 + src/viewer/app/transfer.ts | 6 +- src/viewer/ui/Allocation.tsx | 3 +- src/viewer/ui/AmountField.tsx | 35 +++++ src/viewer/ui/App.tsx | 15 +- src/viewer/ui/BalanceHead.tsx | 5 +- src/viewer/ui/Empty.tsx | 5 + src/viewer/ui/FillBar.tsx | 13 ++ src/viewer/ui/SettingsPanel.tsx | 6 + src/viewer/ui/Summary.tsx | 6 +- src/viewer/ui/TaxSettings.tsx | 58 ++++++++ src/viewer/ui/Taxes.test.tsx | 99 +++++++++++++ src/viewer/ui/Taxes.tsx | 201 +++++++++++++++++++++++++++ src/viewer/ui/format.test.ts | 6 +- src/viewer/ui/format.ts | 2 + 22 files changed, 860 insertions(+), 17 deletions(-) create mode 100644 src/viewer/app/tax-household.test.ts create mode 100644 src/viewer/app/tax-household.ts create mode 100644 src/viewer/app/taxes-page.test.ts create mode 100644 src/viewer/app/taxes-page.ts create mode 100644 src/viewer/ui/AmountField.tsx create mode 100644 src/viewer/ui/Empty.tsx create mode 100644 src/viewer/ui/FillBar.tsx create mode 100644 src/viewer/ui/TaxSettings.tsx create mode 100644 src/viewer/ui/Taxes.test.tsx create mode 100644 src/viewer/ui/Taxes.tsx diff --git a/src/viewer/app/i18n/ru.ts b/src/viewer/app/i18n/ru.ts index 62c5c11..3a5887e 100644 --- a/src/viewer/app/i18n/ru.ts +++ b/src/viewer/app/i18n/ru.ts @@ -780,4 +780,88 @@ export const RU: Record = { 'pending: not paid yet': 'ожидается: ещё не выплачен', 'Found: {n}': 'Найдено: {n}', 'Found in the account: {n}': 'Найдено в счёте: {n}', + // Fidelity Taxes (ui/Taxes.tsx) and Settings -> Taxes (ui/TaxSettings.tsx) + 'Fidelity Taxes': 'Налоги Fidelity', + 'The shown accounts are retirement or tax-free accounts: they add nothing to the tax of the year': 'Показаны только пенсионные счета или счета без налога: к налогу за год они ничего не добавляют', + 'Update the script to {version} and open Fidelity Positions once': 'Обновите скрипт до {version} и один раз откройте Fidelity Positions', + "Fidelity's tax summary of {year} has none of the shown accounts yet: open Fidelity Positions once": 'В налоговой сводке Fidelity за {year} пока нет показанных счетов: один раз откройте Fidelity Positions', + 'Tax year': 'Налоговый год', + 'Tax added by the investments': 'Налог от инвестиций', + 'Room before the next rate': 'Запас до следующей ставки', + 'Foreign tax paid is over {limit}: the credit is counted up to {limit}, more needs Form 1116': 'Иностранный налог больше {limit}: зачёт посчитан до {limit}, для большего нужна форма 1116', + 'Wages and investment income are over {limit}: the {rate} net investment income tax may apply, it is not counted here': 'Зарплата и инвестиционный доход больше {limit}: может добавиться налог {rate} на чистый инвестиционный доход, здесь он не посчитан', + 'YTD as of {day}, before the 1099s; an estimate, not tax advice': 'С начала года на {day}, до форм 1099; оценка, не налоговая консультация', + 'Federal': 'Федеральный', + 'With the investments minus without them, after a foreign tax credit of {credit}': 'Налог с инвестициями минус налог без них, после зачёта иностранного налога {credit}', + 'With the investments minus without them': 'Налог с инвестициями минус налог без них', + 'New Jersey': 'Нью-Джерси', + 'With the investments minus without them; New Jersey has no lower rate for dividends or gains and no foreign tax credit': 'Налог с инвестициями минус налог без них; в Нью-Джерси нет пониженной ставки для дивидендов и прибыли и нет зачёта иностранного налога', + 'Effective rate': 'Эффективная ставка', + 'The tax added divided by the investment income the federal return counts': 'Добавленный налог, делённый на инвестиционный доход, который учитывает федеральная декларация', + 'Ordinary rate': 'Обычная ставка', + 'The federal rate of the next dollar of ordinary income: interest, non-qualified dividends, short-term gains': 'Федеральная ставка следующего доллара обычного дохода: проценты, неквалифицированные дивиденды, краткосрочная прибыль', + 'Qualified rate': 'Ставка квалиф.', + 'The federal rate of the next dollar of qualified dividends and long-term gains': 'Федеральная ставка следующего доллара квалифицированных дивидендов и долгосрочной прибыли', + 'New Jersey rate': 'Ставка Нью-Джерси', + 'The New Jersey rate of the next dollar of any investment income': 'Ставка Нью-Джерси для следующего доллара любого инвестиционного дохода', + 'Federal and New Jersey together, at the brackets the household is in now': 'Федеральный налог и Нью-Джерси вместе, по ступеням, в которых семья сейчас', + 'One more dollar of short-term gain costs {pct}': 'Ещё один доллар краткосрочной прибыли стоит {pct}', + 'The app has no {year} rules yet: counted with those of {rules}': 'Правил {year} года в приложении пока нет: посчитано по правилам {rules}', + 'Ordinary income before {rate}': 'Обычный доход до ставки {rate}', + 'Already in the {rate} bracket': 'Уже в ступени {rate}', + 'Ordinary taxable income (wages after the deduction, interest, non-qualified dividends, short-term gains) left before {line}, where each dollar starts to pay {rate}': 'Сколько обычного облагаемого дохода (зарплата после вычета, проценты, неквалифицированные дивиденды, краткосрочная прибыль) осталось до {line}, где каждый доллар начинает платить {rate}', + 'Qualified dividends and long-term gains at 0%': 'Квалиф. дивиденды и долгосрочная прибыль по 0%', + 'Qualified dividends and long-term gains already pay {rate}': 'Квалиф. дивиденды и долгосрочная прибыль уже платят {rate}', + 'Total taxable income left before {line}: up to it qualified dividends and long-term gains pay 0%, above it {rate}': 'Сколько всего облагаемого дохода осталось до {line}: до этой суммы квалифицированные дивиденды и долгосрочная прибыль платят 0%, выше - {rate}', + 'New Jersey before {rate}': 'Нью-Джерси до ставки {rate}', + 'New Jersey: already at its top rate': 'Нью-Джерси: уже высшая ставка', + 'New Jersey taxable income left before {line}, where its rate goes up to {rate}': 'Сколько облагаемого дохода Нью-Джерси осталось до {line}, где ставка поднимается до {rate}', + '{left} left': 'осталось {left}', + 'Ordinary dividends': 'Обычные дивиденды', + '1099-DIV box 1a: qualified and non-qualified together': '1099-DIV поле 1a: квалифицированные и неквалифицированные вместе', + '1099-DIV box 1b: taxed at 0, 15 or 20% federally, as ordinary income by New Jersey': '1099-DIV поле 1b: федеральный налог 0, 15 или 20%, Нью-Джерси облагает как обычный доход', + 'Only when the shares were held more than 60 days of the 121 around the ex-date': 'Только если бумаги были на счёте больше 60 дней из 121 вокруг экс-даты', + 'Non-qualified': 'Неквалиф.', + 'Taxed as ordinary income': 'Облагаются как обычный доход', + 'Capital gain distributions': 'Распределения прироста капитала', + '1099-DIV box 2a: long-term, whatever the holding period': '1099-DIV поле 2a: долгосрочные при любом сроке владения', + '1099-INT box 1: ordinary income, federal and New Jersey': '1099-INT поле 1: обычный доход, федеральный и Нью-Джерси', + 'Treasury interest': 'Проценты казначейских бумаг', + '1099-INT box 3: U.S. Treasury interest, federal only': '1099-INT поле 3: проценты по бумагам Казначейства США, только федеральный налог', + 'Not taxed by New Jersey': 'Нью-Джерси не облагает', + 'Other income': 'Прочий доход', + '1099-MISC boxes 2, 3, 8 and 1099-OID boxes 1, 8: ordinary income': '1099-MISC поля 2, 3, 8 и 1099-OID поля 1, 8: обычный доход', + 'Realized short-term': 'Реализованная краткосрочная', + 'Sold within a year: ordinary income': 'Продано в течение года: обычный доход', + 'Realized long-term': 'Реализованная долгосрочная', + 'Sold after more than a year: 0, 15 or 20% federally': 'Продано больше чем через год: федеральный налог 0, 15 или 20%', + 'A net loss: up to {limit} a year federally, the rest carries over; none for New Jersey': 'Чистый убыток: федерально до {limit} в год, остаток переносится; в Нью-Джерси не учитывается', + 'Foreign tax paid': 'Уплаченный иностранный налог', + '1099-DIV box 7 and 1099-INT box 6': '1099-DIV поле 7 и 1099-INT поле 6', + 'A federal credit only: up to {limit} with no Form 1116': 'Зачёт только федеральный: до {limit} без формы 1116', + 'Federal tax withheld': 'Удержанный федеральный налог', + 'Already paid toward the federal tax': 'Уже уплачено в счёт федерального налога', + 'Margin interest paid': 'Уплаченные проценты по марже', + 'Deductible only when itemizing; not counted here': 'Вычитаются только при постатейном вычете; здесь не учтены', + 'Section 199A dividends': 'Дивиденды по разделу 199A', + '1099-DIV box 5: part of the ordinary dividends; its deduction is not counted here': '1099-DIV поле 5: часть обычных дивидендов; их вычет здесь не учтён', + 'Line': 'Строка', + 'Taxes': 'Налоги', + 'Standard': 'Стандартный', + 'Itemized': 'Постатейный', + 'Filing': 'Декларация', + 'Married filing jointly, New Jersey': 'Супруги совместно, Нью-Джерси', + 'The only filing status and state the Taxes page counts for now': 'Пока страница налогов считает только для этого статуса и штата', + 'Gross wages': 'Зарплата брутто', + 'Wages of the household for the year, both of you, before anything is taken out. Default {amount}: your own estimate; the ADP pay statements replace it later': 'Зарплата семьи за год, обоих супругов, до всех удержаний. По умолчанию {amount}: ваша оценка; позже её заменят расчётные листы ADP', + 'Pre-tax 401(k)': '401(k) до налогов', + 'Your pre-tax 401(k) contributions of the year: they lower the federal and New Jersey wages. Default 0': 'Ваши взносы в 401(k) до налогов за год: уменьшают зарплату для федерального налога и Нью-Джерси. По умолчанию 0', + 'Other pre-tax': 'Прочее до налогов', + 'Health, dental, HSA, FSA and commuter money taken before tax: lowers the federal wages only, New Jersey taxes it. Default 0': 'Медицина, стоматология, HSA, FSA и проезд до налогов: уменьшают только федеральную зарплату, Нью-Джерси их облагает. По умолчанию 0', + 'NJ dependents': 'Иждивенцы NJ', + 'Children and other dependents: {each} each off New Jersey taxable income; left out federally (the child tax credit lowers the bill, not what the investments add). Default {n}: your children': 'Дети и другие иждивенцы: по {each} с облагаемого дохода Нью-Джерси; в федеральном расчёте не учтены (налоговый кредит на детей уменьшает итог, а не то, что добавляют инвестиции). По умолчанию {n}: ваши дети', + 'Deduction': 'Вычет', + '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', }; diff --git a/src/viewer/app/prefs.test.ts b/src/viewer/app/prefs.test.ts index 7a1a576..df6d323 100644 --- a/src/viewer/app/prefs.test.ts +++ b/src/viewer/app/prefs.test.ts @@ -98,3 +98,10 @@ test('the positions sort starts by Market cap, largest first; a sort saved befor expect(load(JSON.stringify({ sort: { key: 'x', dir: 2 }, columnsV: COLUMNS_V })).sort).toEqual({ key: 'marketCap', dir: -1 }); expect(load(JSON.stringify({ columnsV: 8 })).columnsV).toBe(COLUMNS_V); }); + +test('the tax year of Fidelity Taxes: a four-digit year, else the newest one', () => { + expect(load('{"taxYear":"2025"}').taxYear).toBe('2025'); + expect(load('{"taxYear":"25"}').taxYear).toBe(''); + expect(load('{"taxYear":2025}').taxYear).toBe(''); + expect(load('{"tab":"taxes"}').tab).toBe('taxes'); +}); diff --git a/src/viewer/app/prefs.ts b/src/viewer/app/prefs.ts index 2bacaf8..023b20d 100644 --- a/src/viewer/app/prefs.ts +++ b/src/viewer/app/prefs.ts @@ -15,8 +15,9 @@ import { asAdpHidden, type AdpSourceChip } from './adp-sources'; import { INCOME_SPANS, SPANS, asSpans, type Span } from './spans'; 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) -export const MAIN_TABS = ['summary', 'positions', 'activity', 'reports', 'adpSummary', 'adpActivity'] as const; +// 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; @@ -75,9 +76,11 @@ export interface Prefs { noticesAt: NoticeCorner; // the symbol whose Fundamentals window is open ('' none): a reload opens it again (app/fundamentals.ts reopens) fundamentalsOpen: string; + // the tax year of the Fidelity Taxes page ('' = the newest Fidelity has; app/taxes-page.ts shownYear) + 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: '' }; +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: '' }; const KEY = 'accounts.prefs'; export function loadPrefs(storage: Pick | undefined = globalThis.localStorage): Prefs { @@ -131,6 +134,7 @@ export function loadPrefs(storage: Pick | undefined = global fundamentalsSplit: asSplits(p.fundamentalsSplit), noticesAt: asNoticeCorner(p.noticesAt), fundamentalsOpen: typeof p.fundamentalsOpen === 'string' ? p.fundamentalsOpen.slice(0, 24) : '', + taxYear: typeof p.taxYear === 'string' && /^\d{4}$/.test(p.taxYear) ? p.taxYear : '', }; } catch { return DEFAULT_PREFS; diff --git a/src/viewer/app/tax-household.test.ts b/src/viewer/app/tax-household.test.ts new file mode 100644 index 0000000..504234f --- /dev/null +++ b/src/viewer/app/tax-household.test.ts @@ -0,0 +1,55 @@ +/// +/// +/// +import { expect, test } from 'bun:test'; +import { HOUSEHOLD_KEY, household, parseAmount, parseHousehold, saveHousehold } from './tax-household'; +import { DEFAULT_HOUSEHOLD } from './taxes'; + +test('nothing stored or junk: the default household', () => { + expect(parseHousehold(null)).toEqual(DEFAULT_HOUSEHOLD); + expect(parseHousehold(undefined)).toEqual(DEFAULT_HOUSEHOLD); + expect(parseHousehold('')).toEqual(DEFAULT_HOUSEHOLD); + expect(parseHousehold('{not json')).toEqual(DEFAULT_HOUSEHOLD); + expect(parseHousehold('[1,2]')).toEqual(DEFAULT_HOUSEHOLD); + expect(parseHousehold('"text"')).toEqual(DEFAULT_HOUSEHOLD); +}); + +test('a stored household reads back; filing and state stay the only supported ones', () => { + const kept = { filing: 'single', state: 'NY', grossWages: 90_000, pretax401k: 5_000.5, otherPretax: 1_200, njDependents: 3, deduction: { kind: 'itemized', amount: 40_000 } }; + expect(parseHousehold(JSON.stringify(kept))).toEqual({ filing: 'mfj', state: 'NJ', grossWages: 90_000, pretax401k: 5_000.5, otherPretax: 1_200, njDependents: 3, deduction: { kind: 'itemized', amount: 40_000 } }); +}); + +test('a field out of range falls back to its own default, the others are kept', () => { + const h = parseHousehold(JSON.stringify({ grossWages: -1, pretax401k: '5000', otherPretax: 300, njDependents: 2.5, deduction: { kind: 'itemized', amount: -10 } })); + expect(h).toEqual({ ...DEFAULT_HOUSEHOLD, otherPretax: 300 }); + expect(parseHousehold(JSON.stringify({ njDependents: 21 })).njDependents).toBe(DEFAULT_HOUSEHOLD.njDependents); + expect(parseHousehold(JSON.stringify({ njDependents: 20 })).njDependents).toBe(20); + expect(parseHousehold(JSON.stringify({ njDependents: 0 })).njDependents).toBe(0); + expect(parseHousehold(JSON.stringify({ grossWages: 0 })).grossWages).toBe(0); + expect(parseHousehold(JSON.stringify({ deduction: { kind: 'itemized' } })).deduction).toEqual({ kind: 'standard' }); + expect(parseHousehold(JSON.stringify({ deduction: { kind: 'itemized', amount: 0 } })).deduction).toEqual({ kind: 'itemized', amount: 0 }); +}); + +test('typed amounts: commas, dollars and spaces are fine, a minus or a word is not', () => { + expect(parseAmount('125,000')).toBe(125_000); + expect(parseAmount(' $1 500.50 ')).toBe(1_500.5); + expect(parseAmount('0')).toBe(0); + expect(parseAmount('.5')).toBe(0.5); + expect(parseAmount('12.')).toBe(12); + expect(parseAmount('')).toBeNull(); + expect(parseAmount('-5')).toBeNull(); + expect(parseAmount('1e5')).toBeNull(); + expect(parseAmount('abc')).toBeNull(); +}); + +test('a change shows at once, is checked and kept under accounts.taxes', () => { + const kept: Record = {}; + const to = { setItem: (k: string, v: string) => { kept[k] = v; } }; + saveHousehold({ grossWages: 100_000, njDependents: 1 }, to); + expect(household.get()).toEqual({ ...DEFAULT_HOUSEHOLD, grossWages: 100_000, njDependents: 1 }); + expect(JSON.parse(kept[HOUSEHOLD_KEY]!)).toEqual(household.get()); + saveHousehold({ njDependents: 99, deduction: { kind: 'itemized', amount: 35_000 } }, to); + expect(household.get()).toEqual({ ...DEFAULT_HOUSEHOLD, grossWages: 100_000, njDependents: DEFAULT_HOUSEHOLD.njDependents, deduction: { kind: 'itemized', amount: 35_000 } }); + saveHousehold(DEFAULT_HOUSEHOLD, undefined); + expect(household.get()).toEqual(DEFAULT_HOUSEHOLD); +}); diff --git a/src/viewer/app/tax-household.ts b/src/viewer/app/tax-household.ts new file mode 100644 index 0000000..fc03c8f --- /dev/null +++ b/src/viewer/app/tax-household.ts @@ -0,0 +1,54 @@ +/// +import { createStore } from '../../shared/store'; +import { DEFAULT_HOUSEHOLD, type Household } from './taxes'; + +// The household of the Fidelity Taxes page, set in ⚙️ Settings -> Taxes (owner 2026-12-03: gross wages, two children +// counted for New Jersey only, the standard deduction): kept in this browser under `accounts.taxes` and carried by +// Export and Import with the other settings. One filing status and one state for now, so those two are never read back +// from storage; every other field that is not a usable number falls back to its default alone +export const HOUSEHOLD_KEY = 'accounts.taxes'; +export const MAX_DEPENDENTS = 20; + +const money = (v: unknown, fallback: number): number => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : fallback); + +/** the stored text back to a household: nothing stored, junk or a field out of range = the default of that field */ +export function parseHousehold(raw: string | null | undefined): Household { + let p: Record = {}; + try { + const json: unknown = raw ? JSON.parse(raw) : {}; + if (json && typeof json === 'object' && !Array.isArray(json)) p = json as Record; + } catch { /* junk: the defaults */ } + const d = DEFAULT_HOUSEHOLD; + const deps = p.njDependents; + const ded = (p.deduction ?? {}) as { kind?: unknown; amount?: unknown }; + const itemized = ded.kind === 'itemized' && typeof ded.amount === 'number' && Number.isFinite(ded.amount) && ded.amount >= 0; + return { + filing: 'mfj', + state: 'NJ', + grossWages: money(p.grossWages, d.grossWages), + pretax401k: money(p.pretax401k, d.pretax401k), + otherPretax: money(p.otherPretax, d.otherPretax), + njDependents: typeof deps === 'number' && Number.isInteger(deps) && deps >= 0 && deps <= MAX_DEPENDENTS ? deps : d.njDependents, + deduction: itemized ? { kind: 'itemized', amount: ded.amount as number } : { kind: 'standard' }, + }; +} + +/** a typed amount ("125,000", "$1 500.50") as a number of 0 or more; anything else null */ +export function parseAmount(text: string): number | null { + const s = text.replace(/[$,\s]/g, ''); + if (!/^\d*\.?\d+$/.test(s) && !/^\d+\.$/.test(s)) return null; + const n = Number(s); + return Number.isFinite(n) && n >= 0 ? n : null; +} + +const storage = (): Storage | undefined => { try { return globalThis.localStorage; } catch { return undefined; } }; +const read = (): Household => { try { return parseHousehold(storage()?.getItem(HOUSEHOLD_KEY)); } catch { return DEFAULT_HOUSEHOLD; } }; +export const household = createStore(read()); + +/** one or more fields changed: checked like a stored copy, shown at once and kept */ +export function saveHousehold(patch: Partial>, to: Pick | undefined = storage()): Household { + const next = parseHousehold(JSON.stringify({ ...household.get(), ...patch })); + household.set(next); + try { to?.setItem(HOUSEHOLD_KEY, JSON.stringify(next)); } catch { /* private window */ } + return next; +} diff --git a/src/viewer/app/taxes-page.test.ts b/src/viewer/app/taxes-page.test.ts new file mode 100644 index 0000000..e6456a6 --- /dev/null +++ b/src/viewer/app/taxes-page.test.ts @@ -0,0 +1,102 @@ +/// +/// +/// +import { expect, test } from 'bun:test'; +import { emptyDataset, type Account, type Dataset } from '../../shared/model'; +import type { TaxYtd } from '../../shared/tax-summary'; +import { INCOME_LINES, roomRows, shownYear, taxPage, taxYears } from './taxes-page'; +import { DEFAULT_HOUSEHOLD } from './taxes'; + +// made-up accounts and amounts only; the expected numbers are worked out by hand in the comments +const acct = (number: string, type = 'Brokerage'): Account => ({ number, name: `Acct ${number.slice(-2)}`, group: 'Investment', type, asOf: '2026-12-01T00:00:00Z' }); +const A = acct('X10000001'); +const B = acct('X10000002'); +const ROTH = acct('X10000003', 'ROTH IRA'); +const ytd = (boxes: Record, o: Partial = {}): TaxYtd => ({ asOf: '2026-11-30', boxes, shortTerm: null, longTerm: null, ...o }); +const ds: Dataset = { + ...emptyDataset('2026-12-01T00:00:00Z'), + accounts: [A, B, ROTH], + taxSummary: { + years: { + '2025': { X10000001: ytd({ '1099-DIV 1A': 10 }, { asOf: '2025-12-31' }) }, + '2026': { + X10000001: ytd({ '1099-DIV 1A': 1_000, '1099-DIV 1B': 600, '1099-DIV 1C': 400, '1099-INT 1': 100 }, { asOf: '2026-11-29' }), + X10000002: ytd({}, { shortTerm: 500, longTerm: 200 }), + X10000003: ytd({ '1099-DIV 1A': 9_999, '1099-DIV 1C': 9_999 }), + }, + '2024': {}, + }, + }, +}; + +test('the years with any account, the newest first; the chosen one while it is there', () => { + expect(taxYears(ds.taxSummary)).toEqual(['2026', '2025']); + expect(taxYears(undefined)).toEqual([]); + expect(shownYear(['2026', '2025'], '2025')).toBe('2025'); + expect(shownYear(['2026', '2025'], '2024')).toBe('2026'); + expect(shownYear(['2026', '2025'], '')).toBe('2026'); + expect(shownYear([], '2026')).toBe(''); +}); + +test('the taxable shown accounts summed, the tax and the room of the default household', () => { + const p = taxPage(ds, [A, B, ROTH], '2026', DEFAULT_HOUSEHOLD); + // the Roth is left out although it has numbers + expect(p.taxableShown).toBe(2); + expect(p.columns.map((c) => c.account.number)).toEqual(['X10000001', 'X10000002']); + expect(p.income.asOf).toBe('2026-11-29'); + expect(p.fallback).toBe(false); + // federal: wages 125,000 - 32,200 = 92,800; ordinary 400 + 100 + 500 = 1,000 all at 12% = 120; qualified 600 + long 200 + // on top end at 94,600, under 98,900: 0% + const t = p.tax!; + expect(t.federal.added).toBeCloseTo(120, 6); + // NJ: 125,000 - 2,000 - 2 x 1,500 = 120,000 before; + 1,000 dividends + 100 interest + 700 gains = 121,800; 1,800 x 5.525% + expect(t.nj.added).toBeCloseTo(99.45, 6); + expect(t.total).toBeCloseTo(219.45, 6); + expect(t.effectiveRate!).toBeCloseTo(219.45 / 1_800, 9); + expect(t.nextDollar.shortTerm).toBeCloseTo(0.17525, 6); // 12% + 5.525% + expect(t.federal.marginalOrdinary).toBe(0.12); + expect(t.federal.preferentialRate).toBe(0); + // room: 100,800 - 93,800 = 7,000; 98,900 - 94,600 = 4,300; NJ 150,000 - 121,800 = 28,200 before 6.37% + expect(p.room).toEqual([ + { key: 'ordinary22', left: 7_000, line: 100_800, used: 93_800 / 100_800, rate: 0.22 }, + { key: 'preferential', left: 4_300, line: 98_900, used: 94_600 / 98_900, rate: 0.15 }, + { key: 'nj', left: 28_200, line: 150_000, used: 121_800 / 150_000, rate: 0.0637 }, + ]); +}); + +test('the Income rows: every line in Fidelity\'s order, zeros kept, each account\'s part', () => { + const p = taxPage(ds, [A, B], '2026', DEFAULT_HOUSEHOLD); + expect(p.rows.map((r) => r.key)).toEqual(INCOME_LINES.map((l) => l.key)); + const row = (k: string) => p.rows.find((r) => r.key === k)!; + expect(row('ordinaryDividends')).toEqual({ key: 'ordinaryDividends', sub: false, total: 1_000, byAccount: [1_000, 0] }); + expect(row('qualified')).toEqual({ key: 'qualified', sub: true, total: 600, byAccount: [600, 0] }); + expect(row('shortTerm').byAccount).toEqual([0, 500]); + expect(row('foreignTax')).toEqual({ key: 'foreignTax', sub: false, total: 0, byAccount: [0, 0] }); +}); + +test('nothing for the year or no taxable account shown: no tax, the rows at zero, the room bars empty', () => { + const none = taxPage(ds, [ROTH], '2026', DEFAULT_HOUSEHOLD); + expect(none.taxableShown).toBe(0); + expect(none.tax).toBeNull(); + expect(none.columns).toEqual([]); + expect(none.rows.every((r) => r.total === 0 && r.byAccount.length === 0)).toBe(true); + expect(none.room.map((r) => [r.key, r.left, r.used])).toEqual([['ordinary22', null, 0], ['preferential', null, 0], ['nj', null, 0]]); + const notRead = taxPage(ds, [B], '2025', DEFAULT_HOUSEHOLD); + expect(notRead.taxableShown).toBe(1); + expect(notRead.yearRead).toBe(true); // A has 2025, B does not + expect(taxPage(ds, [A], '2023', DEFAULT_HOUSEHOLD).yearRead).toBe(false); + expect(notRead.tax).toBeNull(); + // 2025 has no rules of its own yet: the latest are used and the page says so + expect(notRead.fallback).toBe(true); + expect(notRead.rulesYear).toBe('2026'); +}); + +test('the room at a line and past the top NJ row', () => { + const rich = taxPage(ds, [A], '2026', { ...DEFAULT_HOUSEHOLD, grossWages: 2_000_000 }); + const [ord, pref, nj] = rich.room; + expect(ord!.left).toBe(0); + expect(ord!.used).toBe(1); + expect(pref!.left).toBe(0); + expect(nj).toEqual({ key: 'nj', left: null, line: null, used: 1, rate: null }); + expect(roomRows(null, '2026')[0]!.rate).toBe(0.22); +}); diff --git a/src/viewer/app/taxes-page.ts b/src/viewer/app/taxes-page.ts new file mode 100644 index 0000000..a66eb49 --- /dev/null +++ b/src/viewer/app/taxes-page.ts @@ -0,0 +1,104 @@ +/// +import type { Account, Dataset } from '../../shared/model'; +import { taxable } from '../../shared/tax'; +import { rulesFor } from '../../shared/tax-rules-2026'; +import type { TaxSummary, TaxYtd } from '../../shared/tax-summary'; +import { investmentIncome, investmentTax, type Household, type InvestmentIncome, type InvestmentTax } from './taxes'; + +// What the Fidelity Taxes page shows (owner 2026-12-03: "I have a buffer about 1500$-1600$ approx. but this is exactly +// info what I want to see on line and constantly updating / calculation on my viewer"): for one tax year and the +// taxable accounts of the strip, Fidelity's Tax Info YTD summed, the tax the investments add and the room before the +// next rates (app/taxes.ts does the math). Pure: the page component only draws this + +/** the tax years Fidelity's summary has any account of, the newest first */ +export function taxYears(s: TaxSummary | undefined): string[] { + if (!s) return []; + return Object.keys(s.years).filter((y) => Object.keys(s.years[y] ?? {}).length > 0).sort().reverse(); +} + +/** the year chosen on the page while the summary has it, else the newest; '' with no year at all */ +export const shownYear = (years: readonly string[], chosen: string): string => (years.indexOf(chosen) >= 0 ? chosen : years[0] ?? ''); + +/** the lines of the Income card, in the order of Fidelity's Tax Info page; `sub`: a part of the line above it */ +export type IncomeKey = Exclude; +export const INCOME_LINES: ReadonlyArray<{ key: IncomeKey; sub?: boolean }> = [ + { key: 'ordinaryDividends' }, + { key: 'qualified', sub: true }, + { key: 'nonQualified', sub: true }, + { key: 'capGainDistributions' }, + { key: 'interest' }, + { key: 'treasuryInterest' }, + { key: 'otherOrdinary' }, + { key: 'shortTerm' }, + { key: 'longTerm' }, + { key: 'foreignTax' }, + { key: 'withheld' }, + { key: 'marginInterest' }, + { key: 'section199a' }, +]; + +/** one shown account with its year so far */ +export interface TaxColumn { account: Account; ytd: TaxYtd; income: InvestmentIncome } +/** one line of the Income card: the sum and each account's part, in the order of `columns` */ +export interface IncomeRow { key: IncomeKey; sub: boolean; total: number; byAccount: number[] } + +/** one bar of the Room card: dollars left before `line` and the rate past it; `left` null = already in the top row */ +export type RoomKey = 'ordinary22' | 'preferential' | 'nj'; +export interface RoomRow { key: RoomKey; left: number | null; line: number | null; used: number; rate: number | null } + +export interface TaxPageView { + year: string; + taxableShown: number; // the shown accounts that are taxable, with or without data + yearRead: boolean; // Fidelity's summary has the year for some account, shown or not + columns: TaxColumn[]; + income: InvestmentIncome; + rows: IncomeRow[]; + tax: InvestmentTax | null; // null when no shown account has the year + room: RoomRow[]; + rulesYear: string; // the year of the rules counted with + fallback: boolean; // the year has no rules of its own: the latest ones are used +} + +// how far along the way to a line: 0 to 1 +const share = (used: number, line: number): number => (line > 0 ? Math.min(1, Math.max(0, used / line)) : 0); + +/** the rows of the Room card from the tax and the rules of the year */ +export function roomRows(tax: InvestmentTax | null, year: string): RoomRow[] { + const { rules } = rulesFor(year); + const f = rules.federal; + const at22 = f.ordinary.findIndex((b) => b.rate >= 0.22); + const line22 = at22 > 0 ? f.ordinary[at22 - 1]!.upTo : 0; + const linePref = f.preferential[0]!.upTo; + if (!tax) { + return [ + { key: 'ordinary22', left: null, line: line22, used: 0, rate: f.ordinary[at22]?.rate ?? null }, + { key: 'preferential', left: null, line: linePref, used: 0, rate: f.preferential[1]?.rate ?? null }, + { key: 'nj', left: null, line: null, used: 0, rate: null }, + ]; + } + const r = tax.room; + // the NJ row whose next rate is the one the room reaches: its top is the line + const nj = rules.nj.brackets; + const njAt = r.njNextRate === null ? -1 : nj.findIndex((b, i) => nj[i + 1]?.rate === r.njNextRate); + const njLine = njAt >= 0 ? nj[njAt]!.upTo : null; + return [ + { key: 'ordinary22', left: r.before22, line: line22, used: share(line22 - r.before22, line22), rate: f.ordinary[at22]?.rate ?? null }, + { key: 'preferential', left: r.beforePreferential15, line: linePref, used: share(linePref - r.beforePreferential15, linePref), rate: f.preferential[1]?.rate ?? null }, + { key: 'nj', left: r.njNext, line: njLine, used: njLine === null || r.njNext === null ? 1 : share(njLine - r.njNext, njLine), rate: r.njNextRate }, + ]; +} + +/** + * The page for one year: the shown accounts that are taxable and have the year in Fidelity's summary (each a column of + * the ⤢ table, in the strip's order), their income summed, the tax and the room for the household + */ +export function taxPage(ds: Dataset, accounts: readonly Account[], year: string, household: Household): TaxPageView { + const shown = accounts.filter(taxable); + const of = ds.taxSummary?.years[year] ?? {}; + const columns: TaxColumn[] = shown.filter((a) => !!of[a.number]).map((a) => ({ account: a, ytd: of[a.number]!, income: investmentIncome([of[a.number]!]) })); + const income = investmentIncome(columns.map((c) => c.ytd)); + const rows: IncomeRow[] = INCOME_LINES.map((l) => ({ key: l.key, sub: !!l.sub, total: income[l.key], byAccount: columns.map((c) => c.income[l.key]) })); + const { rules, fallback } = rulesFor(year); + const tax = columns.length ? investmentTax(rules, household, income) : null; + return { year, taxableShown: shown.length, yearRead: Object.keys(of).length > 0, columns, income, rows, tax, room: roomRows(tax, year), rulesYear: rules.year, fallback }; +} diff --git a/src/viewer/app/transfer.test.ts b/src/viewer/app/transfer.test.ts index b3503b7..8df3605 100644 --- a/src/viewer/app/transfer.test.ts +++ b/src/viewer/app/transfer.test.ts @@ -14,6 +14,7 @@ test('only the setup and the view travel: never the Google token or a neighbour const s = store({ 'accounts-gs-config': '{"clientId":"c"}', 'accounts.prefs': '{}', 'accounts-google-token': 'secret', 'other-app.setting': '1' }); expect(collectSettings(s)).toEqual({ 'accounts-gs-config': '{"clientId":"c"}', 'accounts.prefs': '{}' }); expect(TRANSFER_KEYS).not.toContain('accounts-google-token'); + expect(TRANSFER_KEYS).toContain('accounts.taxes'); // the household of Settings -> Taxes travels too }); test('a file opens with its password and shows nothing without it', async () => { diff --git a/src/viewer/app/transfer.ts b/src/viewer/app/transfer.ts index 01aa498..1f3df2e 100644 --- a/src/viewer/app/transfer.ts +++ b/src/viewer/app/transfer.ts @@ -8,12 +8,14 @@ import { EARLIER_NAME, renamedKey } from '../../shared/rename'; import { CONFIG_KEY } from '../../shared/sheets/gis'; import { VIEW_KEYS } from './prefs'; +import { HOUSEHOLD_KEY } from './tax-household'; export const FILE_APP = 'accounts'; export const ITERATIONS = 600000; export const MIN_PASSWORD = 8; -/** the only keys that leave this browser and the only ones a file may write */ -export const TRANSFER_KEYS: readonly string[] = [CONFIG_KEY, ...VIEW_KEYS]; +/** the only keys that leave this browser and the only ones a file may write; the household of Settings -> Taxes is + * setup, so Reset view keeps it, but it travels */ +export const TRANSFER_KEYS: readonly string[] = [CONFIG_KEY, ...VIEW_KEYS, HOUSEHOLD_KEY]; export interface SettingsFile { app: string; kind: 'settings'; v: 1; kdf: 'PBKDF2-SHA256'; cipher: 'AES-256-GCM'; iterations: number; salt: string; iv: string; data: string } export type TransferError = 'not-ours' | 'wrong-password'; diff --git a/src/viewer/ui/Allocation.tsx b/src/viewer/ui/Allocation.tsx index 1ccab69..584d351 100644 --- a/src/viewer/ui/Allocation.tsx +++ b/src/viewer/ui/Allocation.tsx @@ -5,6 +5,7 @@ import { t } from '../app/i18n'; import { prefs, setPrefs } from '../app/prefs'; import { animate } from './animate'; import { Donut } from './Donut'; +import { FillBar } from './FillBar'; import { pct, usd } from './format'; import { BarsIcon, PieIcon } from './icons'; import { Toggle } from './Toggle'; @@ -41,7 +42,7 @@ function Bars({ slices, all }: { slices: Slice[]; all?: boolean }) { {(all ? slices : slices.slice(0, 8)).map((s) => (
{s.name}{s.note && {s.note}}{usd(s.value)} · {pct(s.pct)}
-
+
))}
diff --git a/src/viewer/ui/AmountField.tsx b/src/viewer/ui/AmountField.tsx new file mode 100644 index 0000000..8512711 --- /dev/null +++ b/src/viewer/ui/AmountField.tsx @@ -0,0 +1,35 @@ +/// +import { useEffect, useRef, useState } from 'react'; +import { parseAmount } from '../app/tax-household'; + +// One number typed in ⚙️ Settings (rules/reusable-components.md: the wages, the pre-tax money, the dependents and the +// itemized deduction of Settings -> Taxes): its name and a box. Commas and a $ may be typed; each usable number is kept +// at once, a box that reads as no number is framed red and keeps the last good one; leaving the box shows the kept value +// again with its thousands. `integer` and `max` narrow what is usable (the count of dependents) +const shown = (n: number): string => n.toLocaleString('en-US', { maximumFractionDigits: 2 }); + +export function AmountField({ label, value, onSave, integer = false, max, name }: { label: string; value: number; onSave: (n: number) => void; integer?: boolean; max?: number; name: string }) { + const [text, setText] = useState(() => shown(value)); + const editing = useRef(false); + // a value changed elsewhere (an import, a reset) shows unless the owner is typing in the box + useEffect(() => { if (!editing.current) setText(shown(value)); }, [value]); + const read = (s: string): number | null => { + const n = parseAmount(s); + return n === null || (integer && !Number.isInteger(n)) || (max !== undefined && n > max) ? null : n; + }; + const bad = read(text) === null; + return ( + + ); +} diff --git a/src/viewer/ui/App.tsx b/src/viewer/ui/App.tsx index e02b988..b21ce96 100644 --- a/src/viewer/ui/App.tsx +++ b/src/viewer/ui/App.tsx @@ -9,6 +9,7 @@ import { MAIN_TABS, prefs, setPrefs, type MainTab } from '../app/prefs'; import { USERSCRIPT_ATTR, userscriptVersion } from '../app/status'; import { rovingIndex } from '../app/focus'; import { squashed } from '../app/squash'; +import { taxYears } from '../app/taxes-page'; import { APP_VERSION, isOlder } from '../app/version'; import { loadConfig } from '../../shared/sheets/gis'; import { AccountTabs } from './AccountTabs'; @@ -30,6 +31,7 @@ import { SettingsPanel, SettingsTools } from './SettingsPanel'; import { SlidePanel } from './SlidePanel'; import { TabLine } from './TabLine'; import { Summary } from './Summary'; +import { Taxes } from './Taxes'; import { animate } from './animate'; import { readTime } from './format'; import { GutterScrollbars } from './GutterScrollbars'; @@ -39,7 +41,7 @@ import { PHONE_QUERY, useMedia } from './useMedia'; // the pages of one source carry its name (owner 2026-11-29: "Fidelity Summary, Fidelity Positions and Fidelity // Activity": the pages of the ADP 401k come next to them) -const tabName = (tab: MainTab): string => ({ summary: t('Fidelity Summary'), positions: t('Fidelity Positions'), activity: t('Fidelity Activity'), reports: t('Fidelity Reports'), adpSummary: t('ADP Summary'), adpActivity: t('ADP Activity') })[tab]; +const tabName = (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]; const TAB_PANEL = 'main-tabpanel'; // open or closed panels are remembered per browser (twitter: `${PREFIX}-panel-setup`) @@ -55,8 +57,11 @@ 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); a page saved but not shown falls back to Summary - const tabs = useMemo(() => MAIN_TABS.filter((x) => (x !== 'adpActivity' && x !== 'adpSummary') || !!adp), [adp]); + // 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 + const taxYearsRead = taxYears(rawDs?.taxSummary).length > 0; + const tabs = useMemo(() => MAIN_TABS.filter((x) => (x === 'taxes' ? taxYearsRead : (x !== 'adpActivity' && x !== 'adpSummary') || !!adp)), [adp, taxYearsRead]); const openTab: MainTab = tabs.indexOf(pr.tab) >= 0 ? pr.tab : 'summary'; const adpPage = openTab === 'adpSummary' || openTab === 'adpActivity'; // the owner's own order of accounts applies everywhere: the bar, Positions, the Accounts card @@ -277,7 +282,7 @@ export function App() {
{tabs.map((tab) => ( + className={`main-tab flex h-9 items-center ${tab === 'positions' ? 'order-3' : tab === 'summary' ? 'order-1' : tab === 'activity' ? 'order-4' : tab === 'reports' ? 'order-5' : tab === 'taxes' ? 'order-6' : tab === 'adpSummary' ? 'order-7' : 'order-8'} ${openTab === tab ? 'on' : ''}`} onClick={() => setPrefs({ tab })} data-main-tab={tab}>{tabName(tab)} ))}
{/* drawn between Summary and Positions (owner 2026-11-27): the gap from Summary to the icon is the page @@ -305,7 +310,7 @@ export function App() { {/* the cards start one gutter below the tabs panel */}
- {openTab === 'adpSummary' && adp ?
diff --git a/src/viewer/ui/BalanceHead.tsx b/src/viewer/ui/BalanceHead.tsx index 9fd7ec4..74f6b97 100644 --- a/src/viewer/ui/BalanceHead.tsx +++ b/src/viewer/ui/BalanceHead.tsx @@ -14,12 +14,13 @@ import { signedUsd, usd } from './format'; // both, and the head is at least as tall as the balance and four lines (7.5rem: 40 px + 4 x 20 px, or six facts of 20 px), // so the chart starts at the same place on both cards (owner 2026-11-30: "total gain/loss must be on the same location", // "consistent"); ADP has no Today line, Fidelity no Cash or Pending on ADP -export function BalanceHead({ value, lines, facts, id }: { value: string; lines: ReactNode; facts: ReactNode; id?: string }) { +// `free`: a head with no chart under it (Fidelity Taxes) is as tall as its content, not held at the balance cards' height +export function BalanceHead({ value, lines, facts, id, free }: { value: string; lines: ReactNode; facts: ReactNode; id?: string; free?: boolean }) { return ( // the balance side never gets narrower than its widest unbreakable part (min-content: the big number, a change with // its percent), the words of its lines wrap first; when even that and the facts do not fit on one line (a phone, a // narrow card of a three-column page: owner 2026-12-03, the big number ran under the facts) the facts go under it -
+
{value}
{lines}
diff --git a/src/viewer/ui/Empty.tsx b/src/viewer/ui/Empty.tsx new file mode 100644 index 0000000..5ad14ae --- /dev/null +++ b/src/viewer/ui/Empty.tsx @@ -0,0 +1,5 @@ +/// + +// What a card says when it has nothing to show yet (rules/reusable-components.md): one quiet line under the card's head, +// which keeps its controls (owner 2026-11-30: "so our plates will jump less") +export const Empty = ({ text, name }: { text: string; name?: string }) =>

{text}

; diff --git a/src/viewer/ui/FillBar.tsx b/src/viewer/ui/FillBar.tsx new file mode 100644 index 0000000..7eaed06 --- /dev/null +++ b/src/viewer/ui/FillBar.tsx @@ -0,0 +1,13 @@ +/// + +// A thin track filled from the left (rules/reusable-components.md: one bar for every "how far along" line): the share of +// the Income card's expected total already received, an allocation slice of the whole, how much of the way to the next +// tax rate is used on Fidelity Taxes. `pct` is 0 to 100, clamped; `color` the fill, the brand colour by default +export function FillBar({ pct, color = 'var(--brand)', title, className = '', name }: { pct: number; color?: string; title?: string; className?: string; name?: string }) { + const w = Number.isFinite(pct) ? Math.min(100, Math.max(0, pct)) : 0; + return ( +
+
+
+ ); +} diff --git a/src/viewer/ui/SettingsPanel.tsx b/src/viewer/ui/SettingsPanel.tsx index 3204e41..85b262b 100644 --- a/src/viewer/ui/SettingsPanel.tsx +++ b/src/viewer/ui/SettingsPanel.tsx @@ -10,6 +10,7 @@ import { NotifySetting, PanelSetting } from './NotifySetting'; import { PalettePicker } from './PalettePicker'; import { Section } from './Section'; import { SettingsTransfer } from './SettingsTransfer'; +import { TaxSettings } from './TaxSettings'; import { LoginForm } from './Logins'; import { openFidelity, openMykplan } from '../app/data'; import { loginConfirmed, logins } from '../app/logins'; @@ -30,6 +31,7 @@ export function SettingsPanel({ userscript, done, fresh, expand, theme }: { user const [prefsOpen, setPrefsOpen] = useState(() => sectionOpen(choices, 'preferences', true)); const [fidelityOpen, setFidelityOpen] = useState(() => sectionOpen(choices, 'fidelity', false)); const [adpOpen, setAdpOpen] = useState(() => sectionOpen(choices, 'adp', false)); + const [taxesOpen, setTaxesOpen] = useState(() => sectionOpen(choices, 'taxes', false)); const l = useStore(logins); // a site with no saved login opens its section (not kept as a choice); each Save that the script confirms folds it and // keeps it folded, a Save of the same login again too (owner 2026-11-30: "after clicked save if success - collapse that @@ -72,6 +74,10 @@ export function SettingsPanel({ userscript, done, fresh, expand, theme }: { user
fold('adp', !adpOpen, setAdpOpen)}>
+ {/* the household the Fidelity Taxes page counts for (owner 2026-12-03): wages, pre-tax money, dependents, deduction */} +
fold('taxes', !taxesOpen, setTaxesOpen)}> + +
); } diff --git a/src/viewer/ui/Summary.tsx b/src/viewer/ui/Summary.tsx index 1d69833..3d8fe0a 100644 --- a/src/viewer/ui/Summary.tsx +++ b/src/viewer/ui/Summary.tsx @@ -34,6 +34,8 @@ import { paidDividends, paidTax, pastBy, sortPaid } from '../app/paid-dividends' import { INCOME_SPANS, shownSpans, type Span } from '../app/spans'; import { SpanPills } from './SpanPills'; import { pulseKey, type PulseMark } from '../app/pulse'; +import { Empty } from './Empty'; +import { FillBar } from './FillBar'; import { HeadGroup } from './HeadGroup'; import { lang, t } from '../app/i18n'; import { maskAccount, pct, qty, signedUsd, siteDate, usd, usd0 } from './format'; @@ -68,8 +70,6 @@ function Tickers({ ps, tone, title }: { ps: Position[]; tone: 'gain' | 'loss'; t ); } -const Empty = ({ text }: { text: string }) =>

{text}

; - // Summary: cards of information like the Fidelity summary page, for the chosen scope, each card a Card (Card.tsx) // `title`: the name of what is shown (All accounts, a group, the accounts chosen), the Balance card's title; `today`: the // owner's date (localToday) from App, so the numbers move to the next day on App's first draw after midnight, as before @@ -281,7 +281,7 @@ export const Summary = memo(function Summary({ ds, accounts, title, titleHint, t {t('of {total}', { total: usd0(v.planned) })}{words.expected}
{/* progress of the facts towards the expected total */} -
0 ? Math.min(100, (v.received / v.planned) * 100) : 0}%`, background: 'var(--brand)' }} />
+ 0 ? (v.received / v.planned) * 100 : 0} /> {/* the average first, then the share of the balance (owner 2026-11-24); the year has no average, an empty line keeps its share level with the others */}
{med ? <>{words.median}: {usd(med.usd)} : '\u00a0'}
diff --git a/src/viewer/ui/TaxSettings.tsx b/src/viewer/ui/TaxSettings.tsx new file mode 100644 index 0000000..71e38a9 --- /dev/null +++ b/src/viewer/ui/TaxSettings.tsx @@ -0,0 +1,58 @@ +/// +import { RULES_2026 } from '../../shared/tax-rules-2026'; +import { t } from '../app/i18n'; +import { MAX_DEPENDENTS, household, saveHousehold } from '../app/tax-household'; +import { DEFAULT_HOUSEHOLD } from '../app/taxes'; +import { AmountField } from './AmountField'; +import { usd0 } from './format'; +import { Pills } from './Pills'; +import { SettingRow } from './SettingRow'; +import { useStore } from './useStore'; + +// ⚙️ Settings -> Taxes: the household the Fidelity Taxes page counts for (app/tax-household.ts). Each line says where +// its default comes from (owner 2026-12-03: the gross wages, two children counted for New Jersey only, the standard +// deduction); the ADP pay statements replace the guesses later. One filing status and one state, shown as text +const DEDUCTIONS = ['standard', 'itemized'] as const; +type DeductionKind = (typeof DEDUCTIONS)[number]; + +export function TaxSettings() { + const h = useStore(household); + const d = DEFAULT_HOUSEHOLD; + const rules = RULES_2026; + const kind: DeductionKind = h.deduction.kind; + const itemized = h.deduction.kind === 'itemized' ? h.deduction.amount : rules.federal.standardDeduction; + const dedName = { standard: t('Standard'), itemized: t('Itemized') } as const; + return ( +
+ {t('Filing')}{t('Married filing jointly, New Jersey')}}> + {t('The only filing status and state the Taxes page counts for now')} + + saveHousehold({ grossWages: n })} />}> + {t('Wages of the household for the year, both of you, before anything is taken out. Default {amount}: your own estimate; the ADP pay statements replace it later', { amount: usd0(d.grossWages) })} + + saveHousehold({ pretax401k: n })} />}> + {t('Your pre-tax 401(k) contributions of the year: they lower the federal and New Jersey wages. Default 0')} + + saveHousehold({ otherPretax: n })} />}> + {t('Health, dental, HSA, FSA and commuter money taken before tax: lowers the federal wages only, New Jersey taxes it. Default 0')} + + saveHousehold({ njDependents: n })} />}> + {t('Children and other dependents: {each} each off New Jersey taxable income; left out federally (the child tax credit lowers the bill, not what the investments add). Default {n}: your children', { each: usd0(rules.nj.exemptionPerDependent), n: d.njDependents })} + + + {t('Deduction')} + dedName[k]} + onChange={(k) => saveHousehold({ deduction: k === 'standard' ? { kind: 'standard' } : { kind: 'itemized', amount: itemized } })} /> + + )}> + {t('Federal: the standard deduction of {year} is {amount}, or your itemized total. Default standard', { year: rules.year, amount: usd0(rules.federal.standardDeduction) })} + + {h.deduction.kind === 'itemized' && ( + saveHousehold({ deduction: { kind: 'itemized', amount: n } })} />}> + {t('Mortgage interest, state and property taxes up to the cap, gifts to charity: the total of Schedule A')} + + )} +
+ ); +} diff --git a/src/viewer/ui/Taxes.test.tsx b/src/viewer/ui/Taxes.test.tsx new file mode 100644 index 0000000..238f099 --- /dev/null +++ b/src/viewer/ui/Taxes.test.tsx @@ -0,0 +1,99 @@ +/// +/// +/// +// The Fidelity Taxes page draws its three cards from made-up numbers, keeps them with their heads when the year has no +// summary, and Settings -> Taxes keeps a typed amount +import { afterAll, beforeAll, expect, test } from 'bun:test'; +import { GlobalRegistrator } from '@happy-dom/global-registrator'; +import type { Account, Dataset } from '../../shared/model'; + +beforeAll(() => { + GlobalRegistrator.register({ url: 'http://localhost:1237/' }); + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; +}); +afterAll(() => GlobalRegistrator.unregister()); + +// made-up accounts and amounts only +const acct = (number: string, type = 'Brokerage'): Account => ({ number, name: `Acct ${number.slice(-2)}`, group: 'Investment', type, asOf: '2026-12-01T00:00:00Z' }); +const A = acct('X10000001'); +const B = acct('X10000002'); +const ds = (): Dataset => ({ + version: 1, builtAt: '2026-12-01T00:00:00Z', asOf: null, accounts: [A, B], positions: [], warnings: [], + taxSummary: { years: { + '2026': { + X10000001: { asOf: '2026-11-29', boxes: { '1099-DIV 1A': 1_000, '1099-DIV 1B': 600, '1099-DIV 1C': 400, '1099-INT 1': 100 }, shortTerm: null, longTerm: null }, + X10000002: { asOf: '2026-11-30', boxes: {}, shortTerm: 500, longTerm: 200 }, + }, + '2025': { X10000002: { asOf: '2025-12-31', boxes: { '1099-DIV 1A': 10 }, shortTerm: null, longTerm: null } }, + } }, +}); + +test('three cards with the tax, the room and the income; a year with no summary keeps the heads and says what to do', async () => { + const { act } = await import('react'); + const { createRoot } = await import('react-dom/client'); + const { Taxes } = await import('./Taxes'); + const { setPrefs } = await import('../app/prefs'); + const { saveHousehold } = await import('../app/tax-household'); + const { DEFAULT_HOUSEHOLD } = await import('../app/taxes'); + saveHousehold(DEFAULT_HOUSEHOLD, undefined); + setPrefs({ taxYear: '' }); + document.body.innerHTML = '
'; + const root = createRoot(document.getElementById('root')!); + const data = ds(); + await act(async () => root.render()); + const q = (sel: string) => document.querySelector(sel); + // the newest year first; the numbers of app/taxes-page.test.ts: 120 federal + 99.45 NJ + expect(q('[data-taxes]')?.dataset.taxes).toBe('2026'); + expect(q('[data-balance-head="taxes"]')?.textContent).toContain('$219.45'); + expect(q('[data-tax-as-of]')?.textContent).toContain('Nov-29-2026'); + expect(q('[data-next-dollar]')?.textContent).toContain('17.525%'); + expect(document.querySelectorAll('[data-room]').length).toBe(3); + expect(q('[data-room="ordinary22"]')?.textContent).toContain('$7,000 left'); + // every Income line, a zero one dimmed but kept + expect(document.querySelectorAll('[data-income-line]').length).toBe(13); + expect(q('[data-income-line="foreignTax"]')?.hasAttribute('data-zero')).toBe(true); + expect(q('[data-income-line="qualified"]')?.textContent).toContain('$600.00'); + // two years: the year pills; 2025 has none of A's numbers and only B's ten dollars + const pills = Array.from(document.querySelectorAll('[role=radio]')); + expect(pills.map((p) => p.textContent)).toEqual(['2026', '2025']); + await act(async () => root.render()); + await act(async () => pills[1]!.click()); + expect(q('[data-taxes]')?.dataset.taxes).toBe('2025'); + expect(document.querySelectorAll('[data-card]').length).toBe(3); + expect(q('[data-empty="tax-added"]')?.textContent).toBe("Fidelity's tax summary of 2025 has none of the shown accounts yet: open Fidelity Positions once"); + expect(document.querySelectorAll('[role=radio]').length).toBe(2); // the controls stay + await act(async () => root.unmount()); + setPrefs({ taxYear: '' }); +}); + +test('Settings -> Taxes: a typed amount is kept, a word frames the box and keeps the last good one', async () => { + const { act } = await import('react'); + const { createRoot } = await import('react-dom/client'); + const { TaxSettings } = await import('./TaxSettings'); + const { household, saveHousehold } = await import('../app/tax-household'); + const { DEFAULT_HOUSEHOLD } = await import('../app/taxes'); + saveHousehold(DEFAULT_HOUSEHOLD, undefined); + document.body.innerHTML = '
'; + const root = createRoot(document.getElementById('root')!); + await act(async () => root.render()); + const box = () => document.querySelector('[data-amount-field="gross"] input')!; + expect(box().value).toBe('125,000'); + // React listens for the input event and reads the value through the prototype's setter + const type = async (el: HTMLInputElement, v: string) => act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(el, v); + el.dispatchEvent(new Event('input', { bubbles: true })); + }); + await type(box(), '90,000'); + expect(household.get().grossWages).toBe(90_000); + await type(box(), 'abc'); + expect(household.get().grossWages).toBe(90_000); + expect(box().getAttribute('aria-invalid')).toBe('true'); + // the itemized box shows only with Itemized chosen + expect(document.querySelector('[data-amount-field="itemized"]')).toBeNull(); + const itemized = Array.from(document.querySelectorAll('[role=radio]')).find((b) => b.textContent === 'Itemized')!; + await act(async () => itemized.click()); + expect(household.get().deduction).toEqual({ kind: 'itemized', amount: 32_200 }); + expect(document.querySelector('[data-amount-field="itemized"]')).not.toBeNull(); + await act(async () => root.unmount()); + saveHousehold(DEFAULT_HOUSEHOLD, undefined); +}); diff --git a/src/viewer/ui/Taxes.tsx b/src/viewer/ui/Taxes.tsx new file mode 100644 index 0000000..0c0ba31 --- /dev/null +++ b/src/viewer/ui/Taxes.tsx @@ -0,0 +1,201 @@ +/// +import { memo, useMemo } from 'react'; +import type { Account, Dataset } from '../../shared/model'; +import { rulesFor } from '../../shared/tax-rules-2026'; +import type { TypedColumn } from '../../shared/typed-columns'; +import { t } from '../app/i18n'; +import { prefs, setPrefs } from '../app/prefs'; +import { pulseKey, type PulseMark } from '../app/pulse'; +import { household } from '../app/tax-household'; +import { shownYear, taxPage, taxYears, type IncomeKey, type IncomeRow, type RoomRow, type TaxPageView } from '../app/taxes-page'; +import type { TaxNote } from '../app/taxes'; +import { animate } from './animate'; +import { BalanceHead, FactRow } from './BalanceHead'; +import { Card } from './Card'; +import { Empty } from './Empty'; +import { FillBar } from './FillBar'; +import { DASH, maskAccount, pct, rate, siteDate, usd, usd0 } from './format'; +import { Pills } from './Pills'; +import type { HeadColumn } from './TypedHead'; +import { useStore } from './useStore'; +import { ZoomTable } from './ZoomTable'; + +// Fidelity Taxes (owner 2026-12-03: "I have a buffer about 1500$-1600$ approx. but this is exactly info what I want to +// see on line and constantly updating / calculation on my viewer"): for the year chosen and the taxable accounts of the +// strip, what the investments add to the household's federal and New Jersey tax, the room left before the next rates +// and the income as Fidelity's Tax Info page lists it. The numbers come from app/taxes-page.ts, the household from +// ⚙️ Settings -> Taxes; this file only draws. An estimate from Fidelity's preliminary numbers, the page says so + +// the script that reads Fidelity's tax summary first (userscript 0.1.89) +const SCRIPT_WITH_SUMMARY = '0.1.89'; + +export const Taxes = memo(function Taxes({ ds, accounts }: { ds: Dataset; accounts: Account[] }) { + const pr = useStore(prefs); + const h = useStore(household); + const years = useMemo(() => taxYears(ds.taxSummary), [ds.taxSummary]); + const year = shownYear(years, pr.taxYear); + const view = useMemo(() => taxPage(ds, accounts, year, h), [ds, accounts, year, h]); + // a card glows when a new read changed its numbers (app/pulse.ts) + const mark = (...parts: unknown[]): PulseMark => ({ key: pulseKey(year, ...parts), version: `${ds.builtAt}|${ds.taxSummaryAt ?? ''}`, site: 'fidelity' }); + // the cards say why they are empty: no taxable account shown; the year read for other accounts only (an account opened + // later, or one Fidelity left out); or no summary of the year at all (a script older than the summary read) + const empty = view.tax ? null : view.taxableShown === 0 + ? t('The shown accounts are retirement or tax-free accounts: they add nothing to the tax of the year') + : view.yearRead + ? t('Fidelity\'s tax summary of {year} has none of the shown accounts yet: open Fidelity Positions once', { year }) + : t('Update the script to {version} and open Fidelity Positions once', { version: SCRIPT_WITH_SUMMARY }); + // the years as a choice of one, only when Fidelity has more than one (the filing season keeps last year too) + const yearPills = years.length > 1 + ? y} onChange={(y) => animate(() => setPrefs({ taxYear: y }))} /> + : undefined; + return ( + // the space between cards equals the space from the screen edge to the navbar, as on Summary +
+ + {empty ? : } + + r.left))} title={t('Room before the next rate')}> + {empty ? : } + + r.total))} title={t('Income')} expand={}> + {empty && } + + +
+ ); +}); + +// the reasons the estimate may be off, in words +const NOTE_TEXT = (note: TaxNote, year: string): string => { + const f = rulesFor(year).rules.federal; + return note === 'form-1116' + ? t('Foreign tax paid is over {limit}: the credit is counted up to {limit}, more needs Form 1116', { limit: usd0(f.foreignCreditWithout1116) }) + : t('Wages and investment income are over {limit}: the {rate} net investment income tax may apply, it is not counted here', { limit: usd0(f.niitThreshold), rate: rate(f.niitRate) }); +}; + +/** the tax added: the total big, federal and New Jersey under it, the rates of the next dollar on the right */ +function TaxAdded({ view }: { view: TaxPageView }) { + const tax = view.tax!; + const line = (value: number, text: string, hint: string) => ( + {usd(value)}{text} + ); + return ( + <> +

{t('YTD as of {day}, before the 1099s; an estimate, not tax advice', { day: siteDate(view.income.asOf) })}

+ + {line(tax.federal.added, t('Federal'), tax.federal.foreignCredit > 0 + ? t('With the investments minus without them, after a foreign tax credit of {credit}', { credit: usd(tax.federal.foreignCredit) }) + : t('With the investments minus without them'))} + {line(tax.nj.added, t('New Jersey'), t('With the investments minus without them; New Jersey has no lower rate for dividends or gains and no foreign tax credit'))} + } + facts={<> + {tax.effectiveRate === null ? DASH : pct(tax.effectiveRate * 100)} + {rate(tax.federal.marginalOrdinary)} + {rate(tax.federal.preferentialRate)} + {rate(tax.nj.marginal)} + } /> +

+ {t('One more dollar of short-term gain costs {pct}', { pct: rate(tax.nextDollar.shortTerm) })} +

+ {(tax.notes.length > 0 || view.fallback) && ( +
    + {view.fallback &&
  • {t('The app has no {year} rules yet: counted with those of {rules}', { year: view.year, rules: view.rulesYear })}
  • } + {tax.notes.map((n) =>
  • {NOTE_TEXT(n, view.year)}
  • )} +
+ )} + + ); +} + +// a room row's words: before the line, or already past it +const ROOM_WORDS = (r: RoomRow): { name: string; past: string; hint: string } => { + const at = rate(r.rate); + if (r.key === 'ordinary22') return { name: t('Ordinary income before {rate}', { rate: at }), past: t('Already in the {rate} bracket', { rate: at }), hint: t('Ordinary taxable income (wages after the deduction, interest, non-qualified dividends, short-term gains) left before {line}, where each dollar starts to pay {rate}', { line: usd0(r.line), rate: at }) }; + if (r.key === 'preferential') return { name: t('Qualified dividends and long-term gains at 0%'), past: t('Qualified dividends and long-term gains already pay {rate}', { rate: at }), hint: t('Total taxable income left before {line}: up to it qualified dividends and long-term gains pay 0%, above it {rate}', { line: usd0(r.line), rate: at }) }; + return { name: t('New Jersey before {rate}', { rate: at }), past: t('New Jersey: already at its top rate'), hint: t('New Jersey taxable income left before {line}, where its rate goes up to {rate}', { line: usd0(r.line), rate: at }) }; +}; + +/** three bars: how much of the way to each line is used, the dollars left on the right; a line passed is amber */ +function Room({ rows }: { rows: RoomRow[] }) { + return ( +
+ {rows.map((r) => { + const w = ROOM_WORDS(r); + const past = r.left === null || r.left <= 0; + return ( +
+
+ {past ? w.past : w.name} + {!past && {t('{left} left', { left: usd0(r.left) })}} +
+ +
+ ); + })} +
+ ); +} + +// the names of the Income lines, their tooltip and, where it matters, a short hint under the line +const INCOME_WORDS = (year: string): Record => { + const f = rulesFor(year).rules.federal; + const limit = usd0(f.capitalLossLimit); + return { + ordinaryDividends: { name: t('Ordinary dividends'), hint: t('1099-DIV box 1a: qualified and non-qualified together') }, + qualified: { name: t('Qualified'), hint: t('1099-DIV box 1b: taxed at 0, 15 or 20% federally, as ordinary income by New Jersey'), note: t('Only when the shares were held more than 60 days of the 121 around the ex-date') }, + nonQualified: { name: t('Non-qualified'), hint: t('Taxed as ordinary income') }, + capGainDistributions: { name: t('Capital gain distributions'), hint: t('1099-DIV box 2a: long-term, whatever the holding period') }, + interest: { name: t('Interest'), hint: t('1099-INT box 1: ordinary income, federal and New Jersey') }, + treasuryInterest: { name: t('Treasury interest'), hint: t('1099-INT box 3: U.S. Treasury interest, federal only'), note: t('Not taxed by New Jersey') }, + otherOrdinary: { name: t('Other income'), hint: t('1099-MISC boxes 2, 3, 8 and 1099-OID boxes 1, 8: ordinary income') }, + shortTerm: { name: t('Realized short-term'), hint: t('Sold within a year: ordinary income') }, + longTerm: { name: t('Realized long-term'), hint: t('Sold after more than a year: 0, 15 or 20% federally'), note: t('A net loss: up to {limit} a year federally, the rest carries over; none for New Jersey', { limit }) }, + foreignTax: { name: t('Foreign tax paid'), hint: t('1099-DIV box 7 and 1099-INT box 6'), note: t('A federal credit only: up to {limit} with no Form 1116', { limit: usd0(f.foreignCreditWithout1116) }) }, + withheld: { name: t('Federal tax withheld'), hint: t('Already paid toward the federal tax') }, + marginInterest: { name: t('Margin interest paid'), hint: t('Deductible only when itemizing; not counted here') }, + section199a: { name: t('Section 199A dividends'), hint: t('1099-DIV box 5: part of the ordinary dividends; its deduction is not counted here') }, + }; +}; +const QUIET = 'text-slate-400 dark:text-slate-500'; + +/** the lines like Fidelity's Tax Info page: the sums of the shown accounts, a zero line dimmed but kept */ +function IncomeList({ view }: { view: TaxPageView }) { + const words = INCOME_WORDS(view.year); + return ( +
+ {view.rows.map((r) => { + const w = words[r.key]; + return ( +
+
+ {w.name} + {usd(r.total)} +
+ {w.note &&
{w.note}
} +
+ ); + })} +
+ ); +} + +/** ⤢: the same lines with an account a column and the Total last */ +function IncomeTable({ view }: { view: TaxPageView }) { + const words = INCOME_WORDS(view.year); + const cols: (TypedColumn & HeadColumn)[] = [ + { key: 'line', label: t('Line'), text: (r) => words[r.key].name }, + ...view.columns.map((c, i): TypedColumn & HeadColumn => ({ key: `a${i}`, label: c.account.name, hint: maskAccount(c.account.number), text: (r) => usd(r.byAccount[i]), value: (r) => r.byAccount[i] })), + { key: 'total', label: t('Total'), text: (r) => usd(r.total), value: (r) => r.total }, + ]; + return ( + ( + td]:px-2 [&>td]:py-1.5 ${r.total === 0 ? QUIET : ''}`} title={words[r.key].hint}> + {words[r.key].name} + {r.byAccount.map((v, i) => {usd(v)})} + {usd(r.total)} + + )} /> + ); +} diff --git a/src/viewer/ui/format.test.ts b/src/viewer/ui/format.test.ts index 35915ff..a6023d1 100644 --- a/src/viewer/ui/format.test.ts +++ b/src/viewer/ui/format.test.ts @@ -2,7 +2,7 @@ /// /// import { expect, test } from 'bun:test'; -import { clockTime, maskAccount, readTime, shortUsd, signedUsdPct } from './format'; +import { clockTime, maskAccount, rate, readTime, shortUsd, signedUsdPct } from './format'; test('shortUsd prints thousands as K and a million and more as M', () => { expect(shortUsd(850000)).toBe('$850.0K'); @@ -32,3 +32,7 @@ test('signedUsdPct writes the $ and the % of a change', () => { expect(signedUsdPct(-4, -0.5)).toBe('-$4.00 (-0.50%)'); expect(signedUsdPct(undefined, null)).toBe('-- (--)'); }); + +test('rate prints a tax rate as written: no trailing zeros, three decimals at most', () => { + expect([rate(0.22), rate(0.05525), rate(0), rate(0.0637), rate(0.17525), rate(null)]).toEqual(['22%', '5.525%', '0%', '6.37%', '17.525%', '--']); +}); diff --git a/src/viewer/ui/format.ts b/src/viewer/ui/format.ts index 273216d..4c82c5f 100644 --- a/src/viewer/ui/format.ts +++ b/src/viewer/ui/format.ts @@ -11,6 +11,8 @@ const usd0Fmt = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'U export const usd0 = (n: number | undefined | null): string => (typeof n === 'number' && Number.isFinite(n) ? usd0Fmt.format(n) : DASH); export const signedUsd = (n: number | undefined | null): string => (typeof n === 'number' && Number.isFinite(n) ? `${n > 0 ? '+' : n < 0 ? '-' : ''}${usdFmt.format(Math.abs(n))}` : DASH); export const pct = (n: number | undefined | null): string => (typeof n === 'number' && Number.isFinite(n) ? `${n.toFixed(2)}%` : DASH); +/** a tax rate as a law writes it, from a fraction: 0.22 -> "22%", 0.05525 -> "5.525%", 0 -> "0%" (pct would say 22.00%, 5.53%) */ +export const rate = (r: number | undefined | null): string => (typeof r === 'number' && Number.isFinite(r) ? `${Math.round(r * 100_000) / 1000}%` : DASH); export const signedPct = (n: number | undefined | null): string => (typeof n === 'number' && Number.isFinite(n) ? `${n > 0 ? '+' : ''}${n.toFixed(2)}%` : DASH); /** "+$12.30 (+1.25%)" */ export const signedUsdPct = (usd: number | undefined | null, pct: number | undefined | null): string => `${signedUsd(usd)} (${signedPct(pct)})`;