# Bills Return Controller Documentation

**File**: `/controllers/billsreturn.php`  
**Purpose**: Manages product returns and refund processing for optical sales  
**Last Updated**: December 20, 2024  
**Total Functions**: 15+  
**Lines of Code**: 734

---

## 📋 Overview

The Bills Return Controller handles the complete return process for optical products sold through the ERP system. It provides:
- Product return processing from sales bills
- Partial and full return handling
- Inventory restoration management
- Customer refund processing (cash/account credit)
- Financial accounting for returns
- Return audit trail and reporting
- Integration with original sales bills
- Multi-product return support
- Return authorization and validation
- Cost tracking for returned items

### Primary Functions
- [x] Product return processing from sales bills
- [x] Partial and full quantity returns
- [x] Inventory quantity restoration
- [x] Customer refund processing (cash/credit)
- [x] Financial journal entries for returns
- [x] Return validation against original sales
- [x] Multi-product return handling
- [x] Return audit trail and reporting
- [x] Cost tracking for returned inventory
- [x] Integration with sales bill system

### Related Controllers
- [billsfunctions.php](billsfunctions.md) - Sales utilities
- [sellbillController.php](sellbillController.md) - Sales operations
- [buyBillController.php](buyBillController.md) - Purchase operations

---

## 🗄️ Database Tables

### Primary Return Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **billsreturn** | Return bill master | id, billid, returnedprice, clientreceivevalue, date, userid, deleted, dailyentryid |
| **billsreturnproducts** | Return line items | id, returnbillid, productid, productno, productprice, producttotalprice, billproductid, deleted |
| **bills** | Original sales bills | id, clientid, billno, finalnetbillvalue, clientdebt, deleted |
| **billsproducts** | Original sales line items | id, billid, productid, productno, productprice, producttotalprice, deleted |

### Supporting Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **client** | Customer master data | clientid, clientname, clientdebt, treeId |
| **product** | Product catalog | productid, productName, productBuyPrice, lastbuyprice, meanbuyprice |
| **storedetail** | Current inventory | storedetailid, productid, storeid, productquantity |
| **storereport** | Inventory movement log | id, productid, storeid, productbefore, productafter, storereporttype, tablename |

### Financial Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **dailyentry** | Accounting journal entries | dailyentryid, dDateTime, entryComment, fromFlag |
| **dailyentrycreditor** | Credit entries | id, dailyentryid, accountstreeid, value, pluginControllerName |
| **dailyentrydebtor** | Debit entries | id, dailyentryid, accountstreeid, value, pluginControllerName |
| **save** | Cash registers | saveid, savename, savecurrentvalue, treeId |

---

## 🔑 Key Functions

### 1. **Default Action / Return Form** - Return Processing Interface
**Location**: Line 166  
**Purpose**: Display return creation form with store selection

**Process Flow**:
1. Load all available stores for dropdown
2. Display return form template
3. Enable bill selection and return processing

---

### 2. **add()** - Process Complete Return
**Location**: Line 395  
**Purpose**: Process complete return transaction with all components

**Function Signature**:
```php
function add()
```

**Process Flow**:
1. Save return bill details via `saveBillDetails()`
2. Process returned products via `saveBillProducts()`
3. Create financial entries via `saveDailyEntry()`
4. Handle transaction completion

**Features**:
- Complete return processing
- Inventory restoration
- Financial accounting integration
- Customer refund handling

---

### 3. **saveBillDetails()** - Return Bill Creation
**Location**: Line 401  
**Purpose**: Create return bill master record

**Function Signature**:
```php
function saveBillDetails()
// Returns: Return bill ID
```

**Process Flow**:
1. Extract return parameters (bill ID, amounts)
2. Load original bill information
3. Create return bill record
4. Set system metadata (date, user, branch)

**Key Data Captured**:
```php
$billId = filter_input(INPUT_POST, "billId");                    // Original bill
$discValue = filter_input(INPUT_POST, "discValue");              // Total return value
$clientReceiveValue = filter_input(INPUT_POST, "clientReceiveValue"); // Cash refund
```

