# KCG Inventory - Application Documentation

## Overview

KCG Inventory is a Laravel-based **Warehouse Management System (WMS)** designed for a construction/project-based company operating in the UAE (currency: AED). The system manages materials from procurement through delivery to project sites, tracking stock across warehouses, divisions, and multiple project sites simultaneously.

---

## Table of Contents

1. [Authentication & Admin Panel](#1-authentication--admin-panel)
2. [Item & Category Registration](#2-item--category-registration)
3. [Supplier Management](#3-supplier-management)
4. [Project & Division Management](#4-project--division-management)
5. [Incoming Transactions](#5-incoming-transactions)
6. [Outgoing Transactions](#6-outgoing-transactions)
7. [Material Issue Decision Center](#7-material-issue-decision-center)
8. [Transfer Modules](#8-transfer-modules)
9. [Returns Module](#9-returns-module)
10. [Inventory Management](#10-inventory-management)
11. [LPO Management](#11-lpo-management)
12. [Reporting Module](#12-reporting-module)
13. [Analytics Module](#13-analytics-module)
14. [Settings & Administration](#14-settings--administration)
15. [Key Technical Details](#15-key-technical-details)

---

## 1. Authentication & Admin Panel

### Authentication
- Admin login/logout via `/admin/login`
- Session-based authentication with role-based access control
- All warehouse routes require `auth` middleware + `warehouse.access` middleware

### User Management (`/admin/users`)
- Create, edit, delete users
- Assign roles to users
- Reset user passwords
- Fields: first name, last name, email, phone, department, employee ID, avatar, role, status

### Role & Permission Management (`/admin/roles`)
- Create custom roles with granular permissions
- Duplicate existing roles as templates
- Toggle role active/inactive status
- Permissions are grouped by module (e.g., `warehouse.items.view`, `warehouse.items.create`)

#### Permission Groups
| Module | Permissions |
|--------|------------|
| Dashboard | `warehouse.dashboard.view` |
| Items | `warehouse.items.view`, `.create`, `.edit`, `.delete` |
| Inventory | `warehouse.inventory.view`, `.adjust`, `.transfer`, `.count` |
| Incoming | `warehouse.incoming.view`, `.create` |
| Outgoing | `warehouse.outgoing.view`, `.create` |
| Returns | `warehouse.returns.view`, `.create` |
| Suppliers | `warehouse.suppliers.view`, `.create` |
| Projects | `warehouse.projects.view`, `.create` |
| Locations | `warehouse.locations.view`, `.create` |
| Reports | `warehouse.reports.view` |
| Settings | `warehouse.settings.view` |
| Users | `warehouse.users.view`, `.create`, `.roles` |
| Activity Log | `warehouse.activity-log.view` |

### Department Management (`/admin/departments`)
- CRUD for company departments

### Activity Logs (`/admin/activity-logs`)
- View system-wide activity logs (audit trail)
- Clear log history

### Site Settings (`/admin/site-settings`)
- Bulk update of application-wide settings

---

## 2. Item & Category Registration

### Items (`/warehouse/items`)

The Item module is the master data foundation for all inventory operations.

**Features:**
- Full CRUD for items (create, view, edit, delete)
- Item fields: `item_code`, `item_description`, `category`, `item_type`, `unit_of_measure`, `min_stock_level`, `max_stock_level`, `reorder_point`, `status`, `notes`
- **Barcode & QR Code Generation** - Generate barcode/QR code per item for scanning
- **Excel Import/Export** - Bulk import items from Excel template; export all items to Excel
- **Low Stock Alerts** - Dedicated view for items below reorder point
- **AJAX Dropdowns** - Units dropdown and items dropdown for use in other forms

**Computed Properties:**
- `total_quantity` - Sum of stock across all inventory records
- `average_unit_price` - Weighted average price across batches
- `below_reorder_point` - Boolean flag when stock is low
- `is_out_of_stock` - Boolean flag when quantity is zero

### Item Categories (`/warehouse/items/categories` & `/warehouse/item-categories`)
- Group items into categories
- Full CRUD with import/export support
- Used for reporting breakdowns and filtering

### Item Types (`/warehouse/item-types`)
- Classify items by type (e.g., raw material, consumable, equipment)
- Full CRUD operations

---

## 3. Supplier Management

### Suppliers (`/warehouse/suppliers`)

**Features:**
- Full CRUD for suppliers
- Fields: `supplier_code` (auto-generated: `SUP{NNNN}`), `name`, `contact_person`, `email`, `phone`, `address`, `tax_number`, `payment_terms`, `credit_limit`, `currency`, `status`, `rating`
- **Excel Import/Export** - Bulk import from template; export supplier list
- **AJAX Dropdown** - For use in incoming operations and deliveries
- **Supplier Rating** - Manual rating update (1-5 scale)
- **Supplier Performance Dashboard** - Calculated score based on:
  - Rating (40%)
  - On-time delivery (30%)
  - Quality score (20%)
  - Responsiveness (10%)
- **Supplier-Item Linking** - Many-to-many relationship via `supplier_items` pivot table tracking unit cost, lead time, and minimum order quantity per item

---

## 4. Project & Division Management

### Projects (`/warehouse/projects`)

**Features:**
- Full CRUD for projects
- Fields: `project_number`, `project_name`, `project_division_id`
- **External System Sync** - Sync projects from external ERP via `ExternalProjectImportService`
- Inspect external data before syncing
- View sync statistics

### Project Divisions (`/warehouse/project-divisions`)
- Group projects by division (e.g., Building Division, Civil Division)
- Fields: `division_name`, `division_code`, `description`, `status`
- Supports external system sync via `external_division_id`

### Locations (`/warehouse/locations`)
- Physical warehouse locations management
- Full CRUD operations
- Used for inventory placement tracking

---

## 5. Incoming Transactions

All inbound material flows are handled through the **Incoming Operations** module. The system supports multiple types of incoming transactions.

### 5.1 Supplier Delivery (`/warehouse/incoming-operations` & `/warehouse/supplier-delivery`)

Standard purchase from a supplier, typically linked to an LPO (Local Purchase Order).

**Flow:**
```
Create Incoming Operation (type: supplier_delivery)
    → Add line items with quantities and pricing (dual currency)
    → Optional: Quality Inspection (pass/fail per item with checklist)
    → Complete Operation
        → Adds to warehouse inventory (weighted average pricing)
        → Records division delivery aggregates
        → Creates stock movement (type: IN)
        → Updates LPO delivery status if linked
```

**Key Fields:**
- Operation number: `INC-YYYYMMDD-NNNN` (auto-generated)
- Status flow: `draft` → `pending_inspection` → `approved` → `completed`
- Supplier, project, division, LPO number
- Financial: total amount, total amount in AED, VAT amount, VAT rate, exchange rate
- Per item: quantity ordered, quantity delivered, quantity accepted, quantity rejected
- Per item: batch number, serial number, production date, expiry date, manufacturer, country of origin
- Quality: quality status (pending/passed/failed/conditional), quality checklist

**Dedicated Views:**
- Supplier delivery list with DataTable
- Supplier delivery creation form
- AJAX data endpoint for DataTable
- Export to Excel

### 5.2 Direct Delivery (`/warehouse/direct-deliveries`)

Supplier delivers directly to a project site, bypassing the warehouse.

**Flow:**
```
Create Direct Delivery (supplier + project + items)
    → Optional: Approval workflow
    → Process Receipt at site
        → Updates warehouse inventory (by project division + batch)
        → Updates project inventory
        → Creates dual stock movements: IN (from supplier) + OUT (to project site)
    → Can initiate Site Return if items need to go back
```

**Key Fields:**
- Delivery number: `DD-YYYYMM-NNNN`
- Reference number: `DDR-YYYYMMDD-NNN` (for site return linking)
- Status: `pending` → `partially_delivered` → `delivered` → `received` / `partially_received`
- Delivery type: `purchase_order`, `direct_purchase`, `emergency`
- Per item: ordered quantity, delivered quantity, received quantity, returned quantity

### 5.3 Site Return (`/warehouse/site-return`)

Materials returned from a project site back to the warehouse. See [Section 9: Returns Module](#9-returns-module) for details.

### 5.4 Emergency Procurement

Urgent procurement bypassing the standard LPO approval process.

### 5.5 Inter-Division Transfer

Transfer of materials between company divisions (as an incoming operation type).

---

## 6. Outgoing Transactions

### Material Requests (`/warehouse/outgoing`)

The primary mechanism for projects to request materials from the warehouse.

**Flow:**
```
Create Material Request (project, division, requester, items with quantities)
    → Each item gets quantity_balance = quantity_requested
    → Request enters pending-approval queue
    → Approve request
    → Dispatch (approveAndDispatch):
        → FIFO deduction from inventory (ordered by expiry date)
        → Updates project inventory (adds to project site)
        → Creates stock movement (type: OUT)
        → Records division delivery issue
    → quantity_balance updated on each OutgoingItem
    → Status → 'successful' when all items fulfilled
```

**Key Fields:**
- Material request number (unique reference)
- Status flow: `pending` → `approved` → `successful` / `completed` / `closed`
- Additional statuses: `cancelled`, `rejected`, `converted_to_direct_delivery`, `converted_to_transfer`, `processed_multi_source`
- Project, division, requester, approver
- Per item: quantity requested, quantity released, quantity balance, unit price (weighted avg at dispatch)
- FOC available flag per item

**Features:**
- Pending approval queue view
- Approval workflow
- Dispatch with FIFO inventory deduction
- Search items for new request (AJAX)
- Material delivery note generation

---

## 7. Material Issue Decision Center

### Decision Center (`/warehouse/material-issue`)

A specialized module where warehouse staff decide HOW to fulfill material requests. This is the core intelligence of the system - it allows fulfillment from multiple sources.

**Flow:**
```
Material request arrives at Decision Center
    → System shows: requested quantities, inventory availability, FOC availability, fulfillment history
    → User decides per item from which source to fulfill:

    Source: "inventory" (standard warehouse stock)
        → Deducts from inventory (FIFO by expiry)
        → Creates OutgoingFulfillment (type: 'inventory')
        → Updates quantity_balance on OutgoingItem
        → Creates stock movement

    Source: "direct_delivery" (fulfill via new direct delivery)
        → Creates OutgoingFulfillment (type: 'direct_delivery')
        → Routes to Direct Delivery creation

    Source: "project_transfer" (from another project's stock)
        → Creates OutgoingFulfillment (type: 'project_transfer')
        → Routes to transfer process

    Source: "foc" (free-of-charge from damaged/returned pool)
        → FocInventory.dispatch()
        → Creates OutgoingFulfillment (type: 'foc')
        → Creates FocInventoryAdjustment
```

**Multi-Source Fulfillment:**
- A single material request can be fulfilled from multiple sources simultaneously
- The `processMultiSource()` method handles mixed-source fulfillment in one operation

**FOC API Endpoints:**
- Get FOC items available for a request
- Get FOC reference numbers
- Get FOC available quantities
- Get FOC stock by division

**Views:**
- Pending requests tab (with balance remaining to fulfill)
- Completed requests tab
- Statistics cards (total pending, fulfilled today, etc.)

---

## 8. Transfer Modules

The system supports three levels of material transfer between projects:

### 8.1 Material Transfer Request - Formal (`/warehouse/transfer-requests`)

A formal, approval-based transfer process for project-to-project material movements.

**Flow:**
```
Create Transfer Request (draft)
    → Validates transferrer project has sufficient stock
    → Submit → status: pending_transferrer_approval
    → Transferrer approves/partially approves
        → status: approved / partially_approved
    → Can be rejected or cancelled at any stage
```

**Key Fields:**
- Transfer request number: `MTR-YYYY-NNNN`
- Status: `draft` → `pending_transferrer_approval` → `approved` / `partially_approved` / `rejected` / `cancelled`
- Priority: `low`, `medium`, `high`, `urgent`
- Transferrer project, receiver project, requester, approvers
- Per item: quantity requested, quantity available (at request time), estimated unit price

### 8.2 Material Transfer Issue - Physical Dispatch (`/warehouse/transfer-issues`)

The physical execution of an approved Material Transfer Request.

**Flow:**
```
Create Transfer Issue (against approved MTR)
    → Dispatch:
        → Deducts from transferrer's project_inventory
        → Creates project_transfer_out stock movement
    → Mark In Transit (with vehicle/driver info)
    → Receive at destination:
        → If no inspection required: adds to receiver's project_inventory
        → Creates project_transfer_in stock movement
    → Complete Inspection (if required):
        → If passed: adds to receiver's project_inventory
        → If failed: records issues
    → Can attach delivery documents
    → Can cancel issue
```

**Key Fields:**
- Transfer issue number: `MTI-YYYY-NNNN`
- Status: `draft` → `dispatched` → `in_transit` → `delivered` / `partially_received` → `completed`
- Vehicle info, driver info, inspection workflow

### 8.3 Site Transfer - Simplified (`/warehouse/site-transfers`)

A simplified, direct project-to-project material transfer without approval workflow.

**Flow:**
```
Create Site Transfer (from/to project, items)
    → System deducts from source project_inventory
    → System adds to destination project_inventory
    → Creates MaterialSiteTransferItemAllocation records
      (tracks which MR/DD/SD/MT references contributed stock)
    → Creates stock movements
```

**Key Fields:**
- Transfer number: `ST-NNNNN`
- From project, to project, transferred by user
- Per item: allocation tracking by original delivery reference

**AJAX Endpoints:**
- Get project inventory (for source selection)
- Get item allocation details (which references contributed stock)
- Get consolidated project items across all delivery sources

---

## 9. Returns Module

### Site Returns (`/warehouse/site-return`)

Materials returned from a project site back to the warehouse. The system tracks 4 types of returns based on the original delivery method:

| Return Type | Original Source | Reference Link |
|-------------|----------------|----------------|
| MR Return | Material Request | `outgoing_item_id` |
| DD Return | Direct Delivery | `direct_delivery_item_id` |
| MT Return | Material Transfer | `material_transfer_item_id` |
| SD Return | Supplier Delivery | `supplier_delivery_item_id` |

**Flow:**
```
Create Incoming Operation (type: site_return)
    → Select reference type (MR / DD / MT / SD)
    → System loads returnable items from original transaction
    → On Complete:
        → Adds to warehouse inventory (back to stock)
        → Records DivisionDelivery.recordReturn()
        → Subtracts from project_inventory:
            - MR returns: finds project from OutgoingTransaction.project_id
            - DD returns: uses site return's project_id
            - MT returns: finds project from MaterialTransferRequest.receiver_project_id
            - SD returns: uses site return's project_id
        → Creates stock movement (type: IN)
        → For DD returns: updates DirectDeliveryItem.returned_quantity
```

**AJAX Endpoints:**
- Get material request data for return lookup
- Get direct delivery data for return lookup
- Get material transfer data for return lookup
- Get supplier delivery data for return lookup
- Get ALL returnable items by project (consolidated across all delivery types)

**Print Views:**
- Print individual site return
- Print material request returns
- Print project consolidated returns

### General Returns (`/warehouse/returns`)
- Standard return transaction CRUD
- Create, view, edit, delete returns
- Process/complete return workflow

---

## 10. Inventory Management

### Inventory Dashboard (`/warehouse/inventory`)

The central hub for all inventory operations.

**Features:**
- DataTable with AJAX loading for real-time inventory data
- Dashboard metrics and chart data
- Filter by location

### Three-Level Inventory Tracking System

The system maintains inventory at three (plus one) levels simultaneously:

**Level 1: Main Warehouse Inventory (`inventory` table)**
- Physical stock in the warehouse, tracked by item + division + batch
- Increases when: supplier delivers to warehouse, site returns materials
- Decreases when: material requests are fulfilled (dispatched to project)
- Uses **FIFO by expiry date** for deductions (earliest expiry first)
- Uses **weighted average pricing** for additions
- Auto-sets status: `in_stock`, `low_stock`, `out_of_stock`
- Tracks: batch number, supplier batch number, PO number, production date, expiry date, quality status

**Level 2: Project Inventory (`project_inventory` table)**
- Materials currently at project sites, tracked by project + item
- Increases when: warehouse issues to project, direct delivery received at site, transfer from another project
- Decreases when: site return (back to warehouse), transfer to another project
- `available_for_transfer` = `quantity_available - allocated_quantity`
- Weighted average pricing on additions

**Level 3: Division Delivery Aggregates (`division_deliveries` table)**
- Running totals per division per item
- Tracks: total delivered, current available, total issued, average unit price, total value
- Updated by: `recordDelivery()`, `recordIssue()`, `recordReturn()`, `recordDamagedReturn()`

**Level 4: FOC Inventory (`foc_inventory` table)**
- Free-of-Charge pool from damaged/returned items
- Can be issued to fulfill material requests at no cost
- Tracks: condition, damage severity, estimated value, recoverable value
- Operations: `reserve()`, `dispatch()`, `adjustQuantity()`, `changeCondition()`, `dispose()`

### Inventory Operations

**Low Stock View** (`/warehouse/inventory/low-stock`)
- Items below reorder point across all divisions

**Inventory Valuation** (`/warehouse/inventory/valuation`)
- Total value of all inventory by item/category/division

**Aging Report** (`/warehouse/inventory/aging-report`)
- Stock age based on production/delivery date
- Identifies slow-moving items

**Condition Conversion** (`/warehouse/inventory/condition-conversion`)
- Convert item condition: Good → Damaged → FOC
- Flow:
  ```
  Select item from inventory as damaged/FOC
      → Deducts quantity from inventory table
      → Creates DamagedItem record (damage description, severity, cost responsibility, recoverable/loss amounts)
      → Creates FocInventory record (condition, estimated/recoverable value)
      → Creates stock movement (adjustment type)
      → DivisionDelivery.recordDamagedReturn()
  ```

**Manual Adjustments** (`/warehouse/inventory/adjustments`)
- Create ad-hoc quantity adjustments (increase/decrease) with reason
- Import adjustments from Excel template
- View adjustment history with details
- Clear all adjustments

**Physical Stock Count** (`/warehouse/inventory/physical-count`)
- Perform physical count reconciliation
- Compare system vs actual quantities
- Auto-generate adjustment records

**Internal Stock Transfers** (`/warehouse/inventory/transfers`)
- Transfer stock between warehouse locations/divisions (not project-to-project)

**Stock Reserve/Release** (`/warehouse/inventory/{itemId}/reserve` & `/release-reserved`)
- Reserve stock for planned operations
- Release previously reserved stock

**Stock Movement History** (`/warehouse/inventory/{itemId}/stock-movements`)
- Complete movement audit trail per item
- Movement types: `in`, `out`, `return`, `adjustment`, `transfer`, `project_transfer_in`, `project_transfer_out`

### Material Request Processing (from Inventory)

**Material Requests View** (`/warehouse/inventory/material-requests`)
- View pending material requests from projects
- View individual request details
- Dispatch material requests
- Print request documents
- Delete requests

**Material Issued View** (`/warehouse/inventory/material-issued`)
- View completed material issues
- Issue detail view
- Print material issue documents

**Division Stock & Deliveries**
- Get stock levels for a specific item in a division
- Get delivery history for a division
- Check bulk availability for multiple items

---

## 11. LPO Management

### Local Purchase Orders (`lpo_management` table)

**Key Fields:**
- LPO number: `LPO-YYYY-NNNNNN`
- Status: `draft` → `pending_approval` → `approved` → `sent_to_supplier` → `partially_delivered` → `completed` / `cancelled`
- Supplier, project, department
- Budget allocation, budget consumed, budget approval workflow
- Line items via `LpoItem`

**Flow:**
```
Create LPO
    → Budget Approval (if budget_allocated > 0)
    → LPO Approval
    → Send to Supplier
    → As deliveries arrive (via Incoming Operations with lpo_number):
        → lpo.updateDeliveryStatus() tracks total delivered vs ordered
        → Status auto-updates: partially_delivered → completed (at 100%)
```

---

## 12. Reporting Module

### Reports Dashboard (`/warehouse/reports`)

Centralized access point for all system reports.

### Available Reports

| # | Report | Route | Source Data | Export Formats |
|---|--------|-------|-------------|----------------|
| 1 | **Inventory Report** | `/reports/inventory` | `inventory` + `items` + `item_categories` | Excel |
| 2 | **Materials Report** | `/reports/materials` | Same + `project_inventory` + `foc_inventory` | Excel, PDF |
| 3 | **Supplier Delivery Report** | `/reports/incoming` | `incoming_operation_items` + legacy `incoming_items` | - |
| 4 | **Material Request Report** | `/reports/outgoing` | `outgoing_items` + `outgoing_transactions` | - |
| 5 | **Site Return Report** | `/reports/returns` | `incoming_operation_items` (type=site_return) | - |
| 6 | **Material Issue Report** | `/reports/transactions` | `outgoing_fulfillments` | Excel, PDF |
| 7 | **Stock Movements** | `/reports/stock-movements` | `stock_movements` | - |
| 8 | **Inventory Aging** | `/reports/aging` | `inventory` | - |
| 9 | **Low Stock** | `/reports/low-stock` | `inventory` + `items` | - |
| 10 | **Supplier Performance** | `/reports/supplier-performance` | `suppliers` + transaction history | - |
| 11 | **Project Transfers** | `/reports/project-transfers` | `material_transfer_requests` + `material_transfer_issues` | - |
| 12 | **Direct Deliveries** | `/reports/direct-deliveries` | `direct_deliveries` | - |
| 13 | **Stock on Project** | `/reports/stock-on-project` | `project_inventory` | - |
| 14 | **FOC / Damaged Items** | `/reports/damaged-items` | `damaged_items` + `foc_inventory` | - |
| 15 | **Division Deliveries** | `/reports/division-deliveries` | `division_deliveries` | - |

### Report Details

**1. Inventory Report**
- Aggregated by item: total quantity, average unit price, total value, price range
- Batch breakdown, stock status, division breakdown
- Production and expiry dates
- Drill-down to item-level detail with pricing history

**2. Materials Report (Three-Way View)**
- Same as Inventory but shows split across:
  - Warehouse stock
  - Project site stock
  - FOC pool
- Drill-down shows warehouse inventory, project inventory, and FOC inventory per item

**3. Supplier Delivery Report**
- Supplier code, LPO reference, division
- Items, quantities, prices, quality status
- Batch numbers, operation dates
- Drill-down to item-level incoming history

**4. Material Request Report**
- Requested quantities, status, requester
- Project, division, type of goods
- Drill-down to item-level and specific request details

**5. Site Return Report**
- Returns grouped by project
- Reference type (MR/DD/MT/SD)
- Quantities, dates, conditions
- Drill-down to item-level return history

**6. Material Issue Report**
- Based on `OutgoingFulfillment` records (filters internal transactions)
- Quantity fulfilled, fulfillment type (inventory/DD/transfer/FOC)
- Division, project, item details

**7. Stock Movements**
- Full movement history: in/out/return/adjustment/transfer per item
- Filterable by date range, movement type, item

**8. Inventory Aging**
- Stock age based on production/delivery date
- Identifies slow-moving and stagnant inventory

**9. Low Stock**
- Items below reorder point across all divisions
- Urgent restocking priorities

**10. Supplier Performance**
- Calculated composite score per supplier:
  - Manual rating (40%)
  - Delivery timeliness (30%)
  - Quality score (20%)
  - Responsiveness (10%)

**11. Project Transfers Report**
- Transfer requests and their approval status
- Transfer issues and dispatch status
- From/to project details

**12. Direct Deliveries Report**
- Supplier, project, delivery status
- Amounts, received quantities

**13. Stock on Project Report**
- Materials currently at each project site
- Available vs allocated quantities
- Drill-down to project stock details
- **Item Reference Allocations** - Shows which delivery references (MR, DD, SD, MT) contributed to current stock for each item on a project

**14. FOC / Damaged Items Report**
- Damaged item records with severity and cost responsibility
- FOC quantities and conditions
- Recoverable vs loss values

**15. Division Deliveries Report**
- Total delivered, current available, total issued per division per item

### Item-Level Detail Reports
For Inventory, Materials, Incoming, Outgoing, and Returns reports, each row links to a detailed page showing:
- Pricing history from all supplier deliveries
- Inventory breakdown by division and batch
- Full stock movement history (paginated)
- Project inventory breakdown
- FOC inventory breakdown

### Export Capabilities

| Format | Available For |
|--------|--------------|
| Excel (.xlsx) | Inventory report, Materials report, Material Issue report, Supplier delivery export, Items, Suppliers, Categories |
| PDF | Materials report, Material Issue report |
| Template Downloads | Items import, Categories import, Suppliers import, Inventory adjustments |

---

## 13. Analytics Module

### Analytics Dashboard (`/warehouse/analytics`)

**Available Analytics:**

| Analytics | Route | Description |
|-----------|-------|-------------|
| **Inventory Turnover** | `/analytics/inventory-turnover` | Turnover rate calculation per item/category |
| **Stock Forecast** | `/analytics/stock-forecast` | Predictive stocking analysis based on historical data |
| **Performance Metrics** | `/analytics/performance-metrics` | Overall warehouse performance KPIs |

---

## 14. Settings & Administration

### Warehouse Settings (`/warehouse/settings`)
- **General Settings** - Warehouse-wide configuration
- **Notification Settings** - Configure alert preferences
- **Workflow Settings** - Customize approval workflows

### Warehouse Users (`/warehouse/users`)
- Manage warehouse-specific user accounts
- Create, edit, delete users
- Change user roles

### Activity Log (`/warehouse/activity-log`)
- Warehouse-specific activity audit trail

### Universal Search (`/warehouse/search`)
- Search across all modules (items, suppliers, projects, transactions)

### Dashboard Quick Stats (`/warehouse/api/quick-stats`)
- JSON API for sidebar widget showing total items, low stock count, pending transactions

---

## 15. Key Technical Details

### Document Numbering Formats

| Document | Format | Example |
|----------|--------|---------|
| Incoming Operation | `INC-YYYYMMDD-NNNN` | `INC-20260414-0001` |
| LPO | `LPO-YYYY-NNNNNN` | `LPO-2026-000001` |
| Material Transfer Request | `MTR-YYYY-NNNN` | `MTR-2026-0001` |
| Material Transfer Issue | `MTI-YYYY-NNNN` | `MTI-2026-0001` |
| Direct Delivery | `DD-YYYYMM-NNNN` | `DD-202604-0001` |
| Direct Delivery Reference | `DDR-YYYYMMDD-NNN` | `DDR-20260414-001` |
| Site Transfer | `ST-NNNNN` | `ST-00001` |
| Supplier Code | `SUP{NNNN}` | `SUP0001` |

### Currency Handling
- All items can be priced in any currency
- Every price is also stored in AED (`unit_price_aed`, `total_amount_aed`)
- Exchange rate stored per transaction (4 decimal places)
- VAT tracked separately (`vat_rate`, `vat_amount`)

### FIFO Implementation
- When issuing stock, inventory is deducted ordered by `expiry_date ASC` (earliest expiry first)
- Falls back to oldest batches when no expiry date is set

### Weighted Average Pricing
- When new stock arrives with a different price, existing and new quantities are averaged:
  ```
  new_price = ((old_qty × old_price) + (new_qty × new_price)) / (old_qty + new_qty)
  ```
- Applied at both `Inventory` model level and `ProjectInventory.updateQuantity()`

### Soft Deletes
Models using soft deletes: `IncomingOperation`, `MaterialTransferRequest`, `MaterialSiteTransfer`, `MaterialTransferIssue`, `Supplier`, `FocInventory`, `DamagedItem`, `ReturnTransaction`

### External System Integration
- `Project` model supports `external_project_id` and `last_synced_at`
- `ProjectDivision` supports `external_division_id`
- `ExternalProjectImportService` handles sync from external ERP system

### Stock Movement Types
| Type | Description |
|------|-------------|
| `in` | Stock received into warehouse |
| `out` | Stock issued from warehouse |
| `return` | Stock returned from project site |
| `adjustment` | Manual quantity adjustment |
| `transfer` | Internal warehouse transfer |
| `project_transfer_in` | Received at project via transfer |
| `project_transfer_out` | Sent from project via transfer |

---

## Complete Transaction Type Summary

### Incoming Transactions (Inventory IN)
1. **Supplier Delivery** - Standard purchase via LPO → inspection → warehouse inventory
2. **Direct Delivery** - Supplier delivers directly to project site
3. **Site Return** - Materials returned from project (4 sub-types: MR, DD, MT, SD)
4. **Emergency Procurement** - Urgent procurement without standard LPO
5. **Inter-Division Transfer** - Between company divisions

### Outgoing Transactions (Inventory OUT)
6. **Material Request** - Project requests warehouse materials → approval → dispatch
7. **Material Issue (Inventory)** - Fulfillment from warehouse stock
8. **Material Issue (FOC)** - Fulfillment from free-of-charge pool
9. **Material Issue (Direct Delivery)** - Fulfillment via new direct delivery
10. **Material Issue (Project Transfer)** - Fulfillment from another project's stock

### Transfer Transactions
11. **Material Transfer Request (MTR)** - Formal request with approval workflow
12. **Material Transfer Issue (MTI)** - Physical dispatch of approved MTR
13. **Site Transfer (ST)** - Simplified direct transfer (no approval needed)

### Inventory Adjustments
14. **Manual Adjustment** - Ad-hoc quantity increase/decrease
15. **Physical Count** - Reconciliation from physical count
16. **Condition Conversion** - Good stock → Damaged → FOC conversion
17. **FOC Dispatch** - Issue of FOC items
18. **FOC Reserve** - Reserve FOC items for planned issue

### Returns
19. **Return Transaction** - Generic return processing
