# Caterpoint Module - Quick Reference Guide

## Configuration

```php
'modules' => [
    'caterpoint' => [
        'class' => 'PortalPeople\caterpoint\Module',
        'apiEndpoint' => 'https://cp3-bayley-test.caterpoint.co.uk/api',
        'apiToken' => env('CATERPOINT_API_TOKEN'),
    ],
],
```

## Console Commands

```bash
# Import orders
php yii caterpoint/order-import

# Preview only (dry-run)
php yii caterpoint/order-import --dry-run

# Import max 50 orders
php yii caterpoint/order-import --limit=50

# Reset and start fresh
php yii caterpoint/order-import --reset

# Verbose output
php yii caterpoint/order-import --verbose
```

## REST API Endpoints

### Import Orders
```bash
POST /api/caterpoint/orders/import
Content-Type: application/json

{
    "dryRun": false,
    "limit": 50,
    "reset": false
}
```

**Response:**
```json
{
    "success": true,
    "message": "Import completed",
    "result": {
        "fetched": 50,
        "processed": 50,
        "created": 10,
        "updated": 40,
        "failed": 0,
        "nextCursor": "2026-03-06T12:34:56Z"
    }
}
```

### Get Status
```bash
GET /api/caterpoint/orders/status
```

### Reset Cursor
```bash
POST /api/caterpoint/orders/reset
```

### Mark Order Exported
```bash
POST /api/caterpoint/orders/mark-exported?id=ORDER_ID
```

### Fetch Raw Orders
```bash
GET /api/caterpoint/orders/fetch-raw?limit=100
```

## Programmatic Usage

### Basic Import
```php
$module = Yii::$app->getModule('caterpoint');
$service = $module->createOrderImportService();

// Run import
$result = $service->run();

// Check results
echo "Created: {$result['created']}\n";
echo "Updated: {$result['updated']}\n";
echo "Failed: {$result['failed']}\n";
```

### With Options
```php
// Import 50 orders with dry-run
$result = $service->run(
    $cursor = null,      // Resume from cursor
    $limit = 50,         // Max orders
    $dryRun = true       // Preview only
);
```

### API Client
```php
$client = $module->createClient();

// Get orders
$response = $client->getOrdersUpdatedSince(null, 100);
$orders = $response['orders'];
$nextCursor = $response['nextCursor'];

// Get single order
$order = $client->getOrder('ORDER_ID');

// Mark as exported
$client->markOrderExported('ORDER_ID');

// Submit confirmation
$client->submitOrderConfirmation([
    'orderId' => 'external_id',
    'status' => 'confirmed',
]);

// Submit invoice
$client->submitInvoice([
    'orderId' => 'external_id',
    'invoiceNumber' => 'INV-123',
]);
```

## Module Methods

### Get Module
```php
$module = Yii::$app->getModule('caterpoint');
```

### Create Client
```php
$client = $module->createClient();
```

### Create Service
```php
$service = $module->createOrderImportService();
```

### Check Configuration
```php
if ($module->isConfigured()) {
    // Safe to use
}
```

### Map Status
```php
$localStatus = $module->mapStatus('confirmed');
```

### Generate Order Number
```php
$orderNo = $module->makeOrderNumber('CP-12345');
// Result: "CP-CP-12345" (with prefix)
```

## Error Handling

```php
try {
    $service = $module->createOrderImportService();
    $result = $service->run();
    
    if ($result['failed'] > 0) {
        foreach ($result['errors'] as $error) {
            Yii::error($error['message']);
            // $error['code'] - HTTP status or error code
            // $error['order'] - Failed order data
        }
    }
} catch (\Throwable $e) {
    Yii::error('Import failed: ' . $e->getMessage());
}
```

## Configuration Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `apiEndpoint` | string | - | **Required** - Caterpoint API URL |
| `apiToken` | string | - | **Required** - API authentication token |
| `requestTimeout` | int | 30 | HTTP request timeout (seconds) |
| `pollLimit` | int | 100 | Orders per API request |
| `orderNumberPrefix` | string | `CP-` | Prefix for generated order numbers |
| `orderImportCursorKey` | string | `caterpoint.order-import.cursor` | Cache key for cursor |
| `orderImportCursorFile` | string | `@runtime/caterpoint/order-import.cursor` | File path for cursor |
| `statusMap` | array | (see below) | Status code mappings |
| `debug` | bool | false | Enable debug logging |

## Default Status Mapping

```php
'statusMap' => [
    'pending' => 'Pending',
    'processing' => 'Processing',
    'confirmed' => 'Confirmed',
    'dispatched' => 'Dispatched',
    'delivered' => 'Delivered',
    'cancelled' => 'Cancelled',
]
```

## Implementation Checklist

- [ ] Add module to Yii2 configuration
- [ ] Set `CATERPOINT_API_TOKEN` environment variable
- [ ] Create Order model for your system
- [ ] Configure model class in OrderImportService
- [ ] Implement `findOrCreateOrder()` method
- [ ] Implement `mapOrderData()` method
- [ ] Create database schema for orders
- [ ] Test with `--dry-run` first
- [ ] Set up cron/scheduler for regular imports
- [ ] Monitor logs for import errors

## File Structure

```
src/
├── Module.php                    # Main module
├── components/
│   └── CaterpointClient.php     # API client
├── services/
│   ├── OrderImportService.php   # Import logic
│   └── CaterpointCursorStore.php # Cursor storage
├── commands/
│   └── OrderImportController.php # CLI command
├── controllers/
│   └── OrderController.php      # REST API
├── models/
│   └── CaterpointOrder.php      # Template model
└── config/
    └── caterpoint.php           # Config examples
```

## Useful Links

- [Full Documentation](README.md)
- [Implementation Details](IMPLEMENTATION_SUMMARY.md)
- [Configuration Guide](src/config/caterpoint.php)
- [Caterpoint API Docs](https://cp3-bayley-test.caterpoint.co.uk/api/documentation)
- [Repository](https://dev.azure.com/PortalPeopleUK/NGauge_Modules/_git/ngauge-caterpoint)

## Troubleshooting

### "Module not configured"
- Ensure `apiEndpoint` and `apiToken` are set
- Check environment variables
- Verify configuration in application config

### Orders not being imported
- Run with `--dry-run` to verify API connectivity
- Check logs for specific error messages
- Verify cursor with `GET /api/caterpoint/orders/status`

### Connection timeouts
- Increase `requestTimeout` in configuration
- Check network connectivity to Caterpoint API
- Verify firewall/proxy settings

### Cursor issues
- Reset cursor: `php yii caterpoint/order-import --reset`
- Or: `POST /api/caterpoint/orders/reset`
- Check cursor file: `@runtime/caterpoint/order-import.cursor`

## Need Help?

1. Check [IMPLEMENTATION_SUMMARY.md](IMPLEMENTATION_SUMMARY.md) for detailed info
2. Review [README.md](README.md) for complete guide
3. Check [src/config/caterpoint.php](src/config/caterpoint.php) for examples
4. See error logs in `@runtime/logs/`
5. Contact Portal People development team
