# 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 calculation sessions for anonymous users.

**Key Features:**
- Calculate monthly loan payments using standard amortization formulas
- Generate complete amortization schedules with period-by-period breakdowns
- Export calculation results to CSV and PDF formats
- Track user sessions for analytics (no authentication required)
- Support for loans up to $1 billion with terms up to 600 months

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

## Requirements

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

## Install uv

Install `uv` using the official installer:

```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)
- Additional utilities for CSV/PDF export

## 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`
- **ReDoc:** `http://localhost:8000/redoc`

## API Docs

Once the server is running, visit the interactive API documentation:

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

### Key Endpoints

| Method | Endpoint | Description |
|--------|----------|-------------|
| `POST` | `/loan-calculations/calculate` | Calculate loan payment and generate amortization schedule |
| `GET` | `/loan-calculations/{id}` | Retrieve a specific loan calculation |
| `GET` | `/loan-calculations/{id}/details` | Get calculation with full amortization schedule |
| `GET` | `/loan-calculations/{id}/amortization-schedule` | Get amortization schedule entries |
| `GET` | `/loan-calculations/{id}/export-csv` | Export calculation to CSV format |
| `GET` | `/loan-calculations/{id}/export-pdf` | Export calculation to PDF format |
| `POST` | `/calculation-sessions` | Create or update a calculation session |
| `GET` | `/calculation-sessions/{session_id}` | Retrieve session information |

## OpenAPI JSON

The OpenAPI specification is available at:

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

Download it for use with code generators, testing tools, or API clients.

## Project Files

```
.
├── main.py                          # FastAPI application entry point
├── models/
│   ├── loan_calculation.py          # LoanCalculation entity model
│   ├── amortization_schedule_entry.py  # AmortizationScheduleEntry model
│   └── calculation_session.py       # CalculationSession model
├── schemas/
│   ├── loan_calculation.py          # Pydantic schemas for requests/responses
│   ├── amortization_schedule_entry.py
│   └── calculation_session.py
├── services/
│   ├── loan_calculator.py           # Core loan calculation logic
│   └── amortization_generator.py    # Amortization schedule generation
├── routers/
│   ├── loan_calculations.py         # Loan calculation endpoints
│   └── calculation_sessions.py      # Session tracking endpoints
├── utils/
│   ├── export_csv.py                # CSV export functionality
│   └── export_pdf.py                # PDF export functionality
├── pyproject.toml                   # Project dependencies and metadata
└── README.md                        # This file
```

## Example Workflow

### 1. Calculate a Loan

Create a new loan calculation with principal, interest rate, and term:

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

**Response:**
```json
{
  "id": "calc-abc123",
  "principal": 250000.00,
  "annual_interest_rate": 4.5,
  "loan_term_months": 360,
  "monthly_payment": 1266.71,
  "total_interest": 206015.60,
  "total_amount": 456015.60,
  "calculation_method": "standard-amortization",
  "session_id": "session-123",
  "created_at": "2025-01-15T10:30:00Z"
}
```

### 2. Retrieve Calculation with Amortization Schedule

Get the full calculation details including all payment periods:

```bash
curl -X GET "http://localhost:8000/loan-calculations/calc-abc123/details"
```

**Response includes:**
- Calculation summary (monthly payment, total interest, total amount)
- Complete amortization schedule (360 entries)
- Each entry shows: payment number, beginning balance, payment amount, principal portion, interest portion, ending balance, cumulative totals

### 3. Export to CSV

Download the calculation results as a CSV file:

```bash
curl -X GET "http://localhost:8000/loan-calculations/calc-abc123/export-csv" \
  --output loan-calculation.csv
```

## Next Steps

This generated backend provides a functional foundation. To prepare for production:

### 1. **Database Persistence**
   - Currently uses in-memory storage
   - Integrate PostgreSQL or MySQL using SQLAlchemy
   - Apply database migrations with Alembic
   - Configure connection pooling and environment-based settings

### 2. **Authentication & Authorization**
   - Add optional user authentication (OAuth2, JWT)
   - Implement session-based access control
   - Secure sensitive endpoints with API keys

### 3. **Code Organization**
   - Split `main.py` into separate routers (`routers/`)
   - Extract business logic into services (`services/`)
   - Separate database models (`models/`) from Pydantic schemas (`schemas/`)
   - Add dependency injection for database sessions

### 4. **Testing**
   - Add unit tests for calculation logic (pytest)
   - Implement integration tests for API endpoints
   - Add test coverage reporting
   - Create fixtures for common test scenarios

### 5. **Production Readiness**
   - Add logging and monitoring (structured logging)
   - Implement rate limiting and request validation
   - Configure CORS for frontend integration
   - Add health check endpoints
   - Set up Docker containerization
   - Configure environment variables for secrets

### 6. **Enhanced Features**
   - Implement caching for frequently accessed calculations
   - Add background tasks for PDF generation
   - Support batch calculations
   - Add webhook notifications for long-running exports

---

**Generated for:** Simple Loan Calculator  
**Mode:** Strict (follows schema and PRD exactly)  
**Modules:** loan_calculation, session_tracking
