# ERP to WooCommerce Order Sync Implementation

## Overview

This implementation provides a complete solution for syncing ERP orders to WooCommerce. The system includes:

1. **Job-based processing** for reliable order synchronization
2. **Automatic customer creation** in WooCommerce
3. **Product mapping** using WooCommerce product IDs
4. **Payment method mapping** between ERP and WooCommerce
5. **Comprehensive error handling** and logging
6. **Test functionality** for verification

## Components

### 1. WooCommerceWebhookSaleOrder Job

**File:** `app/Jobs/WooCommerceWebhookSaleOrder.php`

This job handles the actual synchronization process:

- Loads transaction with all related data (sell lines, products, variations, contact, payments)
- Determines whether to create or update the WooCommerce order
- Calls appropriate methods in WoocommerceUtil
- Provides comprehensive logging for debugging

**Usage:**
```php
// Dispatch the job when a transaction is created/updated
WooCommerceWebhookSaleOrder::dispatch($transaction_id);
```

### 2. WoocommerceUtil Methods

**File:** `Modules/Woocommerce/Utils/WoocommerceUtil.php`

#### createOrderInWooCommerce($business_id, $transaction)
Creates a new order in WooCommerce from an ERP transaction.

#### updateOrderInWooCommerce($business_id, $transaction)
Updates an existing order in WooCommerce from an ERP transaction.

#### formatTransactionToWooCommerceOrder($business_id, $transaction)
Formats ERP transaction data to WooCommerce API format.

#### createOrFindWooCommerceCustomer($business_id, $contact)
Creates or finds a customer in WooCommerce based on ERP contact data.

#### erpStatusToWooCommerceStatus($erp_status, $payment_status)
Maps ERP status to WooCommerce order status.

#### erpPaymentMethodToWooCommerce($erp_method)
Maps ERP payment methods to WooCommerce payment methods.

### 3. Test Controller Method

**File:** `Modules/Woocommerce/Http/Controllers/WoocommerceController.php`

#### testErpToWooOrderSync()
Provides a test endpoint to verify the sync functionality.

**Route:** `GET /woocommerce/test-erp-to-woo-order-sync`

## Data Flow

### 1. Order Creation Flow

```
ERP Transaction Created
        ↓
WooCommerceWebhookSaleOrder::dispatch($transaction_id)
        ↓
Job loads transaction with relationships
        ↓
Check if woocommerce_order_id exists
        ↓
If exists: updateOrderInWooCommerce()
If not: createOrderInWooCommerce()
        ↓
Format transaction data for WooCommerce API
        ↓
Create/find customer in WooCommerce
        ↓
Map products using woocommerce_product_id
        ↓
Map payment methods and status
        ↓
Send API request to WooCommerce
        ↓
Update transaction with woocommerce_order_id
        ↓
Log success/failure
```

### 2. Data Mapping

#### Customer Data
- **ERP Contact** → **WooCommerce Customer**
  - `first_name`, `last_name` → `first_name`, `last_name`
  - `email` → `email`
  - `mobile` → `phone`
  - `address_line_1`, `city`, `state`, etc. → `billing` and `shipping` addresses

#### Product Data
- **ERP Sell Lines** → **WooCommerce Line Items**
  - `product.woocommerce_product_id` → `product_id`
  - `variation.woocommerce_variation_id` → `variation_id` (for variable products)
  - `quantity` → `quantity`
  - `unit_price` → `total`, `subtotal`
  - `item_tax` → `total_tax`, `subtotal_tax`

#### Order Data
- **ERP Transaction** → **WooCommerce Order**
  - `status` + `payment_status` → `status` (mapped)
  - `final_total` → `total`
  - `total_before_tax` → `subtotal`
  - `tax_amount` → `total_tax`
  - `discount_amount` → `discount_total`
  - `payment_status` → `set_paid`

#### Payment Methods
- `cash` → `cod` (Cash on Delivery)
- `card` → `stripe`
- `bank_transfer` → `bacs`
- `cheque` → `cheque`
- `other` → `bacs`

#### Status Mapping
- `draft` → `pending`
- `final` + `paid` → `completed`
- `final` + `due` → `processing`
- `ordered` → `processing`

## Prerequisites

### 1. WooCommerce API Configuration
Ensure WooCommerce API is properly configured in the ERP:
- WooCommerce site URL
- Consumer Key
- Consumer Secret
- Location mapping

