mirror of
https://github.com/sharevb/it-tools.git
synced 2026-11-28 00:10:00 +03:00
feat(amortization-calculator): implement amortization-calculator tool
This commit is contained in:
9 files changed
+1188
-1
No files matched your search
Vendored
+30
-1
@@ -5,7 +5,7 @@
|
||||
// Read more: https://github.com/vuejs/core/pull/3399
|
||||
import '@vue/runtime-core'
|
||||
|
||||
export { }
|
||||
export {}
|
||||
|
||||
declare module '@vue/runtime-core' {
|
||||
export interface GlobalComponents {
|
||||
@@ -15,6 +15,7 @@ declare module '@vue/runtime-core' {
|
||||
AgeCrypto: typeof import('./src/tools/age-crypto/age-crypto.vue')['default']
|
||||
AiPromptSplitter: typeof import('./src/tools/ai-prompt-splitter/ai-prompt-splitter.vue')['default']
|
||||
AlarmSoundToggle: typeof import('./src/tools/pomodoro-timer/app/components/AlarmSoundToggle.vue')['default']
|
||||
AmortizationCalculator: typeof import('./src/tools/amortization-calculator/amortization-calculator.vue')['default']
|
||||
AngleConverter: typeof import('./src/tools/angle-converter/angle-converter.vue')['default']
|
||||
AnsibleVaultCryptDecrypt: typeof import('./src/tools/ansible-vault-crypt-decrypt/ansible-vault-crypt-decrypt.vue')['default']
|
||||
AnsiEscapeTester: typeof import('./src/tools/ansi-escape-tester/ansi-escape-tester.vue')['default']
|
||||
@@ -22,6 +23,7 @@ declare module '@vue/runtime-core' {
|
||||
App: typeof import('./src/App.vue')['default']
|
||||
AppColorPicker: typeof import('./src/tools/pomodoro-timer/app/components/AppColorPicker.vue')['default']
|
||||
AreaConverter: typeof import('./src/tools/area-converter/area-converter.vue')['default']
|
||||
Argon2Hash: typeof import('./src/tools/argon2-hash/argon2-hash.vue')['default']
|
||||
AsciiTextDrawer: typeof import('./src/tools/ascii-text-drawer/ascii-text-drawer.vue')['default']
|
||||
AspectRatioCalculator: typeof import('./src/tools/aspect-ratio-calculator/aspect-ratio-calculator.vue')['default']
|
||||
BarcodeGenerator: typeof import('./src/tools/barcode-generator/barcode-generator.vue')['default']
|
||||
@@ -101,9 +103,11 @@ declare module '@vue/runtime-core' {
|
||||
CSelect: typeof import('./src/ui/c-select/c-select.vue')['default']
|
||||
'CSelect.demo': typeof import('./src/ui/c-select/c-select.demo.vue')['default']
|
||||
CsrGenerator: typeof import('./src/tools/csr-generator/csr-generator.vue')['default']
|
||||
CssGradientGenerator: typeof import('./src/tools/css-gradient-generator/css-gradient-generator.vue')['default']
|
||||
CssPrettifier: typeof import('./src/tools/css-prettifier/css-prettifier.vue')['default']
|
||||
CssSelectors: typeof import('./src/tools/css-selectors-memo/css-selectors.md')['default']
|
||||
CssSelectorsMemo: typeof import('./src/tools/css-selectors-memo/css-selectors-memo.vue')['default']
|
||||
CssUnitsConverter: typeof import('./src/tools/css-units-converter/css-units-converter.vue')['default']
|
||||
CssXpathConverter: typeof import('./src/tools/css-xpath-converter/css-xpath-converter.vue')['default']
|
||||
CsvToData: typeof import('./src/tools/csv-to-data/csv-to-data.vue')['default']
|
||||
CsvToJson: typeof import('./src/tools/csv-to-json/csv-to-json.vue')['default']
|
||||
@@ -193,6 +197,7 @@ declare module '@vue/runtime-core' {
|
||||
FortuneWheel: typeof import('./src/tools/fortune-wheel/fortune-wheel.vue')['default']
|
||||
FstabGenerator: typeof import('./src/tools/fstab-generator/fstab-generator.vue')['default']
|
||||
GeoDistanceCalculator: typeof import('./src/tools/geo-distance-calculator/geo-distance-calculator.vue')['default']
|
||||
GitignoreGenerator: typeof import('./src/tools/gitignore-generator/gitignore-generator.vue')['default']
|
||||
GitMemo: typeof import('./src/tools/git-memo/git-memo.vue')['default']
|
||||
'GitMemo.content': typeof import('./src/tools/git-memo/git-memo.content.md')['default']
|
||||
'GitSem.memo': typeof import('./src/tools/git-semantic-commit-memo/git-sem.memo.md')['default']
|
||||
@@ -231,6 +236,8 @@ declare module '@vue/runtime-core' {
|
||||
IcoConverter: typeof import('./src/tools/ico-converter/ico-converter.vue')['default']
|
||||
'IconMdi:brushVariant': typeof import('~icons/mdi/brush-variant')['default']
|
||||
'IconMdi:kettleSteamOutline': typeof import('~icons/mdi/kettle-steam-outline')['default']
|
||||
IconMdiArrowDown: typeof import('~icons/mdi/arrow-down')['default']
|
||||
IconMdiArrowUp: typeof import('~icons/mdi/arrow-up')['default']
|
||||
IconMdiCheck: typeof import('~icons/mdi/check')['default']
|
||||
IconMdiChevronDown: typeof import('~icons/mdi/chevron-down')['default']
|
||||
IconMdiChevronRight: typeof import('~icons/mdi/chevron-right')['default']
|
||||
@@ -240,6 +247,7 @@ declare module '@vue/runtime-core' {
|
||||
IconMdiEye: typeof import('~icons/mdi/eye')['default']
|
||||
IconMdiEyeOff: typeof import('~icons/mdi/eye-off')['default']
|
||||
IconMdiHeart: typeof import('~icons/mdi/heart')['default']
|
||||
IconMdiRefresh: typeof import('~icons/mdi/refresh')['default']
|
||||
IconMdiSearch: typeof import('~icons/mdi/search')['default']
|
||||
IconMdiTranslate: typeof import('~icons/mdi/translate')['default']
|
||||
IconMdiTriangleDown: typeof import('~icons/mdi/triangle-down')['default']
|
||||
@@ -263,6 +271,7 @@ declare module '@vue/runtime-core' {
|
||||
Ipv4AddressConverter: typeof import('./src/tools/ipv4-address-converter/ipv4-address-converter.vue')['default']
|
||||
Ipv4RangeExpander: typeof import('./src/tools/ipv4-range-expander/ipv4-range-expander.vue')['default']
|
||||
Ipv4SubnetCalculator: typeof import('./src/tools/ipv4-subnet-calculator/ipv4-subnet-calculator.vue')['default']
|
||||
Ipv4SubnetsList: typeof import('./src/tools/ipv4-subnets-list/ipv4-subnets-list.vue')['default']
|
||||
Ipv6AddressConverter: typeof import('./src/tools/ipv6-address-converter/ipv6-address-converter.vue')['default']
|
||||
Ipv6SubnetCalculator: typeof import('./src/tools/ipv6-subnet-calculator/ipv6-subnet-calculator.vue')['default']
|
||||
Ipv6UlaGenerator: typeof import('./src/tools/ipv6-ula-generator/ipv6-ula-generator.vue')['default']
|
||||
@@ -302,6 +311,7 @@ declare module '@vue/runtime-core' {
|
||||
JsonToSqlDdl: typeof import('./src/tools/json-to-sql-ddl/json-to-sql-ddl.vue')['default']
|
||||
JsonToSqlInsert: typeof import('./src/tools/json-to-sql-insert/json-to-sql-insert.vue')['default']
|
||||
JsonToToml: typeof import('./src/tools/json-to-toml/json-to-toml.vue')['default']
|
||||
JsonToToon: typeof import('./src/tools/json-to-toon/json-to-toon.vue')['default']
|
||||
JsonToTs: typeof import('./src/tools/json-to-ts/json-to-ts.vue')['default']
|
||||
JsonToTypescript: typeof import('./src/tools/json-to-typescript/json-to-typescript.vue')['default']
|
||||
JsonToXml: typeof import('./src/tools/json-to-xml/json-to-xml.vue')['default']
|
||||
@@ -330,6 +340,7 @@ declare module '@vue/runtime-core' {
|
||||
ManyUnitsConverter: typeof import('./src/tools/many-units-converter/many-units-converter.vue')['default']
|
||||
MarkdownCheatsheet: typeof import('./src/tools/markdown-cheatsheet/markdown-cheatsheet.vue')['default']
|
||||
MarkdownEditor: typeof import('./src/tools/markdown-editor/markdown-editor.vue')['default']
|
||||
MarkdownLoremIpsum: typeof import('./src/tools/markdown-lorem-ipsum/markdown-lorem-ipsum.vue')['default']
|
||||
MarkdownTablePrettifier: typeof import('./src/tools/markdown-table-prettifier/markdown-table-prettifier.vue')['default']
|
||||
MarkdownTocGenerator: typeof import('./src/tools/markdown-toc-generator/markdown-toc-generator.vue')['default']
|
||||
MarkdownToDocx: typeof import('./src/tools/markdown-to-docx/markdown-to-docx.vue')['default']
|
||||
@@ -358,15 +369,19 @@ declare module '@vue/runtime-core' {
|
||||
MultiLinkDownloader: typeof import('./src/tools/multi-link-downloader/multi-link-downloader.vue')['default']
|
||||
MyIp: typeof import('./src/tools/my-ip/my-ip.vue')['default']
|
||||
NA: typeof import('naive-ui')['NA']
|
||||
NAlert: typeof import('naive-ui')['NAlert']
|
||||
NanoidGenerator: typeof import('./src/tools/nanoid-generator/nanoid-generator.vue')['default']
|
||||
NanoMemo: typeof import('./src/tools/nano-memo/nano-memo.vue')['default']
|
||||
'NanoMemo.content': typeof import('./src/tools/nano-memo/nano-memo.content.md')['default']
|
||||
NavbarButtons: typeof import('./src/components/NavbarButtons.vue')['default']
|
||||
NButton: typeof import('naive-ui')['NButton']
|
||||
NCard: typeof import('naive-ui')['NCard']
|
||||
NCheckbox: typeof import('naive-ui')['NCheckbox']
|
||||
NCode: typeof import('naive-ui')['NCode']
|
||||
NColorPicker: typeof import('naive-ui')['NColorPicker']
|
||||
NConfigProvider: typeof import('naive-ui')['NConfigProvider']
|
||||
NDataTable: typeof import('naive-ui')['NDataTable']
|
||||
NDatePicker: typeof import('naive-ui')['NDatePicker']
|
||||
NDivider: typeof import('naive-ui')['NDivider']
|
||||
NEllipsis: typeof import('naive-ui')['NEllipsis']
|
||||
NForm: typeof import('naive-ui')['NForm']
|
||||
@@ -381,15 +396,26 @@ declare module '@vue/runtime-core' {
|
||||
NicewareBytesToPassphrase: typeof import('./src/tools/niceware-bytes-to-passphrase/niceware-bytes-to-passphrase.vue')['default']
|
||||
NIcon: typeof import('naive-ui')['NIcon']
|
||||
NImage: typeof import('naive-ui')['NImage']
|
||||
NInput: typeof import('naive-ui')['NInput']
|
||||
NInputGroup: typeof import('naive-ui')['NInputGroup']
|
||||
NInputGroupLabel: typeof import('naive-ui')['NInputGroupLabel']
|
||||
NInputNumber: typeof import('naive-ui')['NInputNumber']
|
||||
NInputNumberI18n: typeof import('./src/ui/n-input-number-i18n/n-input-number-i18n.vue')['default']
|
||||
'NInputNumberI18n.demo': typeof import('./src/ui/n-input-number-i18n/n-input-number-i18n.demo.vue')['default']
|
||||
NLayout: typeof import('naive-ui')['NLayout']
|
||||
NLayoutSider: typeof import('naive-ui')['NLayoutSider']
|
||||
NMenu: typeof import('naive-ui')['NMenu']
|
||||
NModal: typeof import('naive-ui')['NModal']
|
||||
NP: typeof import('naive-ui')['NP']
|
||||
NProgress: typeof import('naive-ui')['NProgress']
|
||||
NRadio: typeof import('naive-ui')['NRadio']
|
||||
NRadioGroup: typeof import('naive-ui')['NRadioGroup']
|
||||
NScrollbar: typeof import('naive-ui')['NScrollbar']
|
||||
NSelect: typeof import('naive-ui')['NSelect']
|
||||
NSlider: typeof import('naive-ui')['NSlider']
|
||||
NSpace: typeof import('naive-ui')['NSpace']
|
||||
NStatistic: typeof import('naive-ui')['NStatistic']
|
||||
NSwitch: typeof import('naive-ui')['NSwitch']
|
||||
NTable: typeof import('naive-ui')['NTable']
|
||||
NTag: typeof import('naive-ui')['NTag']
|
||||
NTooltip: typeof import('naive-ui')['NTooltip']
|
||||
@@ -463,7 +489,9 @@ declare module '@vue/runtime-core' {
|
||||
SensitiveDataMasker: typeof import('./src/tools/sensitive-data-masker/sensitive-data-masker.vue')['default']
|
||||
SerialConsole: typeof import('./src/tools/serial-console/serial-console.vue')['default']
|
||||
Settings: typeof import('./src/tools/pomodoro-timer/app/views/Settings.vue')['default']
|
||||
ShamirsSecretSharing: typeof import('./src/tools/shamirs-secret-sharing/shamirs-secret-sharing.vue')['default']
|
||||
SharepointDecoder: typeof import('./src/tools/sharepoint-decoder/sharepoint-decoder.vue')['default']
|
||||
ShortUrlsExpander: typeof import('./src/tools/short-urls-expander/short-urls-expander.vue')['default']
|
||||
SipAuth: typeof import('./src/tools/sip-auth/sip-auth.vue')['default']
|
||||
SlaCalculator: typeof import('./src/tools/sla-calculator/sla-calculator.vue')['default']
|
||||
SlugifyString: typeof import('./src/tools/slugify-string/slugify-string.vue')['default']
|
||||
@@ -503,6 +531,7 @@ declare module '@vue/runtime-core' {
|
||||
TomlToYaml: typeof import('./src/tools/toml-to-yaml/toml-to-yaml.vue')['default']
|
||||
'Tool.layout': typeof import('./src/layouts/tool.layout.vue')['default']
|
||||
ToolCard: typeof import('./src/components/ToolCard.vue')['default']
|
||||
ToonToJson: typeof import('./src/tools/toon-to-json/toon-to-json.vue')['default']
|
||||
TorrentToMagnet: typeof import('./src/tools/torrent-to-magnet/torrent-to-magnet.vue')['default']
|
||||
TraefikComposeMaker: typeof import('./src/tools/traefik-compose-maker/traefik-compose-maker.vue')['default']
|
||||
Translator: typeof import('./src/tools/translator/translator.vue')['default']
|
||||
|
||||
Generated
+27
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"nodes": {
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1763464769,
|
||||
"narHash": "sha256-AJHrsT7VoeQzErpBRlLJM1SODcaayp0joAoEA35yiwM=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "6f374686605df381de8541c072038472a5ea2e2d",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
"owner": "NixOS",
|
||||
"ref": "nixpkgs-unstable",
|
||||
"repo": "nixpkgs",
|
||||
"type": "github"
|
||||
}
|
||||
},
|
||||
"root": {
|
||||
"inputs": {
|
||||
"nixpkgs": "nixpkgs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"root": "root",
|
||||
"version": 7
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
# SPDX-License-Identifier: Unlicense
|
||||
{
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable";
|
||||
};
|
||||
|
||||
outputs = { nixpkgs, ... }:
|
||||
let
|
||||
eachSystem = f:
|
||||
nixpkgs.lib.genAttrs nixpkgs.lib.systems.flakeExposed (system: f nixpkgs.legacyPackages.${system});
|
||||
in
|
||||
{
|
||||
devShells = eachSystem (pkgs:
|
||||
let
|
||||
playwright-browsers = pkgs.playwright-driver.browsers.override {
|
||||
withFirefox = true;
|
||||
withWebkit = true;
|
||||
withFfmpeg = false;
|
||||
};
|
||||
in
|
||||
{
|
||||
default = pkgs.mkShell {
|
||||
packages = [
|
||||
pkgs.nodejs_22
|
||||
pkgs.pnpm
|
||||
pkgs.nodePackages.typescript
|
||||
pkgs.nodePackages.typescript-language-server
|
||||
playwright-browsers
|
||||
pkgs.playwright-test
|
||||
];
|
||||
|
||||
shellHook = ''
|
||||
export PLAYWRIGHT_NODEJS_PATH="${pkgs.nodejs_22}/bin/node";
|
||||
export PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
|
||||
export PLAYWRIGHT_BROWSERS_PATH="${playwright-browsers}"
|
||||
export PLAYWRIGHT_HOST_PLATFORM_OVERRIDE="ubuntu-24.04"
|
||||
'';
|
||||
};
|
||||
});
|
||||
};
|
||||
}
|
||||
@@ -1169,6 +1169,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 1 and 100
|
||||
angle-converter:
|
||||
title: Angle Units Converter
|
||||
description: Convert values between angle units
|
||||
|
||||
@@ -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 1 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 1 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-z$,]/g, ''));
|
||||
const sixthBalanceValue = Number.parseFloat(sixthBalance!.replace(/[A-z$,]/g, ''));
|
||||
const lastBalanceValue = Number.parseFloat(lastMonthBalance!.replace(/[A-z$,]/g, ''));
|
||||
|
||||
expect(firstBalanceValue).toBeGreaterThan(sixthBalanceValue);
|
||||
expect(sixthBalanceValue).toBeGreaterThan(lastBalanceValue);
|
||||
expect(lastBalanceValue).toBeCloseTo(0, 0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,489 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
AmortizationCalculator,
|
||||
type AmortizationParams,
|
||||
type CachedPaymentResults,
|
||||
type GetNthResult,
|
||||
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 = {
|
||||
principle: 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 = {
|
||||
principle: 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 = {
|
||||
principle: 12000,
|
||||
periodInterestRate: 0,
|
||||
numberOfPayments: 12,
|
||||
};
|
||||
|
||||
const result = calculator.getPayment(params);
|
||||
|
||||
// With 0% interest, payment should be principle / numberOfPayments
|
||||
expect(result.payment).toBe(1000);
|
||||
expect(result.totalPayments).toBe(12000);
|
||||
});
|
||||
|
||||
it('caches payment calculations', () => {
|
||||
const params: AmortizationParams = {
|
||||
principle: 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 = {
|
||||
principle: 100000,
|
||||
periodInterestRate: 0.005,
|
||||
numberOfPayments: 360,
|
||||
};
|
||||
|
||||
const params2: AmortizationParams = {
|
||||
principle: 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 = {
|
||||
principle: 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.principlePayment).toBeCloseTo(99.55, 2); // 599.55 - 500
|
||||
expect(result.remainingBalance).toBeCloseTo(99900.45, 2); // 100000 - 99.55
|
||||
|
||||
// Payment should equal principal + interest
|
||||
expect(result.principlePayment + result.interestPayment).toBeCloseTo(result.payment, 2);
|
||||
});
|
||||
|
||||
it('calculates correct values for middle payment', () => {
|
||||
const params: AmortizationParams = {
|
||||
principle: 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.principle);
|
||||
expect(result.principlePayment + result.interestPayment).toBeCloseTo(result.payment, 2);
|
||||
});
|
||||
|
||||
it('calculates correct values for final payment', () => {
|
||||
const params: AmortizationParams = {
|
||||
principle: 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.principlePayment + result.interestPayment).toBeCloseTo(result.payment, 2);
|
||||
});
|
||||
|
||||
it('shows increasing principal payment over time for standard amortization', () => {
|
||||
const params: AmortizationParams = {
|
||||
principle: 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.principlePayment).toBeLessThan(payment180.principlePayment);
|
||||
expect(payment180.principlePayment).toBeLessThan(payment360.principlePayment);
|
||||
});
|
||||
|
||||
it('shows decreasing interest payment over time', () => {
|
||||
const params: AmortizationParams = {
|
||||
principle: 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 = {
|
||||
principle: 12000,
|
||||
periodInterestRate: 0,
|
||||
numberOfPayments: 12,
|
||||
};
|
||||
|
||||
const result = calculator.getNth(params, 1);
|
||||
|
||||
expect(result.payment).toBe(1000);
|
||||
expect(result.interestPayment).toBe(0);
|
||||
expect(result.principlePayment).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getAmortizationSchedule', () => {
|
||||
it('generates complete amortization schedule with month and year rows', () => {
|
||||
const params: AmortizationParams = {
|
||||
principle: 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 = {
|
||||
principle: 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('principlePayment');
|
||||
expect(payment).toHaveProperty('interestPayment');
|
||||
expect(payment).toHaveProperty('remainingBalance');
|
||||
expect(payment).toHaveProperty('totalPayments');
|
||||
expect(payment).toHaveProperty('type');
|
||||
|
||||
expect(payment.paymentIndex).toBe(index + 1);
|
||||
expect(payment.principlePayment + payment.interestPayment).toBeCloseTo(payment.payment, 2);
|
||||
});
|
||||
});
|
||||
|
||||
it('shows decreasing remaining balance over time', () => {
|
||||
const params: AmortizationParams = {
|
||||
principle: 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 = {
|
||||
principle: 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 = {
|
||||
principle: 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 = {
|
||||
principle: 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 = {
|
||||
principle: 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 = {
|
||||
principle: 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 totalPrinciple = monthRows.reduce((sum, row) => sum + row.principlePayment, 0);
|
||||
const totalInterest = monthRows.reduce((sum, row) => sum + row.interestPayment, 0);
|
||||
|
||||
expect(yearRows[0].principlePayment).toBeCloseTo(totalPrinciple, 2);
|
||||
expect(yearRows[0].interestPayment).toBeCloseTo(totalInterest, 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('handles very small loan amounts', () => {
|
||||
const params: AmortizationParams = {
|
||||
principle: 100,
|
||||
periodInterestRate: 0.01,
|
||||
numberOfPayments: 12,
|
||||
};
|
||||
|
||||
const result = calculator.getPayment(params);
|
||||
expect(result.payment).toBeGreaterThan(0);
|
||||
expect(result.totalPayments).toBeGreaterThan(params.principle);
|
||||
});
|
||||
|
||||
it('handles very large loan amounts', () => {
|
||||
const params: AmortizationParams = {
|
||||
principle: 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 = {
|
||||
principle: 50000,
|
||||
periodInterestRate: 0.0001,
|
||||
numberOfPayments: 60,
|
||||
};
|
||||
|
||||
const result = calculator.getPayment(params);
|
||||
expect(result.payment).toBeGreaterThan(params.principle / params.numberOfPayments);
|
||||
});
|
||||
|
||||
it('handles short loan terms', () => {
|
||||
const params: AmortizationParams = {
|
||||
principle: 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 = {
|
||||
principle: 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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
export interface AmortizationParams {
|
||||
readonly principle: 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 principlePayment: number;
|
||||
readonly interestPayment: number;
|
||||
readonly remainingBalance: number;
|
||||
}
|
||||
|
||||
export interface AmortizationScheduleItem extends GetNthResult {
|
||||
readonly type: 'month' | 'year';
|
||||
}
|
||||
|
||||
type AmortizationPaymentCacheKey = `principle:${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<AmortizationScheduleItem> {
|
||||
let period = 0;
|
||||
let periodTotalPrinciple = 0;
|
||||
let periodTotalInterest = 0;
|
||||
|
||||
while (period < params.numberOfPayments) {
|
||||
const periodResults = this.getNth(params, ++period);
|
||||
|
||||
periodTotalPrinciple += periodResults.principlePayment;
|
||||
periodTotalInterest += periodResults.interestPayment;
|
||||
|
||||
yield {
|
||||
...periodResults,
|
||||
type: 'month',
|
||||
};
|
||||
|
||||
// Yield yearly totals at end of year
|
||||
if (period % 12 === 0) {
|
||||
yield {
|
||||
...periodResults,
|
||||
paymentIndex: period / 12,
|
||||
principlePayment: periodTotalPrinciple,
|
||||
interestPayment: periodTotalInterest,
|
||||
type: 'year',
|
||||
};
|
||||
|
||||
periodTotalPrinciple = 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;
|
||||
} else {
|
||||
return cache;
|
||||
}
|
||||
}
|
||||
|
||||
/** Private Methods */
|
||||
private paymentCache: Map<AmortizationPaymentCacheKey, CachedPaymentResults> = new Map();
|
||||
|
||||
private calculatePayment({ principle, periodInterestRate, numberOfPayments }: AmortizationParams): number {
|
||||
if (periodInterestRate === 0) {
|
||||
return principle / numberOfPayments;
|
||||
}
|
||||
|
||||
const numerator = periodInterestRate * (1 + periodInterestRate) ** numberOfPayments;
|
||||
const denominator = (1 + periodInterestRate) ** numberOfPayments - 1;
|
||||
|
||||
return principle * (numerator / denominator);
|
||||
}
|
||||
|
||||
private calculateTotalPayments({ numberOfPayments }: AmortizationParams, payment: number): number {
|
||||
return payment * numberOfPayments;
|
||||
}
|
||||
|
||||
private getCacheString({
|
||||
principle,
|
||||
periodInterestRate,
|
||||
numberOfPayments,
|
||||
}: AmortizationParams): AmortizationPaymentCacheKey {
|
||||
return `principle:${principle};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 { principle, periodInterestRate, numberOfPayments } = params;
|
||||
|
||||
if (periodInterestRate === 0) {
|
||||
const principlePayment = principle / numberOfPayments;
|
||||
const remainingBalance = principle - principlePayment * paymentIndex;
|
||||
|
||||
return {
|
||||
payment,
|
||||
totalPayments,
|
||||
remainingBalance: Math.max(0, remainingBalance),
|
||||
interestPayment: 0,
|
||||
principlePayment,
|
||||
paymentIndex,
|
||||
};
|
||||
}
|
||||
|
||||
const r = 1 + periodInterestRate;
|
||||
|
||||
const balanceBeforePayment =
|
||||
principle * r ** (paymentIndex - 1) - payment * ((r ** (paymentIndex - 1) - 1) / periodInterestRate);
|
||||
|
||||
const interestPayment = balanceBeforePayment * periodInterestRate;
|
||||
|
||||
const principlePayment = payment - interestPayment;
|
||||
|
||||
const remainingBalance = balanceBeforePayment - principlePayment;
|
||||
|
||||
return {
|
||||
payment,
|
||||
totalPayments,
|
||||
remainingBalance,
|
||||
interestPayment,
|
||||
principlePayment,
|
||||
paymentIndex,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<script setup lang="ts">
|
||||
import { useI18n } from 'vue-i18n';
|
||||
|
||||
import { AmortizationCalculator, StandardAmortizationCalculator } from './amortization-calculator.service';
|
||||
import { useQueryParamOrStorage } from '@/composable/queryParams';
|
||||
import { useValidation } from '@/composable/validation';
|
||||
|
||||
const { t, locale } = useI18n();
|
||||
|
||||
const amortizationCalculator = ref(new StandardAmortizationCalculator());
|
||||
|
||||
const currencyDisplayNames = computed(() => new Intl.DisplayNames(locale.value, { type: 'currency' }));
|
||||
|
||||
const supportedCurrencies = ref(
|
||||
Intl.supportedValuesOf('currency').map((value) => ({
|
||||
value,
|
||||
label: currencyDisplayNames.value.of(value),
|
||||
})),
|
||||
);
|
||||
|
||||
const selectedCurrency = useQueryParamOrStorage({
|
||||
name: 'selectedCurrency',
|
||||
storageName: 'amortization-calculator:selectedCurrency',
|
||||
defaultValue: 'USD',
|
||||
});
|
||||
|
||||
const loanAmount = useQueryParamOrStorage({
|
||||
name: 'amount',
|
||||
storageName: 'amortization-calculator:amount',
|
||||
defaultValue: '200000',
|
||||
});
|
||||
const loanAmountValidation = useValidation({
|
||||
source: loanAmount,
|
||||
rules: [
|
||||
{
|
||||
message: t('tools.amortization-calculator.texts.message-loan-amount-must-be-positive'),
|
||||
validator: AmortizationCalculator.validateLoanAmount,
|
||||
},
|
||||
],
|
||||
});
|
||||
const parsedLoanAmount = computed(() => Number(loanAmount.value));
|
||||
|
||||
const loanMonths = useQueryParamOrStorage({
|
||||
name: 'months',
|
||||
storageName: 'amortization-calculator:months',
|
||||
defaultValue: '360',
|
||||
});
|
||||
const loanMonthsValidation = useValidation({
|
||||
source: loanMonths,
|
||||
rules: [
|
||||
{
|
||||
message: t('tools.amortization-calculator.texts.message-loan-term-must-be-positive-integer'),
|
||||
validator: AmortizationCalculator.validateLoanMonths,
|
||||
},
|
||||
],
|
||||
});
|
||||
const parsedLoanMonths = computed(() => Number(loanMonths.value));
|
||||
|
||||
const interestRate = useQueryParamOrStorage({
|
||||
name: 'interestRate',
|
||||
storageName: 'amortization-calculator:interestRate',
|
||||
defaultValue: '6',
|
||||
});
|
||||
const interestRateValidation = useValidation({
|
||||
source: interestRate,
|
||||
rules: [
|
||||
{
|
||||
message: t('tools.amortization-calculator.texts.message-interest-rate-must-be-between-1-and-100'),
|
||||
validator: AmortizationCalculator.validateInterestRate,
|
||||
},
|
||||
],
|
||||
});
|
||||
const parsedInterestRate = computed(() => Number(interestRate.value));
|
||||
|
||||
const allValid = computed(
|
||||
() => interestRateValidation.isValid && loanMonthsValidation.isValid && loanAmountValidation.isValid,
|
||||
);
|
||||
|
||||
const payment = computed(() =>
|
||||
amortizationCalculator.value.getPayment({
|
||||
principle: parsedLoanAmount.value,
|
||||
periodInterestRate: parsedInterestRate.value / 1200,
|
||||
numberOfPayments: parsedLoanMonths.value,
|
||||
}),
|
||||
);
|
||||
|
||||
const amortizationSchedule = computed(() => {
|
||||
// Re-initialize generator when currency changes
|
||||
selectedCurrency.value;
|
||||
return amortizationCalculator.value.getAmortizationSchedule({
|
||||
principle: parsedLoanAmount.value,
|
||||
periodInterestRate: parsedInterestRate.value / 1200,
|
||||
numberOfPayments: parsedLoanMonths.value,
|
||||
});
|
||||
});
|
||||
|
||||
function formatCurrency(num: number): string {
|
||||
return num.toLocaleString(undefined, {
|
||||
style: 'currency',
|
||||
currency: selectedCurrency.value,
|
||||
// "negative" is a valid value for signDisplay and supported by all major browsers:
|
||||
// https://caniuse.com/mdn-javascript_builtins_intl_numberformat_numberformat_options_parameter_options_signdisplay_parameter_negative
|
||||
signDisplay: 'negative' as any,
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<c-card :title="t('tools.amortization-calculator.texts.title-loan-parameters')" mb-5>
|
||||
<c-input-text
|
||||
v-model:value="loanAmount"
|
||||
:placeholder="'e.g. 200000'"
|
||||
:label="t('tools.amortization-calculator.texts.label-loan-amount')"
|
||||
raw-text
|
||||
mb-5
|
||||
:validation="loanAmountValidation"
|
||||
/>
|
||||
|
||||
<c-input-text
|
||||
v-model:value="loanMonths"
|
||||
:placeholder="'e.g. 360'"
|
||||
:label="t('tools.amortization-calculator.texts.label-loan-term')"
|
||||
raw-text
|
||||
mb-5
|
||||
:validation="loanMonthsValidation"
|
||||
/>
|
||||
|
||||
<c-input-text
|
||||
v-model:value="interestRate"
|
||||
:placeholder="'e.g. 6.0'"
|
||||
:label="t('tools.amortization-calculator.texts.label-interest-rate')"
|
||||
raw-text
|
||||
mb-5
|
||||
:validation="interestRateValidation"
|
||||
/>
|
||||
|
||||
<c-select v-model:value="selectedCurrency" :options="supportedCurrencies" :label="t('tools.amortization-calculator.texts.label-displayed-currency')" mb-5 />
|
||||
</c-card>
|
||||
|
||||
<div v-if="allValid">
|
||||
<n-table mb-5>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{{ t('tools.amortization-calculator.texts.label-monthly-payment') }}</th>
|
||||
<th>{{ t('tools.amortization-calculator.texts.label-total-of-payments') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>
|
||||
{{ formatCurrency(payment.payment) }}
|
||||
</td>
|
||||
<td>
|
||||
{{ formatCurrency(payment.totalPayments) }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</n-table>
|
||||
<n-table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>{{ t('tools.amortization-calculator.texts.label-month') }}</th>
|
||||
<th>{{ t('tools.amortization-calculator.texts.label-interest') }}</th>
|
||||
<th>{{ t('tools.amortization-calculator.texts.label-principal') }}</th>
|
||||
<th>{{ t('tools.amortization-calculator.texts.label-ending-balance') }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="period in amortizationSchedule" :key="period.type + period.paymentIndex">
|
||||
<template v-if="period.type === 'month'">
|
||||
<td v-if="period.type === 'month'">{{ period.paymentIndex }}</td>
|
||||
<td>{{ formatCurrency(period.interestPayment) }}</td>
|
||||
<td>{{ formatCurrency(period.principlePayment) }}</td>
|
||||
<td>{{ formatCurrency(period.remainingBalance) }}</td>
|
||||
</template>
|
||||
<template v-else>
|
||||
<th>{{ t('tools.amortization-calculator.texts.label-end-of-year', { year: period.paymentIndex }) }}</th>
|
||||
<th>{{ formatCurrency(period.interestPayment) }}</th>
|
||||
<th>{{ formatCurrency(period.principlePayment) }}</th>
|
||||
<th>{{ formatCurrency(period.remainingBalance) }}</th>
|
||||
</template>
|
||||
</tr>
|
||||
</tbody>
|
||||
</n-table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style lang="less" scoped></style>
|
||||
@@ -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',
|
||||
});
|
||||
Reference in new issue
Block a user