---

### 4. **saveBillProducts()** - Process Returned Products
**Location**: Line 427  
**Purpose**: Process individual returned products with inventory restoration

**Function Signature**:
```php
function saveBillProducts($billsReturnId)
```

**Process Flow**:
1. Process each returned product line
2. Create return product records
3. Update inventory quantities (restore stock)
4. Log inventory movements
5. Update product cost tracking

**Inventory Restoration Logic**:
```php
if ($billProductId && $billProductId != -1 && $productNum > 0) {
    // Get current inventory
    $storeDetail = $storeDetailEX->getProductQuantity($billsProducts->productid, $storeId);
    $productbefore = $storeDetail->productquantity;
    $productafter = $productbefore + $productNum; // Add back to inventory
    
    // Update inventory
    $storeDetail->productquantity = $productafter;
    $storeDetailDAO->update($storeDetail);
    
    // Log movement
    insertStorereportupdate($billsProducts->productid, $storeId, $productNum, 
                           $productbefore, $productafter, 0, $billsReturnId, 
                           "مرتجع فاتورة مبيعات", "billsreturn.php", date('Y-m-d'));
}
```

---

### 5. **saveDailyEntry()** - Return Financial Processing
**Location**: Line 524  
**Purpose**: Create accounting entries for return transactions

**Function Signature**:
```php
function saveDailyEntry($billsReturnId)
```

**Accounting Logic**:
1. **Debit**: Returns & Allowances account (expense)
2. **Credits**:
   - Cash account (if cash refund given)
   - Customer receivable (if account credit)

**Journal Entry Structure**:
```php
// Debit: Returns account
$dailyEntryDebtor->value = $discValue;           // Total return amount
$dailyEntryDebtor->accountstreeid = 16;          // Returns account

// Credit: Cash account (if cash refund)
if ($clientReceiveValue > 0) {
    $dailyEntryCreditor->value = $clientReceiveValue;
    $dailyEntryCreditor->accountstreeid = $save->treeId; // Cash register
}

// Credit: Customer account (if account credit)
if ($clientDeptChangeValue > 0) {
    $dailyEntryCreditor2->value = $clientDeptChangeValue;
    $dailyEntryCreditor2->accountstreeid = $client->treeId; // Customer receivable
}
```

---

### 6. **show()** - Return Listing
**Location**: Line 192  
**Purpose**: Display all return transactions with filtering options

**Process Flow**:
1. Load customer data for filtering
2. Load bill numbers for reference
3. Display return listing template
4. Enable return management operations

---

### 7. **details()** - Return Detail View
**Location**: Line 275  
**Purpose**: Display comprehensive return transaction details

**Function Signature**:
```php
// Called via: GET parameter 'id' (return bill ID)
$billsReturnId = filter_input(INPUT_GET, "id");
```

**Process Flow**:
1. Load return bill record
2. Calculate other returns for same bill
3. Display bill details via `getBillDetails()`
4. Show return-specific information

---

### 8. **edit() / update()** - Return Modification
**Location**: Line 240 (edit), Line 699 (update)  
**Purpose**: Modify existing return transactions

**Edit Process**:
1. Load return record and related data
2. Calculate return totals and balances
3. Display edit form with current values

**Update Process**:
1. Update return bill details via `updateBillDetails()`
2. Update returned products via `updateBillProducts()`
3. Reverse and recreate financial entries
4. Handle transaction completion

---

### 9. **delete()** - Return Deletion
**Location**: Line 210  
**Purpose**: Soft delete return with inventory reversal

**Process Flow**:
1. Mark return as deleted
2. Reverse financial entries
3. Reverse inventory changes (remove returned quantities)
4. Log inventory movements

