๐Ÿ“š ERP Documentation Viewer

Beautiful, colorful documentation for your ERP system

Buy Bill Controller Documentation

File: /controllers/buyBillController.php

Purpose: Manages purchase orders, buy bills, purchase returns, and supplier transactions

Last Updated: December 19, 2024

Total Functions: 57

Lines of Code: ~7000+

---

๐Ÿ“‹ Overview

The Buy Bill Controller is the core component for managing all purchase-related operations in the ERP system. It handles:

Primary Functions

Related Controllers

---

๐Ÿ—„๏ธ Database Tables

Primary Tables (Direct Operations)

Table NamePurposeKey Columns
**buybill**Main purchase billsbuybillid, buybillserial, buybilldate, buybilltotalbill, buybillsupplierid, buybillstoreid, buybillsaveid
**buybilldetail**Purchase bill line itemsbuybilldetailid, buybillid, buybilldetailproductid, buybilldetailquantity, buybilldetailprice
**returnbuybill**Purchase return billsreturnbuybillid, returnbuybillserial, returnbuybilltotalbill
**returnbuybilldetail**Return bill line itemsreturnbuybilldetailid, returnbuybillid, returnbuybilldetailproductid
**buyandruternbill**Combined buy & returnbuybillid (combined operations)
**buyandruternbilldetail**Combined detailsDetails for mixed operations
**buybilloffer**Purchase quotations/offersSame structure as buybill, conditions=1
**buybilldetailoffer**Offer line itemsDetails for offers
### Inventory Tables

Table NamePurposeRelationship
**storedetail**Stock quantities by storeUpdated on buy/return
**sizecolorstoredetail**Stock by size/colorFor variant products
**storereport**Stock movement historyAudit trail
**buypriceshistorybook**Purchase price historyPrice tracking
**productserial**Serial number trackingFor serialized items
### Financial Tables

Table NamePurposeRelationship
**supplier**Supplier master databuybill.buybillsupplierid
**save**Cash registers/safesbuybill.buybillsaveid
**savedaily**Daily cash movementsFinancial reconciliation
**dailyentry**Accounting journal entriesAuto-generated from bills
**buybillcurr**Multi-currency supportCurrency conversion
### Reference Tables

Table NamePurposeRelationship
**product**Product master dataForeign key in details
**productcat**Product categoriesproduct.productCatId
**productunit**Units of measurementbuybilldetail.productunitid
**store**Warehouses/storesbuybill.buybillstoreid
**billname**Bill templates/typesbuybill.billnameid
**billsettings**Bill configurationPer bill type settings
**currency**Currency definitionsFor multi-currency
**costcenter**Cost centersFor cost allocation
---

๐Ÿ”ง Key Functions

1. add()

Purpose: Create a new purchase bill (main entry point)

Called By: Form submission with ?do=add

Line: 3952

Parameters (via $_POST):

Returns: Array [billType, returnBuyBill_Id, buyBill_Id, buyAndReturnBill_Id, ordertype, billnameId]

Database Operations:

1. BEGIN TRANSACTION

2. INSERT into buybill - Main bill record

3. INSERT into buybilldetail - For each product line

4. UPDATE storedetail SET productquantity = productquantity + quantity - Increase stock

5. INSERT into storereport - Stock movement record

6. INSERT into buypriceshistorybook - Price history

7. UPDATE supplier SET supplierdebt = supplierdebt + totalBill - Update supplier debt

8. INSERT into savedaily - Cash movement (if payment made)

9. INSERT into dailyentry - Accounting journal entry

10. COMMIT TRANSACTION

Business Logic Flow:

1. Validate form data
2. Determine bill type (Buy, Return, or Both)
3. Create bill header record
4. Loop through products:
   a. Insert detail record
   b. Update stock quantity (call increaseProductQuantity)
   c. Record price history
   d. Handle serial numbers if applicable
5. Update supplier debt
6. Record cash payment
7. Create accounting entries (call doBillDailyEntry)
8. Commit or rollback on error
9. Redirect to success page with bill ID

