# Simple Loan Calculator — Generated Backend

## Overview

This is a **FastAPI-based backend** for the Simple Loan Calculator, a single-page web application that calculates loan payments, total interest, and amortization schedules for anonymous users without authentication.

**Key Features:**
- Calculate monthly loan payments using standard amortization formulas
- Generate complete amortization schedules with payment breakdowns
- Track anonymous user sessions for analytics
- Support for loan amounts up to $100,000,000
- Interest rates from 0% to 99.99%
- Loan terms from 1 to 600 months (50 years)
- RESTful API with automatic OpenAPI documentation

**Domain:** freemeal.dev.dalfin.ai

## Requirements

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

## Install uv

Install `uv`, the fast Python package manager:

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

After installation, restart your shell 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 (for future database integration)
- Python-dateutil

## Run the Backend

Start the 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 running, visit `http://localhost:8000/docs` for the interactive Swagger UI documentation where you can:
- Browse all available endpoints
- Test API calls directly from the browser
- View request/response schemas
- See validation rules and examples

## OpenAPI JSON

The OpenAPI specification is available at:
```
http://localhost:8000/openapi.json
```

Use this for:
- Generating client SDKs
- API testing tools
- Documentation generation
- Integration with API gateways

## Project Files

```
.
├── main.py                          # FastAPI application entry point
├── models/
│   ├── calculation_session.py      # CalculationSession entity
│   ├── calculation.py               # Calculation entity
│   └── amortization_entry.py       # AmortizationEntry entity
├── schemas/
│   ├── calculation_session.py      # Pydantic schemas for sessions
│   ├── calculation.py               # Pydantic schemas for calculations
│   └── amortization_entry.py       # Pydantic schemas for amortization
├── services/
│   ├── calculation_service.py      # Loan calculation business logic
│   └── session_service.py          # Session tracking logic
├── routers/
│   ├── calculations.py             # Calculation endpoints
│   ├── sessions.py                 # Session endpoints
│   └── amortization.py             # Amortization endpoints
├── utils/
│   └── loan_calculator.py          # Amortization formula implementation
├── pyproject.toml                   # Project dependencies
└── README.md                        # This file
```

## Example Workflow

### 1. Create or Track a Session

```bash
curl -X POST http://localhost:8000/sessions/track \
  -H "Content-Type: application/json" \
  -d '{
    "session_id": "550e8400-e29b-41d4-a716-446655440000",
    "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
    "ip_address": "192.168.1.100"
  }'
```

**Response:**
```json
{
  "id": "abc123",
  "session_id": "550e8400-e29b-41d4-a716-446655440000",
  "first_access_at": "2024-01-15T10:30:00Z",
  "last_access_at": "2024-01-15T10:30:00Z",
  "calculation_count": 0,
  "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
  "ip_address": "192.168.1.xxx"
}
```

### 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-446655440000",
    "principal": 250000.00,
    "annual_interest_rate": 4.5,
    "loan_term_months": 360
  }'
```

**Response:**
```json
{
  "id": "calc456",
  "session_id": "550e8400-e29b-41d4-a716-446655440000",
  "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/calc456/details
```

**Response:**
```json
{
  "id": "calc456",
  "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. Get All Calculations for a Session

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

## Next Steps

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

1. **Database Persistence**
   - Integrate PostgreSQL or MySQL using SQLAlchemy ORM
   - Implement proper database migrations with Alembic
   - Add connection pooling and transaction management

2. **Authentication & Authorization**
   - Add optional user accounts for saving calculation history
   - Implement JWT-based authentication
   - Add API key support for rate limiting

3. **Code Organization**
   - Split `main.py` into separate routers for each module
   - Extract business logic into service layer classes
   - Separate data models from Pydantic schemas
   - Create repository pattern for data access

4. **Testing**
   - Add unit tests for calculation formulas
   - Create integration tests for API endpoints
   - Implement test fixtures and factories
   - Add test coverage reporting (aim for >80%)

5. **Production Features**
   - Add proper logging and monitoring
   - Implement rate limiting (100 requests/minute per IP)
   - Set up CORS for frontend integration
   - Add health check endpoints
   - Implement data retention policies (90-day cleanup)
   - Add GDPR-compliant IP anonymization
   - Configure environment-based settings

6. **Performance**
   - Add caching for frequently accessed calculations
   - Optimize amortization schedule generation for large terms
   - Implement pagination for session calculations list

7. **Documentation**
   - Add detailed API usage examples
   - Document calculation formulas and business rules
   - Create deployment guide
   - Add troubleshooting section
