# Zhik Myoba Integration Module

## Overview

The Zhik Myoba module provides bi-directional integration between Magento 2 and MYOB AccountRight ERP system. It synchronizes customers, products, inventory, prices, orders, and shipments to maintain data consistency across both platforms.

**Version**: 1.4.4
**Compatibility**: Magento 2.4.8-p1 Enterprise Edition
**ERP System**: MYOB AccountRight API v2

## Features

### Core Integration
- **Bi-directional Data Sync**: Real-time and scheduled synchronization
- **Customer Management**: Sync customer data, price classes, and credit terms
- **Product & Inventory**: Real-time stock levels and product data sync
- **Price Synchronization**: Multi-currency, customer-specific, and price class pricing
- **Order Processing**: Submit orders to MYOB with real-time status updates
- **Shipment Tracking**: Sync shipment data and tracking information

### Inventory Management
- **Multi-warehouse Support**: Track inventory across multiple MYOB warehouses
- **Stock Bypass System**: Configurable inventory reservation control for special order types
- **Real-time Updates**: Instant stock level synchronization from MYOB

### Advanced Features
- **Custom Price Types**: Support for Base (B), Customer (C), Price Class (P), and custom types
- **Order Type Differentiation**: FO (Forward Order) and SF (Sales Forward) type support
- **Tax Integration**: MYOB tax code synchronization
- **Watchdog Service**: Automated sync job monitoring and recovery

## Installation

### Via Composer (Recommended)

```bash
composer require zhik/myoba
bin/magento module:enable Zhik_Myoba
bin/magento setup:upgrade
bin/magento setup:di:compile
bin/magento setup:static-content:deploy -f
bin/magento cache:flush
```

### Manual Installation

1. Create the module directory:
   ```bash
   mkdir -p app/code/Zhik/Myoba
   ```

2. Copy module files to the directory

3. Enable the module:
   ```bash
   bin/magento module:enable Zhik_Myoba
   bin/magento setup:upgrade
   bin/magento setup:di:compile
   bin/magento setup:static-content:deploy -f
   bin/magento cache:flush
   ```

## Configuration

Navigate to **Stores > Configuration > Zhik Extensions > Myoba Integration** in the admin panel.

### Connection Settings
- **API URL**: MYOB AccountRight API endpoint
- **Username**: MYOB API username
- **Password**: MYOB API password
- **Tenant**: MYOB tenant identifier
- **Branch**: MYOB branch identifier

### Synchronization Settings
Configure sync schedules for each entity type:
- **Customers**: Cron expression for customer sync
- **Products**: Cron expression for product sync
- **Inventory**: Cron expression for inventory sync
- **Prices**: Cron expression for price sync
- **Orders**: Cron expression for order sync
- **Shipments**: Cron expression for shipment sync

### Price Management
- **Default Price Class**: Default price class for new customers
- **Currency Mapping**: Map MYOB currencies to Magento stores

## Synchronization Jobs

The module includes 9 automated synchronization jobs:

| Job | Purpose | Frequency | Direction |
|-----|---------|-----------|-----------|
| **Customer** | Sync customer data and price classes | Configurable | Bi-directional |
| **Product** | Sync product catalog | Configurable | MYOB → Magento |
| **Inventory** | Sync stock levels | Configurable | MYOB → Magento |
| **Prices** | Sync pricing data | Configurable | MYOB → Magento |
| **Order** | Submit orders to MYOB | Configurable | Magento → MYOB |
| **Shipment** | Sync shipment tracking | Configurable | Bi-directional |
| **Purchase** | Sync purchase orders | Configurable | MYOB → Magento |
| **Cron** | Master sync coordinator | Every minute | N/A |
| **Watchdog** | Monitor and recover failed syncs | Every 5 minutes | N/A |

### Manual Sync Triggers

Admin users can manually trigger synchronization:
- **Admin > Zhik Extensions > MYOB Synchronization**
- Individual entity sync buttons
- Full sync option for complete data refresh

## Database Tables

The module creates and manages the following tables:

### Core Tables

```sql
-- Sync status tracking
myoba_status

-- Sync logs and history
myoba_logs

-- Price data from MYOB
myoba_prices

-- MYOB connection configurations
myoba_connections

-- Customer mapping
myoba_customer_mapping
```

