# Caterpoint Module - Implementation Summary

## What Was Created

The ngauge-caterpoint module has been completely rebuilt from scratch to provide a production-ready Caterpoint API integration for managing and synchronizing orders.

### Project Structure

```
src/
├── Module.php                          # Main module class with configuration
├── components/
│   └── CaterpointClient.php           # GuzzleHTTP-based API client
├── services/
│   ├── CaterpointCursorStore.php      # Persistent cursor management
│   └── OrderImportService.php         # Core order import and sync logic
├── commands/
│   └── OrderImportController.php      # Console command for CLI imports
├── controllers/
│   └── OrderController.php             # REST API endpoints
├── models/
│   └── CaterpointOrder.php            # Template model for orders
└── config/
    └── caterpoint.php                 # Configuration examples
```

## Key Components

### 1. **Module.php** - Main Module Class
- Bootstraps the module and registers it with Yii2
- Loads configuration from application params
- Provides factory methods for creating clients and services
- Maps Caterpoint order statuses to your system
- Generates local order numbers from Caterpoint references

**Key Methods:**
- `createClient()` - Create a CaterpointClient instance
- `createOrderImportService()` - Create an OrderImportService instance
- `mapStatus()` - Map Caterpoint status to local system
- `makeOrderNumber()` - Generate local order numbers
- `isConfigured()` - Check if module has required configuration

### 2. **CaterpointClient** - API Communication
HTTP client built on GuzzleHTTP that handles:
- Bearer token authentication
- Request building and response parsing
- Error handling and logging

**Available Methods:**
- `getOrders()` - Fetch orders with filters
- `getOrdersUpdatedSince()` - Fetch orders since cursor
- `getOrder()` - Get single order
- `markOrderExported()` - Mark order as exported
- `submitOrderConfirmation()` - Submit confirmations
- `submitInvoice()` - Submit invoices
- `submitCreditNote()` - Submit credit notes

### 3. **OrderImportService** - Core Import Logic
Orchestrates the order import process:
- Fetches orders from API using client
- Tracks import progress with cursor
- Supports dry-run mode for previewing
- Handles transaction-based imports
- Comprehensive error reporting
- Placeholder methods for system-specific mapping

**Key Methods:**
- `run()` - Main import method
- `previewOrder()` - Preview changes
- `importOrder()` - Import single order
- `normalizeOrders()` - Normalize API response data

### 4. **CaterpointCursorStore** - Progress Tracking
Persists import cursor across runs:
- Cache-based storage (primary)
- File-based fallback storage
- Get/set/clear operations
- Automatic directory creation

### 5. **OrderImportController** - CLI Command
Console command for batch imports with options:

```bash
php yii caterpoint/order-import [options]
```

**Options:**
- `--dry-run` - Preview without persisting
- `--limit=N` - Max orders to import
- `--reset` - Clear cursor and start fresh
- `--verbose` - Detailed output

### 6. **OrderController** - REST API
HTTP endpoints for web-based triggers:

**Endpoints:**
- `POST /api/caterpoint/orders/import` - Trigger import
- `GET /api/caterpoint/orders/status` - Get import status
- `POST /api/caterpoint/orders/reset` - Reset cursor
- `POST /api/caterpoint/orders/mark-exported?id=X` - Mark exported
- `GET /api/caterpoint/orders/fetch-raw` - Get raw API data

### 7. **CaterpointOrder** - Template Model
Template ActiveRecord model showing:
- Database schema example
- External ID tracking
- Status mapping
- Helper methods (findByExternalId, findOrCreate)

### 8. **Configuration Examples**
Complete configuration guide with:
- Required parameters
- Optional parameters with defaults
- Usage examples
- API endpoint reference

## Configuration

Add to your Yii2 configuration (web.php, console/config/main.php):

```php
'modules' => [
    'caterpoint' => [
        'class' => 'PortalPeople\caterpoint\Module',
        'apiEndpoint' => 'https://cp3-bayley-test.caterpoint.co.uk/api',
        'apiToken' => env('CATERPOINT_API_TOKEN'),
        
        // Optional
        'requestTimeout' => 30,
        'pollLimit' => 100,
        'orderNumberPrefix' => 'CP-',
        'statusMap' => [
            'pending' => 'Pending',
            'confirmed' => 'Confirmed',
            'dispatched' => 'Dispatched',
            'delivered' => 'Delivered',
            'cancelled' => 'Cancelled',
        ],
        'debug' => false,
    ],
],
```

## Caterpoint API Endpoints Supported

The module provides integration with:

1. **GET /api/integration/distributor/orders**
   - Fetch orders with optional filters
   - Pagination support (limit, offset)

2. **DELETE /api/integration/distributor/order/{order_id}/mark-exported**
   - Mark orders as exported/deleted

3. **POST /api/integration/distributor/order-confirmations**
   - Submit order confirmations

4. **POST /api/integration/distributor/invoices**
   - Submit invoices

5. **POST /api/integration/distributor/credit-notes**
   - Submit credit notes

See: https://cp3-bayley-test.caterpoint.co.uk/api/documentation

## Usage Patterns

### 1. Console Import (Scheduled/Manual)
```bash
php yii caterpoint/order-import
```

### 2. REST API Import
```bash
curl -X POST http://localhost/api/caterpoint/orders/import \
  -d '{"dryRun": false, "limit": 100}'
```

### 3. Programmatic Usage
```php
$module = Yii::$app->getModule('caterpoint');
$service = $module->createOrderImportService();
$result = $service->run();
```

### 4. Direct API Access
```php
$client = $module->createClient();
$orders = $client->getOrders([], 100);
$client->markOrderExported('ORDER_ID');
```

## Next Steps for Implementation

1. **Create Order Model**: Extend CaterpointOrder template with your system's fields
2. **Implement Mapping**: Add logic to `OrderImportService::mapOrderData()`
3. **Implement Storage**: Add logic to `OrderImportService::findOrCreateOrder()`
4. **Configure Module**: Add configuration to your application
5. **Test Import**: Run dry-run to verify API connectivity
6. **Schedule Imports**: Use console command in cron or task scheduler

## Error Handling

The module provides:
- Comprehensive error messages
- `--verbose` flag for debugging
- Dry-run mode for testing
- Transaction-based imports for data consistency
- Detailed error logs per order

## Features at a Glance

✅ **Incremental Syncs** - Resume from cursor on every run
✅ **Dry-Run Mode** - Preview changes without persisting
✅ **Flexible Mapping** - Adapt data to your system
✅ **Status Translation** - Configurable status mapping
✅ **Error Recovery** - Individual order failures don't crash import
✅ **API Support** - Submit confirmations, invoices, credit notes
✅ **CLI Command** - Integrate with cron/task scheduler
✅ **REST Endpoints** - Trigger via HTTP
✅ **Persistent State** - Resume across restarts
✅ **Comprehensive Logging** - Debug any issues

## Documentation Files

- [README.md](../README.md) - Full user guide
- [SETTINGS.md](../SETTINGS.md) - Configuration details
- [composer.json](../composer.json) - Dependencies and metadata
- [src/config/caterpoint.php](caterpoint.php) - Configuration examples

## Support

For issues or questions:
- Azure DevOps: https://dev.azure.com/PortalPeopleUK/NGauge_Modules
- Repository: https://dev.azure.com/PortalPeopleUK/NGauge_Modules/_git/ngauge-caterpoint
