# Purchase Requisition Module

A comprehensive Laravel module for automated purchase requisition generation, supplier management, and approval workflows.

## Features

- **Automatic Generation**: Auto-calculate required quantities based on sales history and stock levels
- **Multi-Currency Support**: Handle supplier pricing in different currencies with automatic conversion
- **Supplier Portal**: Public links for suppliers to submit their pricing and availability
- **Approval Workflow**: Review supplier responses with margin analysis
- **Location-Based Permissions**: Granular access control per user and location
- **Purchase Integration**: Convert approved requisitions directly to purchase orders

## Installation

### 1. Run Migrations

```bash
php artisan module:migrate PurchaseRequisition
```

This will create the following tables:
- `pr_requests` - Main requisition records
- `pr_products` - Requisition products with calculations
- `pr_supplier_responses` - Supplier responses with share tokens
- `pr_supplier_products` - Supplier pricing details
- `pr_currencies` - Multi-currency configuration
- `pr_settings` - Module settings
- `pr_user_locations` - User location permissions
- Permissions (46 total)

### 2. Seed Default Data

```bash
php artisan module:seed PurchaseRequisition
```

This will create default currencies (EGP, USD, CNY, EUR) for all businesses.

### 3. Enable the Module

The module should be automatically enabled. If not, ensure it's listed in `modules_statuses.json`:

```json
{
    "PurchaseRequisition": true
}
```

### 4. Assign Permissions

Go to **Settings > Roles** and assign Purchase Requisition permissions to appropriate roles:

- `purchase_requisition.access_module` - Access the module
- `purchase_requisition.create` - Generate new requisitions
- `purchase_requisition.view_all` - View all requisitions
- `purchase_requisition.approve` - Approve supplier responses
- `purchase_requisition.make_purchase` - Create purchase orders
- `purchase_requisition.access_settings` - Access settings

## Usage Guide

### 1. Configure Settings

Navigate to **Purchase Requisition > Settings**

**Default Values:**
- Selling Interval: 365 days (period to analyze sales)
- Stock Cover Interval: 180 days (future period to cover)
- Margin Ratio: 20% (minimum acceptable margin)

**Currencies:**
- Add/edit currencies with conversion rates to EGP
- Disable unused currencies

**User Permissions:**
- Assign location-based access to users
- Control which locations users can access for generating, viewing, and approving requisitions

### 2. Generate Purchase Requisition

Navigate to **Purchase Requisition > Generate**

1. **Select Filters:**
   - Brand, Category, Subcategory
   - Business Location (required)

2. **Set Parameters:**
   - Selling Interval (days to analyze)
   - Stock Cover Interval (days to cover)

3. **Auto Generate:**
   - Click "Auto Generate" to calculate required quantities
   - Formula: `Required Qty = Covered QTY - (Current Stock + Pending Purchase Qty)`
   - Where: `Covered QTY = (((Total Sold - Total Return) * Stock Cover) / Selling Interval)`

4. **Review Products:**
   - Products with no previous purchases are highlighted
   - Products with zero required quantity are highlighted
   - Add notes to specific products if needed

5. **Save:**
   - Click "Save" to create the requisition
   - Status will be set to "Draft"

### 3. Share with Suppliers

Navigate to **Purchase Requisition > List All**

1. **Select Requisition:**
   - Click "Share Link" action on a requisition

2. **Choose Suppliers:**
   - Select one or more suppliers
   - Click "Generate Links"

3. **Share Links:**
   - Copy unique links for each supplier
   - Send via email/SMS manually
   - Status changes to "Pending Supplier"

### 4. Supplier Response (Public)

Suppliers access the link (no login required):

1. **View Products:**
   - See required quantities and product details
   - Click images for fullscreen view

2. **Fill Response:**
   - Enter available quantity (≤ required quantity)
   - Enter price in selected currency
   - Add supplier notes if needed

3. **Submit:**
   - **Save**: Can access link again to edit
   - **Submit**: Locks the response (cannot edit)
   - Confirmation popup warns about permanent submission

### 5. Approve Requisition

Navigate to **Purchase Requisition > Approve**