### Extended Tables

The module extends existing Magento tables:

- **sales_order**: `myoba_id`, `myoba_type`, `myoba_created`
- **sales_shipment**: `myoba_id`, `myoba_type`, `myoba_created`
- **inventory_reservation**: `myoba_stock_bypass`
- **inventory_source_item**: `myoba_stock_bypass`

## Price Type Management

The module manages different price types with strict isolation:

### MYOB-Managed Price Types (Synced)

| Type | Code | Description | Range |
|------|------|-------------|-------|
| **Base** | B | Base selling price | 1 - 19,999,999 |
| **Customer** | C | Customer-specific price | 1 - 19,999,999 |
| **Price Class** | P | Price class pricing | 1 - 19,999,999 |
| **None** | N | Other/uncategorized | 1 - 19,999,999 |

### Custom Price Types (Not Synced)

| Type | Code | Description | Range |
|------|------|-------------|-------|
| **Forward Order** | F | Seasonal forward order pricing | 20,000,000+ |

**Important**: The MYOB price sync is configured to **only manage types B, C, P, N**. Custom price types (like Forward Order type 'F') are completely isolated from MYOB synchronization to prevent accidental deletion.

### Price Type Filtering

```php
// Price sync only processes MYOB types
$priceCol->addFieldToFilter('price_type', ['in' => ['B', 'C', 'P', 'N']]);

// Forward Order prices (type 'F') are never touched by MYOB sync
```

## Order Type Management

The module supports different order types for specialized processing:

### Order Types

| Type | Code | Description | Stock Bypass |
|------|------|-------------|--------------|
| **Standard** | SO | Regular sales order | No |
| **Forward Order** | FO | Seasonal pre-order | Yes |
| **Sales Forward** | SF | Forward order (new) | Yes |

### Stock Bypass Logic

Orders with types FO or SF bypass inventory reservations:

```php
// Inventory reservation prevention
if (in_array($order->getData('myoba_type'), ['FO', 'SF'])) {
    // Skip inventory reservation
    return;
}
```

This allows unlimited quantities for forward orders without affecting current stock.

## Integration with Other Modules

### Zhik_ForwardOrder Integration

The Myoba module provides critical infrastructure for Forward Order functionality:

- **Price Table**: Forward Order uses `myoba_prices` table with type 'F'
- **Stock Bypass**: Forward Order orders (SF type) bypass inventory reservations
- **Price Isolation**: MYOB sync excludes Forward Order prices from deletion

### Zhik_Portal Integration

- **Customer Pricing**: Portal uses MYOB price data for dealer pricing
- **Inventory Display**: Real-time stock from MYOB
- **Order Submission**: Orders route through MYOB sync

### Zhik_ThresholdTaxes Integration

- **Tax Code Sync**: MYOB tax codes sync to Magento tax rates
- **Multi-region Support**: Tax calculation based on MYOB tax configuration

## API Documentation

### REST Endpoints

```
POST /V1/myoba/sync/customer
POST /V1/myoba/sync/order
POST /V1/myoba/sync/product
POST /V1/myoba/sync/inventory
POST /V1/myoba/sync/prices
```

### MYOB API Client

```php
// Get API connection
$client = $this->myobaHelper->getApiConnectionForWebsite($websiteId);

// Fetch current trade prices
$prices = $client->getCurrentTradePrices();

// Submit order to MYOB
$myobOrder = $client->createSale($orderData);
```

## Console Commands

```bash
# Manual sync triggers
bin/magento myoba:sync:customer
bin/magento myoba:sync:product
bin/magento myoba:sync:inventory
bin/magento myoba:sync:prices
bin/magento myoba:sync:order
bin/magento myoba:sync:purchase

# Full sync (all entities)
bin/magento myoba:sync:all

# View sync status
bin/magento myoba:status
```

## Troubleshooting

### Common Issues

#### Price Sync Deleting Custom Prices

**Problem**: MYOB price sync deletes Forward Order prices

**Solution**: Ensure you're running version 1.4.4+ which filters price types:
```php
// Check your Prices.php has this filter
$priceCol->addFieldToFilter('price_type', ['in' => ['B', 'C', 'P', 'N']]);
```

