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:
- โข Purchase bill deletion and modification operations
- โข Inventory quantity adjustments and tracking
- โข Supplier debt management and changes
- โข Financial transaction logging (cash flow tracking)
- โข Store detail updates and reporting
- โข Multi-currency support for international transactions
- โข Product serial number management
- โข Product service type validation
Primary Functions
- โ Purchase bill deletion with full rollback
- โ Return bill processing and inventory adjustments
- โ Store detail quantity management
- โ Supplier debt tracking and changes
- โ Cash flow management (save daily operations)
- โ Product serial number tracking
- โ Multi-currency transaction support
- โ Store reporting and audit trails
- โ Product service type identification
Related Controllers
- โข buyBillController.php - Main purchase bill operations
- โข returnBuyBillController.php - Purchase return processing
- โข supplierController.php - Supplier management
- โข storeController.php - Inventory management
---
๐๏ธ Database Tables
Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **buybill** | Purchase bills | buybillid, buybillsupplierid, buybillfinalbill, conditions | |
| **buybilldetail** | Purchase bill items | buybilldetailid, buybillid, buybilldetailproductid, buybilldetailquantity | |
| **returnbuybill** | Purchase returns | returnbuybillid, returnbuybillsupplierid, returnbuybillfinalbill | |
| **returnbuybilldetail** | Return bill items | returnbuybilldetailid, returnbuybillid, returnbuybilldetailproductid | |
| **buyandruternbill** | Combined buy/return | buybillid, buybillsupplierid, buybillfinalbill | |
| **buyandruternbilldetail** | Combined bill items | buybilldetailid, buybillid, buybilldetailproductid |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **storedetail** | Product stock levels | storedetailid, storeid, productid, productquantity, sizeid, colorid | |
| **storereport** | Inventory movements | storereportid, productid, storeid, productChangeAmount, storereporttype | |
| **sizecolorstoredetail** | Size/color inventory | sizecolorstoredetailid, productid, storeid, sizeid, colorid | |
| **productserial** | Serial number tracking | productserailid, productid, parcode, don, sizeid, colorid |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **supplier** | Supplier master data | supplierid, suppliername, suppliercurrentDebt, suppliercurrentDebtInCurrency | |
| **supplierdebtchange** | Supplier debt history | supplierdebtchangeid, supplierid, supplierdebtchangeamount, supplierdebtchangetype | |
| **save** | Cash registers/safes | saveid, savename, savevalue | |
| **savedaily** | Daily cash movements | savedailyid, saveid, savedailychangeamount, savedailychangetype | |
| **buybillcurrency** | Multi-currency data | buybillcurrencyid, 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:
- โข Size and color variant support
- โข Multi-unit product handling
- โข Cost calculation with discounts
- โข Currency conversion support
- โข Buy price history tracking
---
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:
- โข Tracks debt in supplier currency
- โข Converts to main system currency
- โข Maintains exchange rate history
- โข Supports currency fluctuation tracking
---
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:
- โข
0- Cash outflow (payments) - โข
1- Cash inflow (receipts) - โข Automatic before/after balance calculation
- โข Integration with bill processing
---
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:
- โข
0- Inventory increase (purchases) - โข
1- Inventory decrease (sales/returns) - โข Complete before/after tracking
- โข Size and color variant support
---
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:
- โข
0- Physical product (requires inventory) - โข
1- Service product (no inventory tracking)
---
๐ Workflows
Workflow 1: Complete Purchase Bill Deletion
---
๐งฎ 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
- โข No Authentication: Functions lack user permission checks
- โข No Input Validation: Parameters not validated
- โข Direct Database Access: No authorization layers
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
- โข CLAUDE.md - PHP 8.2 migration guide
- โข buyBillController.md - Main purchase operations
- โข Database Schema Documentation - Complete table relationships
- โข Inventory Management Guide - Stock control procedures
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When inventory management changes occur