# TripTalley Deployment Guide

## Overview

TripTalley is a travel money tracking application. This guide covers setting up the development environment and running the backend server.

## Tech Stack

- **Backend**: FastAPI (Python 3.11+)
- **Database**: SQLite (development) / PostgreSQL (production)
- **ORM**: SQLAlchemy 2.0 (async)
- **API Docs**: OpenAPI/Swagger
- **Testing**: pytest

## Prerequisites

- Python 3.11 or higher
- pip (Python package manager)
- Virtual environment recommended

## Development Setup

### 1. Clone and Install Dependencies

```bash
cd /srv/projects/triptalley/backend
pip install -r requirements.txt
```

### 2. Configure Environment

Create a `.env` file in the backend directory:

```env
# Server
HOST=0.0.0.0
PORT=8000
DEBUG=True

# Database (SQLite for development)
DATABASE_URL=sqlite+aiosqlite:///./triptalley.db

# Security (generate with: openssl rand -hex 32)
SECRET_KEY=your-secret-key-here
ACCESS_TOKEN_EXPIRE_MINUTES=1440

# FX Service
FRANKFURTER_API_URL=https://api.frankfurter.app
FX_CACHE_TTL_DAYS=7

# CORS
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:8080
```

### 3. Run Database Migrations

```bash
cd backend
alembic upgrade head
```

### 4. Start the Development Server

```bash
cd backend
python -m uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
```

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

### 5. API Documentation

Once the server is running, visit:
- Swagger UI: `http://localhost:8000/docs`
- ReDoc: `http://localhost:8000/redoc`

## Running Tests

```bash
cd backend
pytest tests/ -v
```

To run tests with coverage:

```bash
pytest tests/ -v --cov=app --cov-report=html
```

## Production Deployment

### Database

For production, use PostgreSQL instead of SQLite:

```env
DATABASE_URL=postgresql+asyncpg://user:password@host:5432/triptalley
```

Install PostgreSQL driver:

```bash
pip install asyncpg
```

### Environment

Set these in production:

```env
DEBUG=False
SECRET_KEY=<secure-random-key>
ALLOWED_ORIGINS=<your-frontend-domain>
```

### Running with Uvicorn (Production)

```bash
uvicorn app.main:app --host 0.0.0.0 --port 8000 --workers 4
```

## Project Structure

```
backend/
├── app/
│   ├── core/
│   │   ├── config.py      # Settings (Pydantic)
│   │   ├── db.py          # Database connection
│   │   ├── money.py       # Currency handling
│   │   ├── split.py       # Expense splitting logic
│   │   └── settle.py      # Debt settlement logic
│   ├── models/
│   │   └── models.py      # SQLAlchemy models
│   ├── schemas/
│   │   └── schemas.py     # Pydantic schemas
│   ├── services/
│   │   └── fx_service.py  # FX rate service
│   ├── routers/
│   │   ├── auth.py        # Authentication endpoints
│   │   ├── trips.py       # Trip endpoints
│   │   ├── expenses.py    # Expense endpoints
│   │   ├── settlements.py # Settlement endpoints
│   │   └── sync.py        # Sync endpoints
│   └── main.py            # FastAPI app entry
├── alembic/               # Database migrations
├── tests/                 # pytest tests
├── requirements.txt       # Python dependencies
└── .env                   # Environment variables (not in git)
```

## API Endpoints

### Authentication (`/api/v1/auth`)
- `POST /register` - Register new user
- `POST /login` - Login and get access token
- `POST /refresh-token` - Refresh access token

### Trips (`/api/v1/trips`)
- `GET /{trip_id}` - Get trip details
- `POST /` - Create new trip
- `PUT /{trip_id}` - Update trip
- `DELETE /{trip_id}` - Delete trip
- `POST /{trip_id}/invite` - Create invitation link

### Expenses (`/api/v1/expenses`)
- `GET /{expense_id}` - Get expense details
- `POST /` - Create expense
- `PUT /{expense_id}` - Update expense
- `DELETE /{expense_id}` - Delete expense

### Settlements (`/api/v1/settlements`)
- `GET /{trip_id}/balances` - Get participant balances
- `GET /{trip_id}/settlement` - Get settlement plan
- `POST /{trip_id}/payments` - Record a payment

### Sync (`/api/v1/sync`)
- `POST /` - Sync client data with server

## Key Features

- **Multi-currency support**: Store amounts in original currency, settle in trip's canonical currency
- **Historical FX rates**: Rates fetched at expense date with business-day fallback
- **Flexible splits**: Equal, percentage, or custom splits with largest-remainder rounding
- **Debt simplification**: Minimize number of transfers needed to settle
- **Per-viewer display**: Convert settlement amounts to viewer's home currency

## Design Documents

- `docs/DESIGN.md` - Technical design and architecture
- `docs/ERD.md` - Entity-Relationship Diagram
- `docs/UI_DESIGN.md` - User interface design