**Inventory Reversal Logic**:
```php
foreach ($billsReturnProducts as $productR) {
    $productNum = $productR->productno;
    $storeDetail = $storeDetailEX->getProductQuantity($productR->productid, $storeId);
    $productbefore = $storeDetail->productquantity;
    $productafter = $productbefore - $productNum; // Remove returned quantity
    $storeDetail->productquantity = $productafter;
    $storeDetailDAO->update($storeDetail);
}
```

---

### 10. **getBillDetails() / getBillProducts()** - Return Data Assembly
**Location**: Line 302 (details), Line 336 (products)  
**Purpose**: Assemble complete return transaction information

**Data Assembly Components**:
1. **Original Bill**: Load source sales bill
2. **Customer Info**: Client details and history
3. **Return Calculations**: Net amounts after returns
4. **Product Details**: Line-by-line return information
5. **Return History**: Previous returns for same bill

---

## 🔄 Workflows

### Workflow 1: Complete Product Return Processing
```
┌─────────────────────────────────────────────────────────────┐
│              START: Process Product Return                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Return Authorization                                    │
│     - Select original sales bill                            │
│     - Validate return eligibility                           │
│     - Check return timeframe and policies                   │
│     - Verify product condition                              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Return Details Specification                            │
│     FOR EACH product to return:                             │
│       │                                                     │
│       ├─→ Select product from original bill                │
│       ├─→ Specify return quantity (≤ original quantity)    │
│       ├─→ Validate return quantity against previous returns│
│       ├─→ Calculate return value (qty × original price)    │
│       └─→ Specify return reason/notes                      │
│                                                             │
│     Return Value Calculation:                               │
│       ├─→ Total return value = Sum of product returns      │
│       ├─→ Cash refund amount (customer choice)             │
│       └─→ Account credit = Total return - Cash refund      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Inventory Restoration                                   │
│     FOR EACH returned product:                              │
│       │                                                     │
│       ├─→ Get current inventory quantity                   │
│       │                                                     │
│       ├─→ Add returned quantity back to inventory:         │
│       │   New_Qty = Current_Qty + Returned_Qty             │
│       │                                                     │
│       ├─→ Update product cost tracking:                    │
│       │   ├─ Restore last buy price                        │
│       │   └─ Maintain mean buy price                       │
│       │                                                     │
│       └─→ Log inventory movement:                           │
│           ├─ Movement type: Return (increase)               │
│           ├─ Quantity before/after                         │
│           └─ Reference return bill                         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Financial Processing                                    │
│     Create return journal entries:                          │
│       │                                                     │
│       ├─→ Debit: Returns & Allowances Account              │
│       │   Amount: Total return value                       │
│       │   Purpose: Record return expense                   │
│       │                                                     │
│       ├─→ Credit: Cash Account (if cash refund):           │
│       │   Amount: Cash refund amount                       │
│       │   Purpose: Cash paid to customer                   │
│       │                                                     │
│       └─→ Credit: Customer Receivable (if account credit): │
│           Amount: Total return - Cash refund               │
│           Purpose: Reduce customer debt                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Return Documentation                                    │
│     - Create return bill record                             │
│     - Link to original sales bill                           │
│     - Generate return receipt/documentation                 │
│     - Update original bill net values                       │
│     - Complete transaction and commit changes               │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Return Validation and Business Rules
```
┌─────────────────────────────────────────────────────────────┐
│          START: Validate Return Request                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Original Bill Validation                                │
│     - Verify bill exists and is not deleted                 │
│     - Check bill status (paid/unpaid)                       │
│     - Validate customer information                         │
│     - Ensure bill is within return period                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Product Return Eligibility                              │
│     FOR EACH product on return request:                     │
│       │                                                     │
│       ├─→ Verify product was on original bill              │
│       │                                                     │
│       ├─→ Check returnable quantity:                       │
│       │   Original_Qty - Previously_Returned_Qty           │
│       │                                                     │
│       ├─→ Validate requested return quantity:              │
│       │   Return_Qty ≤ Available_For_Return                │
│       │                                                     │
│       └─→ Check product condition and policy:              │
│           ├─ Physical condition acceptable                 │
│           ├─ Custom products (may not be returnable)       │
│           └─ Service items (special handling)              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Financial Impact Calculation                            │
│     - Calculate total return value impact                   │
│     - Determine refund vs account credit split              │
│     - Validate against customer account limits              │
│     - Check for outstanding customer debt                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Authorization and Processing                            │
│     IF all validations pass:                                │
│       └─→ Proceed with return processing                   │
│     ELSE:                                                   │
│       ├─→ Display validation errors                        │
│       ├─→ Suggest corrective actions                       │
│       └─→ Require manager override if applicable           │
└─────────────────────────────────────────────────────────────┘
```

---

## 🧮 Return Calculations

### Return Value Calculation
```php
// Calculate total return amount
$totalReturnValue = 0;
for ($i = 1; $i <= $itr; $i++) {
    $returnQty = filter_input(INPUT_POST, 'retnum' . $i);
    $productPrice = filter_input(INPUT_POST, 'proprice' . $i);
    $lineReturnValue = $returnQty * $productPrice;
    $totalReturnValue += $lineReturnValue;
}
```

### Refund Distribution
```php
$discValue = filter_input(INPUT_POST, "discValue");              // Total return value
$clientReceiveValue = filter_input(INPUT_POST, "clientReceiveValue"); // Cash refund
$clientDeptChangeValue = $discValue - $clientReceiveValue;       // Account credit
```

### Inventory Impact
```php
// For each returned product
$storeDetail = $storeDetailEX->getProductQuantity($productid, $storeId);
$productbefore = $storeDetail->productquantity;
$productafter = $productbefore + $returnedQuantity; // Add back to stock

