๐Ÿ“š ERP Documentation Viewer

Beautiful, colorful documentation for your ERP system

Buy Bill Functions Controller Documentation

File: /controllers/buyBillfunction.php

Purpose: Core utility functions for buy bill operations, inventory management, and financial transactions

Last Updated: December 20, 2024

Total Functions: 11

Lines of Code: ~1,440

---

๐Ÿ“‹ Overview

The Buy Bill Functions Controller is a critical utility module that provides core functions for purchase bill operations, inventory management, and financial tracking. It handles:

Primary Functions

Related Controllers

---

๐Ÿ—„๏ธ Database Tables

Primary Tables (Direct Operations)

Table NamePurposeKey Columns
**buybill**Purchase billsbuybillid, buybillsupplierid, buybillfinalbill, conditions
**buybilldetail**Purchase bill itemsbuybilldetailid, buybillid, buybilldetailproductid, buybilldetailquantity
**returnbuybill**Purchase returnsreturnbuybillid, returnbuybillsupplierid, returnbuybillfinalbill
**returnbuybilldetail**Return bill itemsreturnbuybilldetailid, returnbuybillid, returnbuybilldetailproductid
**buyandruternbill**Combined buy/returnbuybillid, buybillsupplierid, buybillfinalbill
**buyandruternbilldetail**Combined bill itemsbuybilldetailid, buybillid, buybilldetailproductid
### Inventory Management Tables

Table NamePurposeKey Columns
**storedetail**Product stock levelsstoredetailid, storeid, productid, productquantity, sizeid, colorid
**storereport**Inventory movementsstorereportid, productid, storeid, productChangeAmount, storereporttype
**sizecolorstoredetail**Size/color inventorysizecolorstoredetailid, productid, storeid, sizeid, colorid
**productserial**Serial number trackingproductserailid, productid, parcode, don, sizeid, colorid
### Financial Management Tables

Table NamePurposeKey Columns
**supplier**Supplier master datasupplierid, suppliername, suppliercurrentDebt, suppliercurrentDebtInCurrency
**supplierdebtchange**Supplier debt historysupplierdebtchangeid, supplierid, supplierdebtchangeamount, supplierdebtchangetype
**save**Cash registers/safessaveid, savename, savevalue
**savedaily**Daily cash movementssavedailyid, saveid, savedailychangeamount, savedailychangetype
**buybillcurrency**Multi-currency databuybillcurrencyid, buybillid, conversionFactor, saveConversionFactor
---

๐Ÿ”‘ Key Functions

1. deletebill() - Complete Purchase Bill Deletion

Location: Line 19

Purpose: Completely reverse a purchase bill including inventory, supplier debt, and cash flow

Function Signature:

function deletebill($id)

Process Flow:

1. Load Bill Data: Retrieve complete bill information

2. Inventory Rollback: Reverse all inventory changes

3. Supplier Debt Adjustment: Decrease supplier debt

4. Cash Flow Reversal: Reverse cash register changes

5. Serial Number Management: Mark serials as deleted

6. Audit Trail: Create comprehensive log entries

Key Operations:

// Load bill and validate conditions
$buyBillData = $buyBillDAO->load($buyBill_Id);
$deleteOrNot = $buyBillData->conditions;
if ($deleteOrNot != 1) {
    // Process deletion
    foreach ($buyBillDetailsData as $data) {
        $productId = $data->buybilldetailproductid;
        $finalquantity = $pronum * $productnumber;
        
        // Reverse inventory
        decreaseProductQuantity($storeDetailId, $productQuantityBefore, 
            $finalquantity, $proprice, $productnumber, ...);
            
        // Update supplier debt
        updateSupplierDebt($supplierId, $supplierDeptAfter, 
            $supplierDeptAfterInMainCurr);
    }
}

---

2. deletebuyruturn() - Combined Buy/Return Bill Deletion

Location: Line 413

Purpose: Handle deletion of combined purchase and return bills

Process Flow:

1. Load combined bill data

2. Process purchase portion (decrease inventory)

3. Process return portion (increase inventory)

4. Adjust supplier debt for net amount

5. Handle cash flow for net payment

6. Update all audit trails

Complexity: Handles both positive and negative inventory movements in single transaction

---

3. deleteruturn() - Pure Return Bill Deletion

Location: Line 904

Purpose: Delete purchase return bills and reverse their effects

Process Flow:

1. Load return bill data

2. Reverse return inventory (decrease quantities)

3. Adjust supplier debt (increase debt)

