# Product Requirements Document: Simple Loan Calculator

## 1. Overview

The Simple Loan Calculator is a single-page web application that enables users to calculate loan payments, total interest, and amortization schedules based on loan amount, interest rate, and loan term. The application provides instant calculations without requiring user authentication, offering a straightforward tool for individuals to evaluate loan scenarios and make informed borrowing decisions.

## 2. User Roles

### Anonymous User (Default)
- Access the loan calculator interface without authentication
- Input loan parameters (principal, interest rate, term)
- View calculated monthly payment amounts
- View total interest paid over loan term
- View total amount paid (principal + interest)
- View and download amortization schedule
- Reset calculator inputs
- Share calculation results via URL parameters (optional)

## 3. Core Entities

### LoanCalculation
**Description:** Represents a single loan calculation instance with input parameters and computed results.

**Attributes:**
- `id` (string, UUID): Unique identifier for the calculation
- `principal` (decimal): The loan amount borrowed
- `annualInterestRate` (decimal): Annual interest rate as a percentage
- `loanTermMonths` (integer): Duration of the loan in months
- `monthlyPayment` (decimal, calculated): Monthly payment amount
- `totalInterest` (decimal, calculated): Total interest paid over loan term
- `totalAmount` (decimal, calculated): Total amount paid (principal + interest)
- `createdAt` (timestamp): When the calculation was performed
- `calculationMethod` (string): Method used (e.g., "standard-amortization")

### AmortizationScheduleEntry
**Description:** Represents a single payment period in the loan amortization schedule.

**Attributes:**
- `id` (string, UUID): Unique identifier for the entry
- `loanCalculationId` (string, UUID): Reference to parent calculation
- `paymentNumber` (integer): Sequential payment number (1 to N)
- `paymentDate` (date): Scheduled payment date
- `beginningBalance` (decimal): Loan balance at start of period
- `paymentAmount` (decimal): Total payment for the period
- `principalPortion` (decimal): Amount applied to principal
- `interestPortion` (decimal): Amount applied to interest
- `endingBalance` (decimal): Loan balance at end of period
- `cumulativeInterest` (decimal): Total interest paid to date
- `cumulativePrincipal` (decimal): Total principal paid to date

### CalculationSession (Optional)
**Description:** Tracks user session for analytics and temporary storage.

**Attributes:**
- `sessionId` (string, UUID): Unique session identifier
- `createdAt` (timestamp): Session start time
- `lastActivityAt` (timestamp): Last interaction time
- `calculationCount` (integer): Number of calculations performed in session
- `userAgent` (string): Browser/device information

## 4. Entity Relationships

### LoanCalculation ↔ AmortizationScheduleEntry
- **Relationship Type:** One-to-Many
- **Description:** One LoanCalculation has many AmortizationScheduleEntries (one per payment period)
- **Cardinality:** 1 LoanCalculation : N AmortizationScheduleEntries (where N = loanTermMonths)
- **Cascade Behavior:** Deleting a LoanCalculation deletes all associated AmortizationScheduleEntries

### CalculationSession ↔ LoanCalculation
- **Relationship Type:** One-to-Many (Optional)
- **Description:** One session may contain multiple calculations
- **Cardinality:** 1 CalculationSession : N LoanCalculations
- **Cascade Behavior:** Session deletion does not affect calculations (soft reference)

## 5. Key Workflows

### Workflow 1: Perform Loan Calculation

**Actors:** Anonymous User

**Steps:**
1. User navigates to the loan calculator page
2. System displays default input form with empty/default values
3. User enters loan principal amount
4. User enters annual interest rate (as percentage)
5. User enters loan term (in months or years, converted to months)
6. System validates inputs in real-time:
   - Principal > 0
   - Interest rate ≥ 0 and < 100
   - Loan term > 0 and ≤ 600 months (50 years)
7. User clicks "Calculate" button (or calculation triggers automatically)
8. System performs calculation:
   - Calculate monthly interest rate (annual rate / 12 / 100)
   - Calculate monthly payment using amortization formula
   - Calculate total amount paid (monthly payment × term)
   - Calculate total interest (total amount - principal)
9. System displays results:
   - Monthly payment amount
   - Total interest paid
   - Total amount paid
10. System generates amortization schedule
11. System displays amortization schedule in table format
12. Workflow ends

**Alternative Flows:**
- **3a.** If validation fails, display error message and prevent calculation
- **7a.** If auto-calculate enabled, trigger calculation on input change with debounce

### Workflow 2: View Amortization Schedule

**Actors:** Anonymous User

