# Trips Email Worker

Forward booking confirmation emails to your Trips app for automatic parsing.

## How It Works

1. Email arrives at `travel@quadjourney.com`
2. Cloudflare Email Routing forwards to this Worker
3. Worker extracts email content and attachments
4. Sends to Trips API for AI parsing
5. You get a Telegram notification with parsed details

## Setup Steps

### 1. Generate an API Key

Generate a secure random key:
```bash
openssl rand -hex 32
```

### 2. Add API Key to Trips Docker

In your `docker-compose.yml`, add the environment variable:
```yaml
services:
  trips:
    environment:
      - EMAIL_API_KEY=your-generated-key-here
      - TELEGRAM_BOT_TOKEN=your-bot-token  # Optional
      - TELEGRAM_CHAT_ID=your-chat-id      # Optional
```

Restart the container:
```bash
docker compose up -d
```

### 3. Create Cloudflare Worker

1. Go to [Cloudflare Dashboard](https://dash.cloudflare.com) → Workers & Pages
2. Click "Create Worker"
3. Name it `trips-email-worker`
4. Paste the contents of `worker.js`
5. Click "Deploy"

### 4. Add Worker Secrets

In the Worker settings, add these environment variables:

| Variable | Value |
|----------|-------|
| `TRIPS_API_URL` | `https://trips.quadjourney.com` |
| `TRIPS_API_KEY` | Your generated API key |
| `FORWARD_TO` | (Optional) Backup email address |

Or via CLI:
```bash
cd email-worker
npm install wrangler
wrangler secret put TRIPS_API_KEY
```

### 5. Set Up Email Routing

1. Go to Cloudflare Dashboard → quadjourney.com → Email → Email Routing
2. Click "Routing Rules" → "Create address"
3. Set:
   - Custom address: `travel`
   - Action: "Send to Worker"
   - Destination: `trips-email-worker`
4. Click "Save"

### 6. Verify DNS

Cloudflare should auto-configure MX records. Verify:
- MX record pointing to Cloudflare's email servers
- SPF/DKIM records if sending replies

## Testing

Forward a booking confirmation email to `travel@quadjourney.com`.

Check your Telegram for the parsed result, or check server logs:
```bash
docker logs trips --tail 50
```

## Supported Email Types

- Flight confirmations (airlines, booking sites)
- Hotel/lodging reservations
- Car rental confirmations
- Activity bookings

## Attachments

The worker can process:
- PDF attachments (itineraries, e-tickets)
- Image attachments (screenshots)
- Plain text/HTML email body

## Troubleshooting

**Worker not receiving emails:**
- Check Email Routing is enabled for domain
- Verify MX records are configured
- Check Worker logs in Cloudflare dashboard

**API returns 401:**
- Verify API key matches in Worker and Docker

**No Telegram notification:**
- Check TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID are set
- Verify bot has permission to message the chat
