# Manual Test Instructions for CSV Rate System

## Prerequisites

Before running tests, ensure you have:

1. ✅ PostgreSQL running (port 5432)
2. ✅ Redis running (port 6379)
3. ✅ Backend API started (port 4000)
4. ✅ A user account with credentials
5. ✅ An admin account (optional, for admin tests)

## Step 1: Start Infrastructure

```bash
cd /Users/david/Documents/xpeditis/dev/xpeditis2.0

# Start PostgreSQL and Redis
docker-compose up -d

# Verify services are running
docker ps
```

Expected output should show `postgres` and `redis` containers running.

## Step 2: Run Database Migration

```bash
cd apps/backend

# Run migrations to create csv_rate_configs table
npm run migration:run
```

This will:
- Create `csv_rate_configs` table
- Seed 5 companies: SSC Consolidation, ECU Worldwide, TCC Logistics, NVO Consolidation, **Test Maritime Express**

## Step 3: Start Backend API

```bash
cd apps/backend

# Start development server
npm run dev
```

Expected output:
```
[Nest] INFO  [NestFactory] Starting Nest application...
[Nest] INFO  [InstanceLoader] AppModule dependencies initialized
[Nest] INFO  Application is running on: http://localhost:4000
```

Keep this terminal open and running.

## Step 4: Get JWT Token

Open a new terminal and run:

```bash
# Login to get JWT token
curl -X POST http://localhost:4000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "test4@xpeditis.com",
    "password": "SecurePassword123"
  }'
```

**Copy the `accessToken` from the response** and save it for later tests.

Example response:
```json
{
  "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "user": {
    "id": "...",
    "email": "test4@xpeditis.com"
  }
}
```

## Step 5: Test Public Endpoints

### Test 1: Get Available Companies

```bash
curl -X GET http://localhost:4000/api/v1/rates/companies \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"
```

**Expected Result:**
```json
{
  "companies": [
    "SSC Consolidation",
    "ECU Worldwide",
    "TCC Logistics",
    "NVO Consolidation",
    "Test Maritime Express"
  ],
  "total": 5
}
```

✅ **Verify:** You should see 5 companies including "Test Maritime Express"

### Test 2: Get Filter Options

```bash
curl -X GET http://localhost:4000/api/v1/rates/filters/options \
  -H "Authorization: Bearer YOUR_TOKEN_HERE"
```

**Expected Result:**
```json
{
  "companies": ["SSC Consolidation", "ECU Worldwide", "TCC Logistics", "NVO Consolidation", "Test Maritime Express"],
  "containerTypes": ["LCL"],
  "currencies": ["USD", "EUR"]
}
```

### Test 3: Basic Rate Search (NLRTM → USNYC)

```bash
curl -X POST http://localhost:4000/api/v1/rates/search-csv \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d '{
    "origin": "NLRTM",
    "destination": "USNYC",
    "volumeCBM": 25.5,
    "weightKG": 3500,
    "palletCount": 10,
    "containerType": "LCL"
  }'
```

**Expected Result:**
- Multiple results from different companies
- Total price calculated based on max(volume × pricePerCBM, weight × pricePerKG)
- Match scores (0-100%) indicating relevance

**Example response:**
```json
{
  "results": [
    {
      "companyName": "Test Maritime Express",
      "origin": "NLRTM",
      "destination": "USNYC",
      "totalPrice": {
        "amount": 950.00,
        "currency": "USD"
      },
      "transitDays": 22,
      "matchScore": 95,
      "hasSurcharges": false
    },
    {
      "companyName": "SSC Consolidation",
      "origin": "NLRTM",
      "destination": "USNYC",
      "totalPrice": {
        "amount": 1100.00,
        "currency": "USD"
      },
      "transitDays": 22,
      "matchScore": 92,
      "hasSurcharges": true
    }
    // ... more results
  ],
  "totalResults": 15,
  "matchedCompanies": 5
}
```

✅ **Verify:**
1. Results from multiple companies appear
2. Test Maritime Express has lower price than others (~$950 vs ~$1100+)
3. Match scores are calculated
4. Both "all-in" (no surcharges) and surcharged rates appear