// Log the movement
insertStorereportupdate($productid, $storeId, $returnedQuantity, 
                       $productbefore, $productafter, 0, $returnBillId,
                       "مرتجع فاتورة مبيعات", "billsreturn.php", date('Y-m-d'));
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Return creation form |
| `do=add` | `add()` | Process new return |
| `do=show` | `show()` | List all returns |
| `do=edit` | `edit()` | Edit return form |
| `do=update` | `update()` | Update return |
| `do=delete` | `delete()` | Delete return (soft) |
| `do=details` | `details()` | View return details |
| `do=sucess` | Success page | Operation completed |
| `do=error` | Error page | Operation failed |

### Required Parameters by Action

**Add Return** (`do=add`):
- `billId` - Original sales bill ID
- `discValue` - Total return value
- `clientReceiveValue` - Cash refund amount
- `hidden_itr` - Number of returned products
- `product[i]` - Product IDs
- `retnum[i]` - Return quantities
- `proprice[i]` - Product prices
- `storeid` - Store location

**Edit Return** (`do=edit`):
- `id` - Return bill ID

**Delete Return** (`do=delete`):
- `id` - Return bill ID

**View Details** (`do=details`):
- `id` - Return bill ID

---

## 🔒 Security & Permissions

### Input Validation
```php
$billId = filter_input(INPUT_POST, "billId");
$discValue = filter_input(INPUT_POST, "discValue");
$clientReceiveValue = filter_input(INPUT_POST, "clientReceiveValue");
```

### Business Rule Validation
- Return quantities cannot exceed original sales quantities
- Return dates must be within acceptable timeframe
- Product condition must meet return policy
- Financial limits and authorization requirements

### Transaction Integrity
- All return operations wrapped in transactions
- Rollback on any validation failure
- Consistent inventory and financial updates

---

## 📊 Performance Considerations

### Database Optimization
1. **Critical Indexes**:
   - `billsreturn(billid, deleted)`
   - `billsreturnproducts(returnbillid, billproductid)`
   - `billsproducts(billid, productid)`
   - `storereport(productid, storeid, tablename)`

2. **Query Optimization**:
   - Efficient return history queries
   - Fast product availability checks
   - Optimized inventory updates

### Return Processing Performance
- Batch inventory updates
- Efficient return validation
- Quick return total calculations