**Preconditions:** Loan calculation has been performed

**Steps:**
1. User views calculation results
2. System displays "View Amortization Schedule" option
3. User clicks to expand/view schedule
4. System generates complete amortization schedule:
   - For each payment period (1 to N):
     - Calculate beginning balance
     - Calculate interest portion (balance × monthly rate)
     - Calculate principal portion (payment - interest)
     - Calculate ending balance (beginning balance - principal)
     - Track cumulative totals
5. System displays schedule in tabular format with columns:
   - Payment #
   - Payment Date (optional)
   - Beginning Balance
   - Payment Amount
   - Principal
   - Interest
   - Ending Balance
   - Cumulative Interest
6. User can scroll through all payment periods
7. Workflow ends

### Workflow 3: Reset Calculator

**Actors:** Anonymous User

**Steps:**
1. User clicks "Reset" or "Clear" button
2. System clears all input fields
3. System clears all calculated results
4. System hides amortization schedule
5. System returns to initial state
6. Workflow ends

### Workflow 4: Export/Download Results (Optional)

**Actors:** Anonymous User

**Preconditions:** Loan calculation has been performed

**Steps:**
1. User clicks "Download" or "Export" button
2. System prompts for export format (CSV, PDF, or Print)
3. User selects format
4. System generates export file containing:
   - Input parameters
   - Summary results
   - Complete amortization schedule
5. System initiates download or print dialog
6. Workflow ends

## 6. Features & Requirements

### 6.1 Input Module

**FR-1.1:** Display input form with three required fields:
- Loan Amount (Principal)
- Annual Interest Rate (%)
- Loan Term

**FR-1.2:** Support loan term input in both months and years with toggle/dropdown

**FR-1.3:** Provide clear labels and placeholder text for each input field

**FR-1.4:** Implement real-time input validation with inline error messages

**FR-1.5:** Support numeric input with appropriate formatting (currency for principal, percentage for rate)

**FR-1.6:** Allow decimal values for all inputs (e.g., 5.25% interest rate)

**FR-1.7:** Provide input field focus states and keyboard navigation support

**FR-1.8:** Display input constraints/hints (e.g., "Maximum 50 years")

### 6.2 Calculation Engine Module

**FR-2.1:** Implement standard amortization formula for monthly payment calculation:
```
M = P × [r(1 + r)^n] / [(1 + r)^n - 1]
Where:
M = Monthly payment
P = Principal loan amount
r = Monthly interest rate (annual rate / 12 / 100)
n = Number of payments (loan term in months)
```

**FR-2.2:** Handle edge case where interest rate = 0:
```
M = P / n
```

**FR-2.3:** Calculate total interest paid: `(M × n) - P`

**FR-2.4:** Calculate total amount paid: `M × n`

**FR-2.5:** Generate complete amortization schedule with period-by-period breakdown

**FR-2.6:** Round all monetary values to 2 decimal places

**FR-2.7:** Perform calculations with high precision (use decimal/BigDecimal types)

**FR-2.8:** Support instant recalculation when inputs change (with debounce)

### 6.3 Results Display Module

**FR-3.1:** Display monthly payment amount prominently with currency formatting

**FR-3.2:** Display total interest paid with currency formatting

**FR-3.3:** Display total amount paid with currency formatting

**FR-3.4:** Show visual distinction between calculated results and input fields

**FR-3.5:** Display results in a summary card/panel

**FR-3.6:** Use appropriate typography hierarchy for readability

**FR-3.7:** Show calculation timestamp (optional)

**FR-3.8:** Provide visual feedback during calculation (loading state)

### 6.4 Amortization Schedule Module

**FR-4.1:** Generate complete amortization schedule table with columns:
- Payment Number
- Beginning Balance
- Payment Amount
- Principal Portion
- Interest Portion
- Ending Balance
- Cumulative Interest (optional)
- Cumulative Principal (optional)

**FR-4.2:** Display schedule in scrollable table format

**FR-4.3:** Support table sorting by column (optional)

**FR-4.4:** Highlight key milestones (e.g., halfway point, when principal > interest)

**FR-4.5:** Show payment dates based on assumed start date (optional)

**FR-4.6:** Provide collapsible/expandable schedule view

**FR-4.7:** Format all monetary values with currency symbols and thousand separators

**FR-4.8:** Support responsive table design for mobile devices

### 6.5 User Interface Module

**FR-5.1:** Implement single-page layout with all features visible/accessible

**FR-5.2:** Use responsive design supporting desktop, tablet, and mobile viewports

**FR-5.3:** Provide "Calculate" button to trigger calculation

