# Inventory Tracking System Documentation

## Overview

The inventory tracking system ensures that ALL transactions (Sales, Returns, Exchange, and Transfer) properly update the inventory tables to track goods movement throughout the system. This provides complete visibility into stock movements and maintains accurate inventory records.

## Transaction Types and Inventory Impact

### 1. Sales Transactions (Type 1)

-   **Goods Movement**: Goods OUT from warehouse
-   **Warehouse Update**: Decrease stock quantity
-   **Inventory Records**: Creates `inventory_header` and `inventory_detail` records
-   **Inventory Detail Sign**: Positive qty and positive rtp (type indicates goods out)

### 2. Return Transactions (Type 2)

-   **Goods Movement**: Goods IN to warehouse
-   **Warehouse Update**: Increase stock quantity
-   **Inventory Records**: Creates `inventory_header` and `inventory_detail` records
-   **Inventory Detail Sign**: Negative qty only; rtp (and cost, discount) stored positive

### 3. Exchange Transactions (Type 3)

-   **Goods Movement**: Goods IN (returned items) + Goods OUT (new items)
-   **Warehouse Update**: Increase stock for returned items, decrease for new items
-   **Inventory Records**: Creates `inventory_header` and `inventory_detail` records for both movements
-   **Quantity Sign**: Mixed (positive for returns, negative for new items)

### 4. Transfer Transactions (Type 4)

-   **Goods Movement**: Goods OUT from source location, Goods IN to destination location
-   **Warehouse Update**: Decrease stock at source, increase at destination
-   **Inventory Records**: Creates `inventory_header` and `inventory_detail` records for both locations
-   **Quantity Sign**: Negative at source, positive at destination

## Database Tables

### inventory_header

Stores the main transaction information for each inventory movement:

```sql
- id (Primary Key)
- wrhs_id (Warehouse/Location ID)
- trans_type_id (Transaction Type: 1=Sale, 2=Return, 3=Exchange, 4=Transfer)
- trans_no (Transaction Number)
- doc_no (Document Number)
- invoice_header_id (Reference to invoice)
- date (Transaction Date)
- time (Transaction Time)
- from_wrhs_id (Source Warehouse - for transfers)
- to_wrhs_id (Destination Warehouse - for transfers)
- stock_keeper_id (User who processed the transaction)
- total_rtp (Total Retail Price)
- total_cost (Total Cost)
- qty (Total Quantity)
- comments (Transaction comments)
- status (Transaction status)
```

### inventory_detail

Stores individual item details for each inventory movement:

```sql
- wrhs_id (Warehouse/Location ID)
- trans_no (Transaction Number)
- serial (Serial number for the item)
- item_id (Item ID)
- qty (Quantity - positive for Sales, negative for Returns only)
- rtp (Retail Price - stored positive for both Sales and Returns)
- cost (Cost Price)
- discount (Discount Amount)
- type (Transaction Type: 1=Sale, 2=Return, 3=Exchange, 4=Transfer)
- inventory_header_id (Reference to inventory header)
```

### warehouses

Stores current stock levels for each item at each location:

```sql
- wrhs_id (Warehouse/Location ID)
- item_id (Item ID)
- qty (Current Quantity)
```

## Implementation Details

### InventoryTrackingService

The `InventoryTrackingService` class provides centralized inventory tracking functionality:

#### Methods:

1. **`createInventoryRecords($transactionData)`**

    - Creates inventory header and detail records
    - Updates warehouse stock levels
    - Handles database transactions

2. **`updateWarehouseStock($wrhs_id, $item_id, $qty, $type)`**

    - Updates warehouse stock based on transaction type
    - Creates new warehouse records if needed
    - Applies appropriate stock changes

3. **`createSalesInventory($saleData)`**

    - Creates inventory records for sales transactions
    - Sets negative quantities for goods out

4. **`createReturnInventory($returnData)`**

    - Creates inventory records for return transactions
    - Sets positive quantities for goods in

