# Backend Specification

## 1. System Summary

**System Name:** Simple Loan Calculator

**Description:** A single-page web application that calculates monthly payments, total interest, and amortization schedules for loans based on user-provided parameters. The system enables anonymous users to perform loan calculations with comprehensive amortization breakdowns, view detailed payment schedules, and export results. The application provides configurable default values and display preferences to enhance the user experience.

**Primary Use Cases:**
- Perform loan calculations with custom parameters (principal, interest rate, term)
- Generate detailed amortization schedules showing payment breakdowns
- View and export calculation results and payment schedules
- Configure default calculator settings and display preferences

## 2. Source Input Summary

This backend specification is generated from:

- **DDL Schema File:** `/home/ubuntu/dpg/pipeline/step-02-prd-generation/output/simple_loa_042319/schema.sql`
  - Contains three tables: `calculation_settings`, `loan_calculations`, `amortization_entries`
  - Defines database structure with UUID primary keys, foreign key relationships, and appropriate data types for financial calculations

- **PRD File:** `/home/ubuntu/dpg/pipeline/step-02-prd-generation/output/simple_loa_042319/full_prd.md`
  - Comprehensive product requirements detailing a client-side loan calculator
  - Specifies amortization schedule generation, validation requirements, and export capabilities
  - Defines business rules for loan calculations and data formatting

## 3. Generation Mode

**Mode:** `strict`

The backend will strictly adhere to the entities, fields, relationships, and business rules defined in the source DDL schema and PRD. No additional entities or fields will be introduced beyond those explicitly specified. All API endpoints and business logic will implement only the functionality documented in the source materials.

## 4. Backend Scope

The backend provides:

1. **Calculation Management Module**
   - CRUD operations for calculation settings (default values and display preferences)
   - CRUD operations for loan calculations (input parameters and computed results)
   - CRUD operations for amortization entries (monthly payment breakdowns)
   - Specialized endpoints for loan calculation execution with amortization generation
   - Detail retrieval endpoints with eager loading of related entities

2. **Core Capabilities**
   - Loan payment calculation using standard amortization formulas
   - Amortization schedule generation with per-month breakdowns
   - Transaction-safe batch creation of calculations with associated entries
   - Retrieval of default settings for calculator initialization
   - Filtering and querying of amortization entries by calculation

3. **Data Persistence**
   - SQLite database for storing calculation settings, loan calculations, and amortization schedules
   - Transactional integrity for batch operations
   - Timestamp tracking for audit trails

## 5. Roles

The system supports a single role:

| Role | Description | Permissions |
|------|-------------|-------------|
| Anonymous User | Any user accessing the loan calculator application | Full access to all calculation features, settings retrieval, calculation creation, and result viewing. No authentication required. |

**Note:** The current implementation does not include authentication or authorization mechanisms. All endpoints are publicly accessible.

## 6. Entities and Fields

### 6.1 Calculationsettings

**Table:** `calculation_settings`

**Description:** Stores default values and display preferences for the loan calculator. Used to initialize the calculator UI with predefined values and formatting options.

| Field Name | Type | Required | Description |
|------------|------|----------|-------------|
| id | str (UUID) | Yes | Unique identifier (UUID) |
| settings_id | str | Yes | Unique settings identifier string (max 100 chars) |
| default_loan_amount | float | Yes | Default principal amount on load (DECIMAL 15,2) |
| default_interest_rate | float | Yes | Default annual interest rate on load (DECIMAL 5,2) |
| default_loan_term | int | Yes | Default term in months on load |
| currency_symbol | str | Yes | Display currency symbol (max 10 chars) |
| decimal_precision | int | Yes | Number of decimal places for display |
| date_format | str | Yes | Format string for displaying dates (max 50 chars) |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** None

**Indexes:** Primary key on `id`, unique constraint on `settings_id`

### 6.2 Loancalculation

**Table:** `loan_calculations`

**Description:** Represents a single loan calculation instance with input parameters and computed results. Stores both user inputs and calculated values for monthly payment, total interest, and total amount paid.

