# Simple Loan Calculator — Generated Backend

## Overview

This is a **FastAPI-based backend** for the Simple Loan Calculator system. It provides REST APIs for calculating loan payments, generating amortization schedules, and tracking anonymous user sessions for analytics.

**Key Features:**
- Loan payment calculation using standard amortization formulas
- Complete amortization schedule generation for the entire loan term
- Anonymous session tracking without authentication
- Input validation for principal, interest rate, and loan term
- Detailed calculation results with payment breakdowns

**Technology Stack:**
- FastAPI (Python web framework)
- Pydantic (data validation)
- SQLAlchemy (ORM, ready for database integration)
- Uvicorn (ASGI server)

## Requirements

- Python 3.11 or higher
- uv (Python package installer and environment manager)

## 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. All dependencies are defined in `pyproject.toml`.

```bash
uv sync
```

This will create a virtual environment and install all required packages including:
- fastapi
- uvicorn
- pydantic
- sqlalchemy
- python-dateutil

## Run the Backend

Start the development server with auto-reload enabled:

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

The API will be available at: **http://localhost:8000**

You should see output similar to:
```
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process
INFO:     Started server process
INFO:     Waiting for application startup.
INFO:     Application startup complete.
```

## API Docs

FastAPI automatically generates interactive API documentation:

- **Swagger UI**: http://localhost:8000/docs
- **ReDoc**: http://localhost:8000/redoc

These interfaces allow you to explore all endpoints, view request/response schemas, and test API calls directly from your browser.

## OpenAPI JSON

The OpenAPI specification is available at:

**http://localhost:8000/openapi.json**

This JSON file can be imported into API clients like Postman, Insomnia, or used for code generation.

## Project Files

```
.
├── main.py                          # FastAPI application entry point
├── pyproject.toml                   # Project dependencies and metadata
├── models/
│   ├── __init__.py
│   ├── calculationsession.py       # CalculationSession entity model
│   ├── calculation.py              # Calculation entity model
│   └── amortizationentry.py        # AmortizationEntry entity model
├── schemas/
│   ├── __init__.py
│   ├── calculationsession.py       # Request/response schemas for sessions
│   ├── calculation.py              # Request/response schemas for calculations
│   └── amortizationentry.py        # Request/response schemas for amortization
├── routers/
│   ├── __init__.py
│   ├── calculationsession.py       # Session endpoints
│   ├── calculation.py              # Calculation endpoints
│   └── amortizationentry.py        # Amortization endpoints
└── services/
    ├── __init__.py
    ├── calculation_service.py      # Loan calculation business logic
    └── amortization_service.py     # Amortization schedule generation
```

## Example Workflow

### 1. Create an Anonymous Session

```bash
curl -X POST http://localhost:8000/sessions \
  -H "Content-Type: application/json" \
  -d '{
    "user_agent": "Mozilla/5.0",
    "ip_address": "192.168.1.1"
  }'
```

**Response:**
```json
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "session_id": "550e8400-e29b-41d4-a716-446655440001",
  "first_access_at": "2024-01-15T10:30:00Z",
  "last_access_at": "2024-01-15T10:30:00Z",
  "calculation_count": 0,
  "user_agent": "Mozilla/5.0",
  "ip_address": "192.168.1.1"
}
```

### 2. Perform a Loan Calculation

```bash
curl -X POST http://localhost:8000/calculations/calculate \
  -H "Content-Type: application/json" \
  -d '{
    "session_id": "550e8400-e29b-41d4-a716-446655440001",
    "principal": 250000.00,
    "annual_interest_rate": 4.5,
    "loan_term_months": 360
  }'
```

**Response:**
```json
{
  "id": "660e8400-e29b-41d4-a716-446655440002",
  "session_id": "550e8400-e29b-41d4-a716-446655440001",
  "principal": 250000.00,
  "annual_interest_rate": 4.5,
  "loan_term_months": 360,
  "monthly_payment": 1266.71,
  "total_interest": 206015.60,
  "total_amount": 456015.60,
  "created_at": "2024-01-15T10:31:00Z"
}
```

### 3. Get Calculation Details with Amortization Schedule

```bash
curl -X GET http://localhost:8000/calculations/660e8400-e29b-41d4-a716-446655440002/details
```

**Response:**
```json
{
  "id": "660e8400-e29b-41d4-a716-446655440002",
  "principal": 250000.00,
  "annual_interest_rate": 4.5,
  "loan_term_months": 360,
  "monthly_payment": 1266.71,
  "total_interest": 206015.60,
  "total_amount": 456015.60,
  "amortization_entries": [
    {
      "payment_number": 1,
      "payment_date": "2024-02-15",
      "beginning_balance": 250000.00,
      "payment_amount": 1266.71,
      "principal_portion": 329.21,
      "interest_portion": 937.50,
      "ending_balance": 249670.79,
      "cumulative_interest": 937.50,
      "cumulative_principal": 329.21
    },
    {
      "payment_number": 2,
      "payment_date": "2024-03-15",
      "beginning_balance": 249670.79,
      "payment_amount": 1266.71,
      "principal_portion": 330.44,
      "interest_portion": 936.27,
      "ending_balance": 249340.35,
      "cumulative_interest": 1873.77,
      "cumulative_principal": 659.65
    }
  ]
}
```

### 4. List All Calculations for a Session

```bash
curl -X GET http://localhost:8000/sessions/550e8400-e29b-41d4-a716-446655440001/calculations
```

## Next Steps

This generated backend provides a solid foundation. To make it production-ready, consider:

1. **Database Persistence**: Currently using in-memory storage. Integrate PostgreSQL, MySQL, or SQLite using SQLAlchemy models already defined in the project.

2. **Authentication & Authorization**: Add user authentication if moving beyond anonymous usage. Consider JWT tokens, OAuth2, or API keys for session management.

3. **Code Organization**: Split the monolithic `main.py` into separate modules:
   - Move route handlers to `routers/` directory
   - Extract business logic to `services/` directory
   - Keep data models in `models/` directory
   - Define Pydantic schemas in `schemas/` directory

4. **Testing**: Add comprehensive test coverage:
   - Unit tests for calculation formulas and business logic
   - Integration tests for API endpoints
   - Validation tests for input constraints
   - Use pytest and FastAPI's TestClient

5. **Error Handling**: Implement proper exception handling, custom error responses, and logging.

6. **Rate Limiting**: Add rate limiting middleware (100 requests/minute per IP as specified).

7. **Data Retention**: Implement automatic cleanup of calculations older than 90 days and expired sessions.

8. **Export Features**: Add endpoints for PDF and CSV export of calculation results.

9. **Monitoring**: Add application monitoring, performance metrics, and health check endpoints.

10. **Documentation**: Expand API documentation with more examples, error codes, and usage guidelines.