4. Reverse cash flow if payment was made

5. Update serial numbers and tracking

---

4. insertStoredetailupdate() - Store Detail Management

Location: Line 1295

Purpose: Update or create store detail records with full audit trail

Function Signature:

function insertStoredetailupdate($storeid, $productid, $productChangeAmount, 
    $mydate, $sizeColorStoreDetailId, $sizeId, $colorId, $lastBuyPrice, 
    $productnumber, $colName, $detailId, $tableName, $operation, $billnameId, 
    $prototal, $rowDiscount, $billDiscountVal, $billTotalBeforeDiscount, 
    $rowtaxval, $billPayedTaxPer, $cFactor, $probuyDiscountPer)

Advanced Features:

---

5. insertSupplierDebtChangeupdate() - Supplier Debt Tracking

Location: Line 1399

Purpose: Track all supplier debt changes with full audit trail

Function Signature:

function insertSupplierDebtChangeupdate($supplierId, $supplierDebtChangeBefore,
    $supplierDebtChangeBeforeInMainCurr, $supplierDebtChangeAmountInMainCurr,
    $supplierDebtChangeAmount, $supplierDebtChangeType, $processname,
    $supplierDebtChangeModelId, $supplierDebtChangeAfter, 
    $supplierDebtChangeAfterInMainCurr, $tablename, $comment, $mydate)

Multi-Currency Support:

---

6. insertSavedailyupdate() - Cash Flow Management

Location: Line 1271

Purpose: Track daily cash register movements with detailed logging

Function Signature:

function insertSavedailyupdate($savedailysavebefore, $savedailychangeamount, 
    $savedailychangetype, $saveid, $processname, $savedailymodelid, 
    $savedailysaveafter, $tablename, $mydate)

Cash Flow Types:

---

7. insertStorereportupdate() - Inventory Reporting

Location: Line 1351

Purpose: Create comprehensive inventory movement reports

Function Signature:

function insertStorereportupdate($productid, $storeid, $productChangeAmount, 
    $productbefore, $productafter, $storereporttype, $storereportmodelid, 
    $processname, $tablename, $mydate, $sizeId, $colorId)

Report Types:

---

8. isService() - Product Type Validation

Location: Line 1437

Purpose: Determine if product is service type (no inventory tracking)

Function Signature:

function isService($id)

Return Values:

---

๐Ÿ”„ Workflows

Workflow 1: Complete Purchase Bill Deletion

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
START: Delete Purchase Bill
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
โ–ผ
โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
1Load and Validate Bill
- Load main bill record
- Check deletion conditions
- Load all bill detail items
- Load currency information
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
โ–ผ
โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
2Process Each Bill Item
FOR EACH bill detail:
โ”‚
โ†’ Calculate final quantities
โ”‚ โ”œโ”€ Product unit conversions
โ”‚ โ”‚ โ””โ”€ Size/color variant handling โ”‚
โ”‚
โ†’ Reverse inventory changes
โ”‚ โ”œโ”€ Decrease store quantities
โ”‚ โ”œโ”€ Update buy price history
โ”‚ โ”‚ โ””โ”€ Handle serial numbers โ”‚
โ”‚
โ”‚ โ””โ”€โ†’ Create audit trail entries โ”‚
โ”œโ”€ Store detail updates
โ”‚ โ””โ”€ Store movement reports โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
โ–ผ
โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
3Update Supplier Financial Position
- Calculate debt change amounts
- Update supplier debt balance
- Handle multi-currency conversions
- Log supplier debt change history
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
โ–ผ
โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
4Reverse Cash Flow (if payment made)
- Calculate cash adjustment amount
- Update cash register balance
- Handle currency conversions
- Log daily cash movement
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
โ–ผ
โ–ผ
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
5Finalize Deletion
- Mark bill as deleted (conditions = 1)
- Update system timestamps
- Mark product serials as deleted
- Create final audit entries
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

---

๐Ÿงฎ Calculation Methods

Inventory Quantity Calculations

// Unit conversion and final quantity
$productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);
$productnumber = $productunitData->productnumber;
$finalquantity = $pronum * $productnumber;

// Buy price per unit calculation
$buyPrice = $data->buybilldetailprice / $productnumber;

Multi-Currency Conversion

// Currency conversion for debt tracking
$supplierDeptAfterInMainCurr = ($supplierData->suppliercurrentDebt) - $finalbill;
$supplierDeptAfter = ($supplierData->suppliercurrentDebtInCurrency) - $buybillfinalbillC;