Example Flow:

โ”‚ โ””โ”€โ”€ ...
โ””โ”€โ”€ REDIRECT: ?do=editprint&id=123

---

2. increaseProductQuantity()

Purpose: Increase stock quantity when purchasing products

Line: 6144

CRITICAL: This function was fixed for PHP 8.2 compatibility

Parameters:

Returns: $productquantityAfter (float) - New quantity

Database Operations:

Logic:

if (has size/color) {
    UPDATE sizecolorstoredetail.quantity
    UPDATE storedetail (sum all size/color quantities)
} else {
    UPDATE storedetail.productquantity directly
}

PHP 8.2 Fix Applied:

---

3. doBillDailyEntry()

Purpose: Create accounting journal entries for purchase bills

Line: 6948

Parameters:

Returns: void

Database Operations:

Accounting Entries Created:

For Buy Bill (Type 2):

Debit:  Inventory (Store Account)        XXX
Debit:  VAT Receivable                   XXX
Credit: Supplier Payable                      XXX
Credit: Withholding Tax                       XXX

For Return Bill (Type 1):

Debit:  Supplier Payable                 XXX
Credit: Inventory (Store Account)             XXX
Credit: VAT Receivable                        XXX

---

4. insertStoredetail()

Purpose: Create new stock record or update existing

Line: 6295

CRITICAL: Fixed for PHP 8.2 - now properly handles non-size/color products

Parameters:

Logic:

if (size/color product) {
    // Update sizecolorstoredetail
    // Update main storedetail with SUM
} else {
    if (storedetail exists) {
        // PHP 8.2 FIX: Use updateQuantityPlusEqualORMinusEqual
        // NOT updateQuantityWithSumChild (which returns 0)
    } else {
        // Insert new storedetail record
    }
}

---

5. delete()

Purpose: Soft delete purchase bill (sets conditions=1)

Line: 5537

Parameters (via $_GET):

Database Operations:

---

6. showAll()

Purpose: Display list of all purchase bills

Line: 5347

Returns: Assigns to Smarty template

Database Operations:

---

7. showBillDetails()

Purpose: Load bill header and details for viewing/editing

Line: 5298

Parameters:

Returns: Array [billData, billDetails, currencyData]

Database Operations:

---

๐Ÿ“Š Main Workflows

Workflow 1: Create Purchase Bill

User visits: ?do=bill&billnameid=X
   โ†“
Display Form (bill.html)
   โ†“
User fills:
   - Supplier
   - Store
   - Products (barcode scan or select)
   - Quantities
   - Prices
   โ†“
Submit POST ?do=add
   โ†“
add() Function:
   โ”œโ”€โ”€ Validate data
   โ”œโ”€โ”€ BEGIN TRANSACTION
   โ”œโ”€โ”€ INSERT buybill
   โ”œโ”€โ”€ INSERT buybilldetail (foreach product)
   โ”œโ”€โ”€ increaseProductQuantity() (foreach product)
   โ”œโ”€โ”€ UPDATE supplier debt
   โ”œโ”€โ”€ INSERT savedaily (if payment)
   โ”œโ”€โ”€ doBillDailyEntry() (accounting)
   โ”œโ”€โ”€ COMMIT
   โ””โ”€โ”€ Redirect to success page
   โ†“
Display: notes2.html ("Success")
   โ†“
Auto-redirect (1 sec): ?do=bill (new bill)

Files Involved:

---

Workflow 2: Edit Existing Bill

?do=editbill&id=123
   โ†“
Load bill data: showBillDetails(123)
   โ†“
Display form pre-filled
   โ†“
Submit POST ?do=update
   โ†“
update() Function:
   โ”œโ”€โ”€ Load old bill data
   โ”œโ”€โ”€ Reverse old stock changes
   โ”œโ”€โ”€ Reverse old accounting entries
   โ”œโ”€โ”€ Apply new changes (like add())
   โ””โ”€โ”€ Redirect

---