| Field Name | Type | Required | Description |
|------------|------|----------|-------------|
| id | str (UUID) | Yes | Unique identifier (UUID) |
| calculation_id | str | Yes | Unique calculation identifier string (max 100 chars) |
| settings_id | Optional[str] (UUID) | No | Foreign key reference to calculation_settings (nullable) |
| principal_amount | float | Yes | Original loan amount borrowed (DECIMAL 15,2) |
| annual_interest_rate | float | Yes | Annual interest rate as percentage (DECIMAL 5,2) |
| loan_term_months | int | Yes | Duration of the loan in months |
| monthly_payment | float | Yes | Calculated monthly payment amount (DECIMAL 15,2) |
| total_interest | float | Yes | Total interest paid over loan term (DECIMAL 15,2) |
| total_amount_paid | float | Yes | Total amount paid including principal and interest (DECIMAL 15,2) |
| calculation_timestamp | datetime | Yes | When the calculation was performed |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** None

**Indexes:** Primary key on `id`, unique constraint on `calculation_id`, foreign key on `settings_id`

### 6.3 Amortizationentry

**Table:** `amortization_entries`

**Description:** Represents a single month's payment breakdown in the amortization schedule. Each entry shows how a monthly payment is split between principal and interest, along with the remaining balance.

| Field Name | Type | Required | Description |
|------------|------|----------|-------------|
| id | str (UUID) | Yes | Unique identifier (UUID) |
| entry_id | str | Yes | Unique entry identifier string (max 100 chars) |
| calculation_id | str (UUID) | Yes | Foreign key reference to loan_calculations |
| payment_number | int | Yes | Sequential payment number (1 to N) |
| payment_date | date | Yes | Projected payment date |
| payment_amount | float | Yes | Total payment for this period (DECIMAL 15,2) |
| principal_portion | float | Yes | Amount applied to principal (DECIMAL 15,2) |
| interest_portion | float | Yes | Amount applied to interest (DECIMAL 15,2) |
| remaining_balance | float | Yes | Remaining principal after payment (DECIMAL 15,2) |
| created_at | datetime | Yes | Creation timestamp |
| updated_at | datetime | Yes | Last update timestamp |

**Status Field:** None

**Indexes:** Primary key on `id`, unique constraint on `entry_id`, foreign key on `calculation_id`, composite index on `(calculation_id, payment_number)` for efficient querying

## 7. Enumerations

No enumerations are defined for this system.

## 8. Relationships

### 8.1 Entity Relationships

| Relationship | Type | Description | Navigation Required |
|--------------|------|-------------|---------------------|
| LoanCalculation → CalculationSettings | Many-to-One | A loan calculation optionally references calculation settings used at the time of calculation | Yes |
| AmortizationEntry → LoanCalculation | Many-to-One | Each amortization entry belongs to exactly one loan calculation | Yes |

### 8.2 Relationship Details

**LoanCalculation.settings → CalculationSettings**
- Foreign Key: `loan_calculations.settings_id` → `calculation_settings.id`
- Cardinality: Many LoanCalculations to One CalculationSettings (optional)
- Cascade: No cascade on delete (nullable foreign key)
- Back-reference: `calculations` (list of LoanCalculation objects)

**AmortizationEntry.calculation → LoanCalculation**
- Foreign Key: `amortization_entries.calculation_id` → `loan_calculations.id`
- Cardinality: Many AmortizationEntries to One LoanCalculation (required)
- Cascade: Delete amortization entries when parent loan calculation is deleted
- Back-reference: `amortization_entries` (list of AmortizationEntry objects)

### 8.3 Eager Loading Paths

For the detail endpoint `GET /loan-calculations/{id}/details`:
- `LoanCalculation.settings` - Load associated calculation settings
- `LoanCalculation.amortization_entries` - Load all amortization entries for the calculation

## 9. API Endpoints

### 9.1 CalculationSettings Endpoints

| Method | Route | Description |
|--------|-------|-------------|
| GET | `/calculation-settings` | List all calculation settings |
| GET | `/calculation-settings/{id}` | Retrieve a specific calculation settings record by ID |
| GET | `/calculation-settings/default` | Retrieve the default calculation settings |
| POST | `/calculation-settings` | Create a new calculation settings record |
| PUT | `/calculation-settings/{id}` | Update an existing calculation settings record |
| PATCH | `/calculation-settings/{id}` | Partially update a calculation settings record |
| DELETE | `/calculation-settings/{id}` | Delete a calculation settings record |

### 9.2 LoanCalculation Endpoints

