# 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 estimate their loan obligations and compare different loan scenarios.

## 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 amortization schedule breakdown
- Reset calculator inputs
- Print or export calculation results

## 3. Core Entities

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

**Attributes:**
- `id` (UUID): Unique identifier for the calculation
- `principal` (Decimal): Loan amount borrowed
- `annualInterestRate` (Decimal): Annual interest rate as percentage
- `loanTermMonths` (Integer): Duration of loan in months
- `monthlyPayment` (Decimal): Calculated monthly payment amount
- `totalInterest` (Decimal): Total interest paid over loan term
- `totalAmount` (Decimal): Total amount paid (principal + interest)
- `createdAt` (Timestamp): When calculation was performed
- `sessionId` (String): Browser session identifier for tracking

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

**Attributes:**
- `id` (UUID): Unique identifier for the entry
- `calculationId` (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
**Description:** Tracks user sessions for analytics and usage patterns.

**Attributes:**
- `sessionId` (UUID): Unique session identifier
- `firstAccessAt` (Timestamp): When session started
- `lastAccessAt` (Timestamp): Most recent activity
- `calculationCount` (Integer): Number of calculations performed
- `userAgent` (String): Browser/device information
- `ipAddress` (String): User IP address (anonymized)

## 4. Entity Relationships

### Calculation ↔ AmortizationEntry
- **Relationship Type:** One-to-Many
- **Description:** One Calculation has many AmortizationEntry records (one per payment period)
- **Cardinality:** 1 Calculation : N AmortizationEntries (where N = loanTermMonths)
- **Foreign Key:** `AmortizationEntry.calculationId` references `Calculation.id`
- **Cascade Behavior:** Deleting a Calculation deletes all associated AmortizationEntry records

### CalculationSession ↔ Calculation
- **Relationship Type:** One-to-Many
- **Description:** One CalculationSession can have multiple Calculation records
- **Cardinality:** 1 CalculationSession : N Calculations
- **Foreign Key:** `Calculation.sessionId` references `CalculationSession.sessionId`
- **Cascade Behavior:** Deleting a CalculationSession deletes all associated Calculation records

## 5. Key Workflows

### Workflow 1: Perform Loan Calculation

**Actors:** Anonymous User

**Steps:**
1. User navigates to the application URL
2. System displays calculator interface with empty input fields
3. User enters loan principal amount
4. User enters annual interest rate (as percentage)
5. User enters loan term (in months or years)
6. System validates all inputs in real-time
7. User clicks "Calculate" button
8. System performs calculation using loan payment formula
9. System generates amortization schedule for entire loan term
10. System creates Calculation entity and associated AmortizationEntry records
11. System displays results:
    - Monthly payment amount
    - Total interest paid
    - Total amount paid
    - Summary statistics
12. System displays amortization schedule table (optional expanded view)
13. User can modify inputs to perform new calculation (returns to step 3)

### Workflow 2: View Amortization Schedule

**Actors:** Anonymous User

**Prerequisites:** Calculation has been performed

**Steps:**
1. User views calculation results summary
2. User clicks "View Amortization Schedule" button/link
3. System displays full amortization table with columns:
   - Payment number
   - Payment date
   - Payment amount
   - Principal portion
   - Interest portion
   - Remaining balance
4. User can scroll through all payment periods
5. User can collapse schedule to return to summary view

### Workflow 3: Reset Calculator

**Actors:** Anonymous User

**Steps:**
1. User clicks "Reset" or "Clear" button
2. System clears all input fields
3. System hides calculation results
4. System returns calculator to initial empty state
5. User can begin new calculation

### Workflow 4: Export/Print Results

**Actors:** Anonymous User

**Prerequisites:** Calculation has been performed

**Steps:**
1. User clicks "Print" or "Export" button
2. System formats calculation results and amortization schedule for printing
3. System opens browser print dialog OR generates PDF/CSV file
4. User completes print/download action
5. System returns to calculator view

## 6. Features & Requirements

### 6.1 Calculator Input Module

**FR-1.1:** Display input field for loan principal amount
- Label: "Loan Amount" or "Principal"
- Input type: Numeric
- Currency formatting with $ symbol
- Placeholder: "$0.00"

**FR-1.2:** Display input field for annual interest rate
- Label: "Annual Interest Rate"
- Input type: Numeric
- Percentage symbol (%)
- Placeholder: "0.00%"
- Support decimal values (e.g., 4.25%)

**FR-1.3:** Display input field for loan term
- Label: "Loan Term"
- Input type: Numeric
- Toggle between months/years
- Default: Years
- Conversion between months and years

**FR-1.4:** Provide "Calculate" button
- Prominent call-to-action styling
- Disabled state when inputs are invalid
- Enabled when all required fields are valid

**FR-1.5:** Provide "Reset" button
- Secondary styling
- Clears all inputs and results
- Always enabled

**FR-1.6:** Real-time input validation
- Display validation errors inline
- Prevent invalid characters
- Show helpful error messages

### 6.2 Calculation Engine Module

**FR-2.1:** Calculate monthly payment using standard amortization formula
- Formula: M = P [ i(1 + i)^n ] / [ (1 + i)^n – 1 ]
  - M = Monthly payment
  - P = Principal loan amount
  - i = Monthly interest rate (annual rate / 12)
  - n = Number of payments (loan term in months)

**FR-2.2:** Calculate total interest paid
- Formula: Total Interest = (Monthly Payment × Number of Payments) - Principal

**FR-2.3:** Calculate total amount paid
- Formula: Total Amount = Monthly Payment × Number of Payments

**FR-2.4:** Generate complete amortization schedule
- Calculate for each payment period:
  - Interest portion = Beginning Balance × Monthly Interest Rate
  - Principal portion = Monthly Payment - Interest Portion
  - Ending Balance = Beginning Balance - Principal Portion
- Track cumulative totals

**FR-2.5:** Handle edge cases
- Zero interest rate (simple division)
- Very long loan terms (30+ years)
- Very high interest rates
- Rounding to 2 decimal places for currency

### 6.3 Results Display Module

**FR-3.1:** Display monthly payment amount
- Large, prominent display
- Currency formatting
- Label: "Monthly Payment"

**FR-3.2:** Display total interest paid
- Currency formatting
- Label: "Total Interest Paid"
- Visual indicator (color coding)

**FR-3.3:** Display total amount paid
- Currency formatting
- Label: "Total Amount Paid"
- Breakdown showing principal + interest

**FR-3.4:** Display loan summary statistics
- Loan amount (principal)
- Interest rate
- Loan term
- Number of payments
- First payment date (estimated)
- Final payment date (estimated)

**FR-3.5:** Visual representation of loan breakdown
- Pie chart or bar chart showing principal vs. interest
- Optional: Payment breakdown over time graph

### 6.4 Amortization Schedule Module

**FR-4.1:** Display amortization schedule table
- Columns: Payment #, Date, Payment Amount, Principal, Interest, Balance
- Sortable columns
- Responsive design for mobile devices

**FR-4.2:** Collapsible/expandable schedule view
- Default: Collapsed (show summary only)
- Expand to show full schedule
- Smooth transition animation

**FR-4.3:** Pagination or virtual scrolling for long schedules
- Display 12-24 rows per page
- Navigation controls
- Jump to specific year

**FR-4.4:** Highlight key milestones
- First payment
- Halfway point
- Final payment
- When principal paid exceeds interest paid

**FR-4.5:** Summary rows
- Total row at bottom
- Yearly subtotals (optional)

### 6.5 Export/Print Module

**FR-5.1:** Print functionality
- Print-optimized layout
- Include all calculation inputs and results
- Include full amortization schedule
- Remove navigation and interactive elements

**FR-5.2:** Export to PDF
- Generate PDF with calculation results
- Include amortization schedule
- Professional formatting

**FR-5.3:** Export to CSV
- Export amortization schedule as CSV file
- Include headers
- Proper formatting for spreadsheet import

**FR-5.4:** Copy to clipboard
- Copy calculation summary
- Copy amortization schedule data

### 6.6 User Interface Module

**FR-6.1:** Responsive design
- Mobile-first approach
- Tablet optimization
- Desktop layout
- Touch-friendly controls

**FR-6.2:** Accessibility compliance
- WCAG 2.1 AA compliance
- Keyboard navigation
- Screen reader support
- Proper ARIA labels
- Sufficient color contrast

**FR-6.3:** Loading states
- Show calculation in progress
- Disable inputs during calculation
- Smooth transitions

**FR-6.4:** Error handling
- Display user-friendly error messages
- Graceful degradation
- Retry mechanisms

**FR-6.5:** Help/Information
- Tooltips explaining each field
- Information icon with calculation methodology
- Example calculations
- FAQ section (optional)

### 6.7 Analytics Module (Backend)

**FR-7.1:** Track calculation events
- Number of calculations performed
- Average loan amounts
- Average interest rates
- Average loan terms

**FR-7.2:** Track session information
- Session duration
- Number of calculations per session
- Device/browser information

**FR-7.3:** Privacy-compliant tracking
- No personally identifiable information
- Anonymized IP addresses
- GDPR compliance

## 7. Business Rules

### BR-1: Input Validation Rules

**BR-1.1:** Loan Principal
- Minimum: $1.00
- Maximum: $100,000,000.00
- Must be positive number
- Must be numeric value
- Round to 2 decimal places

**BR-1.2:** Annual Interest Rate
- Minimum: 0.00%
- Maximum: 99.99%
- Must be non-negative number
- Support up to 4 decimal places (e.g., 4.2500%)
- Display as percentage

**BR-1.3:** Loan Term
- Minimum: 1 month
- Maximum: 600 months (50 years)
- Must be positive integer
- When entering years: convert to months (multiply by 12)
- When entering months: must be whole number

### BR-2: Calculation Rules

**BR-2.1:** Monthly Payment Calculation
- Use standard amortization formula
- Round result to 2 decimal places
- If interest rate is 0%, monthly payment = principal / number of months

**BR-2.2:** Amortization Schedule Generation
- Generate exactly N entries where N = loan term in months
- First payment date = 30 days from current date (estimated)
- Subsequent payments = 30 days apart
- Final payment may be adjusted for rounding differences (within $1.00)

**BR-2.3:** Interest Calculation
- Monthly interest rate = Annual rate / 12 / 100
- Interest for each period = Beginning balance × Monthly interest rate
- Round each calculation to 2 decimal places

**BR-2.4:** Rounding Rules
- All currency values rounded to 2 decimal places
- Use banker's rounding (round half to even)
- Final payment adjusted to ensure balance reaches exactly $0.00

### BR-3: Display Rules

**BR-3.1:** Currency Formatting
- Display with $ symbol
- Thousand separators (commas)
- Two decimal places
- Example: $1,234.56

**BR-3.2:** Percentage Formatting
- Display with % symbol
- Two decimal places minimum
- Example: 4.25%

**BR-3.3:** Date Formatting
- Display as MM/DD/YYYY or based on locale
- Use consistent format throughout application

### BR-4: Data Retention Rules

**BR-4.1:** Calculation Storage
- Store calculations for analytics purposes
- No user authentication required
- Associate with anonymous session ID
- Retain for 90 days maximum

**BR-4.2:** Session Management
- Create session on first visit
- Session expires after 24 hours of inactivity
- No sensitive data stored in session

### BR-5: Performance Rules

**BR-5.1:** Calculation Performance
- Calculations must complete within 500ms
- Amortization schedule generation must complete within 1 second
- UI must remain responsive during calculations

**BR-5.2:** Page Load Performance
- Initial page load under 2 seconds
- Time to interactive under 3 seconds

## 8. Non-Functional Requirements

### 8.1 Performance

**NFR-1.1:** Response Time
- Page load time: < 2 seconds on 3G connection
- Calculation execution: < 500ms for standard loans
- Amortization schedule generation: < 1 second for 360-month loan
- API response time: < 200ms (95th percentile)

**NFR-1.2:** Throughput
- Support 100 concurrent users minimum
- Handle 1,000 calculations per hour
- No degradation with multiple simultaneous calculations

**NFR-1.3:** Resource Usage
- Client-side memory usage: < 50MB
- Minimal CPU usage on client device
- Efficient rendering for large amortization tables

### 8.2 Scalability

**NFR-2.1:** Horizontal Scaling
- Stateless application design
- Support load balancing across multiple instances
- Database connection pooling

**NFR-2.2:** Data Scaling
- Support storage of 1M+ calculation records
- Efficient querying for analytics
- Automatic data archival after retention period

### 8.3 Security

**NFR-3.1:** Data Protection
- HTTPS/TLS encryption for all communications
- No storage of personally identifiable information
- Secure session management
- Input sanitization to prevent injection attacks

**NFR-3.2:** Application Security
- Protection against XSS attacks
- CSRF protection
- Rate limiting to prevent abuse (100 requests per minute per IP)
- Content Security Policy headers

**NFR-3.3:** Privacy
- GDPR compliance
- No tracking cookies without consent
- Anonymized analytics data
- Clear privacy policy

### 8.4 Reliability

**NFR-4.1:** Availability
- 99.5% uptime target
- Graceful degradation if backend unavailable
- Client-side calculation fallback

**NFR-4.2:** Error Handling
- Comprehensive error logging
- User-friendly error messages
- Automatic error reporting
- No data loss on errors

**NFR-4.3:** Data Integrity
- Accurate calculations (validated against known test cases)
- Consistent rounding
- Amortization schedule balances to zero

### 8.5 Usability

**NFR-5.1:** User Experience
- Intuitive interface requiring no training
- Clear labeling and instructions
- Immediate feedback on user actions
- Mobile-friendly touch targets (minimum 44×44 pixels)

**NFR-5.2:** Accessibility
- WCAG 2.1 Level AA compliance
- Keyboard navigation support
- Screen reader compatibility
- Minimum contrast ratio 4.5:1 for text
- Focus indicators visible
- Alt text for all images

**NFR-5.3:** Browser Compatibility
- Support latest 2 versions of Chrome, Firefox, Safari, Edge
- Graceful degradation for older browsers
- Mobile browser support (iOS Safari, Chrome Mobile)

### 8.6 Maintainability

**NFR-6.1:** Code Quality
- Modular, well-documented code
- Unit test coverage > 80%
- Integration tests for key workflows
- Automated testing in CI/CD pipeline

**NFR-6.2:** Monitoring
- Application performance monitoring
- Error tracking and alerting
- Usage analytics dashboard
- Server health monitoring

**NFR-6.3:** Deployment
- Automated deployment process
- Zero-downtime deployments
- Easy rollback capability
- Environment parity (dev/staging/production)

### 8.7 Localization

**NFR-7.1:** Internationalization Support
- Support for multiple currencies (future)
- Support for different date formats
- Decimal separator based on locale
- Thousand separator based on locale

**NFR-7.2:** Language Support
- English (initial release)
- Framework for additional languages (future)

### 8.8 Compliance

**NFR-8.1:** Legal Compliance
- GDPR compliance for EU users
- CCPA compliance for California users
- Disclaimer that calculations are estimates
- No financial advice provided

**NFR-8.2:** Accuracy Standards
- Calculations accurate to 2 decimal places
- Validated against industry-standard loan calculators
- Documented calculation methodology

---

## Appendix A: Calculation Formulas

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

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

Special case: If i = 0, then M = P / n
```

### Amortization Schedule Formulas
```
For each payment period k (where k = 1 to n):

Interest_k = Balance_(k-1) × i
Principal_k = M - Interest_k
Balance_k = Balance_(k-1) - Principal_k

Where:
Balance_0 = P (initial loan amount)
Balance_n = 0 (final balance)
```

## Appendix B: Example Test Cases

### Test Case 1: Standard 30-Year Mortgage
- Principal: $300,000
- Annual Interest Rate: 4.5%
- Loan Term: 30 years (360 months)
- Expected Monthly Payment: $1,520.06
- Expected Total Interest: $247,220.13
- Expected Total Amount: $547,220.13

### Test Case 2: Auto Loan
- Principal: $25,000
- Annual Interest Rate: 6.0%
- Loan Term: 5 years (60 months)
- Expected Monthly Payment: $483.32
- Expected Total Interest: $3,999.20
- Expected Total Amount: $28,999.20

### Test Case 3: Zero Interest
- Principal: $10,000
- Annual Interest Rate: 0.0%
- Loan Term: 12 months
- Expected Monthly Payment: $833.33
- Expected Total Interest: $0.00
- Expected Total Amount: $10,000.00

---

**Document Version:** 1.0  
**Last Updated:** 2025  
**Document Owner:** Product Management  
**Status:** Final