Workflow 3: Purchase Return

User scans "return" products
   โ†“
Submit with negative quantities
   โ†“
add() detects returns
   โ†“
Creates returnbuybill record
   โ†“
decreaseProductQuantity() (opposite of buy)
   โ†“
Reverse accounting entries

---

๐ŸŽฏ URL Routes & Actions

Action (`?do=`)MethodDescriptionView TemplateLine
**bill**GETDisplay new bill formbill.html492
**editbill**GETEdit existing bill formedit.html756
**add**POSTCreate new bill-1245
**update**POSTUpdate existing bill-1308
**details**GETView bill details (read-only)details.html1412
**editprint**GETView/print billeditprint.html1485
**delete**POSTSoft delete bill-1846
**show**GETList all billsshow.html1744
**showoffers**GETList quotations/offersshowoffers.html2209
**excelToBill**GET/POSTImport from ExcelexcelToBill.html1877
**sucess**GETSuccess messagenotes2.html1869
---

โš ๏ธ Known Issues & Fixes

Issue 1: Stock Quantity Set to 0 on Second Buy (FIXED)

Problem: When buying a product for the second time, stock quantity becomes 0 instead of increasing

Cause: updateQuantityWithSumChild() was called for all products, which does SUM(quantity) FROM sizecolorstoredetail. For products without size/color, this table is empty, so SUM returns NULL โ†’ 0

Fix: In insertStoredetail() line 6330-6340, added conditional:

if (has size/color) {
    $storeDetailExt->updateQuantityWithSumChild(...);
} else {
    $storeDetailExt->updateQuantityPlusEqualORMinusEqual(...);
}

Date Fixed: December 19, 2024

File: buyBillController.php lines 6330-6340

---

Issue 2: Property Assignment on Null (FIXED)

Problem: Fatal error: Attempt to assign property "entryComment" on null

Cause: PHP 8.2 doesn't allow assigning properties to uninitialized objects

Fix: Added $dailyEntry = new stdClass(); before property assignments

Line: 6993

Date Fixed: December 19, 2024

---

Issue 3: abs() TypeError (FIXED)

Problem: TypeError: abs(): Argument #1 must be of type int|float, string given

Cause: Empty string $billAdditionVal = '' passed to abs()

Fix: Cast to float before abs(): abs((float)$billAdditionVal)

Line: 7001

Date Fixed: December 19, 2024

---

๐Ÿ” Permissions & Security

Required Permissions

Security Checks

// Line 1246
include_once("../public/authentication.php");

// Store restrictions
if ($userdata->viewbills == 0) {
    // Show only user's own bills
} elseif ($userdata->viewbills == 2) {
    // Show group's bills
}

Input Validation

---

๐Ÿ“ Notes

Important Considerations

1. Transactions: All bill operations use database transactions for data integrity

2. Stock Updates: Stock is updated immediately upon bill creation

3. Accounting: Daily entries are auto-generated and linked to bills

4. Multi-Currency: System supports multiple currencies with conversion factors

5. Serial Numbers: Products can have serial number tracking

6. Cost Centers: Bills can be allocated to cost centers

7. Taxes: Multiple tax types supported (VAT, withholding tax)

8. Bill Templates: Different bill types via billname table

Performance Optimizations

Data Integrity

---

๐Ÿ”ง Configuration & Settings

Bill Settings (via billsettings table)

Program Settings (via programsettings table)

---

๐Ÿ“š Related Documentation

---

๐Ÿ” Debugging Tips

Enable Debug Mode

// In buyBillController.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

Check Stock Updates

SELECT * FROM storereport 
WHERE storereportproductid = [PRODUCT_ID] 
ORDER BY storereportdate DESC 
LIMIT 10;

Verify Accounting Entries

SELECT * FROM dailyentry 
WHERE dailyentrymodelid = [BILL_ID] 
AND tablename = 'buybill';

Test Transaction Rollback

---

Documented By: AI Assistant

Review Status: โœ… Complete

Next Review: When major changes occur

โ†‘