# Loan Calculator — Generated Backend

## Overview

This is a **FastAPI-based backend** for a **Loan Calculator** web application. It calculates loan payment details including monthly payment, total interest, and amortization schedules based on principal, interest rate, and term.

**Key Features:**
- Calculate monthly payments using standard amortization formulas
- Generate detailed amortization schedules showing principal and interest breakdown for each payment
- Store calculation history with session tracking
- Configurable validation constraints and default values
- Support for interest rates from 0% to 50% and loan terms up to 50 years

**Modules:**
- `calculator_config` — System-wide configuration and constraints for loan calculator inputs and defaults
- `loan_calculation` — Loan calculation engine, results storage, and amortization schedule generation

**Entities:**
- `Calculatordefaults` — Global configuration storing default values and validation constraints
- `Loancalculation` — Stored loan calculation results with input parameters and computed values
- `Amortizationscheduleentry` — Individual payment breakdown for each period of the loan term

## Requirements

- **Python 3.11+**
- **uv** (fast Python package installer and resolver)
- **FastAPI** and **Uvicorn** (installed via dependencies)

## Install uv

Install `uv` using the official installation script:

```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 `uv` for dependency management. Install all required packages:

```bash
uv sync
```

This will create a virtual environment and install:
- FastAPI
- Uvicorn
- Pydantic
- SQLAlchemy (or your chosen ORM)
- Other dependencies specified in `pyproject.toml`

## Run the Backend

Start the FastAPI development server with auto-reload:

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

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

## API Docs

Once the server is running, visit `http://localhost:8000/docs` for **interactive Swagger UI** documentation.

### Available Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/calculator-defaults` | Retrieve current calculator defaults and validation constraints |
| PUT | `/calculator-defaults/{id}` | Update calculator defaults (admin only) |
| POST | `/loan-calculations` | Create new loan calculation with computed results |
| GET | `/loan-calculations/{id}` | Retrieve stored loan calculation |
| GET | `/loan-calculations` | List loan calculations (optionally filtered by session_id) |
| GET | `/loan-calculations/{id}/details` | Retrieve loan calculation with full amortization schedule |
| POST | `/loan-calculations/{id}/generate-schedule` | Generate amortization schedule for existing calculation |
| GET | `/amortization-schedule-entries` | List schedule entries for a calculation_id |

## 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               # SQLAlchemy models (Calculatordefaults, Loancalculation, Amortizationscheduleentry)
├── schemas.py              # Pydantic schemas for request/response validation
├── database.py             # Database connection and session management
├── services.py             # Business logic (calculation engine, amortization schedule generation)
├── pyproject.toml          # Project dependencies and configuration
├── README.md               # This file
└── .python-version         # Python version specification
```

## Example Workflow

### 1. Get Calculator Defaults

Retrieve the default values and validation constraints:

```bash
curl -X GET http://localhost:8000/calculator-defaults
```

**Response:**
```json
{
  "id": "default-1",
  "default_principal": "250000.00",
  "default_interest_rate": "6.5000",
  "default_term_months": 360,
  "min_principal": "1000.00",
  "max_principal": "10000000.00",
  "min_interest_rate": "0.0000",
  "max_interest_rate": "50.0000",
  "min_term_months": 1,
  "max_term_months": 600
}
```

### 2. Create a Loan Calculation

Calculate a loan with $300,000 principal, 5.5% interest rate, and 360 months (30 years):

```bash
curl -X POST http://localhost:8000/loan-calculations \
  -H "Content-Type: application/json" \
  -d '{
    "principal": "300000.00",
    "annual_interest_rate": "5.5000",
    "loan_term_months": 360,
    "session_id": "session-abc-123"
  }'
```

**Response:**
```json
{
  "id": "calc-xyz-789",
  "principal": "300000.00",
  "annual_interest_rate": "5.5000",
  "loan_term_months": 360,
  "monthly_payment": "1703.37",
  "total_payment": "613213.20",
  "total_interest": "313213.20",
  "session_id": "session-abc-123",
  "created_at": "2025-01-15T10:30:00Z"
}
```

### 3. Generate Amortization Schedule

Generate the complete payment schedule for the calculation:

```bash
curl -X POST http://localhost:8000/loan-calculations/calc-xyz-789/generate-schedule
```

### 4. Get Calculation with Full Details

Retrieve the calculation including all amortization schedule entries:

```bash
curl -X GET http://localhost:8000/loan-calculations/calc-xyz-789/details
```

**Response:**
```json
{
  "id": "calc-xyz-789",
  "principal": "300000.00",
  "monthly_payment": "1703.37",
  "total_payment": "613213.20",
  "total_interest": "313213.20",
  "amortization_schedule_entries": [
    {
      "payment_number": 1,
      "payment_date": "2025-02-15",
      "beginning_balance": "300000.00",
      "payment_amount": "1703.37",
      "principal_portion": "328.37",
      "interest_portion": "1375.00",
      "ending_balance": "299671.63"
    },
    {
      "payment_number": 2,
      "payment_date": "2025-03-15",
      "beginning_balance": "299671.63",
      "payment_amount": "1703.37",
      "principal_portion": "329.87",
      "interest_portion": "1373.50",
      "ending_balance": "299341.76"
    }
  ]
}
```

### 5. List Calculations by Session

Retrieve all calculations for a specific session:

```bash
curl -X GET "http://localhost:8000/loan-calculations?session_id=session-abc-123"
```

## Next Steps

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

1. **Database Persistence**
   - Configure a real database (PostgreSQL, MySQL, or SQLite)
   - Run migrations to create tables
   - Implement proper connection pooling

2. **Authentication & Authorization**
   - Add user authentication (JWT, OAuth2, etc.)
   - Implement role-based access control for admin endpoints (e.g., updating calculator defaults)
   - Secure session_id generation and validation

3. **Code Organization**
   - Split `main.py` into separate routers (e.g., `routers/calculator.py`, `routers/loans.py`)
   - Move business logic to dedicated service modules
   - Separate models, schemas, and database configuration

4. **Testing**
   - Add unit tests for calculation formulas
   - Write integration tests for API endpoints
   - Test edge cases (0% interest, maximum loan terms, rounding precision)

5. **Validation & Error Handling**
   - Enhance input validation with Pydantic validators
   - Add comprehensive error messages
   - Implement proper exception handling

6. **Performance Optimization**
   - Add caching for calculator defaults
   - Optimize amortization schedule generation for large loan terms
   - Implement pagination for list endpoints

7. **Documentation**
   - Add detailed docstrings
   - Include business rule documentation
   - Provide frontend integration examples

8. **Deployment**
   - Configure production settings (CORS, logging, rate limiting)
   - Set up Docker containerization
   - Deploy to cloud platform (AWS, GCP, Azure)

---

**Generated by FastAPI Backend Generator**