#### Inventory Reservation Errors

**Problem**: Forward Orders creating inventory reservations

**Solution**: Verify order type is set to 'SF' or 'FO':
```sql
SELECT myoba_type FROM sales_order WHERE increment_id = 'ORDER_ID';
```

#### Connection Timeout

**Problem**: API timeout during large data sync

**Solution**: Adjust batch sizes in sync configuration:
```xml
<config_path>myoba/sync/batch_size</config_path>
```

### Debug Mode

Enable debug logging:

1. Navigate to **Stores > Configuration > Zhik Extensions > Myoba**
2. Enable "Debug Logging"
3. View logs at `var/log/myoba.log`

### Sync Status Monitoring

Check sync job status:
- **Admin > System > MYOB Sync Status**
- View last sync time, records processed, errors
- Manual retry for failed jobs

## Technical Architecture

### Plugin System

The module uses Magento's plugin system for core modifications:

```xml
<!-- Inventory reservation bypass -->
<type name="Magento\InventorySales\Model\PlaceReservationsForSalesEvent">
    <plugin name="zhik_myoba_inventory_reservation"
            type="Zhik\Myoba\Plugin\InventorySales\PlaceReservationsForSalesEvent"/>
</type>
```

### Event Observers

Key observers:

- `sales_order_place_after`: Submit order to MYOB
- `sales_order_shipment_save_after`: Sync shipment data
- `customer_save_after`: Sync customer to MYOB

### Preference Overrides

The module provides a preference for inventory reservation:

```xml
<preference for="Magento\InventorySalesApi\Api\PlaceReservationsForSalesEventInterface"
            type="Zhik\Myoba\Model\InventorySales\PlaceReservationsForSalesEvent"/>
```

**Critical**: This preference is used by Zhik_ForwardOrder for stock bypass functionality.

## Security Considerations

- **API Credentials**: Stored encrypted in core_config_data
- **Access Control**: ACL rules for admin sync operations
- **Data Validation**: Input sanitization for all MYOB data
- **Error Handling**: Graceful degradation on API failures

## Performance Optimization

- **Batch Processing**: Large datasets processed in configurable chunks
- **Caching**: Redis cache for frequently accessed MYOB data
- **Connection Pooling**: Reuse MYOB API connections
- **Async Processing**: Queue-based processing for order submissions

## Module Dependencies

```json
{
  "require": {
    "magento/module-inventory-shipping": "*",
    "magento/module-catalog-inventory": "*",
    "magento/module-inventory-sales": "*",
    "magento/module-tax": "*",
    "webshopapps/module-matrixrate": "*",
    "laminas/laminas-mail": "^2.21",
    "laminas/laminas-mime": "^2.11"
  }
}
```

## Development Guidelines

### Adding New Sync Jobs

1. Extend `AbstractSyncJob`
2. Implement `processSyncRequest()`
3. Register in `crontab.xml`
4. Add admin configuration

### Custom Price Types

To add new price types:

1. **Choose Range**: Use 30,000,000+ for future custom types
2. **Update Filter**: Exclude from MYOB sync in `Prices.php`
3. **Document**: Add to this README and code comments

### Testing

```bash
# Run integration tests
bin/magento dev:tests:run integration Zhik_Myoba

# Run unit tests
vendor/bin/phpunit app/code/Zhik/Myoba/Test/Unit
```

## Support

- **Documentation**: See `docs/` folder for detailed guides
- **Issues**: Report at internal issue tracker
- **API Docs**: MYOB API documentation at https://developer.myob.com

## Version History

| Version | Date | Changes |
|---------|------|---------|
| 1.4.4 | Oct 2025 | Added price type filtering, Forward Order compatibility |
| 1.4.3 | Aug 2025 | Stock bypass improvements for FO/SF orders |
| 1.4.2 | Apr 2025 | Purchase order sync, watchdog enhancements |
| 1.4.0 | Jan 2025 | Multi-warehouse support, price class improvements |

## License

Copyright © Zhik Pty Ltd. All rights reserved.
See LICENSE.txt for license details.

---

**End of Zhik Myoba Integration Documentation**
