From bf5833524cd0993de53b38f65faa76a8d19f5f89 Mon Sep 17 00:00:00 2001 From: sharevb Date: Wed, 17 Dec 2025 22:39:06 +0100 Subject: [PATCH] feat(new tool): implement amortization-calculator tool (#242) This PR adds a new tool in the finance category called Amortization Calculator. It's used for calculating the amount of interest and principle that are a part of a payment to an amortized loan, like a car-loan or home-mortgage. --------- Co-authored-by: Jacob Alford Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- locales/en.yml | 24 + .../amortization-calculator.e2e.spec.ts | 192 +++++++ .../amortization-calculator.service.test.ts | 487 ++++++++++++++++++ .../amortization-calculator.service.ts | 183 +++++++ .../amortization-calculator.vue | 188 +++++++ src/tools/amortization-calculator/index.ts | 14 + 6 files changed, 1088 insertions(+) create mode 100644 src/tools/amortization-calculator/amortization-calculator.e2e.spec.ts create mode 100644 src/tools/amortization-calculator/amortization-calculator.service.test.ts create mode 100644 src/tools/amortization-calculator/amortization-calculator.service.ts create mode 100644 src/tools/amortization-calculator/amortization-calculator.vue create mode 100644 src/tools/amortization-calculator/index.ts diff --git a/locales/en.yml b/locales/en.yml index 1825d5dc..08d23c69 100644 --- a/locales/en.yml +++ b/locales/en.yml @@ -1210,6 +1210,30 @@ tools: placeholder-put-your-full-prompt-here: Put your full prompt here... label-character-length-for-each-chunk: Character length for each chunk title-divided-prompts: Divided prompts + amortization-calculator: + title: Amortization Calculator + description: Calculate loan amortization schedules with monthly payment breakdowns + footer: Amortization Calculator + texts: + title-loan-parameters: Loan Parameters + title-overview: Overview + title-amortization-schedule: Amortization Schedule + label-loan-amount: Loan Amount + label-loan-term: Loan Term + label-interest-rate: Interest Rate + label-displayed-currency: Displayed Currency + label-end-of-year: "End of Year {year}" + label-year: Year + label-month: Month + label-interest: Interest + label-principal: Principal + label-ending-balance: Ending Balance + label-monthly-payment: Monthly Payment + label-total-of-payments: Total of Payments + label-total-interest: Total Interest + message-loan-amount-must-be-positive: Loan amount must be a positive value + message-loan-term-must-be-positive-integer: Loan term must be a positive integer + message-interest-rate-must-be-between-1-and-100: Interest rate must be a positive value between 0 and 100 angle-converter: title: Angle Units Converter description: Convert values between angle units diff --git a/src/tools/amortization-calculator/amortization-calculator.e2e.spec.ts b/src/tools/amortization-calculator/amortization-calculator.e2e.spec.ts new file mode 100644 index 00000000..5eac42c9 --- /dev/null +++ b/src/tools/amortization-calculator/amortization-calculator.e2e.spec.ts @@ -0,0 +1,192 @@ +import { expect, test } from '@playwright/test'; + +test.describe('Tool - Amortization Calculator', () => { + test.beforeEach(async ({ page }) => { + await page.goto('/amortization-calculator'); + }); + + test('Has correct title', async ({ page }) => { + await expect(page).toHaveTitle('Amortization Calculator - IT Tools'); + }); + + test('Calculates amortization schedule with default values', async ({ page }) => { + const loanAmountInput = page.getByLabel('Loan Amount'); + const loanTermInput = page.getByLabel('Loan Term'); + const interestRateInput = page.getByLabel('Interest Rate'); + + await expect(loanAmountInput).toHaveValue('200000'); + await expect(loanTermInput).toHaveValue('360'); + await expect(interestRateInput).toHaveValue('6'); + + const monthlyPaymentCell = page.locator('tbody tr td').first(); + await expect(monthlyPaymentCell).toContainText('$1,199.10'); + + const totalPaymentsCell = page.locator('tbody tr td').nth(1); + await expect(totalPaymentsCell).toContainText('$431,676.38'); + }); + + test('Updates calculation when loan amount changes', async ({ page }) => { + const loanAmountInput = page.getByLabel('Loan Amount'); + + await loanAmountInput.clear(); + await loanAmountInput.fill('100000'); + + const monthlyPaymentCell = page.locator('tbody tr td').first(); + await expect(monthlyPaymentCell).toContainText('$599.55'); + + const totalPaymentsCell = page.locator('tbody tr td').nth(1); + await expect(totalPaymentsCell).toContainText('$215,838.19'); + }); + + test('Updates calculation when loan term changes', async ({ page }) => { + const loanTermInput = page.getByLabel('Loan Term'); + + await loanTermInput.clear(); + await loanTermInput.fill('180'); + + const monthlyPaymentCell = page.locator('tbody tr td').first(); + await expect(monthlyPaymentCell).toContainText('$1,687.71'); + }); + + test('Updates calculation when interest rate changes', async ({ page }) => { + const interestRateInput = page.getByLabel('Interest Rate'); + + await interestRateInput.clear(); + await interestRateInput.fill('4.5'); + + const monthlyPaymentCell = page.locator('tbody tr td').first(); + await expect(monthlyPaymentCell).toContainText('$1,013.37'); + }); + + test('Displays amortization schedule table', async ({ page }) => { + const scheduleTable = page.locator('table').nth(1); + + await expect(scheduleTable.locator('thead th').nth(0)).toContainText('Month'); + await expect(scheduleTable.locator('thead th').nth(1)).toContainText('Interest'); + await expect(scheduleTable.locator('thead th').nth(2)).toContainText('Principal'); + await expect(scheduleTable.locator('thead th').nth(3)).toContainText('Ending Balance'); + + const firstMonthRow = scheduleTable.locator('tbody tr').first(); + await expect(firstMonthRow.locator('td').nth(0)).toContainText('1'); + await expect(firstMonthRow.locator('td').nth(1)).toContainText('$1,000.00'); + await expect(firstMonthRow.locator('td').nth(2)).toContainText('$199.10'); + await expect(firstMonthRow.locator('td').nth(3)).toContainText('$199,800.90'); + }); + + test('Shows validation error for invalid loan amount', async ({ page }) => { + const loanAmountInput = page.getByLabel('Loan Amount'); + + await loanAmountInput.clear(); + await loanAmountInput.fill('-1000'); + await loanAmountInput.blur(); + + await expect(page.locator('text=Loan amount must be a positive value')).toBeVisible(); + }); + + test('Shows validation error for zero loan amount', async ({ page }) => { + const loanAmountInput = page.getByLabel('Loan Amount'); + + await loanAmountInput.clear(); + await loanAmountInput.fill('0'); + await loanAmountInput.blur(); + + await expect(page.locator('text=Loan amount must be a positive value')).toBeVisible(); + }); + + test('Shows validation error for non-integer loan term', async ({ page }) => { + const loanTermInput = page.getByLabel('Loan Term'); + + await loanTermInput.clear(); + await loanTermInput.fill('12.5'); + await loanTermInput.blur(); + + await expect(page.locator('text=Loan term must be a positive integer')).toBeVisible(); + }); + + test('Shows validation error for negative loan term', async ({ page }) => { + const loanTermInput = page.getByLabel('Loan Term'); + + await loanTermInput.clear(); + await loanTermInput.fill('-12'); + await loanTermInput.blur(); + + await expect(page.locator('text=Loan term must be a positive integer')).toBeVisible(); + }); + + test('Shows validation error for interest rate above 100', async ({ page }) => { + const interestRateInput = page.getByLabel('Interest Rate'); + + await interestRateInput.clear(); + await interestRateInput.fill('101'); + await interestRateInput.blur(); + + await expect(page.locator('text=Interest rate must be a positive value between 0 and 100')).toBeVisible(); + }); + + test('Shows validation error for zero interest rate', async ({ page }) => { + const interestRateInput = page.getByLabel('Interest Rate'); + + await interestRateInput.clear(); + await interestRateInput.fill('0'); + await interestRateInput.blur(); + + await expect(page.locator('text=Interest rate must be a positive value between 0 and 100')).toBeVisible(); + }); + + test('Hides results when inputs are invalid', async ({ page }) => { + const loanAmountInput = page.getByLabel('Loan Amount'); + + await loanAmountInput.clear(); + await loanAmountInput.fill('invalid'); + + const resultsTable = page.locator('table').first(); + await expect(resultsTable).not.toBeVisible(); + }); + + test('Calculates correctly for short-term loan', async ({ page }) => { + const loanAmountInput = page.getByLabel('Loan Amount'); + const loanTermInput = page.getByLabel('Loan Term'); + const interestRateInput = page.getByLabel('Interest Rate'); + + await loanAmountInput.clear(); + await loanAmountInput.fill('10000'); + await loanTermInput.clear(); + await loanTermInput.fill('12'); + await interestRateInput.clear(); + await interestRateInput.fill('12'); + + const monthlyPaymentCell = page.locator('tbody tr td').first(); + await expect(monthlyPaymentCell).toContainText('$888.49'); + + const scheduleTable = page.locator('table').nth(1); + // Find the last month row (before the year summary row) + const lastMonthRow = scheduleTable.locator('tbody tr').nth(11); // 12th month (0-indexed) + await expect(lastMonthRow.locator('td').nth(0)).toContainText('12'); + await expect(lastMonthRow.locator('td').nth(3)).toContainText('$0.00'); + }); + + test('Schedule shows decreasing balance over time', async ({ page }) => { + const loanAmountInput = page.getByLabel('Loan Amount'); + const loanTermInput = page.getByLabel('Loan Term'); + + await loanAmountInput.clear(); + await loanAmountInput.fill('50000'); + await loanTermInput.clear(); + await loanTermInput.fill('12'); + + const scheduleTable = page.locator('table').nth(1); + const firstBalance = await scheduleTable.locator('tbody tr').nth(0).locator('td').nth(3).textContent(); + const sixthBalance = await scheduleTable.locator('tbody tr').nth(5).locator('td').nth(3).textContent(); + // Get the last month row (12th month, index 11) before the year summary row + const lastMonthBalance = await scheduleTable.locator('tbody tr').nth(11).locator('td').nth(3).textContent(); + + // The values may contain country code in e2e tests + const firstBalanceValue = Number.parseFloat(firstBalance!.replace(/[A-Za-z$,]/g, '')); + const sixthBalanceValue = Number.parseFloat(sixthBalance!.replace(/[A-Za-z$,]/g, '')); + const lastBalanceValue = Number.parseFloat(lastMonthBalance!.replace(/[A-Za-z$,]/g, '')); + + expect(firstBalanceValue).toBeGreaterThan(sixthBalanceValue); + expect(sixthBalanceValue).toBeGreaterThan(lastBalanceValue); + expect(lastBalanceValue).toBeCloseTo(0, 0); + }); +}); diff --git a/src/tools/amortization-calculator/amortization-calculator.service.test.ts b/src/tools/amortization-calculator/amortization-calculator.service.test.ts new file mode 100644 index 00000000..b1f8bfa6 --- /dev/null +++ b/src/tools/amortization-calculator/amortization-calculator.service.test.ts @@ -0,0 +1,487 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import { + AmortizationCalculator, + type AmortizationParams, + StandardAmortizationCalculator, +} from './amortization-calculator.service'; + +describe('AmortizationCalculator', () => { + describe('validation methods', () => { + describe('validateLoanAmount', () => { + it('validates positive numbers', () => { + expect(AmortizationCalculator.validateLoanAmount('100000')).toBe(true); + expect(AmortizationCalculator.validateLoanAmount('1.5')).toBe(true); + expect(AmortizationCalculator.validateLoanAmount('0.01')).toBe(true); + }); + + it('rejects zero and negative numbers', () => { + expect(AmortizationCalculator.validateLoanAmount('0')).toBe(false); + expect(AmortizationCalculator.validateLoanAmount('-100')).toBe(false); + }); + + it('rejects invalid inputs', () => { + expect(AmortizationCalculator.validateLoanAmount('')).toBe(false); + expect(AmortizationCalculator.validateLoanAmount('abc')).toBe(false); + expect(AmortizationCalculator.validateLoanAmount('NaN')).toBe(false); + }); + + it('rejects infinity', () => { + expect(AmortizationCalculator.validateLoanAmount('Infinity')).toBe(false); + }); + }); + + describe('validateLoanMonths', () => { + it('validates positive integers', () => { + expect(AmortizationCalculator.validateLoanMonths('12')).toBe(true); + expect(AmortizationCalculator.validateLoanMonths('360')).toBe(true); + expect(AmortizationCalculator.validateLoanMonths('1')).toBe(true); + }); + + it('rejects non-integers', () => { + expect(AmortizationCalculator.validateLoanMonths('12.5')).toBe(false); + expect(AmortizationCalculator.validateLoanMonths('1.1')).toBe(false); + }); + + it('rejects zero and negative numbers', () => { + expect(AmortizationCalculator.validateLoanMonths('0')).toBe(false); + expect(AmortizationCalculator.validateLoanMonths('-12')).toBe(false); + }); + + it('rejects invalid inputs', () => { + expect(AmortizationCalculator.validateLoanMonths('')).toBe(false); + expect(AmortizationCalculator.validateLoanMonths('abc')).toBe(false); + }); + }); + + describe('validateInterestRate', () => { + it('validates fractional interest rates between 0 and 100', () => { + expect(AmortizationCalculator.validateInterestRate('5.5')).toBe(true); + expect(AmortizationCalculator.validateInterestRate('0.01')).toBe(true); + expect(AmortizationCalculator.validateInterestRate('100')).toBe(true); + expect(AmortizationCalculator.validateInterestRate('12.75')).toBe(true); + }); + + it('rejects rates above 100', () => { + expect(AmortizationCalculator.validateInterestRate('100.01')).toBe(false); + expect(AmortizationCalculator.validateInterestRate('200')).toBe(false); + }); + + it('rejects zero and negative rates', () => { + expect(AmortizationCalculator.validateInterestRate('0')).toBe(false); + expect(AmortizationCalculator.validateInterestRate('-5')).toBe(false); + }); + + it('rejects invalid inputs', () => { + expect(AmortizationCalculator.validateInterestRate('')).toBe(false); + expect(AmortizationCalculator.validateInterestRate('abc')).toBe(false); + }); + + it('rejects infinity', () => { + expect(AmortizationCalculator.validateInterestRate('Infinity')).toBe(false); + }); + }); + }); +}); + +describe('StandardAmortizationCalculator', () => { + let calculator: StandardAmortizationCalculator; + + beforeEach(() => { + calculator = new StandardAmortizationCalculator(); + }); + + describe('getPayment', () => { + it('calculates correct payment for standard loan parameters', () => { + const params: AmortizationParams = { + principal: 100000, + periodInterestRate: 0.005, // 0.5% monthly (6% annual) + numberOfPayments: 360, // 30 years + }; + + const result = calculator.getPayment(params); + + // Expected payment using standard amortization formula + // P = L[c(1 + c)^n]/[(1 + c)^n - 1] + // Where P is payment, L is loan amount, c is interest rate per period, n is number of periods + expect(result.payment).toBeCloseTo(599.55, 2); + expect(result.totalPayments).toBeCloseTo(215838, 0); + }); + + it('calculates correct payment for short-term loan', () => { + const params: AmortizationParams = { + principal: 10000, + periodInterestRate: 0.01, // 1% monthly + numberOfPayments: 12, + }; + + const result = calculator.getPayment(params); + + expect(result.payment).toBeCloseTo(888.49, 2); + expect(result.totalPayments).toBeCloseTo(10661.85, 2); + }); + + it('calculates correct payment with zero interest rate', () => { + const params: AmortizationParams = { + principal: 12000, + periodInterestRate: 0, + numberOfPayments: 12, + }; + + const result = calculator.getPayment(params); + + // With 0% interest, payment should be principal / numberOfPayments + expect(result.payment).toBe(1000); + expect(result.totalPayments).toBe(12000); + }); + + it('caches payment calculations', () => { + const params: AmortizationParams = { + principal: 50000, + periodInterestRate: 0.004, + numberOfPayments: 180, + }; + + const result1 = calculator.getPayment(params); + const result2 = calculator.getPayment(params); + + // Should return the same object reference from cache + expect(result1).toBe(result2); + expect(result1.payment).toBeCloseTo(390.21, 2); + }); + + it('calculates different payments for different parameters', () => { + const params1: AmortizationParams = { + principal: 100000, + periodInterestRate: 0.005, + numberOfPayments: 360, + }; + + const params2: AmortizationParams = { + principal: 100000, + periodInterestRate: 0.004, + numberOfPayments: 360, + }; + + const result1 = calculator.getPayment(params1); + const result2 = calculator.getPayment(params2); + + expect(result1.payment).not.toBe(result2.payment); + expect(result1.payment).toBeGreaterThan(result2.payment); + }); + }); + + describe('getNth', () => { + it('calculates correct values for first payment', () => { + const params: AmortizationParams = { + principal: 100000, + periodInterestRate: 0.005, + numberOfPayments: 360, + }; + + const result = calculator.getNth(params, 1); + + expect(result.paymentIndex).toBe(1); + expect(result.payment).toBeCloseTo(599.55, 2); + + // First payment: more interest, less principal in standard amortization + expect(result.interestPayment).toBeCloseTo(500, 2); // 100000 * 0.005 + expect(result.principalPayment).toBeCloseTo(99.55, 2); // 599.55 - 500 + expect(result.remainingBalance).toBeCloseTo(99900.45, 2); // 100000 - 99.55 + + // Payment should equal principal + interest + expect(result.principalPayment + result.interestPayment).toBeCloseTo(result.payment, 2); + }); + + it('calculates correct values for middle payment', () => { + const params: AmortizationParams = { + principal: 100000, + periodInterestRate: 0.005, + numberOfPayments: 360, + }; + + const result = calculator.getNth(params, 180); + + expect(result.paymentIndex).toBe(180); + expect(result.remainingBalance).toBeGreaterThan(0); + expect(result.remainingBalance).toBeLessThan(params.principal); + expect(result.principalPayment + result.interestPayment).toBeCloseTo(result.payment, 2); + }); + + it('calculates correct values for final payment', () => { + const params: AmortizationParams = { + principal: 100000, + periodInterestRate: 0.005, + numberOfPayments: 360, + }; + + const result = calculator.getNth(params, 360); + + expect(result.paymentIndex).toBe(360); + // Last payment should have remaining balance close to 0 + expect(result.remainingBalance).toBeCloseTo(0, 0); + expect(result.principalPayment + result.interestPayment).toBeCloseTo(result.payment, 2); + }); + + it('shows increasing principal payment over time for standard amortization', () => { + const params: AmortizationParams = { + principal: 100000, + periodInterestRate: 0.005, + numberOfPayments: 360, + }; + + const payment1 = calculator.getNth(params, 1); + const payment180 = calculator.getNth(params, 180); + const payment360 = calculator.getNth(params, 360); + + // In standard amortization, principal payment increases as balance decreases + expect(payment1.principalPayment).toBeLessThan(payment180.principalPayment); + expect(payment180.principalPayment).toBeLessThan(payment360.principalPayment); + }); + + it('shows decreasing interest payment over time', () => { + const params: AmortizationParams = { + principal: 100000, + periodInterestRate: 0.005, + numberOfPayments: 360, + }; + + const payment1 = calculator.getNth(params, 1); + const payment180 = calculator.getNth(params, 180); + const payment360 = calculator.getNth(params, 360); + + // Interest payment should decrease over time + expect(payment1.interestPayment).toBeGreaterThan(payment180.interestPayment); + expect(payment180.interestPayment).toBeGreaterThan(payment360.interestPayment); + }); + + it('handles zero interest rate correctly', () => { + const params: AmortizationParams = { + principal: 12000, + periodInterestRate: 0, + numberOfPayments: 12, + }; + + const result = calculator.getNth(params, 1); + + expect(result.payment).toBe(1000); + expect(result.interestPayment).toBe(0); + expect(result.principalPayment).toBeGreaterThan(0); + }); + }); + + describe('getAmortizationSchedule', () => { + it('generates complete amortization schedule with month and year rows', () => { + const params: AmortizationParams = { + principal: 10000, + periodInterestRate: 0.01, + numberOfPayments: 12, + }; + + const schedule = Array.from(calculator.getAmortizationSchedule(params)); + + // 12 months + 1 year summary row = 13 total + expect(schedule).toHaveLength(13); + expect(schedule[0].paymentIndex).toBe(1); + expect(schedule[0].type).toBe('month'); + expect(schedule[11].paymentIndex).toBe(12); + expect(schedule[11].type).toBe('month'); + expect(schedule[12].type).toBe('year'); + expect(schedule[12].paymentIndex).toBe(1); // Year 1 + }); + + it('ensures each payment has consistent structure', () => { + const params: AmortizationParams = { + principal: 50000, + periodInterestRate: 0.004, + numberOfPayments: 60, + }; + + const schedule = Array.from(calculator.getAmortizationSchedule(params)); + + // 60 months + 5 year summary rows = 65 total + expect(schedule).toHaveLength(65); + + const monthRows = schedule.filter(row => row.type === 'month'); + const yearRows = schedule.filter(row => row.type === 'year'); + + expect(monthRows).toHaveLength(60); + expect(yearRows).toHaveLength(5); + + monthRows.forEach((payment, index) => { + expect(payment).toHaveProperty('paymentIndex'); + expect(payment).toHaveProperty('payment'); + expect(payment).toHaveProperty('principalPayment'); + expect(payment).toHaveProperty('interestPayment'); + expect(payment).toHaveProperty('remainingBalance'); + expect(payment).toHaveProperty('totalPayments'); + expect(payment).toHaveProperty('type'); + + expect(payment.paymentIndex).toBe(index + 1); + expect(payment.principalPayment + payment.interestPayment).toBeCloseTo(payment.payment, 2); + }); + }); + + it('shows decreasing remaining balance over time', () => { + const params: AmortizationParams = { + principal: 20000, + periodInterestRate: 0.005, + numberOfPayments: 24, + }; + + const schedule = Array.from(calculator.getAmortizationSchedule(params)); + + // Filter to only month rows for balance comparison + const monthRows = schedule.filter(row => row.type === 'month'); + + for (let i = 1; i < monthRows.length; i++) { + expect(monthRows[i].remainingBalance).toBeLessThan(monthRows[i - 1].remainingBalance); + } + }); + + it('ends with near-zero remaining balance', () => { + const params: AmortizationParams = { + principal: 15000, + periodInterestRate: 0.0075, + numberOfPayments: 36, + }; + + const schedule = Array.from(calculator.getAmortizationSchedule(params)); + const monthRows = schedule.filter(row => row.type === 'month'); + const lastMonthPayment = monthRows[monthRows.length - 1]; + + expect(lastMonthPayment.remainingBalance).toBeCloseTo(0, 0); + }); + + it('handles single payment loan', () => { + const params: AmortizationParams = { + principal: 1000, + periodInterestRate: 0.05, + numberOfPayments: 1, + }; + + const schedule = Array.from(calculator.getAmortizationSchedule(params)); + + // Single payment with no year summary (< 12 months) + expect(schedule).toHaveLength(1); + expect(schedule[0].paymentIndex).toBe(1); + expect(schedule[0].type).toBe('month'); + expect(schedule[0].payment).toBeCloseTo(1050, 2); + }); + + it('maintains consistent payment amount throughout schedule', () => { + const params: AmortizationParams = { + principal: 25000, + periodInterestRate: 0.006, + numberOfPayments: 48, + }; + + const schedule = Array.from(calculator.getAmortizationSchedule(params)); + const monthRows = schedule.filter(row => row.type === 'month'); + const firstPayment = monthRows[0].payment; + + monthRows.forEach((payment) => { + expect(payment.payment).toBeCloseTo(firstPayment, 2); + }); + }); + + it('includes year summary rows after every 12 months', () => { + const params: AmortizationParams = { + principal: 100000, + periodInterestRate: 0.005, + numberOfPayments: 24, + }; + + const schedule = Array.from(calculator.getAmortizationSchedule(params)); + const yearRows = schedule.filter(row => row.type === 'year'); + + expect(yearRows).toHaveLength(2); // 2 years + expect(yearRows[0].paymentIndex).toBe(1); // Year 1 + expect(yearRows[1].paymentIndex).toBe(2); // Year 2 + }); + + it('year summary rows contain cumulative totals', () => { + const params: AmortizationParams = { + principal: 10000, + periodInterestRate: 0.01, + numberOfPayments: 12, + }; + + const schedule = Array.from(calculator.getAmortizationSchedule(params)); + const monthRows = schedule.filter(row => row.type === 'month'); + const yearRows = schedule.filter(row => row.type === 'year'); + + // Calculate cumulative totals for the year + const totalPrincipal = monthRows.reduce((sum, row) => sum + row.principalPayment, 0); + const totalInterest = monthRows.reduce((sum, row) => sum + row.interestPayment, 0); + + expect(yearRows[0].principalPayment).toBeCloseTo(totalPrincipal, 2); + expect(yearRows[0].interestPayment).toBeCloseTo(totalInterest, 2); + }); + }); + + describe('edge cases', () => { + it('handles very small loan amounts', () => { + const params: AmortizationParams = { + principal: 100, + periodInterestRate: 0.01, + numberOfPayments: 12, + }; + + const result = calculator.getPayment(params); + expect(result.payment).toBeGreaterThan(0); + expect(result.totalPayments).toBeGreaterThan(params.principal); + }); + + it('handles very large loan amounts', () => { + const params: AmortizationParams = { + principal: 10000000, + periodInterestRate: 0.003, + numberOfPayments: 360, + }; + + const result = calculator.getPayment(params); + expect(result.payment).toBeGreaterThan(0); + expect(Number.isFinite(result.payment)).toBe(true); + }); + + it('handles very low interest rates', () => { + const params: AmortizationParams = { + principal: 50000, + periodInterestRate: 0.0001, + numberOfPayments: 60, + }; + + const result = calculator.getPayment(params); + expect(result.payment).toBeGreaterThan(params.principal / params.numberOfPayments); + }); + + it('handles short loan terms', () => { + const params: AmortizationParams = { + principal: 5000, + periodInterestRate: 0.02, + numberOfPayments: 3, + }; + + const schedule = Array.from(calculator.getAmortizationSchedule(params)); + // 3 months, no year summary (< 12 months) + expect(schedule).toHaveLength(3); + const monthRows = schedule.filter(row => row.type === 'month'); + expect(monthRows[2].remainingBalance).toBeCloseTo(0, 0); + }); + + it('handles long loan terms', () => { + const params: AmortizationParams = { + principal: 200000, + periodInterestRate: 0.004, + numberOfPayments: 480, // 40 years + }; + + const schedule = Array.from(calculator.getAmortizationSchedule(params)); + // 480 months + 40 year summary rows = 520 total + expect(schedule).toHaveLength(520); + const monthRows = schedule.filter(row => row.type === 'month'); + expect(monthRows).toHaveLength(480); + expect(monthRows[479].remainingBalance).toBeCloseTo(0, 0); + }); + }); +}); diff --git a/src/tools/amortization-calculator/amortization-calculator.service.ts b/src/tools/amortization-calculator/amortization-calculator.service.ts new file mode 100644 index 00000000..f8f463a8 --- /dev/null +++ b/src/tools/amortization-calculator/amortization-calculator.service.ts @@ -0,0 +1,183 @@ +export interface AmortizationParams { + readonly principal: number + readonly periodInterestRate: number + readonly numberOfPayments: number +} + +export interface CachedPaymentResults { + readonly payment: number + readonly totalPayments: number +} + +export interface GetNthResult extends CachedPaymentResults { + readonly paymentIndex: number + readonly principalPayment: number + readonly interestPayment: number + readonly remainingBalance: number +} + +export interface AmortizationScheduleItem extends GetNthResult { + readonly type: 'month' | 'year' +} + +type AmortizationPaymentCacheKey = `principal:${number};interest-rate:${number};number-of-payments:${number}`; + +export abstract class AmortizationCalculator { + public static validateLoanAmount(str: string): boolean { + return AmortizationCalculator.validatePositive(str); + } + + public static validateLoanMonths(str: string): boolean { + return AmortizationCalculator.validatePositiveInteger(str); + } + + public static validateInterestRate(str: string): boolean { + return AmortizationCalculator.validateFractional(str); + } + + abstract getNth(params: AmortizationParams, paymentIndex: number): GetNthResult; + + public *getAmortizationSchedule(params: AmortizationParams): Generator { + let period = 0; + let periodTotalPrincipal = 0; + let periodTotalInterest = 0; + + while (period < params.numberOfPayments) { + const periodResults = this.getNth(params, ++period); + + periodTotalPrincipal += periodResults.principalPayment; + periodTotalInterest += periodResults.interestPayment; + + yield { + ...periodResults, + type: 'month', + }; + + // Yield yearly totals at end of year + if (period % 12 === 0) { + yield { + ...periodResults, + paymentIndex: period / 12, + principalPayment: periodTotalPrincipal, + interestPayment: periodTotalInterest, + type: 'year', + }; + + periodTotalPrincipal = 0; + periodTotalInterest = 0; + } + } + } + + public getPayment(params: AmortizationParams): CachedPaymentResults { + const cacheKey = this.getCacheString(params); + const cache = this.paymentCache.get(cacheKey); + + if (!cache) { + const payment = this.calculatePayment(params); + const totalPayments = this.calculateTotalPayments(params, payment); + + const paymentResult = { + payment, + totalPayments, + }; + + this.paymentCache.set(cacheKey, paymentResult); + + return paymentResult; + } + + return cache; + } + + /** Private Methods */ + private paymentCache: Map = new Map(); + + private calculatePayment({ principal, periodInterestRate, numberOfPayments }: AmortizationParams): number { + if (periodInterestRate === 0) { + return principal / numberOfPayments; + } + + const numerator = periodInterestRate * (1 + periodInterestRate) ** numberOfPayments; + const denominator = (1 + periodInterestRate) ** numberOfPayments - 1; + + return principal * (numerator / denominator); + } + + private calculateTotalPayments({ numberOfPayments }: AmortizationParams, payment: number): number { + return payment * numberOfPayments; + } + + private getCacheString({ + principal, + periodInterestRate, + numberOfPayments, + }: AmortizationParams): AmortizationPaymentCacheKey { + return `principal:${principal};interest-rate:${periodInterestRate};number-of-payments:${numberOfPayments}`; + } + + private static validatePositiveInteger(str: string): boolean { + const parsed = Number(str); + + return !Number.isNaN(parsed) && Number.isSafeInteger(parsed) && parsed > 0; + } + + private static validateFractional(str: string): boolean { + const parsed = Number(str); + + return !Number.isNaN(parsed) && Number.isFinite(parsed) && parsed <= 100 && parsed > 0; + } + + private static validatePositive(str: string): boolean { + const parsed = Number(str); + + return !Number.isNaN(parsed) && Number.isFinite(parsed) && parsed > 0; + } +} + +/** + * An amortization calculator that uses the standard amortization formula + * where interest is calculated on the remaining balance and principal + * payment is the difference between the fixed payment and interest + */ +export class StandardAmortizationCalculator extends AmortizationCalculator { + getNth(params: AmortizationParams, paymentIndex: number): GetNthResult { + const { payment, totalPayments } = this.getPayment(params); + + const { principal, periodInterestRate, numberOfPayments } = params; + + if (periodInterestRate === 0) { + const principalPayment = principal / numberOfPayments; + const remainingBalance = principal - principalPayment * paymentIndex; + + return { + payment, + totalPayments, + remainingBalance: Math.max(0, remainingBalance), + interestPayment: 0, + principalPayment, + paymentIndex, + }; + } + + const r = 1 + periodInterestRate; + + const balanceBeforePayment + = principal * r ** (paymentIndex - 1) - payment * ((r ** (paymentIndex - 1) - 1) / periodInterestRate); + + const interestPayment = balanceBeforePayment * periodInterestRate; + + const principalPayment = payment - interestPayment; + + const remainingBalance = balanceBeforePayment - principalPayment; + + return { + payment, + totalPayments, + remainingBalance, + interestPayment, + principalPayment, + paymentIndex, + }; + } +} diff --git a/src/tools/amortization-calculator/amortization-calculator.vue b/src/tools/amortization-calculator/amortization-calculator.vue new file mode 100644 index 00000000..44fa98c1 --- /dev/null +++ b/src/tools/amortization-calculator/amortization-calculator.vue @@ -0,0 +1,188 @@ + + + diff --git a/src/tools/amortization-calculator/index.ts b/src/tools/amortization-calculator/index.ts new file mode 100644 index 00000000..53c0ca45 --- /dev/null +++ b/src/tools/amortization-calculator/index.ts @@ -0,0 +1,14 @@ +import { ReportMoney } from '@vicons/tabler'; +import { defineTool } from '../tool'; +import { translate as t } from '@/plugins/i18n.plugin'; + +export const tool = defineTool({ + name: t('tools.amortization-calculator.title'), + path: '/amortization-calculator', + description: t('tools.amortization-calculator.description'), + keywords: ['amortization', 'calculator'], + component: () => import('./amortization-calculator.vue'), + icon: ReportMoney, + createdAt: new Date('2025-11-22'), + category: 'Finance', +});