5. **`createExchangeInventory($exchangeData)`**

    - Creates inventory records for exchange transactions
    - Handles both returned and new items

6. **`createTransferInventory($transferData)`**
    - Creates inventory records for transfer transactions
    - Handles source and destination locations

### Usage Examples

#### Sales Transaction

```php
\App\Services\InventoryTrackingService::createSalesInventory([
    'wrhs_id' => $user->loc_id,
    'trans_no' => $invoiceHeader->invo_no,
    'invoice_header_id' => $invoiceHeader->id,
    'stock_keeper_id' => $user->id,
    'total_rtp' => $request->subtotal,
    'total_cost' => 0,
    'total_qty' => collect($request->items)->sum('quantity'),
    'comments' => 'Sale transaction - goods out',
    'items' => $request->items
]);
```

#### Return Transaction

```php
\App\Services\InventoryTrackingService::createReturnInventory([
    'wrhs_id' => $user->loc_id,
    'trans_no' => $nextInvoiceNumber,
    'invoice_header_id' => $returnHeader->id,
    'stock_keeper_id' => $user->id,
    'total_rtp' => $totalReturnAmount,
    'total_cost' => 0,
    'total_qty' => $totalReturnQty,
    'comments' => 'Return transaction - goods in',
    'items' => $returnItems
]);
```

## Benefits

### 1. Complete Audit Trail

-   Every goods movement is tracked
-   Full history of stock changes
-   Ability to trace any item's movement

### 2. Accurate Stock Levels

-   Real-time warehouse updates
-   Consistent stock calculations
-   Prevents stock discrepancies

### 3. Business Intelligence

-   Stock movement analysis
-   Transaction volume tracking
-   Performance metrics

### 4. Compliance

-   Regulatory requirements
-   Financial reporting
-   Tax calculations

## Monitoring and Reporting

### Inventory Summary

```php
$summary = \App\Services\InventoryTrackingService::getInventorySummary(
    $wrhs_id,
    $dateFrom,
    $dateTo
);
```

### Stock Movement Reports

-   Daily stock changes
-   Transaction summaries
-   Location-based reports
-   Item movement history

## Best Practices

### 1. Always Use the Service

-   Don't manually update warehouse tables
-   Use the centralized service for consistency
-   Ensure proper error handling

### 2. Transaction Types

-   Use correct transaction type IDs
-   Maintain consistent naming conventions
-   Document any new transaction types

### 3. Data Validation

-   Validate quantities before processing
-   Check stock availability
-   Ensure proper user permissions

### 4. Error Handling

-   Use database transactions
-   Rollback on errors
-   Log all inventory operations

## Troubleshooting

### Common Issues

1. **Missing Inventory Records**

    - Check if service is being called
    - Verify transaction data format
    - Check database permissions

2. **Incorrect Stock Levels**

    - Verify transaction types
    - Check quantity signs
    - Review recent transactions

3. **Performance Issues**
    - Monitor database indexes
    - Check transaction volume
    - Optimize queries

### Debug Information

Enable logging to track inventory operations:

```php
Log::info('Inventory operation', [
    'type' => 'sale',
    'user_id' => $user->id,
    'location_id' => $user->loc_id,
    'items_count' => count($items)
]);
```

## Future Enhancements

### 1. Real-time Notifications

-   Low stock alerts
-   Movement notifications
-   Exception reporting

### 2. Advanced Analytics

-   Predictive stock management
-   Trend analysis
-   Demand forecasting

### 3. Integration

-   External warehouse systems
-   E-commerce platforms
-   Accounting systems

## Conclusion

The inventory tracking system now provides comprehensive goods movement tracking across all transaction types. This ensures accurate stock levels, complete audit trails, and better business intelligence for informed decision-making.

All controllers (Sales, Returns, Exchange, Transfer) now properly create inventory records, maintaining consistency and providing a single source of truth for inventory management.
