# Product Request Controller Documentation

**File**: `/controllers/productrequest.php`  
**Purpose**: Manages inter-store product transfer requests and inventory redistribution workflows  
**Last Updated**: December 19, 2024  
**Total Functions**: 5  
**Lines of Code**: 367

---

## 📋 Overview

The Product Request Controller manages the complex workflow of product requests between different stores or warehouses within the ERP system. It handles request creation, approval workflows, status tracking, and facilitates inventory redistribution across multiple locations.

### Primary Functions
- [x] Create product transfer requests between stores
- [x] Display requests with different status levels (new, accepted, refused)
- [x] Handle multi-store request management
- [x] Track request status workflows (0=new, 1=refused, 2=accepted, 3=completed)
- [x] Support both centralized and store-specific request management
- [x] Generate hierarchical product category paths
- [x] Delete/cancel product requests
- [x] Integration with store and user management systems

### Related Controllers
- [storeController.php](storeController.md) - Store/warehouse management
- [productController.php](productController.md) - Product management
- [productCatController.php](productCatController.md) - Category management
- [storedetailController.php](storedetailController.md) - Inventory tracking
- [storemovementController.php](storemovementController.md) - Stock transfers
- [userController.php](#) - User and permissions management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| productrequest | Main requests table | productrequestid, productid, requeststoreid, storeid, status, deleted |

### Related Tables (Referenced)
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| product | Product information | Foreign Key: productrequest.productid |
| productcat | Product categories | Foreign Key: product.productCatId |
| store | Store/warehouse info | Foreign Key: productrequest.storeid, requeststoreid |
| user | User store assignments | Foreign Key: user.userstoreid |
| storedetail | Inventory quantities | Related: store inventory tracking |

---

## 🔧 Key Functions

### 1. Main Display Logic (do = "" - Default)
**Purpose**: Displays the product request creation form  
**Called By**: GET request with no 'do' parameter  

**Business Logic**:
1. Get user's assigned store ID from user data
2. If user has no specific store (storeId = 0), show all stores for selection
3. Display add form with appropriate store options

**Template Integration**:
- Uses `/views/default/productrequestview/add.html`
- Passes store data for dropdown selection

### 2. Show Requests (do = "show")
**Purpose**: Displays all product requests with complex filtering based on user store access  
**Called By**: GET request with `do=show`  

**Business Logic Flow**:
```
┌─────────────────────────┐
│ Get user store ID       │
└───────────┬─────────────┘
            │
            ▼
┌─────────────────────────┐
│ Store ID = 0?           │
│ (Admin access)          │
└─────┬─────────────┬─────┘
      │             │
    Yes│             │No
      ▼             ▼
┌───────────────┐ ┌─────────────────────────┐
│ Show ALL      │ │ Show filtered by:       │
│ requests:     │ │ • My requests to others │
│ • New         │ │ • Others' requests to me│ 
│ • Accepted    │ │ • Accepted (both ways)  │
│ • Refused     │ │ • Refused (both ways)   │
└───────────────┘ └─────────────────────────┘
```

**Request Categories**:
- **My Requests**: `p.requeststoreid = {userStoreId}` (requests FROM my store)
- **Other Requests**: `p.storeid = {userStoreId}` (requests TO my store)
- **Status Filters**: 
  - New: `p.status = 0`
  - Refused: `p.status = 1` 
  - Accepted: `p.status in (2, 3)`

**Data Enrichment**:
For each request, the system adds:
- Product name from product table
- Category name from productcat table  
- Full category path using `getProductPath_recursive()`

### 3. Delete Request (do = "delete")
**Purpose**: Soft deletes a product request  
**Called By**: GET request with `do=delete&id={requestId}`  
**Parameters**:
- `$_GET['id']` (int) - Product request ID to delete

**Database Operations**:
- UPDATE `productrequest` SET deleted = 1 WHERE productrequestid = $id

**Business Logic**:
1. Load existing request record
2. Set deleted flag to 1 (soft delete)
3. Update database record
4. Redirect to success or error page

### 4. add() Function (Legacy/Placeholder)
**Purpose**: Originally intended for adding insurance companies (appears to be legacy code)  
**Status**: Contains obsolete code not related to product requests
**Note**: Function contains insurance company logic that should be cleaned up

### 5. getProductPath_recursive($parentid, $categories, $level)
**Purpose**: Builds hierarchical category path for products (e.g., "Electronics/Computers/Laptops")  
**Parameters**:
- `$parentid` (int) - Starting category ID
- `$categories` (string) - Accumulated path string
- `$level` (int) - Recursion depth limiter

**Returns**: string - Complete category path separated by "/"

**Business Logic Flow**:
```
┌─────────────────────────┐
│ Get category data       │
│ for parentid            │
└───────────┬─────────────┘
            │
            ▼
┌─────────────────────────┐
│ Category exists AND     │
│ level < 2?              │
└─────┬─────────────┬─────┘
      │             │
    Yes│             │No
      ▼             ▼
┌───────────────┐ ┌─────────────────────────┐
│ Add category  │ │ Return final path       │
│ name to path  │ │ (remove trailing "/")   │
│ Recurse with  │ │                         │
│ parent ID     │ │                         │
└───────────────┘ └─────────────────────────┘
```

**Recursion Safety**: Limited to 2 levels deep to prevent infinite loops

**Example Output**:
```php
getProductPath_recursive(123, "", 0);
// Returns: "Electronics/Computers"
```

---

## 🔄 Business Logic Flow

### Request Creation Workflow
```
┌─────────────────────────┐
│ User accesses form      │
│ • Store auto-selected   │
│   OR store dropdown     │
└───────────┬─────────────┘
            │
            ▼
┌─────────────────────────┐
│ User selects:           │
│ • Target store          │
│ • Product(s) needed     │
│ • Quantity required     │
└───────────┬─────────────┘
            │
            ▼
┌─────────────────────────┐
│ System creates request  │
│ • Status = 0 (new)      │
│ • Links stores          │
│ • Records product info  │
└─────────────────────────┘
```

### Multi-Store Request Management
```
Admin User (storeId = 0)
├── Can see ALL requests system-wide
├── New requests from any store
├── Accepted requests (all)
└── Refused requests (all)

Regular User (storeId = X)  
├── MY Requests (requeststoreid = X)
│   ├── Requests I sent to other stores
│   ├── Status: New, Accepted, Refused
│   └── Action: View status, cancel
└── INCOMING Requests (storeid = X)
    ├── Requests others sent to my store  
    ├── Status: New (need approval), Accepted, Refused
    └── Action: Approve, refuse, fulfill
```

### Request Status Workflow
```
┌─────────────┐    Approve    ┌─────────────┐    Fulfill    ┌─────────────┐
│ 0 = New     │ ────────────► │ 2 = Accepted│ ────────────► │ 3 = Complete│
│ (Pending)   │               │ (Approved)  │               │ (Done)      │
└──────┬──────┘               └─────────────┘               └─────────────┘
       │
       │ Reject
       ▼
┌─────────────┐
│ 1 = Refused │
│ (Rejected)  │
└─────────────┘
```

---

## ⚠️ Common Issues

### Legacy Code Cleanup Needed
**Issue**: `add()` function contains insurance company code  
**Impact**: Confusion and potential conflicts  
**Recommendation**: Remove or move insurance logic to appropriate controller

### Missing CRUD Operations
**Issue**: No functions for creating, updating, or approving requests  
**Current State**: Only display and delete functionality  
**Missing Functions**:
- Create new request
- Approve/refuse request  
- Update request status
- Fulfill completed requests

### Category Path Performance
**Issue**: Recursive function called for each request in loops  
**Impact**: N+1 query problem with large request lists  
**Recommendation**: Cache category paths or use joins

### Error Handling
**Issue**: Limited error handling in delete operation  
**Risk**: Potential data inconsistency  
**Recommendation**: Add transaction support and better validation

---

## 🔗 Dependencies

### Required Files
```php
include("../public/impOpreation.php");           // Core operations
include("../library/uploadImages.php");         // Image upload (legacy?)
include("../public/config.php");                // Configuration
include("../public/authentication.php");        // User authentication
include("../public/include_dao.php");           // DAO includes
```

### DAO Classes
```php
// Product-related DAOs
ProductDAO.class.php                            // Product operations
ProductcatDAO.class.php                         // Category operations

// Request-related DAOs  
ProductrequestsMySqlDAO.class.php               // Request operations
ProductrequestsMySqlExtDAO.class.php            // Extended request queries

// Store-related DAOs
StoreDAO.class.php                              // Store operations
StoreMySqlExtDAO.class.php                      // Extended store operations

// User management
UserDAO.class.php                               // User operations
UserMySqlExtDAO.class.php                       // Extended user operations
```

### Views
- `/views/default/productrequestview/add.html` - Request creation form
- `/views/default/productrequestview/show.html` - Request listing and management

### Global Objects
```php
$productRequest                                 // Request DTO
$productRequestDAO                              // Request DAO
$productRequestExt                              // Extended request operations
$product, $productDAO, $productExt             // Product objects
$productCatDAO, $productCatExt                 // Category objects  
$store, $storeDAO, $storeEX                    // Store objects
$user, $userDAO, $userEX                       // User objects
```

---

## 📊 Performance Considerations

### Database Queries
- Multiple queries for each request to get product/category names
- Recursive category path function creates additional queries
- Extended DAO methods help optimize some operations

### Memory Usage  
- Processes request lists in memory with enriched data
- Category path building adds memory overhead
- Consider pagination for large request volumes

### Optimization Opportunities
1. **Join Queries**: Get product/category names in single query
2. **Category Path Caching**: Pre-compute and cache category hierarchies  
3. **Pagination**: Add pagination to request listing
4. **Index Optimization**: Ensure proper indexes on request status and store IDs

---

## 🎯 Integration Points

### Store Management Integration
```php
// User assigned to specific store
$storeId = $userdata->userstoreid;

// Request between stores  
requeststoreid = source store
storeid = target store
```

### Inventory System Integration
- Requests should trigger inventory checks
- Fulfilled requests should create store movements
- Integration with `storedetail` and `storemovement` controllers needed

### User Permission System
- Store-based access control
- Admin users (storeId = 0) see all requests
- Regular users see only their store's requests

### Approval Workflow Integration
- Missing approval/rejection functionality
- Should integrate with user permissions
- Status updates should trigger notifications

---

## 🔍 Troubleshooting

### No Requests Showing
**Symptom**: Empty request lists  
**Causes**:
- User has no store assignment (userstoreid = null)
- No requests exist for user's store
- Database connectivity issues
**Solution**: Check user store assignment and database logs

### Category Paths Not Displaying
**Symptom**: Empty or broken category paths  
**Causes**:
- Orphaned category records (parent doesn't exist)
- Infinite recursion in category hierarchy
- Database corruption in productcat table
**Solution**: Validate category hierarchy integrity

### Permission Issues
**Symptom**: Users seeing wrong requests  
**Causes**: 
- Incorrect store assignment in user table
- Logic error in store-based filtering
**Solution**: Verify user.userstoreid values

---

## 💡 Future Enhancements

### Missing Core Functionality
1. **Request Creation**: Complete form and backend processing
2. **Approval Workflow**: Approve/reject functionality with notifications  
3. **Fulfillment**: Mark requests as completed with inventory movement
4. **Status Tracking**: Timeline view of request progress
5. **Bulk Operations**: Handle multiple requests simultaneously

### Advanced Features
1. **Auto-Approval**: Rules-based automatic approval for certain conditions
2. **Inventory Integration**: Real-time availability checking
3. **Notification System**: Email/SMS alerts for request status changes
4. **Reporting**: Analytics on request patterns and fulfillment times
5. **Mobile Support**: Mobile-friendly interface for warehouse staff

### Performance Improvements
1. **Caching Layer**: Cache category hierarchies and frequent queries
2. **Real-time Updates**: WebSocket integration for live status updates
3. **API Integration**: RESTful API for mobile apps and external systems
4. **Batch Processing**: Optimize database operations for large datasets

---

## 📋 Data Flow Example

### Typical Request Scenario
```
Store A needs Product X (ID: 100)
└─ Store A user creates request
   ├─ requeststoreid = A (requesting store)  
   ├─ storeid = B (target store that has inventory)
   ├─ productid = 100
   ├─ status = 0 (new)
   └─ deleted = 0

Store B user sees incoming request
└─ Reviews inventory availability  
   ├─ Approves: status = 2
   ├─ Prepares shipment: status = 3  
   └─ OR Rejects: status = 1

Store A user sees status update
└─ Receives notification of approval/rejection
   └─ If approved, coordinates pickup/delivery
```

This controller serves as a foundation for inter-store inventory management but requires significant development to reach full functionality.