# Simple Loan Calculator — Generated Backend

## Overview

This is a **FastAPI backend** for the Simple Loan Calculator system. It provides REST APIs to manage loan calculations, amortization schedules, and calculator settings.

**Key Features:**
- Calculate monthly loan payments, total interest, and total amount paid
- Generate detailed amortization schedules with month-by-month breakdowns
- Manage calculation settings (default values, currency, date format)
- Retrieve complete calculation details with related amortization entries
- Input validation for loan parameters (amount, rate, term)

**Technology Stack:**
- FastAPI (async web framework)
- Pydantic (data validation)
- Python 3.11+
- SQLAlchemy-ready schema structure

## Requirements

- **Python 3.11+**
- **uv** (fast Python package installer)

## Install uv

Install `uv` to manage dependencies and run the application:

```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```

After installation, restart your terminal or run:

```bash
source $HOME/.cargo/env
```

## Install Dependencies

The project uses `pyproject.toml` for dependency management. Install all dependencies with:

```bash
uv sync
```

Or install manually:

```bash
uv pip install fastapi uvicorn pydantic python-multipart
```

## Run the Backend

Start the development server with auto-reload enabled:

```bash
uv run uvicorn main:app --reload
```

The API will be available at:
- **Base URL:** `http://localhost:8000`
- **Interactive Docs:** `http://localhost:8000/docs`
- **Alternative Docs:** `http://localhost:8000/redoc`

## API Docs

Access the automatically generated interactive API documentation:

- **Swagger UI:** [http://localhost:8000/docs](http://localhost:8000/docs)
- **ReDoc:** [http://localhost:8000/redoc](http://localhost:8000/redoc)

### Main Endpoints

#### Calculation Settings
- `GET /calculation-settings` — List all settings
- `POST /calculation-settings` — Create new settings
- `GET /calculation-settings/{id}` — Get settings by ID
- `PUT /calculation-settings/{id}` — Update settings
- `DELETE /calculation-settings/{id}` — Delete settings
- `GET /calculation-settings/default` — Get default settings

#### Loan Calculations
- `GET /loan-calculations` — List all calculations
- `POST /loan-calculations` — Create new calculation
- `GET /loan-calculations/{id}` — Get calculation by ID
- `PUT /loan-calculations/{id}` — Update calculation
- `DELETE /loan-calculations/{id}` — Delete calculation
- `GET /loan-calculations/{id}/details` — Get calculation with settings and amortization entries
- `POST /loan-calculations/calculate` — Perform loan calculation with amortization schedule generation
- `GET /loan-calculations/{id}/amortization-schedule` — Get amortization schedule for a calculation

#### Amortization Entries
- `GET /amortization-entries` — List all entries (filterable by calculation_id)
- `POST /amortization-entries` — Create new entry
- `GET /amortization-entries/{id}` — Get entry by ID
- `PUT /amortization-entries/{id}` — Update entry
- `DELETE /amortization-entries/{id}` — Delete entry

## OpenAPI JSON

Download the OpenAPI specification:

```bash
curl http://localhost:8000/openapi.json -o openapi.json
```

## Project Files

```
.
├── main.py                 # FastAPI application entry point
├── models.py              # Pydantic schemas and data models
├── database.py            # Database configuration (placeholder)
├── pyproject.toml         # Project dependencies
├── README.md              # This file
└── .python-version        # Python version specification
```

## Example Workflow

### 1. Create Default Calculation Settings

```bash
curl -X POST "http://localhost:8000/calculation-settings" \
  -H "Content-Type: application/json" \
  -d '{
    "settings_id": "default_settings",
    "default_loan_amount": 10000.00,
    "default_interest_rate": 5.0,
    "default_loan_term": 360,
    "currency_symbol": "$",
    "decimal_precision": 2,
    "date_format": "MM/DD/YYYY"
  }'
```

### 2. Perform Loan Calculation

```bash
curl -X POST "http://localhost:8000/loan-calculations/calculate" \
  -H "Content-Type: application/json" \
  -d '{
    "principal_amount": 250000.00,
    "annual_interest_rate": 4.5,
    "loan_term_months": 360,
    "settings_id": "default_settings"
  }'
```

**Expected Response:**
```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "calculation_id": "calc_20240115_001",
  "principal_amount": 250000.00,
  "annual_interest_rate": 4.5,
  "loan_term_months": 360,
  "monthly_payment": 1266.71,
  "total_interest": 206035.60,
  "total_amount_paid": 456035.60,
  "calculation_timestamp": "2024-01-15T10:30:00Z"
}
```

### 3. Get Calculation Details with Amortization

```bash
curl -X GET "http://localhost:8000/loan-calculations/{id}/details"
```

**Response includes:**
- Full calculation details
- Associated settings (currency_symbol, decimal_precision, date_format)
- Complete amortization schedule (all 360 monthly entries)

### 4. Get Amortization Schedule Only

```bash
curl -X GET "http://localhost:8000/loan-calculations/{id}/amortization-schedule"
```

### 5. Filter Amortization Entries

```bash
curl -X GET "http://localhost:8000/amortization-entries?calculation_id={id}"
```

## Business Rules Implemented

- **Loan amount:** $100 to $100,000,000
- **Interest rate:** 0.01% to 99.99%
- **Loan term:** 1 to 480 months
- **Monthly interest rate:** Annual rate / 12 / 100
- **Zero interest handling:** Monthly payment = Principal / Number of Months
- **Rounding:** All monetary values rounded to 2 decimal places
- **Final payment adjustment:** Ensures remaining balance is exactly $0.00
- **Amortization formula:**
  - Interest portion = Remaining balance × Monthly interest rate
  - Principal portion = Payment amount - Interest portion
  - New balance = Previous balance - Principal portion

## Validation

All endpoints validate input according to business rules:

- Numeric fields are positive and within allowed ranges
- Currency values have maximum 2 decimal places
- Interest rates have maximum 2 decimal places
- Loan term is a positive integer between 1 and 480
- Inline error messages provide specific guidance for corrections

## Next Steps

This is a generated backend scaffold. To make it production-ready:

1. **Database Persistence**
   - Implement SQLAlchemy models matching the DDL schema
   - Configure PostgreSQL/MySQL connection
   - Add database migrations with Alembic
   - Implement proper CRUD operations with database sessions

2. **Authentication & Authorization**
   - Add user authentication (JWT, OAuth2)
   - Implement role-based access control if needed
   - Secure sensitive endpoints

3. **Code Organization**
   - Split `main.py` into separate routers (calculation_settings, loan_calculations, amortization_entries)
   - Create service layer for business logic (loan calculation, amortization generation)
   - Organize models into separate schema files
   - Add repository pattern for database access

4. **Testing**
   - Write unit tests for calculation formulas
   - Add integration tests for API endpoints
   - Implement test fixtures and mock data
   - Add validation test cases for edge conditions

5. **Additional Features**
   - Implement batch write service: `create_loan_calculation_with_schedule`
   - Add transaction management for atomic operations
   - Implement export functionality (PDF, CSV generation)
   - Add caching for frequently accessed settings

6. **Deployment**
   - Configure environment variables
   - Add Docker support
   - Set up CI/CD pipeline
   - Implement logging and monitoring