| Method | Route | Description |
|--------|-------|-------------|
| GET | `/loan-calculations` | List all loan calculations with optional filtering |
| GET | `/loan-calculations/{id}` | Retrieve a specific loan calculation by ID |
| GET | `/loan-calculations/{id}/details` | Retrieve loan calculation with eager-loaded settings and amortization entries |
| POST | `/loan-calculations` | Create a new loan calculation record |
| POST | `/loan-calculations/calculate` | Create a loan calculation and generate amortization schedule in a single transaction |
| GET | `/loan-calculations/{id}/amortization-schedule` | Retrieve the complete amortization schedule for a specific calculation |
| PUT | `/loan-calculations/{id}` | Update an existing loan calculation |
| PATCH | `/loan-calculations/{id}` | Partially update a loan calculation |
| DELETE | `/loan-calculations/{id}` | Delete a loan calculation and associated amortization entries |

### 9.3 AmortizationEntry Endpoints

| Method | Route | Description |
|--------|-------|-------------|
| GET | `/amortization-entries` | List amortization entries with optional filtering by calculation_id |
| GET | `/amortization-entries/{id}` | Retrieve a specific amortization entry by ID |
| POST | `/amortization-entries` | Create a new amortization entry |
| PUT | `/amortization-entries/{id}` | Update an existing amortization entry |
| PATCH | `/amortization-entries/{id}` | Partially update an amortization entry |
| DELETE | `/amortization-entries/{id}` | Delete an amortization entry |

### 9.4 Endpoint Details

**GET /calculation-settings/default**
- Returns the default calculation settings to initialize the calculator UI
- If multiple settings exist, returns the first or a designated default record
- Response includes all fields from CalculationSettings entity

**GET /loan-calculations/{id}/details**
- Returns a loan calculation with eager-loaded related entities
- Includes: settings (currency_symbol, decimal_precision, date_format)
- Includes: amortization_entries[] (payment_number, payment_date, payment_amount, principal_portion, interest_portion, remaining_balance)
- Optimized query to avoid N+1 problems

**POST /loan-calculations/calculate**
- Primary endpoint for performing loan calculations
- Request body includes: principal_amount, annual_interest_rate, loan_term_months, optional settings_id, optional start_date
- Validates input parameters according to business rules
- Calculates monthly_payment, total_interest, total_amount_paid
- Generates complete amortization schedule with N entries (N = loan_term_months)
- Creates LoanCalculation and all AmortizationEntry records in a single transaction
- Returns complete calculation result with embedded amortization schedule

**GET /loan-calculations/{id}/amortization-schedule**
- Returns the complete amortization schedule for a specific calculation
- Ordered by payment_number ascending
- Includes all fields from AmortizationEntry entity

**GET /amortization-entries?calculation_id={id}**
- Filters amortization entries by calculation_id query parameter
- Returns entries ordered by payment_number
- Used to retrieve the schedule separately from the calculation

## 10. Workflow Logic

### 10.1 Perform Loan Calculation

**Trigger:** User submits loan calculation request via `POST /loan-calculations/calculate`

**Steps:**
1. Receive and validate user inputs:
   - principal_amount (loan amount)
   - annual_interest_rate (APR as percentage)
   - loan_term_months (term in months)
   - Optional: settings_id, start_date
2. Apply validation rules (Section 12)
3. Calculate monthly interest rate: `monthly_rate = annual_interest_rate / 12 / 100`
4. Calculate monthly payment using amortization formula:
   - If interest_rate > 0: `M = P × [r(1+r)^n] / [(1+r)^n - 1]` where M=payment, P=principal, r=monthly_rate, n=loan_term_months
   - If interest_rate = 0: `M = P / n`
5. Calculate total_amount_paid: `monthly_payment × loan_term_months`
6. Calculate total_interest: `total_amount_paid - principal_amount`
7. Round all monetary values to 2 decimal places
8. Create LoanCalculation record with calculated values
9. Generate amortization schedule:
   - Initialize remaining_balance = principal_amount
   - Set first payment_date = start_date + 1 month (default: calculation_timestamp + 1 month)
   - For each month from 1 to loan_term_months:
     - Calculate interest_portion = remaining_balance × monthly_rate
     - Calculate principal_portion = monthly_payment - interest_portion
     - For final payment: adjust payment_amount to ensure remaining_balance = 0.00
     - Calculate new remaining_balance = previous_balance - principal_portion
     - Create AmortizationEntry with all calculated values
     - Increment payment_date by 1 month
10. Commit transaction (all records created atomically)
11. Return complete calculation result with embedded amortization schedule

**Error Handling:**
- Validation failures return 400 Bad Request with detailed error messages
- Database errors trigger transaction rollback
- Division by zero protection for edge cases

### 10.2 View Amortization Schedule

**Trigger:** User requests amortization schedule via `GET /loan-calculations/{id}/amortization-schedule` or `GET /loan-calculations/{id}/details`

