# Stock Management System

## Overview

The stock management system has been successfully implemented with the following features:

## Features Implemented

### 1. Database Structure
- **Stock Fields Added to Items Table**: `current_stock`, `reorder_level`, `last_updated`
- **Stock Transactions Table**: Tracks all stock movements (receipts, deliveries, sales, returns, adjustments)
- **Stock Receipts Table**: Main table for stock receipt/delivery documents
- **Stock Receipt Items Table**: Detail items for each receipt/delivery

### 2. Core Functionality

#### Stock Tracking
- Automatic stock deduction on sales
- Stock validation before sale completion
- Real-time stock availability checking
- Low stock and out-of-stock alerts

#### Stock Receipts/Deliveries
- Create stock receipts (receiving inventory)
- Create stock deliveries (sending out inventory)
- Auto-generated receipt numbers
- Cost tracking per item
- Supplier/destination information

#### Stock Management Dashboard
- View current stock levels for all items
- Low stock alerts and indicators
- Stock status categorization (In Stock, Low Stock, Out of Stock)
- Manual stock adjustments
- Editable reorder levels
- Stock transaction history

### 3. User Interface Updates

#### POS Interface (items.php)
- Stock indicators on product cards (OK, LOW, OUT)
- Current stock display on each item
- Visual indicators for stock status (green, yellow, red)
- Disabled out-of-stock items
- Stock validation on cart additions

#### Navigation
- New "Stock Management" menu section
- Stock Dashboard link
- Stock Receipt/Delivery link

### 4. Stock Status Indicators

- **In Stock (Green)**: Normal stock levels
- **Low Stock (Yellow)**: Stock at or below reorder level
- **Out of Stock (Red)**: Zero stock, item disabled

## File Structure

```
sql/
├── add_stock_management.sql          # Database migration
├── branch_tables_template.sql        # Updated with stock tables
└── test_stock_data.sql               # Test data

includes/
├── stock_helper.php                  # Stock management functions
└── header.php                        # Updated navigation

pos/
├── items.php                         # Updated with stock display
├── stock_management.php              # Stock dashboard
├── stock_receipt.php                 # Stock receipt/delivery
└── save_sale.php                     # Updated with stock tracking
```

## Database Tables

### Items Table (Enhanced)
```sql
ALTER TABLE m001_items 
ADD COLUMN current_stock decimal(10,3) DEFAULT 0.00,
ADD COLUMN reorder_level decimal(10,3) DEFAULT 0.00,
ADD COLUMN last_updated timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
```

### Stock Transactions
```sql
CREATE TABLE m001_stock_transactions (
  transaction_id int(11) NOT NULL AUTO_INCREMENT,
  item_id int(11) NOT NULL,
  transaction_type enum('receipt','delivery','sale','return','adjustment'),
  quantity_change decimal(10,3) NOT NULL,
  new_balance decimal(10,3) NOT NULL,
  reference_type enum('sale','purchase','manual'),
  reference_id int(11),
  notes text,
  created_by int(11),
  created_at timestamp DEFAULT CURRENT_TIMESTAMP
);
```

### Stock Receipts
```sql
CREATE TABLE m001_stock_receipts (
  receipt_id int(11) NOT NULL AUTO_INCREMENT,
  receipt_number varchar(50) NOT NULL,
  receipt_type enum('receipt','delivery'),
  supplier_name varchar(255),
  reference_number varchar(100),
  total_items int(11) DEFAULT 0,
  status enum('draft','completed','cancelled'),
  notes text,
  created_by int(11),
  created_at timestamp DEFAULT CURRENT_TIMESTAMP,
  completed_at timestamp NULL
);
```

### Stock Receipt Items
```sql
CREATE TABLE m001_stock_receipt_items (
  receipt_item_id int(11) NOT NULL AUTO_INCREMENT,
  receipt_id int(11) NOT NULL,
  item_id int(11) NOT NULL,
  quantity decimal(10,3) NOT NULL,
  unit_cost decimal(10,2) DEFAULT 0.00,
  total_cost decimal(10,2) DEFAULT 0.00,
  expiry_date date,
  batch_number varchar(100)
);
```

## Key Functions

### Stock Helper Functions (includes/stock_helper.php)

- `updateItemStock()` - Updates stock and records transaction
- `processStockReceipt()` - Processes stock receipts/deliveries
- `checkStockAvailability()` - Validates stock before sales
- `getLowStockItems()` - Gets items below reorder level
- `getStockStatus()` - Gets current stock status for all items
- `processSaleReturn()` - Handles returns and stock restoration

## Usage

### 1. Stock Receipt/Delivery
1. Navigate to Stock Management → Stock Receipt/Delivery
2. Select receipt type (Receipt or Delivery)
3. Fill in supplier/destination details
4. Add items and quantities
5. Save to update stock levels

### 2. Stock Dashboard
1. Navigate to Stock Management → Stock Dashboard
2. View current stock levels
3. Check low stock alerts
4. Make manual adjustments
5. Set reorder levels
6. View transaction history

### 3. POS Integration
- Stock levels displayed on all product cards
- Automatic stock validation on sales
- Visual indicators prevent overselling
- Real-time stock deduction on successful sales

## Stock Transaction Types

- **Receipt**: Stock coming in (positive adjustment)
- **Delivery**: Stock going out (negative adjustment)
- **Sale**: Stock sold through POS (negative adjustment)
- **Return**: Returned items (positive adjustment)
- **Adjustment**: Manual stock corrections (positive or negative)

## Deployment Notes

1. Run the database migration:
   ```
   Get-Content sql/add_stock_management.sql | ForEach-Object { $_ -replace '{branch_code}', 'm001' } | & "C:\xampp\mysql\bin\mysql" -u root -h localhost test
   ```

2. Add test stock data:
   ```
   Get-Content sql/test_stock_data.sql | & "C:\xampp\mysql\bin\mysql" -u root -h localhost test
   ```

3. All existing functionality remains intact
4. Stock management is fully integrated with the POS system
5. Branch-specific stock isolation maintained

## Future Enhancements

- Barcode scanning integration
- Advanced reporting and analytics
- Automated reorder notifications
- Inventory valuation (FIFO/LIFO)
- Multi-location stock transfers
- Stock forecasting based on sales patterns 