1. **Review Responses:**
   - View all supplier submissions
   - See converted prices in EGP
   - Margin percentage calculated automatically
   - Rows with low margin highlighted in red

2. **Select Products:**
   - Check products to approve
   - Can approve from multiple suppliers

3. **Submit Approval:**
   - Click "Approve Selected"
   - Status changes to "Approved"
   - Supplier links become inactive

### 6. Make Purchase

From the index page:

1. **Click "Make Purchase"** on approved requisition

2. **Select:**
   - Supplier
   - Business Location
   - Check "Export as CSV" if needed

3. **Create:**
   - Purchase order created with status "Ordered"
   - Products linked via `purchase_requisition_line_id`
   - Redirects to purchase edit page

## Workflow Diagram

```
┌─────────────┐
│   DRAFT     │ ← Generate requisition
└──────┬──────┘
       │ Share with suppliers
       ▼
┌─────────────────┐
│ PENDING_SUPPLIER│ ← Suppliers submit responses
└──────┬──────────┘
       │ All submitted
       ▼
┌──────────────────┐
│ PENDING_APPROVAL │ ← Admin reviews & approves
└──────┬───────────┘
       │ Approved
       ▼
┌─────────────┐
│  APPROVED   │ ← Make purchase
└──────┬──────┘
       │ Purchase created
       ▼
┌─────────────┐
│  COMPLETED  │
└─────────────┘
```

## Calculations Reference

### Covered Quantity
```
Covered QTY = (((Total Sold - Total Return) * Stock Cover Interval) / Selling Interval)
```

### Required Quantity
```
Required Qty = Covered QTY - (Current Stock + Pending Purchase Qty)
```

### Currency Conversion
```
Converted Price (EGP) = Supplier Price × Conversion Rate
```

### Margin Percentage
```
Margin = ((Selling Price - Converted Price) / Converted Price) × 100
```

## Database Schema

### Main Tables

- **pr_requests**: Requisition headers
- **pr_products**: Products in each requisition
- **pr_supplier_responses**: Supplier submissions
- **pr_supplier_products**: Supplier pricing per product
- **pr_currencies**: Currency configurations
- **pr_settings**: Module settings (JSON)
- **pr_user_locations**: Location-based permissions

### Integration

- Links to `purchase_lines` via `purchase_requisition_line_id`
- Uses existing `products`, `variations`, `contacts`, `business_locations`
- Queries `transaction_sell_lines` for sales data
- Queries `variation_location_details` for stock levels

## Permissions Structure

### Main Permissions
- `purchase_requisition.access_module`
- `purchase_requisition.create`
- `purchase_requisition.view_all`
- `purchase_requisition.view_own`
- `purchase_requisition.edit`
- `purchase_requisition.delete`
- `purchase_requisition.approve`
- `purchase_requisition.share_with_suppliers`
- `purchase_requisition.make_purchase`
- `purchase_requisition.access_settings`

### Location Permissions (Dynamic)
Format: `purchase_requisition.location_access_{status}_{direction}_{type}_locations`

- **Status**: generate, index, approve
- **Direction**: from, to
- **Type**: all, his, selected

Example: `purchase_requisition.location_access_generate_from_all_locations`

## API Routes

All routes under `/purchase-requisition` (admin) and `/supplier-response` (public).

See `Routes/web.php` for complete route list.

## Troubleshooting

### Migrations Fail
- Check database connection
- Ensure all foreign key tables exist (business, users, products, etc.)
- Run migrations in order

### Calculations Incorrect
- Verify settings (selling interval, stock cover interval)
- Check transaction_sell_lines data
- Ensure variation_location_details has stock data

### Supplier Links Not Working
- Check share_token is unique
- Verify status is "pending_supplier"
- Ensure public routes don't have auth middleware

### Permissions Not Working
- Clear cache: `php artisan cache:clear`
- Re-assign permissions to roles
- Check middleware stack in routes

## Support

For issues or questions, check:
1. Laravel logs: `storage/logs/laravel.log`
2. Browser console for JavaScript errors
3. Database foreign key constraints

## Version

**1.0.0** - Initial Release

## License

This module is part of the Static ERP system.

---

**Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>**
