# SystemCore Module

**Version:** 1.0.0
**Category:** Core
**Description:** SystemCore provides a centralized single source of truth for master data management including customers, products, suppliers, and orders. It offers flexible integration patterns for other modules with configurable sync strategies.

---

## 📋 Table of Contents

- [Overview](#overview)
- [Architecture](#architecture)
- [Core Features](#core-features)
- [Installation](#installation)
- [Core Entities](#core-entities)
- [Integration Patterns](#integration-patterns)
- [Sync Strategies](#sync-strategies)
- [Module Integration Guide](#module-integration-guide)
- [API Reference](#api-reference)
- [Examples](#examples)
- [Configuration](#configuration)
- [Database Schema](#database-schema)
- [Events & Listeners](#events--listeners)
- [Best Practices](#best-practices)
- [Troubleshooting](#troubleshooting)
- [Roadmap](#roadmap)

---

## 🎯 Overview

SystemCore is the central master data management module for the Open Core Business Suite. It serves as the **single source of truth** for all business entities across multiple modules, enabling:

- ✅ **Centralized Data Management**: One place for all customers, products, suppliers
- ✅ **Flexible Integration**: Modules can sync or operate independently
- ✅ **Multiple Sync Strategies**: Real-time, scheduled, manual, one-way, two-way
- ✅ **Conflict Resolution**: Automatic conflict handling with configurable strategies
- ✅ **Audit Trail**: Complete history of all sync operations
- ✅ **Zero Breaking Changes**: Existing modules continue to work without modification

---

## 🏗️ Architecture

```
┌─────────────────────────────────────────────────────────────┐
│                      SystemCore Module                       │
│  (Single Source of Truth - Master Data Management)          │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  Core Entities:                                              │
│  • CoreCustomer (B2B/B2C/Leads/Prospects)                   │
│  • CoreProduct (with variants, categories, SKUs)             │
│  • CoreSupplier                                              │
│  • CoreSalesOrder & CorePurchaseOrder                        │
│  • CoreAddress & CoreContact (Polymorphic)                   │
│  • CorePaymentTerm & CoreTaxConfiguration                    │
│  • CorePricingRule                                           │
│                                                              │
└──────────────────┬──────────────────────────────────────────┘
                   │
        ┌──────────┴───────────┐
        │  Integration Layer    │
        │  • EntitySyncService  │
        │  • EntityMappingService│
        │  • SyncableEntity Trait│
        └──────────┬───────────┘
                   │
    ┌──────────────┼──────────────┬──────────────┐
    │              │              │              │
┌───▼────┐   ┌────▼───┐   ┌──────▼──┐   ┌──────▼──────┐
│  CRM   │   │  WMS   │   │ Product │   │FieldManager │
│ Module │   │ Module │   │  Order  │   │   Module    │
└────────┘   └────────┘   └─────────┘   └─────────────┘
    │            │              │              │
    │ Sync Mode  │  Sync Mode   │  Sync Mode   │ Independent
    └────────────┴──────────────┴──────────────┘
```

### Key Components

1. **Core Models**: Master data entities (CoreCustomer, CoreProduct, etc.)
2. **Entity Mapping**: Tracks relationships between module entities and core entities
3. **Sync Services**: Handles bidirectional synchronization
4. **Contracts/Interfaces**: Defines integration requirements
5. **Traits**: Reusable functionality for syncable entities
6. **Events & Listeners**: Event-driven sync operations

---

## ✨ Core Features

### 1. **Core Entity Management**

- **CoreCustomer**: B2B, B2C, Leads, Prospects, Distributors, Retailers
- **CoreProduct**: Products with variants, categories, SKUs, barcodes
- **CoreSupplier**: Vendor management
- **CoreSalesOrder / CorePurchaseOrder**: Order management
- **CoreAddress**: Polymorphic addresses (billing, shipping)
- **CoreContact**: Polymorphic contacts (primary, billing, technical)
- **CorePaymentTerm**: Net 30, Net 60, etc.
- **CoreTaxConfiguration**: Tax rates and rules
- **CorePricingRule**: Customer-specific pricing, quantity discounts

### 2. **Flexible Integration Patterns**

#### **Pattern 1: Sync Mode (Recommended for new modules)**
Module entities automatically sync with SystemCore

```php
// Module's Customer model
class Customer extends Model implements SyncableCustomerInterface
{
    use SyncableEntity;

    protected bool $systemCoreSyncEnabled = true;
    protected string $systemCoreEntityType = 'customer';

    public function toSystemCore(): array { /* ... */ }
    public function fromSystemCore(CoreCustomer $customer): self { /* ... */ }
}
```

#### **Pattern 2: Independent Mode (Default for existing modules)**
Module operates independently without SystemCore

```php
// Module's Product model
class Product extends Model
{
    // NO sync - works independently
    protected bool $systemCoreSyncEnabled = false;
}
```

#### **Pattern 3: Read-Only Sync (One-way from Core)**
Module receives updates from SystemCore but doesn't push back

```php
class Product extends Model implements SyncableProductInterface
{
    use SyncableEntity;

    protected bool $systemCoreSyncEnabled = true;
    protected string $syncDirection = 'from_core_only';
}
```

### 3. **Sync Strategies**

| Strategy | Description | Use Case |
|----------|-------------|----------|
| **RealTime** | Immediate sync on create/update | Critical data that must stay in sync |
| **Scheduled** | Batch sync at intervals (hourly/daily) | Large datasets, performance optimization |
| **Manual** | User-triggered sync | Ad-hoc synchronization |
| **OneWay** | Core → Module only (read-only) | Reference data, catalogs |
| **TwoWay** | Bidirectional sync | Collaborative data entry |

### 4. **Conflict Resolution**

When the same entity is modified in both SystemCore and a module, conflicts are resolved using:

- **Core Wins** (default): SystemCore is authoritative
- **Module Wins**: Module data takes precedence
- **Newest Wins**: Most recent modification wins
- **Manual**: User resolves conflicts

---

## 📦 Installation

### Step 1: Enable the Module

```bash
php artisan module:enable SystemCore
```

### Step 2: Run Migrations

```bash
php artisan module:migrate SystemCore
```

### Step 3: Seed Initial Data (Optional)

```bash
php artisan db:seed --class=Modules\\SystemCore\\Database\\Seeders\\SystemCoreDatabaseSeeder
```

### Step 4: Configure Integration (Optional)

Edit `config/systemcore.php` to configure module integrations:

```php
'integrations' => [
    'YourModule' => [
        'enabled' => true,
        'entities' => [
            'customer' => [
                'model' => \Modules\YourModule\App\Models\Customer::class,
                'sync_strategy' => 'realtime',
                'sync_direction' => 'bidirectional',
            ],
        ],
    ],
],
```

---

## 🗂️ Core Entities

### CoreCustomer

**Purpose**: Central customer/client management

**Fields**:
- `customer_code` (auto-generated): CUST-000001
- `name`: Customer name
- `company_name`: Company name (for B2B)
- `customer_type`: b2b, b2c, lead, prospect, distributor, retailer, wholesaler
- `status`: active, inactive, blocked, pending, suspended
- `email`, `phone`, `mobile`, `website`
- `tax_id`, `vat_number`
- `credit_limit`, `payment_term_id`, `currency_code`
- `latitude`, `longitude` (for mapping)
- `notes`, `tags`, `metadata` (JSON)

**Relationships**:
- `addresses()` - Multiple addresses
- `contacts()` - Multiple contacts
- `paymentTerm()` - Payment terms
- `salesOrders()` - All sales orders
- `entityMappings()` - Module integrations

**Usage**:
```php
$customer = CoreCustomer::create([
    'name' => 'Acme Corporation',
    'customer_type' => CustomerType::B2B,
    'status' => CustomerStatus::Active,
    'email' => 'contact@acme.com',
    'credit_limit' => 50000,
]);

// Add address
$customer->addresses()->create([
    'entity_type' => 'customer',
    'address_line_1' => '123 Main St',
    'city' => 'New York',
    'country' => 'USA',
    'is_primary' => true,
]);
```

### CoreProduct

**Purpose**: Central product catalog

**Fields**:
- `product_code` (auto-generated): PROD-000001
- `sku` (unique): Product SKU
- `barcode` (unique, optional)
- `name`: Product name
- `description`, `category_id`, `brand`
- `status`: active, inactive, discontinued, out_of_stock, draft
- `unit_of_measure`: pcs, kg, ltr, etc.
- `base_price`, `cost_price`, `selling_price`
- `tax_id`: Tax configuration
- `weight`, `weight_unit`, `dimensions` (JSON)
- `min_stock_level`, `max_stock_level`, `reorder_level`
- `images` (JSON), `thumbnail`
- `tags` (JSON), `metadata` (JSON)
- `is_trackable`, `has_variants`

**Relationships**:
- `category()` - Product category
- `tax()` - Tax configuration
- `variants()` - Product variants
- `pricingRules()` - Custom pricing
- `entityMappings()` - Module integrations

**Usage**:
```php
$product = CoreProduct::create([
    'name' => 'Wireless Mouse',
    'sku' => 'WM-001',
    'category_id' => 1,
    'base_price' => 15.00,
    'selling_price' => 25.00,
    'unit_of_measure' => 'pcs',
]);

// Add variant
$product->variants()->create([
    'sku' => 'WM-001-BLK',
    'name' => 'Wireless Mouse - Black',
    'attributes' => ['color' => 'black'],
    'price' => 25.00,
]);
```

### CoreSupplier

**Purpose**: Vendor/supplier management

Similar structure to CoreCustomer but for suppliers.

### CoreSalesOrder / CorePurchaseOrder

**Purpose**: Order management

**Fields**:
- `order_number` (auto-generated): SO-20241114-00001
- `customer_id` / `supplier_id`
- `order_date`, `delivery_date`
- `status`: draft, pending, confirmed, processing, shipped, delivered, completed, cancelled
- `subtotal`, `tax_amount`, `discount_amount`, `shipping_cost`, `total_amount`
- `payment_status`, `payment_method`
- `notes`, `metadata`

**Relationships**:
- `orderLines()` - Order line items
- `customer()` / `supplier()`

### EntityMapping

**Purpose**: Track relationships between module entities and core entities

**Fields**:
- `module_name`: FieldManager, CRM, WMS
- `entity_type`: customer, product, supplier
- `module_entity_id`: ID in module's table
- `core_entity_id`: ID in SystemCore table
- `sync_enabled`: boolean
- `sync_strategy`: realtime, scheduled, manual
- `sync_direction`: to_core, from_core, bidirectional
- `last_synced_at`: timestamp
- `sync_hash`: MD5 hash for change detection
- `metadata`: JSON for custom rules

---

## 🔌 Integration Patterns

### Pattern 1: Integrate Existing Module (FieldManager Example)

#### Step 1: Update the Model

```php
// Modules/FieldManager/App/Models/Client.php

use Modules\SystemCore\App\Contracts\SyncableCustomerInterface;
use Modules\SystemCore\App\Traits\SyncableEntity;
use Modules\SystemCore\App\Models\CoreCustomer;

class Client extends Model implements SyncableCustomerInterface
{
    use SyncableEntity;

    // Enable SystemCore sync
    protected bool $systemCoreSyncEnabled = true;
    protected string $systemCoreEntityType = 'customer';
    protected string $syncStrategy = 'realtime'; // or 'scheduled', 'manual'
    protected string $syncDirection = 'bidirectional'; // or 'to_core', 'from_core'

    /**
     * Convert to SystemCore format
     */
    public function toSystemCore(): array
    {
        return [
            'name' => $this->name,
            'email' => $this->email,
            'phone' => $this->phone,
            'address' => $this->address,
            'city' => $this->city,
            'state' => $this->state,
            'postal_code' => $this->postal_code,
            'latitude' => $this->latitude,
            'longitude' => $this->longitude,
            'customer_type' => 'b2b', // Map category to customer type
            'status' => $this->status === 'active' ? 'active' : 'inactive',
            'metadata' => [
                'contact_person_name' => $this->contact_person_name,
                'radius' => $this->radius,
                'remarks' => $this->remarks,
                'category' => $this->category->value,
            ],
        ];
    }

    /**
     * Import from SystemCore
     */
    public function fromSystemCore(CoreCustomer $customer): self
    {
        $this->fill([
            'name' => $customer->name,
            'email' => $customer->email,
            'phone' => $customer->phone,
            'address' => $customer->metadata['address'] ?? null,
            'city' => $customer->metadata['city'] ?? null,
            'state' => $customer->metadata['state'] ?? null,
            'postal_code' => $customer->metadata['postal_code'] ?? null,
            'latitude' => $customer->latitude,
            'longitude' => $customer->longitude,
            'status' => $customer->is_active ? 'active' : 'inactive',
            'contact_person_name' => $customer->metadata['contact_person_name'] ?? null,
            'radius' => $customer->metadata['radius'] ?? 100,
            'remarks' => $customer->metadata['remarks'] ?? null,
        ]);

        return $this;
    }

    /**
     * Get the core customer if synced
     */
    public function getCoreCustomer(): ?CoreCustomer
    {
        $mapping = $this->getEntityMapping();

        return $mapping ? CoreCustomer::find($mapping->core_entity_id) : null;
    }
}
```

#### Step 2: Auto-Sync is Now Active!

The `SyncableEntity` trait automatically triggers sync on:
- `created` event → Syncs to SystemCore
- `updated` event → Updates SystemCore
- `deleted` event → Handles cleanup

#### Step 3: Manual Sync (Optional)

```php
// Sync single client to SystemCore
$syncService = app(EntitySyncService::class);
$coreCustomer = $syncService->syncToCore('FieldManager', 'customer', $client);

// Sync all FieldManager clients
$syncService->syncModule('FieldManager', ['customer']);
```

### Pattern 2: New Module Integration (CRM Example)

```php
// Modules/CRM/App/Models/Customer.php

namespace Modules\CRM\App\Models;

use Illuminate\Database\Eloquent\Model;
use Modules\SystemCore\App\Contracts\SyncableCustomerInterface;
use Modules\SystemCore\App\Traits\SyncableEntity;
use Modules\SystemCore\App\Models\CoreCustomer;

class Customer extends Model implements SyncableCustomerInterface
{
    use SyncableEntity;

    protected bool $systemCoreSyncEnabled = true;
    protected string $systemCoreEntityType = 'customer';
    protected string $syncStrategy = 'twoway';

    public function toSystemCore(): array
    {
        return [
            'name' => $this->company_name,
            'email' => $this->primary_email,
            'phone' => $this->primary_phone,
            'customer_type' => $this->type, // lead, prospect, customer
            'status' => $this->status,
            // ... more fields
        ];
    }

    public function fromSystemCore(CoreCustomer $customer): self
    {
        $this->fill([
            'company_name' => $customer->name,
            'primary_email' => $customer->email,
            'primary_phone' => $customer->phone,
            'type' => $customer->customer_type->value,
            'status' => $customer->status->value,
        ]);

        return $this;
    }

    public function getCoreCustomer(): ?CoreCustomer
    {
        $mapping = $this->getEntityMapping();
        return $mapping ? CoreCustomer::find($mapping->core_entity_id) : null;
    }
}
```

### Pattern 3: Read-Only Integration (WMS Example)

```php
// Modules/WMS/App/Models/Product.php

class Product extends Model implements SyncableProductInterface
{
    use SyncableEntity;

    // Only receive updates FROM SystemCore (read-only)
    protected bool $systemCoreSyncEnabled = true;
    protected string $systemCoreEntityType = 'product';
    protected string $syncDirection = 'from_core_only';

    public function toSystemCore(): array
    {
        // Not used for from_core_only
        return [];
    }

    public function fromSystemCore(CoreProduct $product): self
    {
        $this->fill([
            'sku' => $product->sku,
            'name' => $product->name,
            'price' => $product->selling_price,
            // WMS-specific fields stay independent:
            // 'warehouse_location' => $this->warehouse_location,
            // 'bin_number' => $this->bin_number,
        ]);

        return $this;
    }

    public function getCoreProduct(): ?CoreProduct
    {
        $mapping = $this->getEntityMapping();
        return $mapping ? CoreProduct::find($mapping->core_entity_id) : null;
    }
}
```

---

## 🔄 Sync Strategies

### Real-Time Sync

**When to use**: Critical data that must always be in sync

```php
protected string $syncStrategy = 'realtime';
```

**How it works**:
- Syncs immediately on create/update
- Uses Laravel events
- Best for small datasets

### Scheduled Sync

**When to use**: Large datasets, performance optimization

```php
protected string $syncStrategy = 'scheduled';
```

**Setup**:
```php
// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
    $schedule->call(function () {
        $syncService = app(EntitySyncService::class);
        $syncService->syncModule('CRM', ['customer', 'product']);
    })->hourly();
}
```

### Manual Sync

**When to use**: User-controlled synchronization

```php
protected string $syncStrategy = 'manual';
```

**Trigger**:
```php
// Via UI button or API
$syncService->syncToCore('CRM', 'customer', $customer);
```

---

## 🔧 Configuration

### Global Config

**File**: `config/systemcore.php`

```php
return [
    'default_sync_strategy' => env('SYSTEMCORE_DEFAULT_SYNC_STRATEGY', 'realtime'),
    'default_sync_direction' => env('SYSTEMCORE_DEFAULT_SYNC_DIRECTION', 'bidirectional'),
    'conflict_resolution' => env('SYSTEMCORE_CONFLICT_RESOLUTION', 'core_wins'),
    'sync_batch_size' => env('SYSTEMCORE_SYNC_BATCH_SIZE', 100),
    'enable_sync_logging' => env('SYSTEMCORE_ENABLE_SYNC_LOGGING', true),

    'integrations' => [
        'FieldManager' => [
            'enabled' => true,
            'entities' => [
                'customer' => [
                    'model' => \Modules\FieldManager\App\Models\Client::class,
                    'sync_strategy' => 'realtime',
                    'sync_direction' => 'bidirectional',
                ],
            ],
        ],
    ],
];
```

### Environment Variables

```env
SYSTEMCORE_DEFAULT_SYNC_STRATEGY=realtime
SYSTEMCORE_DEFAULT_SYNC_DIRECTION=bidirectional
SYSTEMCORE_CONFLICT_RESOLUTION=core_wins
SYSTEMCORE_SYNC_BATCH_SIZE=100
SYSTEMCORE_ENABLE_SYNC_LOGGING=true
```

---

## 📊 Database Schema

### Key Tables

1. **core_customers** - Master customer data
2. **core_products** - Master product catalog
3. **core_suppliers** - Supplier/vendor data
4. **core_addresses** - Polymorphic addresses
5. **core_contacts** - Polymorphic contacts
6. **core_sales_orders** - Sales orders
7. **core_purchase_orders** - Purchase orders
8. **system_core_entity_mappings** - Module-to-Core mappings

### Entity Mappings Table

```sql
CREATE TABLE system_core_entity_mappings (
    id BIGINT PRIMARY KEY,
    module_name VARCHAR(255),          -- 'FieldManager', 'CRM'
    entity_type VARCHAR(255),          -- 'customer', 'product'
    module_entity_id BIGINT,           -- ID in module's table
    core_entity_id BIGINT,             -- ID in SystemCore table
    sync_enabled BOOLEAN DEFAULT TRUE,
    sync_strategy VARCHAR(50),         -- 'realtime', 'scheduled', 'manual'
    sync_direction VARCHAR(50),        -- 'to_core', 'from_core', 'bidirectional'
    last_synced_at TIMESTAMP,
    sync_hash VARCHAR(32),             -- MD5 hash for change detection
    is_master BOOLEAN DEFAULT FALSE,   -- Which is authoritative
    metadata JSON,                     -- Custom mapping rules
    created_at TIMESTAMP,
    updated_at TIMESTAMP,
    deleted_at TIMESTAMP,
    UNIQUE KEY unique_module_entity (module_name, entity_type, module_entity_id)
);
```

---

## 🎯 API Reference

### REST Endpoints

#### Customers

```http
GET    /api/v1/systemcore/customers/search?search=acme
```

#### Products

```http
GET    /api/v1/systemcore/products/search?search=mouse
```

### Sync Services

#### EntitySyncService

```php
use Modules\SystemCore\App\Services\Sync\EntitySyncService;

$syncService = app(EntitySyncService::class);

// Sync to core
$coreEntity = $syncService->syncToCore(
    string $module,
    string $entityType,
    SyncableEntityInterface $entity
): Model;

// Sync from core
$moduleEntity = $syncService->syncFromCore(
    Model $coreEntity,
    string $module,
    string $entityType
): Model;

// Check sync status
$isInSync = $syncService->isInSync(
    string $module,
    string $entityType,
    int $moduleEntityId
): bool;

// Sync entire module
$results = $syncService->syncModule(
    string $module,
    array $entityTypes = []
): array;
```

#### EntityMappingService

```php
use Modules\SystemCore\App\Services\Mapping\EntityMappingService;

$mappingService = app(EntityMappingService::class);

// Get mapping
$mapping = $mappingService->getMapping(
    string $module,
    string $entityType,
    int $moduleEntityId
): ?EntityMapping;

// Create mapping
$mapping = $mappingService->createMapping(
    string $module,
    string $entityType,
    int $moduleEntityId,
    int $coreEntityId,
    array $options = []
): EntityMapping;

// Get statistics
$stats = $mappingService->getSyncStatistics(string $module): array;
```

---

## 💡 Examples

### Example 1: Migrate FieldManager Clients to SystemCore

```php
use Modules\FieldManager\App\Models\Client;
use Modules\SystemCore\App\Services\Sync\EntitySyncService;

$syncService = app(EntitySyncService::class);

// Update Client model first (add SyncableEntity trait and implement interface)

// Then sync all clients
Client::chunk(100, function ($clients) use ($syncService) {
    foreach ($clients as $client) {
        try {
            $coreCustomer = $syncService->syncToCore('FieldManager', 'customer', $client);
            echo "Synced client {$client->id} → customer {$coreCustomer->id}\n";
        } catch (\Exception $e) {
            echo "Failed to sync client {$client->id}: {$e->getMessage()}\n";
        }
    }
});
```

### Example 2: Create Customer in SystemCore and Sync to Modules

```php
use Modules\SystemCore\App\Models\CoreCustomer;
use Modules\SystemCore\App\Services\Sync\EntitySyncService;

// Create customer in SystemCore
$customer = CoreCustomer::create([
    'name' => 'New Customer Inc.',
    'email' => 'contact@newcustomer.com',
    'customer_type' => 'b2b',
    'status' => 'active',
]);

// Sync to all integrated modules
$syncService = app(EntitySyncService::class);
$syncService->syncFromCore($customer, 'FieldManager', 'customer');
$syncService->syncFromCore($customer, 'CRM', 'customer');
```

### Example 3: Query Synced Entities

```php
use Modules\FieldManager\App\Models\Client;

$client = Client::find(1);

// Get core customer
$coreCustomer = $client->getCoreCustomer();

// Check if in sync
$mapping = $client->getEntityMapping();
$isInSync = !$mapping->needsSync($client->calculateSyncHash());

// Find which modules use this core customer
$coreCustomer = CoreCustomer::find(1);
$modules = $coreCustomer->entityMappings; // All modules using this customer
```

---

## 🎨 Best Practices

### 1. Field Mapping

**DO**: Use metadata for module-specific fields

```php
public function toSystemCore(): array
{
    return [
        'name' => $this->name,
        'email' => $this->email,
        'metadata' => [
            'field_manager_category' => $this->category->value,
            'field_manager_radius' => $this->radius,
            // Module-specific data
        ],
    ];
}
```

**DON'T**: Try to map all fields directly

### 2. Sync Strategy Selection

- **Real-time**: For <1000 records, critical data
- **Scheduled**: For >1000 records, bulk operations
- **Manual**: For one-time migrations, testing

### 3. Conflict Resolution

Always set clear ownership:

```php
// If SystemCore is master
'conflict_resolution' => 'core_wins'

// If module is master
'conflict_resolution' => 'module_wins'
```

### 4. Testing Sync

```php
// In tests
public function test_client_syncs_to_system_core()
{
    $client = Client::factory()->create();

    $coreCustomer = $client->getCoreCustomer();

    $this->assertNotNull($coreCustomer);
    $this->assertEquals($client->name, $coreCustomer->name);
    $this->assertEquals($client->email, $coreCustomer->email);
}
```

---

## 🐛 Troubleshooting

### Issue: Sync Not Triggering

**Check**:
1. Is `systemCoreSyncEnabled` set to `true`?
2. Is the trait `SyncableEntity` imported?
3. Are events firing? Check logs.

```bash
tail -f storage/logs/laravel.log | grep "Synced"
```

### Issue: Duplicate Entries

**Cause**: Mapping not created or lost

**Fix**:
```php
// Check mapping
$mapping = EntityMapping::where('module_name', 'FieldManager')
    ->where('entity_type', 'customer')
    ->where('module_entity_id', $clientId)
    ->first();

if (!$mapping) {
    // Create mapping manually
    $mappingService->createMapping('FieldManager', 'customer', $clientId, $coreCustomerId);
}
```

### Issue: Performance Problems

**Solution**: Switch to scheduled sync

```php
protected string $syncStrategy = 'scheduled';
```

And set up cron:
```php
$schedule->call(function () {
    app(EntitySyncService::class)->syncModule('FieldManager', ['customer']);
})->hourly();
```

---

## 🗺️ Roadmap

### Phase 1: Foundation ✅
- [x] Core entity models
- [x] Sync services and strategies
- [x] Entity mapping system
- [x] Basic UI dashboard

### Phase 2: Module Integration (Current)
- [ ] Integrate FieldManager module
- [ ] Integrate ProductOrder module
- [ ] Migration tools for existing data
- [ ] Conflict resolution UI

### Phase 3: Advanced Features
- [ ] Bulk sync operations
- [ ] Sync scheduling UI
- [ ] Advanced conflict resolution
- [ ] Sync analytics dashboard
- [ ] Import/Export tools
- [ ] API webhooks for sync events

### Phase 4: WMS & CRM Integration
- [ ] WMS module integration
- [ ] CRM module integration
- [ ] Advanced product variant management
- [ ] Multi-warehouse support
- [ ] Advanced pricing rules

---

## 📚 Related Documentation

- [Module Settings Guide](../../docs/MODULE_SETTINGS_GUIDE.md)
- [CLAUDE.md](../../CLAUDE.md) - Project conventions
- [Laravel Modules Documentation](https://nwidart.com/laravel-modules/)

---

## 🤝 Contributing

Contributions are welcome! Please follow the project's coding standards and submit pull requests for review.

---

## 📄 License

This module is part of the Open Core Business Suite and follows the same license.

---

## 👨‍💻 Support

For issues and questions:
- GitHub Issues: https://github.com/yourusername/open_core_bs/issues
- Documentation: https://docs.yoursite.com

---

**Built with ❤️ for Open Core Business Suite**
