diff --git a/src/shared/tax-rules-2026.test.ts b/src/shared/tax-rules-2026.test.ts
new file mode 100644
index 0000000..8b10549
--- /dev/null
+++ b/src/shared/tax-rules-2026.test.ts
@@ -0,0 +1,43 @@
+///
+///
+///
+import { expect, test } from 'bun:test';
+import { RULES, RULES_2026, rulesFor } from './tax-rules-2026';
+
+test('2026 federal MFJ: standard deduction, the seven brackets, 0/15/20 on top, the limits', () => {
+ const f = RULES_2026.federal;
+ expect(f.standardDeduction).toBe(32_200);
+ expect(f.ordinary.map((b) => [b.upTo, b.rate])).toEqual([[24_800, 0.10], [100_800, 0.12], [211_400, 0.22], [403_550, 0.24], [512_450, 0.32], [768_700, 0.35], [Infinity, 0.37]]);
+ expect(f.preferential.map((b) => [b.upTo, b.rate])).toEqual([[98_900, 0], [613_700, 0.15], [Infinity, 0.20]]);
+ expect([f.foreignCreditWithout1116, f.capitalLossLimit, f.niitRate, f.niitThreshold]).toEqual([600, 3_000, 0.038, 250_000]);
+});
+
+test('2026 NJ Table B joint: eight rows, the exemptions', () => {
+ const nj = RULES_2026.nj;
+ expect(nj.brackets.map((b) => [b.upTo, b.rate])).toEqual([[20_000, 0.014], [50_000, 0.0175], [70_000, 0.0245], [80_000, 0.035], [150_000, 0.05525], [500_000, 0.0637], [1_000_000, 0.0897], [Infinity, 0.1075]]);
+ expect([nj.exemptionPerSpouse, nj.exemptionPerDependent]).toEqual([1_000, 1_500]);
+});
+
+test('NJ subtractions agree with the bracket sum at the top of each row, except the 3.5% row the table puts 0.50 higher', () => {
+ // the bracket sum at a row's top: income x rate - subtract of that row must equal the sum of every row up to there.
+ // 20k: 280 = 20,000 x 1.4%; 50k: 280 + 30,000 x 1.75% = 805 = 50,000 x 1.75% - 70; 70k: 805 + 20,000 x 2.45% = 1,295 =
+ // 70,000 x 2.45% - 420; 80k: 1,295 + 10,000 x 3.5% = 1,645, but 80,000 x 3.5% - 1,154.50 = 1,645.50 (NJ's own table,
+ // kept as published); 150k: 1,645 + 70,000 x 5.525% = 5,512.50 = 150,000 x 5.525% - 2,775; and so on
+ const rows = RULES_2026.nj.brackets;
+ let sum = 0;
+ let from = 0;
+ rows.slice(0, -1).forEach((b) => {
+ sum += (b.upTo - from) * b.rate;
+ from = b.upTo;
+ const formula = b.upTo * b.rate - b.subtract;
+ expect(formula - sum).toBeCloseTo(b.rate === 0.035 ? 0.5 : 0, 6);
+ });
+});
+
+test('a year with its rules uses them; a year without uses the latest and says so', () => {
+ expect(rulesFor('2026')).toEqual({ rules: RULES['2026']!, fallback: false });
+ const later = rulesFor('2031');
+ expect(later.fallback).toBe(true);
+ expect(later.rules.year).toBe('2026');
+ expect(rulesFor('2019').fallback).toBe(true);
+});
diff --git a/src/shared/tax-rules-2026.ts b/src/shared/tax-rules-2026.ts
new file mode 100644
index 0000000..0d12437
--- /dev/null
+++ b/src/shared/tax-rules-2026.ts
@@ -0,0 +1,84 @@
+///
+// The 2026 tax rules the Taxes page counts with (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"): federal and New
+// Jersey, Married Filing Jointly only (the one filing status the page supports). Each block names the page its numbers
+// were read on. A later year gets its own file next to this one (`tax-rules-2027.ts` exporting a `TaxRules`) and one
+// more line in `RULES`; a year without its file is counted with the latest rules, and `rulesFor` says so
+
+/** a rate up to an amount of taxable income ("not over"); the last one has no end (Infinity) */
+export interface Bracket { upTo: number; rate: number }
+/** a New Jersey row: tax = income x rate - subtract (NJ's own Table B) */
+export interface NjBracket extends Bracket { subtract: number }
+
+export interface TaxRules {
+ year: string;
+ federal: {
+ standardDeduction: number;
+ ordinary: Bracket[];
+ // qualified dividends and long-term gains, by TOTAL taxable income: they sit on top of the ordinary income
+ preferential: Bracket[];
+ foreignCreditWithout1116: number;
+ capitalLossLimit: number;
+ niitRate: number;
+ niitThreshold: number; // modified AGI
+ };
+ nj: { brackets: NjBracket[]; exemptionPerSpouse: number; exemptionPerDependent: number };
+}
+
+export const RULES_2026: TaxRules = {
+ year: '2026',
+ federal: {
+ // Rev. Proc. 2025-32, the 2026 inflation adjustments: https://www.irs.gov/pub/irs-drop/rp-25-32.pdf
+ standardDeduction: 32_200,
+ ordinary: [
+ { upTo: 24_800, rate: 0.10 },
+ { upTo: 100_800, rate: 0.12 },
+ { upTo: 211_400, rate: 0.22 },
+ { upTo: 403_550, rate: 0.24 },
+ { upTo: 512_450, rate: 0.32 },
+ { upTo: 768_700, rate: 0.35 },
+ { upTo: Infinity, rate: 0.37 },
+ ],
+ // the same Rev. Proc., the maximum zero rate and 15 percent amounts
+ preferential: [
+ { upTo: 98_900, rate: 0 },
+ { upTo: 613_700, rate: 0.15 },
+ { upTo: Infinity, rate: 0.20 },
+ ],
+ // the foreign tax credit without Form 1116: all of the foreign income passive and on a 1099
+ // https://www.irs.gov/instructions/i1116
+ foreignCreditWithout1116: 600,
+ // a net capital loss against other income, the rest carries forward: https://www.irs.gov/taxtopics/tc409
+ capitalLossLimit: 3_000,
+ // net investment income tax, not indexed: https://www.irs.gov/taxtopics/tc559
+ niitRate: 0.038,
+ niitThreshold: 250_000,
+ },
+ nj: {
+ // Table B (married filing jointly) of the NJ-1040-ES: https://www.nj.gov/treasury/taxation/pdf/current/1040esi.pdf
+ brackets: [
+ { upTo: 20_000, rate: 0.014, subtract: 0 },
+ { upTo: 50_000, rate: 0.0175, subtract: 70 },
+ { upTo: 70_000, rate: 0.0245, subtract: 420 },
+ { upTo: 80_000, rate: 0.035, subtract: 1_154.5 },
+ { upTo: 150_000, rate: 0.05525, subtract: 2_775 },
+ { upTo: 500_000, rate: 0.0637, subtract: 4_042.5 },
+ { upTo: 1_000_000, rate: 0.0897, subtract: 17_042.5 },
+ { upTo: Infinity, rate: 0.1075, subtract: 34_842.5 },
+ ],
+ // no standard deduction, the exemptions only: https://www.nj.gov/treasury/taxation/git_over.shtml
+ exemptionPerSpouse: 1_000,
+ exemptionPerDependent: 1_500,
+ },
+};
+
+/** tax year -> its rules */
+export const RULES: Record = { '2026': RULES_2026 };
+
+/** the rules of a year; a year without its own uses the latest one, `fallback` says the page should tell */
+export function rulesFor(year: string): { rules: TaxRules; fallback: boolean } {
+ const own = RULES[year];
+ if (own) return { rules: own, fallback: false };
+ const latest = Object.keys(RULES).sort().pop()!;
+ return { rules: RULES[latest]!, fallback: true };
+}
diff --git a/src/viewer/app/taxes.test.ts b/src/viewer/app/taxes.test.ts
new file mode 100644
index 0000000..f2ed0e7
--- /dev/null
+++ b/src/viewer/app/taxes.test.ts
@@ -0,0 +1,202 @@
+///
+///
+///
+import { expect, test } from 'bun:test';
+import { RULES_2026 } from '../../shared/tax-rules-2026';
+import type { TaxYtd } from '../../shared/tax-summary';
+import { DEFAULT_HOUSEHOLD, bracketTax, federalTax, investmentIncome, investmentTax, netCapital, nextBracket, njTax, type Household, type InvestmentTax } from './taxes';
+
+// made-up households and incomes only; every expected number is worked out by hand in the comment next to it
+const R = RULES_2026;
+const ytd = (boxes: Record, o: Partial = {}): TaxYtd => ({ asOf: '2026-11-30', boxes, shortTerm: null, longTerm: null, ...o });
+const tax = (h: Household, ...ytds: TaxYtd[]): InvestmentTax => investmentTax(R, h, investmentIncome(ytds));
+// H1: 110,000 wages, one NJ dependent, standard: federal taxable 77,800 (12%), NJ taxable 110,000 - 2,000 - 1,500 = 106,500 (5.525%)
+const H1: Household = { ...DEFAULT_HOUSEHOLD, grossWages: 110_000, njDependents: 1 };
+const close = (actual: number | null, expected: number) => expect(actual!).toBeCloseTo(expected, 6);
+
+test('the default household of Settings -> Taxes', () => {
+ expect(DEFAULT_HOUSEHOLD).toEqual({ filing: 'mfj', state: 'NJ', grossWages: 125_000, pretax401k: 0, otherPretax: 0, njDependents: 2, deduction: { kind: 'standard' } });
+});
+
+test('investment income: the boxes of every shown account summed, nulls as 0, the oldest day', () => {
+ const a = ytd({
+ '1099-DIV 1A': 300, '1099-DIV 1B': 200, '1099-DIV 1C': 100, '1099-DIV 2': 50, '1099-INT 1': 10.1, '1099-INT 3': 20.2,
+ '1099-MISC 2': 1, '1099-MISC 3': 2, '1099-MISC 8': 3, '1099-OID 1': 4, '1099-OID 8': 5,
+ '1099-DIV 7': 6, '1099-INT 6': 0.5, '1099-DIV 4': 7, '1099-INT 4': 8, '1099-MISC 4': 9, '1099-OIF 3': 1.25, '1099-DIV 5': 30,
+ }, { asOf: '2026-11-28', shortTerm: 100.5 });
+ const b = ytd({ '1099-DIV 1A': 0.1, '1099-DIV 1C': 0.1, '1099-INT 1': 0.2 }, { asOf: '2026-12-01', shortTerm: -40, longTerm: 25 });
+ const c = ytd({}, { asOf: '' }); // read, nothing there, no day
+ expect(investmentIncome([a, b, c])).toEqual({
+ nonQualified: 100.1, qualified: 200, ordinaryDividends: 300.1, capGainDistributions: 50, interest: 10.3, treasuryInterest: 20.2,
+ otherOrdinary: 15, // 1 + 2 + 3 + 4 + 5
+ shortTerm: 60.5, longTerm: 25, foreignTax: 6.5, withheld: 24, marginInterest: 1.25, section199a: 30, asOf: '2026-11-28',
+ });
+ expect(investmentIncome([]).asOf).toBe('');
+});
+
+test('brackets: the tax at the 10% and 12% lines and above, the next dollar at a line goes to the higher rate', () => {
+ close(bracketTax(R.federal.ordinary, 24_800), 2_480); // 24,800 x 10%
+ close(bracketTax(R.federal.ordinary, 100_800), 11_600); // 2,480 + 76,000 x 12%
+ close(bracketTax(R.federal.ordinary, 100_801), 11_600.22);
+ close(bracketTax(R.federal.ordinary, 211_400), 35_932); // 11,600 + 110,600 x 22%
+ close(bracketTax(R.federal.ordinary, 800_000), 218_164.5); // 206,583.50 at 768,700 + 31,300 x 37%
+ expect(bracketTax(R.federal.ordinary, -5)).toBe(0);
+ expect(nextBracket(R.federal.ordinary, 24_799.99).bracket.rate).toBe(0.10);
+ expect(nextBracket(R.federal.ordinary, 24_800).bracket.rate).toBe(0.12);
+ expect(nextBracket(R.federal.ordinary, 100_800).bracket.rate).toBe(0.22);
+ expect(nextBracket(R.federal.ordinary, 2_000_000).index).toBe(6);
+});
+
+test('federal: preferential income stacked on top, straddling 98,900 and 613,700', () => {
+ close(federalTax(R, 24_800, 0), 2_480);
+ // 90,000 ordinary: 2,480 + 65,200 x 12% = 10,304; 20,000 preferential from 90,000 to 110,000: 8,900 at 0%, 11,100 x 15% = 1,665
+ close(federalTax(R, 90_000, 20_000), 11_969);
+ // a deduction bigger than the ordinary part eats the preferential: total 115,000, all preferential, 16,100 x 15% = 2,415
+ close(federalTax(R, -5_000, 120_000), 2_415);
+ expect(federalTax(R, -50_000, 10_000)).toBe(0); // never below zero
+ // 600,000 ordinary: 116,896 at 512,450 + 87,550 x 35% = 147,538.50; 50,000 on top: 13,700 x 15% + 36,300 x 20% = 9,315
+ close(federalTax(R, 600_000, 50_000), 156_853.5);
+});
+
+test('NJ by Table B', () => {
+ expect(njTax(R, 0)).toBe(0);
+ close(njTax(R, 20_000), 280);
+ close(njTax(R, 70_000), 1_295); // 2.45% row: 1,715 - 420
+ close(njTax(R, 106_500), 3_109.125); // 106,500 x 5.525% - 2,775
+ close(njTax(R, 1_200_000), 94_157.5); // 129,000 - 34,842.50
+});
+
+test('capital: short and long term net first, the loss limited, the rest carried', () => {
+ expect(netCapital(1_500, 2_000, 3_000)).toEqual({ ordinary: 1_500, preferential: 2_000, carryover: 0 });
+ expect(netCapital(-2_000, 5_000, 3_000)).toEqual({ ordinary: 0, preferential: 3_000, carryover: 0 }); // a net long-term gain
+ expect(netCapital(4_000, -1_000, 3_000)).toEqual({ ordinary: 3_000, preferential: 0, carryover: 0 }); // a net short-term gain
+ expect(netCapital(-6_000, 1_000, 3_000)).toEqual({ ordinary: -3_000, preferential: 0, carryover: 2_000 });
+});
+
+test('a mix in the 12% bracket: federal 12% of the ordinary part, qualified at 0%, NJ 5.525% of all', () => {
+ // ordinary 1,000 non-qualified + 500 interest + 1,500 short-term = 3,000; qualified 2,000
+ const t = tax(H1, ytd({ '1099-DIV 1A': 3_000, '1099-DIV 1B': 2_000, '1099-DIV 1C': 1_000, '1099-INT 1': 500 }, { shortTerm: 1_500 }));
+ close(t.federal.before, 8_840); // 2,480 + 53,000 x 12%
+ close(t.federal.after, 9_200); // 80,800 ordinary: 2,480 + 56,000 x 12%; 2,000 qualified from 80,800 to 82,800 at 0%
+ close(t.federal.added, 360);
+ expect([t.federal.marginalOrdinary, t.federal.preferentialRate, t.federal.foreignCredit]).toEqual([0.12, 0, 0]);
+ close(t.nj.added, 276.25); // 106,500 -> 111,500: 5,000 x 5.525%
+ expect(t.nj.marginal).toBe(0.05525);
+ close(t.total, 636.25);
+ close(t.effectiveRate, 0.12725); // 636.25 / 5,000
+ expect(t.room).toEqual({ before22: 20_000, beforePreferential15: 16_100, njNext: 38_500, njNextRate: 0.0637 }); // 100,800 - 80,800; 98,900 - 82,800; 150,000 - 111,500
+ close(t.nextDollar.shortTerm, 0.17525);
+ expect(t.notes).toEqual([]);
+});
+
+test('ordinary bracket edges of the household: exactly 24,800 and exactly 100,800 of taxable income', () => {
+ const at24 = tax({ ...H1, grossWages: 57_000 }); // 57,000 - 32,200 = 24,800
+ expect(at24.federal.marginalOrdinary).toBe(0.12);
+ close(at24.federal.before, 2_480);
+ expect(at24.room.before22).toBe(76_000);
+ const at100 = tax({ ...H1, grossWages: 133_000 }); // 100,800
+ expect(at100.federal.marginalOrdinary).toBe(0.22);
+ close(at100.federal.before, 11_600);
+ expect(at100.room.before22).toBe(0);
+ // one dollar of non-qualified dividends there is all 22%
+ close(tax({ ...H1, grossWages: 133_000 }, ytd({ '1099-DIV 1A': 1, '1099-DIV 1C': 1 })).federal.added, 0.22);
+});
+
+test('the bump zone: a short-term dollar costs 12% and pushes a qualified dollar from 0% to 15%', () => {
+ // 128,000 wages, no dependents: 95,800 taxable; + 2,000 short-term = 97,800 ordinary; 4,000 qualified from 97,800 to
+ // 101,800: 1,100 at 0%, 2,900 x 15% = 435; federal 240 + 435 = 675
+ const t = tax({ ...H1, grossWages: 128_000, njDependents: 0 }, ytd({ '1099-DIV 1A': 4_000, '1099-DIV 1B': 4_000 }, { shortTerm: 2_000 }));
+ close(t.federal.added, 675);
+ expect([t.federal.marginalOrdinary, t.federal.preferentialRate]).toEqual([0.12, 0.15]);
+ expect(t.room.before22).toBe(3_000);
+ expect(t.room.beforePreferential15).toBe(0);
+ close(t.nj.added, 331.5); // 126,000 -> 132,000 at 5.525%
+ close(t.nextDollar.shortTerm, 0.32525); // 12% + 15% + 5.525%
+});
+
+test('a net capital loss: -3,000 against federal ordinary income, nothing for NJ, one more short-term dollar costs nothing', () => {
+ // -6,000 short + 1,000 long = -5,000 net: -3,000 federal (2,000 carried), NJ counts a net loss as zero
+ const t = tax(H1, ytd({}, { shortTerm: -6_000, longTerm: 1_000 }));
+ close(t.federal.added, -360); // 77,800 -> 74,800 at 12%
+ expect(t.nj.added).toBe(0);
+ close(t.total, -360);
+ expect(t.effectiveRate).toBeNull();
+ expect(t.room.before22).toBe(26_000);
+ expect(t.nextDollar.shortTerm).toBe(0);
+});
+
+test('long-term gain only: 0% federal under 98,900, NJ taxes it as income', () => {
+ // 10,000 long-term + 500 capital gain distributions from 77,800 to 88,300: 0%; NJ 10,500 x 5.525% = 580.125
+ const t = tax(H1, ytd({ '1099-DIV 2': 500 }, { longTerm: 10_000 }));
+ close(t.federal.added, 0);
+ close(t.nj.added, 580.125);
+ close(t.effectiveRate, 0.05525);
+ expect(t.room.beforePreferential15).toBe(10_600);
+ expect(t.room.before22).toBe(23_000); // the ordinary income did not move
+});
+
+test('Treasury interest: federal only; the other ordinary boxes count for both', () => {
+ // federal (2,000 + 1,000) x 12% = 360; NJ 1,000 x 5.525% = 55.25
+ const t = tax(H1, ytd({ '1099-INT 3': 2_000, '1099-MISC 3': 1_000 }));
+ close(t.federal.added, 360);
+ close(t.nj.added, 55.25);
+});
+
+test('foreign tax: all of it up to 600 is a credit; over 600 the credit stops at 600 and asks for Form 1116', () => {
+ // 10,000 non-qualified: 77,800 -> 87,800 at 12% = 1,200
+ const over = tax(H1, ytd({ '1099-DIV 1A': 10_000, '1099-DIV 1C': 10_000, '1099-DIV 7': 800 }));
+ close(over.federal.foreignCredit, 600);
+ close(over.federal.added, 600); // 1,200 - 600
+ expect(over.notes).toEqual(['form-1116']);
+ const under = tax(H1, ytd({ '1099-DIV 1A': 10_000, '1099-DIV 1C': 10_000, '1099-DIV 7': 200, '1099-INT 6': 100 }));
+ close(under.federal.foreignCredit, 300);
+ close(under.federal.added, 900);
+ expect(under.notes).toEqual([]);
+ close(under.nj.added, 552.5); // no NJ credit: 10,000 x 5.525%
+});
+
+test('an itemized deduction replaces the standard one', () => {
+ // 110,000 - 40,000 = 70,000: 2,480 + 45,200 x 12% = 7,904; 1,000 non-qualified adds 120
+ const t = tax({ ...H1, deduction: { kind: 'itemized', amount: 40_000 } }, ytd({ '1099-DIV 1A': 1_000, '1099-DIV 1C': 1_000 }));
+ close(t.federal.before, 7_904);
+ close(t.federal.added, 120);
+ expect(t.room.before22).toBe(29_800); // 100,800 - 71,000
+});
+
+test('a 401(k) deferral: more room, the same tax added while it stays in one bracket; other pre-tax lowers federal only', () => {
+ const income = ytd({ '1099-DIV 1A': 3_000, '1099-DIV 1B': 2_000, '1099-DIV 1C': 1_000, '1099-INT 1': 500 }, { shortTerm: 1_500 });
+ const base = tax(H1, income);
+ const k = tax({ ...H1, pretax401k: 10_000 }, income);
+ close(k.federal.before, 7_640); // 67,800 taxable: 2,480 + 43,000 x 12%
+ close(k.federal.added, base.federal.added);
+ close(k.nj.added, base.nj.added);
+ expect(k.room).toEqual({ before22: 30_000, beforePreferential15: 26_100, njNext: 48_500, njNextRate: 0.0637 }); // each 10,000 more
+ const other = tax({ ...H1, otherPretax: 5_000 }, income);
+ expect(other.room.before22).toBe(25_000);
+ expect(other.room.njNext).toBe(base.room.njNext); // NJ taxes health, HSA, FSA deductions
+});
+
+test('zero income: nothing added, the room of the wages alone', () => {
+ const t = tax(H1);
+ expect([t.federal.added, t.nj.added, t.total]).toEqual([0, 0, 0]);
+ expect(t.effectiveRate).toBeNull();
+ expect(t.room).toEqual({ before22: 23_000, beforePreferential15: 21_100, njNext: 43_500, njNextRate: 0.0637 });
+ close(t.nextDollar.shortTerm, 0.17525);
+ expect(t.notes).toEqual([]);
+});
+
+test('taxable income never below zero: no wages, the deduction and the exemptions take their part, no credit without tax', () => {
+ // federal: -32,200 + 10,000 qualified = 0 taxable; NJ: -2,000 - 3,000 + 10,000 = 5,000 x 1.4% = 70
+ const t = tax({ ...DEFAULT_HOUSEHOLD, grossWages: 0 }, ytd({ '1099-DIV 1A': 10_000, '1099-DIV 1B': 10_000, '1099-DIV 7': 50 }));
+ expect([t.federal.before, t.federal.after, t.federal.foreignCredit]).toEqual([0, 0, 0]);
+ close(t.nj.added, 70);
+ close(t.nextDollar.shortTerm, 0.014); // the deduction is not used up: federal 0
+});
+
+test('NIIT only as a note, over 250,000 modified AGI', () => {
+ // 300,000 wages: 267,800 taxable at 24%; 1,000 non-qualified adds 240; NJ 296,500 -> 297,500 at 6.37% = 63.70
+ const t = tax({ ...H1, grossWages: 300_000 }, ytd({ '1099-DIV 1A': 1_000, '1099-DIV 1C': 1_000 }));
+ close(t.federal.added, 240);
+ close(t.nj.added, 63.7);
+ expect(t.notes).toEqual(['niit']);
+});
diff --git a/src/viewer/app/taxes.ts b/src/viewer/app/taxes.ts
new file mode 100644
index 0000000..b7b5618
--- /dev/null
+++ b/src/viewer/app/taxes.ts
@@ -0,0 +1,216 @@
+///
+import type { TaxYtd } from '../../shared/tax-summary';
+import type { Bracket, NjBracket, TaxRules } from '../../shared/tax-rules-2026';
+
+// What the investments add to the household's tax this year, federal and New Jersey, and how much room is left before
+// the next rate (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"). Pure: the household comes from Settings -> Taxes,
+// the income from Fidelity's Tax Info YTD of the shown accounts. Cents stay in the math, the page rounds for display.
+// An estimate from preliminary numbers, not tax advice
+
+/** the household's inputs; one filing status and one state for now */
+export interface Household {
+ filing: 'mfj';
+ state: 'NJ';
+ grossWages: number;
+ pretax401k: number; // lowers federal and NJ wages (NJ excludes a 401(k) only)
+ otherPretax: number; // health, HSA, FSA, commuter: lowers federal wages only, NJ taxes them
+ njDependents: number;
+ deduction: { kind: 'standard' } | { kind: 'itemized'; amount: number };
+}
+export const DEFAULT_HOUSEHOLD: Household = { filing: 'mfj', state: 'NJ', grossWages: 125_000, pretax401k: 0, otherPretax: 0, njDependents: 2, deduction: { kind: 'standard' } };
+
+/** the year so far of the shown accounts, summed by how it is taxed */
+export interface InvestmentIncome {
+ nonQualified: number; // 1099-DIV 1C
+ qualified: number; // 1099-DIV 1B
+ ordinaryDividends: number; // 1099-DIV 1A (qualified and non-qualified together)
+ capGainDistributions: number; // 1099-DIV 2: always long-term
+ interest: number; // 1099-INT 1
+ treasuryInterest: number; // 1099-INT 3: federal only, New Jersey does not tax it
+ otherOrdinary: number; // 1099-MISC 2, 3, 8 and 1099-OID 1, 8
+ shortTerm: number;
+ longTerm: number;
+ foreignTax: number; // 1099-DIV 7 + 1099-INT 6
+ withheld: number; // federal: 1099-DIV 4 + 1099-INT 4 + 1099-MISC 4
+ marginInterest: number; // 1099-OIF 3
+ section199a: number; // 1099-DIV 5
+ asOf: string; // the oldest day of Fidelity's numbers; '' when none
+}
+
+const BOXES: Record, string[]> = {
+ nonQualified: ['1099-DIV 1C'],
+ qualified: ['1099-DIV 1B'],
+ ordinaryDividends: ['1099-DIV 1A'],
+ capGainDistributions: ['1099-DIV 2'],
+ interest: ['1099-INT 1'],
+ treasuryInterest: ['1099-INT 3'],
+ otherOrdinary: ['1099-MISC 2', '1099-MISC 3', '1099-MISC 8', '1099-OID 1', '1099-OID 8'],
+ foreignTax: ['1099-DIV 7', '1099-INT 6'],
+ withheld: ['1099-DIV 4', '1099-INT 4', '1099-MISC 4'],
+ marginInterest: ['1099-OIF 3'],
+ section199a: ['1099-DIV 5'],
+};
+// sums to the cent: 0.1 + 0.2 stays 0.3
+const cents = (x: number): number => Math.round(x * 100) / 100;
+
+export function investmentIncome(ytds: readonly TaxYtd[]): InvestmentIncome {
+ const out: InvestmentIncome = { nonQualified: 0, qualified: 0, ordinaryDividends: 0, capGainDistributions: 0, interest: 0, treasuryInterest: 0, otherOrdinary: 0, shortTerm: 0, longTerm: 0, foreignTax: 0, withheld: 0, marginInterest: 0, section199a: 0, asOf: '' };
+ const keys = Object.keys(BOXES) as Array;
+ ytds.forEach((t) => {
+ keys.forEach((k) => BOXES[k].forEach((box) => { out[k] = cents(out[k] + (t.boxes[box] ?? 0)); }));
+ out.shortTerm = cents(out.shortTerm + (t.shortTerm ?? 0));
+ out.longTerm = cents(out.longTerm + (t.longTerm ?? 0));
+ if (t.asOf && (!out.asOf || t.asOf < out.asOf)) out.asOf = t.asOf;
+ });
+ return out;
+}
+
+/** the tax on an income through brackets; nothing on zero or less */
+export function bracketTax(brackets: readonly Bracket[], income: number): number {
+ let tax = 0;
+ let from = 0;
+ for (let i = 0; i < brackets.length && income > from; i++) {
+ tax += (Math.min(income, brackets[i]!.upTo) - from) * brackets[i]!.rate;
+ from = brackets[i]!.upTo;
+ }
+ return tax;
+}
+/** the bracket the NEXT dollar over `income` falls in (at exactly a line it is the higher one) */
+export function nextBracket(brackets: readonly B[], income: number): { index: number; bracket: B } {
+ let i = 0;
+ while (i < brackets.length - 1 && Math.max(0, income) >= brackets[i]!.upTo) i++;
+ return { index: i, bracket: brackets[i]! };
+}
+
+/**
+ * Federal tax on taxable income made of an ordinary part and a preferential part (qualified dividends, net long-term
+ * gain): the ordinary part fills the brackets first, the preferential part sits on top at 0, 15 or 20% by the TOTAL
+ * taxable income. A deduction bigger than the ordinary part (ordinary below zero) eats into the preferential part;
+ * taxable income is never below zero. The rate schedule, not the 1040's $50 tax table
+ */
+export function federalTax(rules: TaxRules, ordinaryTaxable: number, preferential: number): number {
+ const total = Math.max(0, ordinaryTaxable + Math.max(0, preferential));
+ const pref = Math.min(Math.max(0, preferential), total);
+ const ordinary = total - pref;
+ let tax = bracketTax(rules.federal.ordinary, ordinary);
+ let from = 0;
+ rules.federal.preferential.forEach((b) => {
+ const lo = Math.max(ordinary, from);
+ const hi = Math.min(total, b.upTo);
+ if (hi > lo) tax += (hi - lo) * b.rate;
+ from = b.upTo;
+ });
+ return tax;
+}
+
+/** New Jersey tax by Table B: income x rate - subtract of its row ("not over" the row's top) */
+export function njTax(rules: TaxRules, njTaxable: number): number {
+ if (njTaxable <= 0) return 0;
+ const rows: readonly NjBracket[] = rules.nj.brackets;
+ let i = 0;
+ while (i < rows.length - 1 && njTaxable > rows[i]!.upTo) i++;
+ return njTaxable * rows[i]!.rate - rows[i]!.subtract;
+}
+
+/**
+ * Short and long term net against each other first: what is left is an ordinary gain (net short-term), a preferential
+ * one (net long-term) or a loss against ordinary income, at most `limit` (the rest carries forward)
+ */
+export function netCapital(shortTerm: number, longTerm: number, limit: number): { ordinary: number; preferential: number; carryover: number } {
+ const net = shortTerm + longTerm;
+ if (shortTerm >= 0 && longTerm >= 0) return { ordinary: shortTerm, preferential: longTerm, carryover: 0 };
+ if (net >= 0) return longTerm >= 0 ? { ordinary: 0, preferential: net, carryover: 0 } : { ordinary: net, preferential: 0, carryover: 0 };
+ return { ordinary: Math.max(net, -limit), preferential: 0, carryover: Math.max(0, -net - limit) };
+}
+
+/** the reasons the estimate may be off, for the page to explain */
+export type TaxNote = 'form-1116' | 'niit';
+
+export interface InvestmentTax {
+ federal: {
+ added: number; // after - before
+ before: number; // the household's tax on the wages alone
+ after: number; // with the investments, after the foreign tax credit
+ marginalOrdinary: number; // the ordinary rate of the next dollar
+ preferentialRate: number; // the rate of the next qualified dividend or long-term dollar
+ foreignCredit: number;
+ };
+ nj: { added: number; marginal: number };
+ total: number;
+ effectiveRate: number | null; // total / the investment income the federal return counts; null when that is not above zero
+ room: {
+ before22: number; // ordinary taxable income left before the 22% line
+ beforePreferential15: number; // total taxable income left before qualified dividends leave 0%
+ njNext: number | null; // NJ taxable income left before the next NJ rate; null in the top row
+ njNextRate: number | null;
+ };
+ nextDollar: { shortTerm: number }; // federal + NJ rate of one more dollar of short-term gain
+ notes: TaxNote[];
+}
+
+// the two returns of one household and one income, before any rate or room
+function returnsOf(rules: TaxRules, h: Household, x: InvestmentIncome) {
+ const f = rules.federal;
+ const fedWages = h.grossWages - h.pretax401k - h.otherPretax;
+ const njWages = h.grossWages - h.pretax401k;
+ const deduction = h.deduction.kind === 'standard' ? f.standardDeduction : h.deduction.amount;
+ const capital = netCapital(x.shortTerm, x.longTerm + x.capGainDistributions, f.capitalLossLimit);
+ const ordinary = x.nonQualified + x.interest + x.treasuryInterest + x.otherOrdinary + capital.ordinary;
+ const preferential = x.qualified + capital.preferential;
+ const base = fedWages - deduction;
+ const before = federalTax(rules, base, 0);
+ const gross = federalTax(rules, base + ordinary, preferential);
+ const foreignCredit = Math.min(x.foreignTax, f.foreignCreditWithout1116, gross); // the credit never makes tax negative
+ const after = gross - foreignCredit;
+ const total = Math.max(0, base + ordinary + preferential);
+ const ordinaryTaxable = total - Math.min(Math.max(0, preferential), total);
+ const exemptions = 2 * rules.nj.exemptionPerSpouse + rules.nj.exemptionPerDependent * h.njDependents;
+ const njBefore = Math.max(0, njWages - exemptions);
+ // NJ: no lower rate for dividends or gains, a net loss counts as zero, Treasury interest not taxed, no foreign credit;
+ // exemptions the wages leave unused take their part of the investments
+ const njTaxable = Math.max(0, njWages - exemptions + x.ordinaryDividends + x.interest + x.otherOrdinary + Math.max(0, x.shortTerm + x.longTerm + x.capGainDistributions));
+ const njAdded = njTax(rules, njTaxable) - njTax(rules, njBefore);
+ return { fedWages, ordinary, preferential, before, after, foreignCredit, total, ordinaryTaxable, njTaxable, njAdded };
+}
+
+export function investmentTax(rules: TaxRules, household: Household, income: InvestmentIncome): InvestmentTax {
+ const f = rules.federal;
+ const r = returnsOf(rules, household, income);
+ const added = r.after - r.before;
+ const total = added + r.njAdded;
+ const counted = r.ordinary + r.preferential;
+ const line22 = f.ordinary.findIndex((b) => b.rate >= 0.22);
+ const start22 = line22 > 0 ? f.ordinary[line22 - 1]!.upTo : 0;
+ const nj = nextBracket(rules.nj.brackets, r.njTaxable);
+ const top = nj.index === rules.nj.brackets.length - 1;
+ // one more cent of short-term gain, as a rate: catches the bump zone (12% on it plus 15% on the qualified dividends
+ // it pushes over the 0% line) and a loss beyond the limit (costs nothing)
+ const CENT = 0.01;
+ const more = returnsOf(rules, household, { ...income, shortTerm: income.shortTerm + CENT });
+ const nextShort = ((more.after - more.before) + more.njAdded - total) / CENT;
+ const notes: TaxNote[] = [];
+ if (income.foreignTax > f.foreignCreditWithout1116) notes.push('form-1116');
+ if (r.fedWages + counted > f.niitThreshold) notes.push('niit');
+ return {
+ federal: {
+ added,
+ before: r.before,
+ after: r.after,
+ marginalOrdinary: nextBracket(f.ordinary, r.ordinaryTaxable).bracket.rate,
+ preferentialRate: nextBracket(f.preferential, r.total).bracket.rate,
+ foreignCredit: r.foreignCredit,
+ },
+ nj: { added: r.njAdded, marginal: nj.bracket.rate },
+ total,
+ effectiveRate: counted > 0 ? total / counted : null,
+ room: {
+ before22: Math.max(0, start22 - r.ordinaryTaxable),
+ beforePreferential15: Math.max(0, f.preferential[0]!.upTo - r.total),
+ njNext: top ? null : nj.bracket.upTo - r.njTaxable,
+ njNextRate: top ? null : rules.nj.brackets[nj.index + 1]!.rate,
+ },
+ nextDollar: { shortTerm: Math.round(nextShort * 1e6) / 1e6 },
+ notes,
+ };
+}