### Test 4: Filter by Company

```bash
curl -X POST http://localhost:4000/api/v1/rates/search-csv \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d '{
    "origin": "NLRTM",
    "destination": "USNYC",
    "volumeCBM": 25.5,
    "weightKG": 3500,
    "palletCount": 10,
    "containerType": "LCL",
    "filters": {
      "companies": ["Test Maritime Express"]
    }
  }'
```

✅ **Verify:** Only Test Maritime Express results appear

### Test 5: Filter by Price Range

```bash
curl -X POST http://localhost:4000/api/v1/rates/search-csv \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d '{
    "origin": "NLRTM",
    "destination": "USNYC",
    "volumeCBM": 25.5,
    "weightKG": 3500,
    "palletCount": 10,
    "containerType": "LCL",
    "filters": {
      "minPrice": 900,
      "maxPrice": 1200,
      "currency": "USD"
    }
  }'
```

✅ **Verify:** All results have price between $900-$1200

### Test 6: Filter by Transit Days

```bash
curl -X POST http://localhost:4000/api/v1/rates/search-csv \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d '{
    "origin": "NLRTM",
    "destination": "USNYC",
    "volumeCBM": 25.5,
    "weightKG": 3500,
    "containerType": "LCL",
    "filters": {
      "maxTransitDays": 23
    }
  }'
```

✅ **Verify:** All results have transit ≤ 23 days

### Test 7: Filter by Surcharges (All-in Prices Only)

```bash
curl -X POST http://localhost:4000/api/v1/rates/search-csv \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d '{
    "origin": "NLRTM",
    "destination": "USNYC",
    "volumeCBM": 25.5,
    "weightKG": 3500,
    "containerType": "LCL",
    "filters": {
      "withoutSurcharges": true
    }
  }'
```

✅ **Verify:** All results have `hasSurcharges: false`

## Step 6: Comparator Verification Test

This is the **MAIN TEST** to verify multiple companies appear with different prices.

```bash
curl -X POST http://localhost:4000/api/v1/rates/search-csv \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d '{
    "origin": "NLRTM",
    "destination": "USNYC",
    "volumeCBM": 25,
    "weightKG": 3500,
    "palletCount": 10,
    "containerType": "LCL"
  }' | jq '.results[] | {company: .companyName, price: .totalPrice.amount, transit: .transitDays, match: .matchScore}'
```

**Expected Output (sorted by price):**

```json
{
  "company": "Test Maritime Express",
  "price": 950.00,
  "transit": 22,
  "match": 95
}
{
  "company": "SSC Consolidation",
  "price": 1100.00,
  "transit": 22,
  "match": 92
}
{
  "company": "TCC Logistics",
  "price": 1120.00,
  "transit": 22,
  "match": 90
}
{
  "company": "NVO Consolidation",
  "price": 1130.00,
  "transit": 22,
  "match": 88
}
{
  "company": "ECU Worldwide",
  "price": 1150.00,
  "transit": 23,
  "match": 86
}
```

### ✅ Verification Checklist

- [ ] All 5 companies appear in results
- [ ] Test Maritime Express has lowest price (~$950)
- [ ] Other companies have higher prices (~$1100-$1200)
- [ ] Price difference is clearly visible (10-20% cheaper)
- [ ] Each company has different pricing
- [ ] Match scores are calculated
- [ ] Transit days are displayed
- [ ] Comparator shows multiple offers correctly ✓

## Step 7: Alternative Routes Test

Test other routes to verify CSV data is loaded:

### DEHAM → USNYC

```bash
curl -X POST http://localhost:4000/api/v1/rates/search-csv \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d '{
    "origin": "DEHAM",
    "destination": "USNYC",
    "volumeCBM": 30,
    "weightKG": 4000,
    "containerType": "LCL"
  }'
```

### FRLEH → CNSHG

```bash
curl -X POST http://localhost:4000/api/v1/rates/search-csv \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_TOKEN_HERE" \
  -d '{
    "origin": "FRLEH",
    "destination": "CNSHG",
    "volumeCBM": 50,
    "weightKG": 8000,
    "containerType": "LCL"
  }'
```

