# Caterpoint Integration Module

A Yii2 extension for integrating with the Caterpoint API to manage and synchronize orders.

## Overview

This module provides:
- **Order Download**: Fetch orders from Caterpoint API
- **Cursor Management**: Resume imports from where you left off
- **RESTful API**: HTTP endpoints for triggering imports
- **Console Commands**: CLI tools for batch imports and scheduled tasks
- **Flexible Data Mapping**: Adapt Caterpoint order data to your system
- **NGauge Cart Integration**: Creates local baskets/orders via `portalpeople/ngauge-cart`
- **Account/Product Mapping**: Resolves delivery accounts and products from Caterpoint-specific metadata fields

## Features

✅ Fetch orders from Caterpoint API  
✅ Track import cursor for incremental syncs  
✅ Dry-run mode for previewing changes  
✅ Console command for scheduled imports  
✅ REST API endpoints for web triggers  
✅ Comprehensive error handling  
✅ Status mapping customization  
✅ Persistent cursor storage  

## Requirements

- PHP 8.4+
- Yii2 Framework ~2.0.0+
- yiisoft/yii2-httpclient ~2.0.0
- Caterpoint API access (test or production)

**Note:** Caterpoint API returns XML responses. The module automatically detects and normalizes XML to JSON.

## Installation

1. Install via Composer:
```bash
composer require portalpeople/ngauge-caterpoint
```

2. Configure the module in your Yii2 application:

```php
// config/web.php or console/config/main.php
return [
    'modules' => [
        'caterpoint' => [
            'class' => 'PortalPeople\caterpoint\Module',
            'apiEndpoint' => 'https://cp3-bayley-test.caterpoint.co.uk/api',
            'apiToken' => env('CATERPOINT_API_TOKEN', 'your-token'),
        ],
    ],
];
```

## Configuration

See [src/config/caterpoint.php](src/config/caterpoint.php) for all available options.

### Required Parameters

- **apiEndpoint**: Base URL of Caterpoint API (e.g., https://cp3-bayley-test.caterpoint.co.uk/api)
- **apiToken**: Bearer token for API authentication

### Optional Parameters

| Parameter | Default | Description |
|-----------|---------|-------------|
| `requestTimeout` | 30 | HTTP request timeout in seconds |
| `pollLimit` | 100 | Max orders per API request |
| `orderNumberPrefix` | `CP-` | Prefix for generated order numbers |
| `orderImportCursorFile` | `@runtime/caterpoint/order-import.cursor` | File for cursor persistence |
| `statusMap` | (see below) | Status code mappings |
| `debug` | false | Enable debug logging |

## Quick Start

### Console Command

```bash
# Basic import
php yii caterpoint/order-import

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

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

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

### REST API

The module provides two routing patterns:

**1. Friendly HTML Interface** (`/NGauge/caterpoint/*`)
- Returns user-friendly HTML views
- Includes flash messages and error handling
- Designed for browser access

```
GET  /NGauge/caterpoint/order/index          - Order management dashboard
GET  /NGauge/caterpoint/order/fetch-raw      - View raw order data (HTML)
POST /NGauge/caterpoint/order/import         - Trigger import
POST /NGauge/caterpoint/order/reset          - Reset cursor
```

**2. Raw JSON/XML API** (`/api/caterpoint/*`)
- Returns raw JSON or XML responses
- No HTML, just structured data
- Designed for programmatic access

```bash
# Fetch raw order data (JSON)
GET /api/caterpoint/order/fetch-raw?limit=1

# Trigger import
POST /api/caterpoint/order/import
{ "dryRun": false, "limit": 50 }

# Get status
GET /api/caterpoint/order/status

# Reset cursor
POST /api/caterpoint/order/reset
```

**Format Override:**
```bash
# Force JSON response on /NGauge routes
GET /NGauge/caterpoint/order/fetch-raw?limit=1&format=json

# Force XML response
GET /NGauge/caterpoint/order/fetch-raw?limit=1&format=xml
```

### Programmatic Usage

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

$result = $service->run();
echo "Created: {$result['created']}, Updated: {$result['updated']}\n";
```

## Order Mapping

The import flow expects Caterpoint-specific identifiers to be stored in NGauge metadata:

- `Accounts.extended.caterpoint_code` is used to resolve the delivery customer account.
- `Products.data.caterpoint.stock_code` is used to resolve local stock codes from Caterpoint line items.
- Imported orders are created through `PortalPeople\cart\models\Cart::fromApi()` and then tagged as Caterpoint orders in the local system.

## Caterpoint API Endpoints

The module supports these Caterpoint API endpoints:

- **GET** `/api/integration/distributor/orders` - Fetch orders
- **DELETE** `/api/integration/distributor/order/{order_id}/mark-exported` - Mark as exported
- **POST** `/api/integration/distributor/order-confirmations` - Submit confirmations
- **POST** `/api/integration/distributor/invoices` - Submit invoices
- **POST** `/api/integration/distributor/credit-notes` - Submit credit notes

See [Caterpoint API Documentation](https://cp3-bayley-test.caterpoint.co.uk/api/documentation)

## Architecture

```
src/
├── Module.php                           # Main module
├── components/CaterpointClient.php      # API client
├── models/
│   ├── accounts/Caterpoint.php          # Account metadata segment (`caterpoint_code`)
│   ├── import/Products.php              # Product lookup helper by Caterpoint stock code
│   └── products/Caterpoint.php          # Product metadata segment
├── services/
│   ├── OrderImportService.php          # Import logic
│   └── CaterpointCursorStore.php       # Cursor storage
├── commands/OrderImportController.php  # CLI command
├── controllers/OrderController.php     # REST API
└── models/CaterpointOrder.php          # Template model
```

## Developer Guidelines

For module development, architecture patterns, and release workflows, see [AI_Guideline.md](AI_Guideline.md).

### Release Workflow

After pushing a new version tag, trigger the Statis package manager webhook:
```bash
php yii statis-webhook/webhook/trigger
```

This updates the Composer package index with the new release.

**Note:** Requires [portalpeople/statis-webhook](https://dev.azure.com/PortalPeopleUK/NGauge_Modules/_git/statis-webhook) module configured in your console application.

## License

MIT License - See [LICENSE.md](LICENSE.md)

## Support

- Issues: https://dev.azure.com/PortalPeopleUK/NGauge_Modules/_workitems
- Source: https://dev.azure.com/PortalPeopleUK/NGauge_Modules/_git/ngauge-caterpoint

## Authors

- **Portal People** - [www.portalpeople.uk](https://www.portalpeople.uk)
