# Inventory Reconciliation Guide

## Overview

The inventory reconciliation system helps identify and fix discrepancies between quantity-based inventory (`Inventory` table) and UID-based inventory (`InventoryItem` table).

## Why Discrepancies Occur

1. **Sales without inventory_item_id**: When sales are made without specifying specific inventory items, only the `Inventory.quantity` is decremented, but `InventoryItem` records remain unchanged.

2. **Manual data entry**: Inventory quantities may be adjusted manually without creating/updating corresponding `InventoryItem` records.

3. **Data import**: Bulk imports might create inventory in one system but not sync to the other.

4. **UID-based sales**: When sales use specific inventory items, the item status changes but the quantity might not be decremented.

## How It Works

The reconciliation service:
1. **Checks discrepancies**: Compares `Inventory.quantity` with count of `IN_STOCK` `InventoryItem` records
2. **Reports differences**: Identifies products with mismatches
3. **Auto-reconciles**: Updates `Inventory.quantity` to match `InventoryItem` count (using UID records as source of truth)

## API Endpoints

### 1. Get Reconciliation Report

**GET** `/api/inventory/reconciliation/report`

Get a detailed report of all inventory discrepancies.

**Query Parameters:**
- `product_id` (optional): Check specific product only

**Example:**
```bash
curl -X GET "http://localhost:4000/api/inventory/reconciliation/report" \
  -H "Authorization: Bearer YOUR_TOKEN"
```

**Response:**
```json
{
  "success": true,
  "message": "Reconciliation report generated successfully",
  "data": {
    "total_discrepancies": 2,
    "discrepancies": [
      {
        "inventory_id": 1,
        "product_id": 11,
        "product_name": "Sample Product",
        "product_sku": "PROD-001",
        "variant_id": null,
        "quantity_based": 5,
        "uid_based": 10,
        "difference": 5,
        "discrepancy_type": "QUANTITY_HIGHER"
      }
    ],
    "summary": {
      "quantity_higher": 1,
      "uid_higher": 1,
      "total_difference": 7
    },
    "timestamp": "2026-01-08T10:00:00.000Z"
  }
}
```

### 2. Check Discrepancies

**GET** `/api/inventory/reconciliation/check`

Quick check for discrepancies without detailed report.

**Query Parameters:**
- `product_id` (optional): Check specific product only

**Example:**
```bash
curl -X GET "http://localhost:4000/api/inventory/reconciliation/check?product_id=11" \
  -H "Authorization: Bearer YOUR_TOKEN"
```

### 3. Auto-Reconcile

**POST** `/api/inventory/reconciliation/auto-reconcile`

Automatically fix all discrepancies by syncing `Inventory.quantity` to match `InventoryItem` count.

**Request Body:**
```json
{
  "product_id": 11  // Optional: reconcile specific product only
}
```

**Example:**
```bash
curl -X POST "http://localhost:4000/api/inventory/reconciliation/auto-reconcile" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{}'
```

**Response:**
```json
{
  "success": true,
  "message": "Reconciliation completed successfully",
  "data": {
    "fixed": [
      {
        "inventory_id": 1,
        "product_id": 11,
        "product_name": "Sample Product",
        "action": "Updated quantity to match UID count",
        "new_quantity": 10
      }
    ],
    "errors": [],
    "skipped": []
  }
}
```

## Usage Recommendations

### Daily/Weekly Reconciliation

Run reconciliation regularly to catch and fix discrepancies early:

```bash
# Check for discrepancies
GET /api/inventory/reconciliation/report

# Auto-reconcile if discrepancies found
POST /api/inventory/reconciliation/auto-reconcile
```

### Before Important Operations

Run reconciliation before:
- End-of-day reports
- Month-end inventory audits
- System upgrades
- Data migrations

### After Bulk Operations

After bulk imports or manual adjustments:
```bash
POST /api/inventory/reconciliation/auto-reconcile
```

## Reconciliation Strategy

**Current Implementation**: Uses `QUANTITY_TO_UID` method
- Updates `Inventory.quantity` to match count of `IN_STOCK` `InventoryItem` records
- Assumes UID records are the source of truth
- Safe operation (doesn't delete data)

**Why UID as Source of Truth?**
- UID records represent actual physical items
- Each item has a specific status (IN_STOCK, RESERVED, SOLD, RETURNED)
- More granular tracking and auditability

## Monitoring

The system logs reconciliation operations:

```
[info]: Starting automatic inventory reconciliation
[info]: Found 2 inventory discrepancies, reconciling...
[info]: Reconciled inventory 1: Updated quantity from 5 to 10 (matched UID count)
[info]: Reconciliation complete: 2 fixed, 0 errors, 0 skipped
```

Check logs for:
- Number of discrepancies found
- Products reconciled
- Any errors during reconciliation

## Manual Reconciliation

If auto-reconciliation doesn't work for your use case:

1. Get the report to identify discrepancies
2. Manually review each discrepancy
3. Determine which system is correct (quantity vs UID)
4. Use inventory adjustment endpoints to fix manually:
   - `PUT /api/inventory/set-quantity` - Set quantity directly
   - `POST /api/inventory/adjust` - Adjust by difference

## Troubleshooting

### Reconciliation doesn't fix discrepancies

**Possible causes:**
- Insufficient permissions (requires manager/admin role)
- Transaction errors (check logs)
- Database connection issues

**Solution:**
- Check user role and permissions
- Review error logs
- Retry reconciliation for specific product

### Discrepancies keep recurring

**Possible causes:**
- Sales process not properly syncing both systems
- Manual adjustments not updating both systems
- Data import process creating mismatches

**Solution:**
- Review sales creation process
- Ensure all inventory adjustments update both systems
- Schedule regular reconciliation (daily/weekly)

## Security

- **Authentication**: Required (Bearer token)
- **Authorization**: Requires `manager` or `system_admin` role
- **Audit Trail**: All reconciliation operations are logged in system logs

## Best Practices

1. **Regular Reconciliation**: Run weekly or daily
2. **Review Before Reconcile**: Check report before auto-reconciling
3. **Monitor Trends**: Track if discrepancies are increasing
4. **Fix Root Cause**: Investigate why discrepancies occur
5. **Document Manual Fixes**: If manual reconciliation is needed, document why

