# Magento to Shopify Price & Inventory Sync Process Summary

This document summarizes the implementation and optimization of the high-performance synchronization script.

## 1. Goal
Synchronize product prices and inventory quantities from Magento 2 to Shopify using GraphQL Bulk Mutations, ensuring high performance for 50k+ products.

## 2. Implementation Details

### Database Migration
- Created the `price_inventory_sync` table to track every synchronization attempt.
- Columns include: `magento_id`, `magento_sku`, `shopify_product_id`, `shopify_variant_id`, `inventory_item_id`, `synced_price`, `synced_qty`, `sync_status`, `error_message`, and `synced_at`.

### Core Synchronization Logic (`SyncPriceInventory.php`)
- **Source of Truth**: Fetches data from Magento's `cataloginventory_stock_item` (Stock) and `catalog_product_entity_decimal` (Price).
- **Target**: Shopify Admin GraphQL API.
- **Batching**: Processes products in chunks (default 250) to optimize throughput.
- **Rules**:
    - Absolute quantity sync (not delta).
    - If Magento Qty = 0, Shopify is updated to 0.
    - Prices are synchronized even if Qty is 0.
    - Prices are formatted to 2 decimal places.

## 3. High-Performance Optimizations

### GraphQL Bulk Mutations
- **Inventory**: Uses `inventorySetQuantities` to update multiple inventory items in a single request.
- **Price**: Groups variants by `shopify_product_id` and uses `productVariantsBulkUpdate` to update all variants of a product in one call.

### Memory Management
- **Query Log Disabling**: Prevents Laravel from storing massive query logs in memory.
- **Garbage Collection**: Explicitly triggers `gc_collect_cycles()` after each batch.
- **Variable Cleanup**: Unsets large arrays immediately after use.
- **Error Truncation**: Limits error message length stored in the DB to prevent memory bloating.

## 4. Key Fixes Applied
- **Location ID Normalization**: Automatically prepends `gid://shopify/Location/` to the provided ID if only the numeric ID is supplied.
- **Mutation Restructuring**: Moved from individual variant updates to bulk product variant updates to respect Shopify's GraphQL schema and performance constraints.

## 5. Usage
To run the synchronization:
```bash
php artisan shopify:sync-price-inventory --chunk=100
```

*Note: Ensure `SHOPIFY_INVENTORY_LOCATION_ID` is set in the `.env` file.*