**Steps:**
1. Retrieve LoanCalculation by ID
2. Return 404 if not found
3. Fetch all associated AmortizationEntry records
4. Order entries by payment_number ascending
5. Return formatted schedule with columns:
   - Payment Number
   - Payment Date
   - Payment Amount
   - Principal Portion
   - Interest Portion
   - Remaining Balance

### 10.3 Reset Calculator

**Trigger:** User requests default settings via `GET /calculation-settings/default`

**Steps:**
1. Retrieve default CalculationSettings record
2. Return settings with:
   - default_loan_amount
   - default_interest_rate
   - default_loan_term
   - currency_symbol
   - decimal_precision
   - date_format
3. Client uses these values to reset calculator inputs

### 10.4 Export/Print Results

**Trigger:** User requests calculation details for export

**Steps:**
1. Retrieve complete calculation via `GET /loan-calculations/{id}/details`
2. Response includes:
   - All LoanCalculation fields
   - Associated CalculationSettings for formatting
   - Complete amortization schedule
3. Client-side logic formats data for export:
   - PDF generation
   - Clipboard copy
   - Browser print dialog

## 11. Business Logic

### 11.1 Loan Calculation Rules

1. **Input Ranges:**
   - Loan amount: $100 to $100,000,000
   - Annual interest rate: 0.01% to 99.99%
   - Loan term: 1 to 480 months

2. **Calculation Formulas:**
   - Monthly interest rate = Annual interest rate ÷ 12 ÷ 100
   - Standard amortization: `M = P × [r(1+r)^n] / [(1+r)^n - 1]`
   - Zero interest: `M = P ÷ n`
   - All monetary calculations rounded to 2 decimal places

3. **Amortization Schedule Generation:**
   - Number of entries = loan_term_months
   - Interest portion = Remaining balance × Monthly interest rate
   - Principal portion = Payment amount - Interest portion
   - New balance = Previous balance - Principal portion
   - Final payment adjusted to ensure remaining balance = $0.00

4. **Mathematical Integrity:**
   - Sum of all principal portions must equal original principal
   - Sum of all interest portions must equal total_interest
   - Final remaining balance must be exactly $0.00
   - Rounding adjustments applied to final payment if necessary

5. **Date Calculations:**
   - First payment date defaults to 1 month from calculation date
   - Subsequent payment dates increment by exactly 1 month
   - No adjustment for weekends or holidays

### 11.2 Default Settings

Default values when no CalculationSettings record exists:
- Loan amount: $10,000.00
- Interest rate: 5.0%
- Loan term: 360 months (30 years)
- Currency symbol: $
- Decimal precision: 2 places
- Date format: MM/DD/YYYY

### 11.3 Settings Application

When a LoanCalculation references a CalculationSettings record:
- Settings are stored for historical reference
- Currency symbol and decimal precision used for display formatting
- Date format applied to payment_date rendering
- Settings do not affect calculation logic, only display

### 11.4 Transaction Management

**Batch Write Operations:**
- `POST /loan-calculations/calculate` creates LoanCalculation + N AmortizationEntry records
- All records created in a single database transaction
- Rollback occurs if any record creation fails
- Ensures data integrity and consistency

## 12. Validation Rules

### 12.1 Input Validation

**Loan Amount (principal_amount):**
- Must be numeric
- Must be positive (> 0)
- Must be >= $100
- Must be <= $100,000,000
- Must have maximum 2 decimal places
- Error message: "Loan amount must be between $100 and $100,000,000"

**Annual Interest Rate (annual_interest_rate):**
- Must be numeric
- Must be positive (> 0) or zero
- Must be >= 0.01%
- Must be <= 99.99%
- Must have maximum 2 decimal places
- Error message: "Interest rate must be between 0.01% and 99.99%"

**Loan Term (loan_term_months):**
- Must be integer
- Must be positive (> 0)
- Must be >= 1 month
- Must be <= 480 months (40 years)
- Error message: "Loan term must be between 1 and 480 months"

### 12.2 Field Validation

**String Fields:**
- settings_id: max 100 characters, required, unique
- calculation_id: max 100 characters, required, unique
- entry_id: max 100 characters, required, unique
- currency_symbol: max 10 characters, required
- date_format: max 50 characters, required

**Numeric Fields:**
- All DECIMAL(15,2) fields: maximum 15 digits, 2 decimal places
- All DECIMAL(5,2) fields: maximum 5 digits, 2 decimal places
- decimal_precision: positive integer