### 2. Product Synchronization
Products must be synced to WooCommerce first to get `woocommerce_product_id` values.

### 3. Database Fields
Ensure the following fields exist:
- `transactions.woocommerce_order_id` (nullable)
- `products.woocommerce_product_id` (nullable)
- `variations.woocommerce_variation_id` (nullable)

## Usage Examples

### 1. Manual Order Sync
```php
// In your controller or service
$transaction = Transaction::find($transaction_id);
$woocommerce = new WoocommerceUtil(new TransactionUtil(), new ProductUtil());

$result = $woocommerce->createOrderInWooCommerce($business_id, $transaction);

if ($result['success']) {
    echo "Order synced successfully. WooCommerce ID: " . $result['woocommerce_order_id'];
} else {
    echo "Sync failed: " . $result['error'];
}
```

### 2. Automatic Sync on Transaction Creation
```php
// In PaymentOrderController or similar
public function createOrder(Request $request)
{
    // ... existing order creation logic ...
    
    $transaction = Transaction::create($transaction_data);
    
    // Dispatch sync job
    WooCommerceWebhookSaleOrder::dispatch($transaction->id);
    
    return response()->json(['success' => true, 'transaction_id' => $transaction->id]);
}
```

### 3. Testing the Sync
Visit: `/woocommerce/test-erp-to-woo-order-sync`

This will:
- Find a suitable transaction for testing
- Attempt to sync it to WooCommerce
- Return success/failure with details

## Error Handling

### 1. Missing WooCommerce Product IDs
If a product doesn't have a `woocommerce_product_id`, it will be skipped with a warning log.

### 2. API Connection Issues
Connection failures are caught and logged with detailed error information.

### 3. Customer Creation Failures
If customer creation fails, the order will be created as a guest order.

### 4. Invalid Data
Missing or invalid data is handled gracefully with appropriate fallbacks.

## Logging

The system provides comprehensive logging:

- **Info logs** for successful operations
- **Warning logs** for skipped items
- **Error logs** for failures with stack traces

Log entries include:
- Transaction IDs
- WooCommerce order IDs
- Error messages
- Performance metrics

## Configuration

### Environment Variables
```env
# Optional: Set sync style
SYNC_STYLE=managemore
```

### WooCommerce API Settings
Configure in ERP admin panel:
- WooCommerce site URL
- Consumer Key
- Consumer Secret
- Default location
- Tax settings
- Product field mappings

## Troubleshooting

### Common Issues

1. **"Product does not have WooCommerce ID"**
   - Sync products to WooCommerce first
   - Check product mapping in admin panel

2. **"Unable to connect with WooCommerce"**
   - Verify API credentials
   - Check WooCommerce site accessibility
   - Ensure API is enabled in WooCommerce

3. **"Customer creation failed"**
   - Check customer data completeness
   - Verify WooCommerce customer permissions
   - Orders will be created as guest orders

4. **"No suitable transaction found"**
   - Create a sale transaction first
   - Ensure transaction has products with WooCommerce IDs

### Debug Steps

1. Check application logs for detailed error messages
2. Verify WooCommerce API credentials
3. Test API connection manually
4. Ensure products are synced to WooCommerce
5. Check transaction data completeness

## Future Enhancements

1. **Batch Processing** - Sync multiple orders at once
2. **Webhook Support** - Real-time sync on order changes
3. **Order Updates** - Handle order modifications
4. **Inventory Sync** - Real-time stock updates
5. **Customer Groups** - Map ERP customer groups to WooCommerce
6. **Shipping Methods** - Enhanced shipping method mapping
7. **Tax Handling** - Advanced tax calculation and mapping

## Security Considerations

1. **API Credentials** - Store securely and rotate regularly
2. **Data Validation** - Validate all input data
3. **Error Handling** - Don't expose sensitive information in errors
4. **Rate Limiting** - Implement API rate limiting
5. **Logging** - Avoid logging sensitive customer data

## Performance Considerations

1. **Job Queues** - Use queues for background processing
2. **Database Indexing** - Index frequently queried fields
3. **API Caching** - Cache WooCommerce API responses where appropriate
4. **Batch Operations** - Use batch operations for multiple items
5. **Connection Pooling** - Reuse API connections when possible 