**FR-5.4:** Provide "Reset" button to clear all inputs and results

**FR-5.5:** Implement clean, professional visual design

**FR-5.6:** Use consistent color scheme and branding

**FR-5.7:** Ensure sufficient color contrast for accessibility

**FR-5.8:** Display application title/header

**FR-5.9:** Include brief instructions or help text (optional)

**FR-5.10:** Show currency selector (USD default, support multiple currencies - optional)

### 6.6 Export/Share Module (Optional)

**FR-6.1:** Provide "Download CSV" option for amortization schedule

**FR-6.2:** Provide "Print" option for results and schedule

**FR-6.3:** Generate PDF export of complete calculation (optional)

**FR-6.4:** Support URL parameter encoding of inputs for sharing (optional)

**FR-6.5:** Provide "Copy Link" functionality to share calculation (optional)

### 6.7 Analytics Module (Optional)

**FR-7.1:** Track number of calculations performed

**FR-7.2:** Track average loan amounts calculated

**FR-7.3:** Track session duration and engagement

**FR-7.4:** Log calculation parameters for analytics (anonymized)

## 7. Business Rules

### BR-1: Input Validation Rules

**BR-1.1:** Loan principal must be greater than 0 and less than or equal to 1,000,000,000

**BR-1.2:** Annual interest rate must be greater than or equal to 0 and less than 100

**BR-1.3:** Loan term must be greater than 0 and less than or equal to 600 months (50 years)

**BR-1.4:** All numeric inputs must be valid numbers (reject non-numeric characters except decimal point)

**BR-1.5:** Interest rate of 0% is valid (represents interest-free loan)

### BR-2: Calculation Rules

**BR-2.1:** Monthly payment must be calculated using standard amortization formula

**BR-2.2:** All monetary calculations must use decimal precision (minimum 4 decimal places internally)

**BR-2.3:** All displayed monetary values must be rounded to 2 decimal places

**BR-2.4:** Final payment may be adjusted to account for rounding differences (ensure ending balance = 0)

**BR-2.5:** Amortization schedule must account for all principal and interest exactly

**BR-2.6:** Sum of all principal portions must equal original loan amount

**BR-2.7:** Sum of all interest portions must equal total interest calculated

### BR-3: Display Rules

**BR-3.1:** Currency values must display with appropriate currency symbol ($ for USD)

**BR-3.2:** Large numbers must include thousand separators (e.g., 1,000,000.00)

**BR-3.3:** Percentages must display with % symbol

**BR-3.4:** Negative values are not permitted in any calculation result

**BR-3.5:** Results must not display until valid inputs are provided and calculation is performed

### BR-4: Data Persistence Rules

**BR-4.1:** No user authentication or data persistence is required

**BR-4.2:** Calculations may be stored temporarily for session continuity (optional)

**BR-4.3:** No personally identifiable information (PII) should be collected

**BR-4.4:** Session data may be stored for analytics purposes (anonymized)

### BR-5: Amortization Schedule Rules

**BR-5.1:** Schedule must contain exactly N entries where N = loan term in months

**BR-5.2:** First payment beginning balance must equal loan principal

**BR-5.3:** Last payment ending balance must equal 0 (or within $0.01 due to rounding)

**BR-5.4:** Each period's ending balance must equal next period's beginning balance

**BR-5.5:** Interest portion for each period = beginning balance × monthly interest rate

**BR-5.6:** Principal portion for each period = payment amount - interest portion

**BR-5.7:** For 0% interest rate, all payments are principal only

## 8. Non-Functional Requirements

### NFR-1: Performance

**NFR-1.1:** Calculation must complete within 100ms for loan terms up to 600 months

**NFR-1.2:** Page load time must be under 2 seconds on standard broadband connection

**NFR-1.3:** Amortization schedule generation must complete within 500ms for 600 payment periods

**NFR-1.4:** UI must remain responsive during calculations (no blocking operations)

**NFR-1.5:** Support debounced auto-calculation with 300ms delay after input change

### NFR-2: Scalability

**NFR-2.1:** Application must support 1,000 concurrent users

**NFR-2.2:** System must handle 10,000 calculations per day

**NFR-2.3:** Client-side calculation preferred to minimize server load

**NFR-2.4:** Stateless architecture to support horizontal scaling (if server-side calculation used)

### NFR-3: Security

**NFR-3.1:** All inputs must be sanitized to prevent XSS attacks

**NFR-3.2:** Implement HTTPS for all connections

**NFR-3.3:** No sensitive data storage required (no authentication)