---

## 🐛 Common Issues & Troubleshooting

### 1. **Inventory Discrepancies After Returns**
**Issue**: Inventory levels incorrect after processing returns  
**Cause**: Missing or incorrect inventory restoration

**Debug**:
```sql
-- Check inventory movement logs
SELECT * FROM storereport 
WHERE tablename = 'billsreturn.php' 
AND productid = [PRODUCT_ID] 
ORDER BY storereportdate DESC;

-- Verify current vs calculated inventory
SELECT 
    p.productName,
    sd.productquantity as current_qty,
    -- Calculate expected based on movements
    (SELECT SUM(CASE WHEN storereporttype = 1 THEN productquantity 
                    ELSE -productquantity END)
     FROM storereport sr 
     WHERE sr.productid = p.productid 
     AND sr.storeid = sd.storeid) as calculated_qty
FROM storedetail sd
JOIN product p ON p.productid = sd.productid
WHERE sd.productid = [PRODUCT_ID];
```

### 2. **Return Validation Failures**
**Issue**: Cannot return products that should be returnable  
**Cause**: Incorrect return quantity calculations

**Debug**:
```sql
-- Check return eligibility
SELECT 
    bp.productid,
    bp.productno as original_qty,
    COALESCE(SUM(brp.productno), 0) as returned_qty,
    bp.productno - COALESCE(SUM(brp.productno), 0) as available_for_return
FROM billsproducts bp
LEFT JOIN billsreturnproducts brp ON brp.billproductid = bp.id AND brp.deleted = 0
WHERE bp.billid = [BILL_ID] AND bp.deleted = 0
GROUP BY bp.id, bp.productid, bp.productno;
```

### 3. **Financial Entry Mismatches**
**Issue**: Return accounting entries don't balance  
**Cause**: Incorrect credit/debit calculations

**Debug**:
```php
// Verify return entry totals
$totalReturn = $discValue;
$cashRefund = $clientReceiveValue;
$accountCredit = $totalReturn - $cashRefund;

// Check that debits = credits
$totalDebits = $totalReturn;
$totalCredits = $cashRefund + $accountCredit;
if ($totalDebits != $totalCredits) {
    throw new Exception("Return entry doesn't balance");
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Partial Product Return
```
1. Create sales bill with multiple products
2. Return only some products with partial quantities
3. Verify inventory restoration is correct
4. Check financial entries are accurate
5. Validate original bill net amounts updated
```

### Test Case 2: Full Bill Return
```
1. Create sales bill with multiple products
2. Return all products in full quantities
3. Verify complete inventory restoration
4. Check full refund processing (cash + credit)
5. Validate bill status after full return
```

### Test Case 3: Multiple Partial Returns
```
1. Create sales bill
2. Process first partial return
3. Process second partial return
4. Verify cumulative return tracking
5. Check inventory levels throughout process
```

### Test Case 4: Return Validation
```
1. Attempt return with quantities > original
2. Attempt return for non-existent products
3. Test return period validation
4. Verify authorization requirements
```

### Test Case 5: Cash vs Credit Returns
```
1. Test full cash refund return
2. Test full account credit return  
3. Test mixed cash + credit return
4. Verify accounting entries for each scenario
```

---

## 🚀 Future Enhancement Opportunities

### 1. **Advanced Return Management**
- Return authorization workflow
- Return reason code tracking
- Product condition assessment
- Return analytics and reporting

### 2. **Customer Experience**
- Self-service return portal
- Return status tracking
- Automated refund processing
- Return policy automation

### 3. **Inventory Optimization**
- Returned product grading
- Refurbishment workflow
- Restocking optimization
- Return cost tracking

### 4. **Financial Integration**
- Advanced return accounting
- Tax handling for returns
- Multi-currency returns
- Return reserve accounting

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [billsfunctions.md](billsfunctions.md) - Sales utilities
- [sellbillController.md](sellbillController.md) - Sales operations

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When return management features are enhanced