**Date/DateTime Fields:**
- All datetime fields: valid ISO 8601 format
- payment_date: valid date, no time component

### 12.3 Business Validation

1. **Prevent Division by Zero:**
   - Check for zero interest rate before applying standard formula
   - Use alternative calculation: monthly_payment = principal / term

2. **Calculation Accuracy:**
   - All calculations must be accurate within $0.01
   - Final remaining balance must be exactly $0.00
   - Total principal portions must equal original principal within rounding tolerance

3. **Referential Integrity:**
   - settings_id must reference existing CalculationSettings if provided
   - calculation_id in AmortizationEntry must reference existing LoanCalculation

4. **Logical Consistency:**
   - payment_number must be sequential (1 to N)
   - payment_date must increment by 1 month
   - remaining_balance must decrease monotonically (except for 0% interest edge cases)

### 12.4 Error Responses

All validation failures return HTTP 400 Bad Request with structured error response:
```json
{
  "detail": "Validation error",
  "errors": [
    {
      "field": "principal_amount",
      "message": "Loan amount must be between $100 and $100,000,000"
    }
  ]
}
```

## 13. Implementation Notes

### 13.1 Technology Stack

- **Framework:** FastAPI (Python 3.11+)
- **ORM:** SQLAlchemy 2.x with async support
- **Database:** SQLite (development and production)
- **Validation:** Pydantic v2 for request/response schemas
- **Dependency Injection:** FastAPI's `Depends(get_db)` for database session management
- **Package Manager:** uv for dependency management and virtual environments
- **API Documentation:** Automatic OpenAPI/Swagger documentation at `/docs` and ReDoc at `/redoc`

### 13.2 Architecture Pattern

**Service Layer Pattern:**
- Controllers (FastAPI route handlers) handle HTTP concerns
- Service classes contain business logic and orchestration
- Repository classes handle database operations
- Clear separation of concerns for maintainability

**Directory Structure:**
```
app/
├── api/
│   ├── calculationsettings.py
│   ├── loancalculation.py
│   └── amortizationentry.py
├── models/
│   ├── calculationsettings.py
│   ├── loancalculation.py
│   └── amortizationentry.py
├── schemas/
│   ├── calculationsettings.py
│   ├── loancalculation.py
│   └── amortizationentry.py
├── services/
│   ├── calculationsettings_service.py
│   ├── loancalculation_service.py
│   └── amortization_service.py
├── repositories/
│   ├── calculationsettings_repository.py
│   ├── loancalculation_repository.py
│   └── amortizationentry_repository.py
├── core/
│   ├── database.py
│   ├── config.py
│   └── dependencies.py
└── main.py
```

### 13.3 Database Session Management

- Use FastAPI's dependency injection: `db: Session = Depends(get_db)`
- Session per request pattern
- Automatic session cleanup via context manager
- Transaction management for batch operations

### 13.4 Calculation Logic

- Implement loan calculation formulas in service layer
- Use Python's `decimal.Decimal` for precise financial calculations
- Round all monetary values to 2 decimal places using `Decimal.quantize()`
- Handle edge cases (0% interest, very large/small values)

### 13.5 Eager Loading

For detail endpoints:
- Use SQLAlchemy's `joinedload()` or `selectinload()` for eager loading
- Prevent N+1 query problems
- Example: `.options(joinedload(LoanCalculation.settings), joinedload(LoanCalculation.amortization_entries))`

### 13.6 API Documentation

FastAPI automatically generates:
- OpenAPI 3.0 schema
- Interactive Swagger UI at `/docs`
- ReDoc documentation at `/redoc`
- JSON schema at `/openapi.json`

### 13.7 Error Handling

- Use FastAPI's exception handlers for consistent error responses
- Custom exception classes for business logic errors
- HTTPException for HTTP-specific errors
- Structured error responses with field-level details

## 14. Assumptions

1. **Deployment Context:**
   - Application is primarily client-side with minimal server interaction
   - Backend serves as lightweight data persistence and calculation validation
   - No high-concurrency requirements expected

2. **User Model:**
   - No user authentication or authorization required
   - All users are anonymous with identical permissions
   - No multi-tenancy or data isolation needed
   - No user sessions or state management

3. **Data Persistence:**
   - SQLite is sufficient for expected data volumes
   - No data persistence required between sessions for client-side calculations
   - Server-side persistence is optional/supplementary

4. **Calculation Approach:**
   - Calculations can be performed entirely in browser
   - Backend provides validation and optional persistence
   - Amortization follows standard fixed-rate loan formula
   - Equal monthly payments throughout loan term