**NFR-3.4:** Implement rate limiting to prevent abuse (100 requests per minute per IP)

**NFR-3.5:** Validate all inputs server-side if server-side calculation is used

**NFR-3.6:** Implement CORS policy appropriately

**NFR-3.7:** Set appropriate security headers (CSP, X-Frame-Options, etc.)

### NFR-4: Usability

**NFR-4.1:** Interface must be intuitive requiring no training or documentation

**NFR-4.2:** Error messages must be clear and actionable

**NFR-4.3:** Support keyboard navigation for all interactive elements

**NFR-4.4:** Provide visual feedback for all user actions (button clicks, input changes)

**NFR-4.5:** Use consistent UI patterns and conventions

**NFR-4.6:** Support browser back/forward navigation without data loss (optional)

### NFR-5: Accessibility

**NFR-5.1:** Comply with WCAG 2.1 Level AA standards

**NFR-5.2:** Support screen readers with appropriate ARIA labels

**NFR-5.3:** Ensure minimum color contrast ratio of 4.5:1 for text

**NFR-5.4:** Support keyboard-only navigation

**NFR-5.5:** Provide text alternatives for all non-text content

**NFR-5.6:** Ensure form inputs have associated labels

**NFR-5.7:** Support browser zoom up to 200% without loss of functionality

### NFR-6: Compatibility

**NFR-6.1:** Support modern browsers: Chrome (last 2 versions), Firefox (last 2 versions), Safari (last 2 versions), Edge (last 2 versions)

**NFR-6.2:** Support mobile browsers: iOS Safari, Chrome Mobile, Samsung Internet

**NFR-6.3:** Responsive design supporting viewports from 320px to 2560px width

**NFR-6.4:** Graceful degradation for older browsers (display message if unsupported)

**NFR-6.5:** Support both portrait and landscape orientations on mobile devices

### NFR-7: Maintainability

**NFR-7.1:** Code must be well-documented with inline comments

**NFR-7.2:** Use modular architecture with separation of concerns

**NFR-7.3:** Implement comprehensive unit tests for calculation logic (90% coverage minimum)

**NFR-7.4:** Use version control (Git) with clear commit messages

**NFR-7.5:** Follow consistent coding standards and style guide

**NFR-7.6:** Implement error logging and monitoring

### NFR-8: Reliability

**NFR-8.1:** Application must have 99.9% uptime

**NFR-8.2:** Graceful error handling with user-friendly error messages

**NFR-8.3:** No data loss during calculation or navigation

**NFR-8.4:** Automatic recovery from transient errors

**NFR-8.5:** Calculation accuracy must be within $0.01 of mathematically correct value

### NFR-9: Localization (Optional)

**NFR-9.1:** Support multiple currencies (USD, EUR, GBP, etc.)

**NFR-9.2:** Support locale-specific number formatting

**NFR-9.3:** Support multiple languages (English default)

**NFR-9.4:** Allow currency symbol customization

### NFR-10: Analytics & Monitoring

**NFR-10.1:** Track page views and unique visitors

**NFR-10.2:** Monitor calculation success/failure rates

**NFR-10.3:** Track average calculation parameters

**NFR-10.4:** Monitor application errors and exceptions

**NFR-10.5:** Track performance metrics (load time, calculation time)

**NFR-10.6:** Implement privacy-compliant analytics (no PII tracking)

---

## Appendix A: Calculation Formula Reference

### Standard Amortization Formula

```
Monthly Payment (M) = P × [r(1 + r)^n] / [(1 + r)^n - 1]

Where:
- P = Principal (loan amount)
- r = Monthly interest rate (annual rate / 12 / 100)
- n = Total number of payments (loan term in months)
```

### Special Case: Zero Interest Rate

```
Monthly Payment (M) = P / n
```

### Amortization Schedule Calculations (per period)

```
Interest Portion = Beginning Balance × Monthly Interest Rate
Principal Portion = Monthly Payment - Interest Portion
Ending Balance = Beginning Balance - Principal Portion
```

## Appendix B: Example Calculation

**Inputs:**
- Loan Amount: $200,000
- Annual Interest Rate: 4.5%
- Loan Term: 360 months (30 years)

**Calculations:**
- Monthly Interest Rate: 4.5 / 12 / 100 = 0.00375
- Monthly Payment: $1,013.37
- Total Amount Paid: $364,813.42
- Total Interest Paid: $164,813.42

---

**Document Version:** 1.0  
**Last Updated:** 2025-01-10  
**Author:** Senior Product Manager  
**Status:** Ready for Development