// Save currency conversion
if ($currencyId > 1) {
    $billCurrData = $buyBillCurrEX->queryOneByBuybillid($buyBill_Id);
    $saveConversionFactor = (float) $billCurrData->saveConversionFactor;
}

Discount Calculations

// Percentage vs fixed discount handling
if ($buyBillData->buybilldiscountrype == "1") {
    $billDiscountVal = ($buyBillData->buybilldiscount / 100) * $billTotalBeforeDiscount;
    $billDiscountVal = round($billDiscountVal, 2);
} else {
    $billDiscountVal = $buyBillData->buybilldiscount; // Fixed amount
}

---

๐Ÿ”’ Security & Permissions

Current Security Status

Security Recommendations

// Add permission checks
function deletebill($id) {
    // Validate user can delete bills
    if (!checkUserPermission('delete_buy_bills')) {
        throw new Exception('Insufficient permissions');
    }
    
    // Validate bill ownership/access
    if (!userCanAccessBill($_SESSION['userid'], $id)) {
        throw new Exception('Access denied');
    }
    
    // Continue with deletion...
}

Data Integrity Safeguards

// Transaction wrapping for data consistency
$transaction = new Transaction();
try {
    $transaction->begin();
    
    // All deletion operations
    deletebill($id);
    
    $transaction->commit();
} catch (Exception $e) {
    $transaction->rollback();
    throw $e;
}

---

๐Ÿ“Š Performance Considerations

Database Optimization

1. Required Indexes:

   CREATE INDEX idx_buybilldetail_billid ON buybilldetail(buybillid);
   CREATE INDEX idx_storedetail_product ON storedetail(productid, storeid);
   CREATE INDEX idx_supplierdebt_supplier ON supplierdebtchange(supplierid, supplierdebtchangedate);
   ```

2. **Query Optimization**:
   - Batch processing of bill items
   - Minimized database round trips
   - Efficient JOIN operations

3. **Memory Management**:
   - Large bills may require memory optimization
   - Process items in batches for very large bills
   - Clean up objects after processing

### Performance Issues
php

// Potential N+1 query problem

foreach ($buyBillDetailsData as $data) {

$productunitData = loadProductUnitWithProductAndUnit($productId, $productunitId);

// This loads product unit data for each item individually

}

// Better approach: Preload all product unit data

$productIds = array_column($buyBillDetailsData, 'buybilldetailproductid');

$productUnitData = loadBatchProductUnitData($productIds);

---

## ๐Ÿ› Common Issues & Troubleshooting

### 1. **Inventory Inconsistencies**
**Issue**: Store quantities become negative after deletion  
**Cause**: Insufficient validation of available quantities

**Debug**:
php

// Check inventory before deletion

$currentQuantity = getCurrentStoreQuantity($storeId, $productId, $sizeId, $colorId);

if ($currentQuantity < $finalquantity) {

error_log("Insufficient inventory for deletion: Need $finalquantity, Have $currentQuantity");

}

### 2. **Currency Conversion Errors**  
**Issue**: Incorrect debt calculations in multi-currency scenarios  
**Cause**: Missing or invalid conversion factors

**Debug**:
php

error_log("Currency conversion - Factor: $cFactor, Amount: $amount, Converted: " . ($amount * $cFactor));

### 3. **Serial Number Conflicts**
**Issue**: Serial numbers not properly released  
**Cause**: Serial number update logic errors

**Debug**:
php

$serialData = $ProductserialEX->queryallisdSerial($productId, $parcode, " and sizeid=$sizeId and colorid=$colorId ");

error_log("Serial data: " . print_r($serialData, true));

---

## ๐Ÿงช Testing Scenarios

### Test Case 1: Standard Bill Deletion

1. Create purchase bill with multiple items

2. Delete bill using deletebill()

3. Verify inventory quantities decreased

4. Check supplier debt decreased

5. Confirm cash register balance adjusted

6. Validate all audit trail entries

### Test Case 2: Multi-Currency Bill Deletion

1. Create bill in foreign currency

2. Delete bill

3. Verify currency conversions accurate

4. Check both currency amounts updated

5. Confirm exchange rate handling

### Test Case 3: Size/Color Variant Handling

1. Create bill with size/color variants

2. Delete bill

3. Verify correct variant quantities updated

4. Check size/color store detail records

5. Confirm variant-specific reporting

```

---

๐Ÿ“š Related Documentation

---

Documented By: AI Assistant

Review Status: โœ… Complete

Next Review: When inventory management changes occur

โ†‘