# Stock Management System

## Overview
The stock management system tracks inventory levels, movements, and provides low-stock alerts for the POS application.

## Database Schema

### Tables
- **`stock_items`**: Current on-hand quantities per product
  - `id`, `product_id`, `current_qty`, `created_at`, `updated_at`
  
- **`stock_movements`**: Historical record of all stock changes
  - `id`, `product_id`, `qty`, `type` (in/out/adjust), `reference_type`, `reference_id`, `note`, `created_by`, `created_at`, `updated_at`

### Product Configuration
- **`products.min_stock`**: Minimum stock threshold for alerts

## API Endpoints

### View Stock
```
GET /api/stock/{product}
```
Returns current stock levels for a product.

### Adjust Stock
```
POST /api/stock/{product}/adjust
Content-Type: application/json

{
  "quantity": 10,
  "type": "in|out|adjust",
  "reference_type": "purchase",
  "reference_id": 123,
  "note": "Stock adjustment reason"
}
```

### List Movements
```
GET /api/stock/{product}/movements
```
Returns the last 200 stock movements for a product.

### Low Stock Report
```
GET /api/stock/low-stock
```
Returns all products below minimum stock threshold.

## Console Commands

### Check Low Stock
```bash
php artisan stock:check-low
```
Scans all products and logs alerts for items below minimum stock. Can be scheduled to run daily.

### Backfill from Legacy Data
```bash
php artisan stock:backfill --dry-run
php artisan stock:backfill
```
Converts legacy `stock_details` table data into the new `stock_movements` and `stock_items` tables.

## UI Routes

### Stock Admin
```
GET /stock
```
Web interface for viewing stock levels and making manual adjustments.

## Integration with POS

When a sale is finalized (`pos/ajax_payment_save.php`), the system automatically:
1. Decrements `stock_items.current_qty`
2. Creates a `stock_movements` record with `type='out'` and `reference_type='invoice'`

This dual-write approach maintains both legacy `stock_details` and new schema during the transition period.

## Testing

Run feature tests:
```bash
php artisan test --filter StockControllerTest
```

## Scheduling (Optional)

Add to `App\Console\Kernel::schedule()`:
```php
$schedule->command('stock:check-low')->daily();
```

## Migration Path

1. Run migrations to add `min_stock` column and create tables:
   ```bash
   php artisan migrate
   ```

2. Backfill historical data (optional):
   ```bash
   php artisan stock:backfill --dry-run
   php artisan stock:backfill
   ```

3. Configure minimum stock levels for products via admin UI or direct DB update.

4. Schedule low-stock checks to run daily.

## Notes

- The system is backward-compatible with legacy `stock_details` table
- New stock writes happen in both old and new schemas during transition
- Location-based stock is supported if `stock_items` has a `location_id` column
- All stock adjustments are logged with user ID and timestamp for audit trail
