# Steadfast Courier Setup Guide

## 🎯 Overview

This system uses **Cloudflare Workers** as a secure backend proxy to communicate with Steadfast Courier API. Your API credentials are stored securely in Worker environment variables and never exposed to the browser.

---

## 📋 Prerequisites

1. **Steadfast Courier Account**
   - Sign up at [steadfast.com.bd](https://steadfast.com.bd)
   - Get your API credentials from the merchant portal

2. **Cloudflare Account**
   - Free account at [cloudflare.com](https://cloudflare.com](https://cloudflare.com)

3. **Wrangler CLI** (Cloudflare's CLI tool)
   ```bash
   npm install -g wrangler
   wrangler login
   ```

---

## 🚀 Step 1: Deploy Cloudflare Worker

### Option A: Using Wrangler CLI (Recommended)

1. Navigate to the project folder:
   ```bash
   cd cod-extractor
   ```

2. Deploy the Worker:
   ```bash
   wrangler deploy
   ```

3. Your Worker will be live at:
   ```
   https://cod-extractor-api.YOUR-SUBDOMAIN.workers.dev
   ```

### Option B: Using Cloudflare Dashboard

1. Go to [Cloudflare Dashboard → Workers & Pages](https://dash.cloudflare.com/?to=/:account/workers)
2. Click **"Create Application"**
3. Select **"Create Worker"**
4. Name: `cod-extractor-api`
5. Replace the default code with content from `worker/index.js`
6. Click **"Deploy"**

---

## 🔐 Step 2: Configure Steadfast Credentials

### Using Wrangler CLI (Secure - Recommended)

```bash
# Navigate to project folder
cd cod-extractor

# Set API Key (you'll be prompted to enter securely)
wrangler secret put STEADFAST_API_KEY

# Set Secret Key
wrangler secret put STEADFAST_SECRET_KEY

# (Optional) Set custom base URL if needed
wrangler secret put STEADFAST_BASE_URL
```

### Using Cloudflare Dashboard

1. Go to your Worker: **Workers & Pages → cod-extractor-api**
2. Click **"Settings"** tab
3. Scroll to **"Variables and Secrets"**
4. Click **"Add variable"**
5. Add these variables:

   | Variable Name | Value | Type |
   |--------------|-------|------|
   | `STEADFAST_API_KEY` | Your API Key | Secret |
   | `STEADFAST_SECRET_KEY` | Your Secret Key | Secret |
   | `STEADFAST_BASE_URL` | `https://portal.steadfast.com.bd/api/v1` | Plaintext |

6. Click **"Save"**

---

## 🔗 Step 3: Connect Frontend to Worker

1. Open your deployed website (e.g., `https://cod-order-extractor.pages.dev`)
2. Click **"🚚 Steadfast"** in the navigation
3. Enter your Worker URL:
   ```
   https://cod-extractor-api.YOUR-SUBDOMAIN.workers.dev
   ```
4. Click **"💾 Save & Connect"**
5. You should see: **"✓ Connected to Steadfast"**

---

## ✅ Step 4: Verify Connection

1. Click **"💰 Check Balance"** in the modal
2. If your balance appears, everything is working!
3. Close the modal

---

## 📦 Step 5: Submit Orders

### Submit Single Order
- Extract orders from WhatsApp text
- Click **"🚚 Submit to Steadfast"** on any order card
- Tracking code will appear on the card

### Submit All Orders
- Extract orders from WhatsApp text
- Click **"🚚 Submit All to Steadfast"** button
- Progress bar shows submission status
- All valid orders will be submitted in batches

---

## 🔍 API Endpoints

Your Worker exposes these endpoints:

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/api/check-config` | GET | Check if credentials are configured |
| `/api/balance` | GET | Get account balance |
| `/api/create-order` | POST | Create single order |
| `/api/create-bulk-orders` | POST | Create bulk orders (max 500) |
| `/api/track/cid/{id}` | GET | Track by consignment ID |
| `/api/track/invoice/{invoice}` | GET | Track by invoice |
| `/api/track/code/{code}` | GET | Track by tracking code |

---

## 🧪 Testing

Test your Worker is working:

```bash
# Check configuration
curl https://cod-extractor-api.YOUR-SUBDOMAIN.workers.dev/api/check-config

# Get balance
curl https://cod-extractor-api.YOUR-SUBDOMAIN.workers.dev/api/balance
```

Expected response:
```json
{
  "configured": true,
  "has_api_key": true,
  "has_secret_key": true
}
```

---

## 🐛 Troubleshooting

### "Not connected" error
- Verify Worker is deployed and accessible
- Check Worker URL in frontend matches your actual Worker URL
- Ensure credentials are set in Worker environment variables

### "Failed to create order" error
- Check Steadfast API credentials are correct
- Verify recipient phone format: `01XXXXXXXXX` (11 digits)
- Ensure all required fields are present (name, phone, address, amount)

### CORS errors
- Worker already handles CORS automatically
- If using custom domain, ensure it matches `ALLOWED_ORIGIN` variable

### "Invalid phone format" error
- Phone must be 11 digits starting with `01`
- Parser automatically converts Bangla digits to English
- Format: `01712345678` (not `+8801712345678`)

---

## 🔒 Security

- ✅ API credentials stored in Worker environment (never in browser)
- ✅ CORS enabled for your frontend domain
- ✅ All requests go through your Worker (proxy pattern)
- ✅ No credentials in client-side code
- ✅ Secrets are encrypted at rest in Cloudflare

---

## 📞 Support

- **Steadfast API Issues**: Contact Steadfast support
- **Worker/Cloudflare Issues**: Check [Cloudflare Docs](https://developers.cloudflare.com/workers/)
- **Parser Issues**: Check browser console for errors

---

## 🎉 You're Ready!

Your COD Order Extractor is now fully integrated with Steadfast Courier. Extract orders from WhatsApp and submit them directly to Steadfast with one click!