5. **Formatting and Display:**
   - Currency symbol and formatting preferences apply globally
   - All monetary values displayed with 2 decimal places
   - Date formatting follows CalculationSettings preferences
   - No localization beyond currency symbol

6. **Date Handling:**
   - Payment dates calculated assuming monthly intervals
   - No adjustment for weekends, holidays, or business days
   - First payment defaults to 1 month from calculation date
   - No timezone considerations

7. **Browser Compatibility:**
   - Modern browsers with JavaScript enabled
   - Export/print functionality leverages browser native capabilities
   - No support for legacy browsers

8. **Configuration:**
   - Default settings loaded from configuration
   - Settings can be updated via admin interface (future)
   - Single set of default settings for all users

9. **Data Volume:**
   - Small to medium data volumes expected
   - No pagination required for amortization schedules (max 480 entries)
   - Simple queries without complex indexing needs

10. **Calculation Frequency:**
    - Low to moderate calculation frequency
    - No caching or optimization required
    - Real-time calculation acceptable

## 15. Future Improvements

### 15.1 Infrastructure Enhancements

1. **Database Migration Management:**
   - Implement Alembic for database schema migrations
   - Version-controlled migration scripts
   - Support for rollback and forward migration
   - Automated migration in deployment pipeline

2. **PostgreSQL Support:**
   - Migrate from SQLite to PostgreSQL for production
   - Improved concurrency and performance
   - Better support for concurrent writes
   - JSON column support for flexible data storage

3. **Containerization:**
   - Docker containerization for backend application
   - Docker Compose for local development environment
   - Multi-stage builds for optimized images
   - Container orchestration readiness

### 15.2 Authentication and Authorization

1. **JWT Authentication:**
   - Implement JWT-based authentication
   - Secure token generation and validation
   - Refresh token mechanism
   - Token expiration and renewal

2. **Role-Based Access Control (RBAC):**
   - Define user roles (Admin, User, Guest)
   - Permission-based endpoint access
   - Admin interface for settings management
   - User-specific calculation history

### 15.3 Testing

1. **Comprehensive Test Suite:**
   - Unit tests for service layer and business logic
   - Integration tests for API endpoints
   - Test fixtures and factories
   - Coverage reporting (target: >80%)

2. **Test Categories:**
   - Calculation accuracy tests
   - Edge case validation
   - Database transaction tests
   - Error handling tests

### 15.4 Feature Enhancements

1. **Advanced Payment Options:**
   - Bi-weekly and weekly payment frequencies
   - Extra payment scenarios
   - Payoff acceleration calculations
   - Variable payment amounts

2. **Comparison Mode:**
   - Side-by-side comparison of multiple loan scenarios
   - Scenario saving and naming
   - Difference highlighting

3. **Visualization:**
   - API endpoints for chart data
   - Principal vs. interest breakdown
   - Balance over time progression
   - Payment composition trends

4. **History and Persistence:**
   - User-specific calculation history
   - Saved calculations with user accounts
   - Calculation naming and categorization
   - Search and filter capabilities

5. **Export Enhancements:**
   - Excel/CSV export with detailed schedules
   - PDF generation with charts
   - Email delivery of results
   - API-driven export formats

6. **Localization:**
   - Multi-currency support with exchange rates
   - Internationalized date formats
   - Multi-language support
   - Regional calculation variations

7. **Advanced Amortization:**
   - Balloon payment options
   - Adjustable rate mortgages
   - Interest-only periods
   - Payment holidays

8. **Integration:**
   - Financial API integration for current market rates
   - Third-party calculator embedding
   - Webhook notifications for calculation events
   - API rate limiting and quotas

### 15.5 Performance Optimization

1. **Caching:**
   - Redis caching for default settings
   - Calculation result caching
   - API response caching with TTL

2. **Query Optimization:**
   - Database indexing strategy
   - Query performance monitoring
   - N+1 query prevention
   - Connection pooling

3. **Async Processing:**
   - Background job queue for complex calculations
   - Async amortization schedule generation
   - Webhook delivery queue

### 15.6 Monitoring and Observability

1. **Logging:**
   - Structured logging with correlation IDs
   - Log aggregation and analysis
   - Error tracking and alerting

2. **Metrics:**
   - API endpoint performance metrics
   - Calculation accuracy monitoring
   - Database query performance
   - Business metrics dashboard

3. **Health Checks:**
   - Readiness and liveness probes
   - Database connectivity checks
   - Service dependency monitoring