## Step 8: Admin Endpoints (Optional)

**Note:** These endpoints require ADMIN role.

### Get All CSV Configurations

```bash
curl -X GET http://localhost:4000/api/v1/admin/csv-rates/config \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
```

### Validate CSV File

```bash
curl -X POST http://localhost:4000/api/v1/admin/csv-rates/validate/Test%20Maritime%20Express \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN"
```

### Upload New CSV File

```bash
curl -X POST http://localhost:4000/api/v1/admin/csv-rates/upload \
  -H "Authorization: Bearer YOUR_ADMIN_TOKEN" \
  -F "file=@/Users/david/Documents/xpeditis/dev/xpeditis2.0/apps/backend/src/infrastructure/storage/csv-storage/rates/test-maritime-express.csv" \
  -F "companyName=Test Maritime Express Updated" \
  -F "fileDescription=Updated fictional carrier rates"
```

## Alternative: Use Automated Test Scripts

Instead of manual curl commands, you can use the automated test scripts:

### Option 1: Bash Script

```bash
cd apps/backend
chmod +x test-csv-api.sh
./test-csv-api.sh
```

### Option 2: Node.js Script

```bash
cd apps/backend
node test-csv-api.js
```

Both scripts will:
1. Authenticate automatically
2. Run all 9 test scenarios
3. Display results with color-coded output
4. Verify comparator functionality

## Troubleshooting

### Error: "Cannot connect to database"

```bash
# Check PostgreSQL is running
docker ps | grep postgres

# Restart PostgreSQL
docker-compose restart postgres
```

### Error: "Unauthorized"

- Verify JWT token is valid (tokens expire after 15 minutes)
- Get a new token using the login endpoint
- Ensure token is correctly copied (no extra spaces)

### Error: "CSV file not found"

- Verify CSV files exist in `apps/backend/src/infrastructure/storage/csv-storage/rates/`
- Check migration was run successfully
- Verify `csv_rate_configs` table has 5 records

### No Results in Search

- Check that origin/destination match CSV data (e.g., NLRTM, USNYC)
- Verify containerType is "LCL"
- Check volume/weight ranges are within CSV limits
- Try without filters first

### Test Maritime Express Not Appearing

- Run migration again: `npm run migration:run`
- Check database: `SELECT company_name FROM csv_rate_configs;`
- Verify CSV file exists: `ls src/infrastructure/storage/csv-storage/rates/test-maritime-express.csv`

## Expected Results Summary

| Test | Expected Result | Verification |
|------|----------------|--------------|
| Get Companies | 5 companies including Test Maritime Express | ✓ Count = 5 |
| Filter Options | Companies, container types, currencies | ✓ Data returned |
| Basic Search | Multiple results from different companies | ✓ Multiple companies |
| Company Filter | Only filtered company appears | ✓ Filter works |
| Price Filter | All results in price range | ✓ Range correct |
| Transit Filter | All results ≤ max transit days | ✓ Range correct |
| Surcharge Filter | Only all-in rates | ✓ No surcharges |
| Comparator | All 5 companies with different prices | ✓ Test Maritime Express cheapest |
| Alternative Routes | Results for DEHAM, FRLEH routes | ✓ CSV data loaded |

## Success Criteria

The CSV rate system is working correctly if:

1. ✅ All 5 companies are available
2. ✅ Search returns results from multiple companies simultaneously
3. ✅ Test Maritime Express appears with lower prices (10-20% cheaper)
4. ✅ All filters work correctly (company, price, transit, surcharges)
5. ✅ Match scores are calculated (0-100%)
6. ✅ Total price includes freight + surcharges
7. ✅ Comparator shows clear price differences between companies
8. ✅ Results can be sorted by different criteria

## Next Steps After Testing

Once all tests pass:

1. **Frontend Integration**: Test the Next.js frontend at http://localhost:3000/rates/csv-search
2. **Admin Interface**: Test CSV upload at http://localhost:3000/admin/csv-rates
3. **Performance**: Run load tests with k6
4. **Documentation**: Update API documentation
5. **Deployment**: Deploy to staging environment
