Bills Controller Documentation
File: /controllers/bills.php
Purpose: Comprehensive billing system for sales and purchase operations with workshop management
Last Updated: December 20, 2024
Total Functions: 25+
Lines of Code: ~1,979
---
๐ Overview
The Bills Controller is the main billing system hub that handles both sales (bills) and purchase (buy bills) operations. It provides:
- โข Sales bill creation, editing, and management
- โข Purchase bill operations
- โข Workshop order management and tracking
- โข Bill printing and Excel export capabilities
- โข Insurance and payment network integration
- โข Product request processing
- โข Branch-based bill transportation
- โข Complete bill lifecycle management
- โข Daily entry accounting integration
- โข Multi-format bill output (print, Excel)
Primary Functions
- โ Sales bill CRUD operations
- โ Purchase bill management
- โ Workshop transportation orders
- โ Bill printing and export
- โ Insurance claim processing
- โ Payment network integration
- โ Product request fulfillment
- โ Branch delivery management
- โ Accounting entry generation
- โ Multi-store inventory management
Related Controllers
- โข sellbillController.php - Detailed sales operations
- โข buyBillController.php - Purchase operations
- โข clientController.php - Customer management
- โข productController.php - Product management
- โข workshoptransport.php - Workshop order details
---
๐๏ธ Database Tables
Primary Bill Tables
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **bills** | Sales bills master | id, billno, clientid, finalnetbillvalue, billdate, insurance, approved | |
| **billsproduct** | Sales bill line items | id, billid, productid, productno, productprice | |
| **billsbuy** | Purchase bills master | id, billno, clientid, finalnetbillvalue, billdate | |
| **billsproductsbuy** | Purchase bill line items | id, billid, productid, productno, productprice |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **toworkshoporder** | Workshop delivery orders | id, orderNo, driverId, workshopId, orderStatus, deliverWorkshopDate | |
| **toworkshoporderbill** | Bills in workshop orders | id, billid, toworkshoporderid | |
| **workshop** | Workshop definitions | id, workshopname |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **client** | Customer master | clientid, clientname, clientdebt | |
| **supplier** | Supplier master | supplierid, suppliername | |
| **clientarea** | Customer areas/regions | id, name |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **insurancecompanie** | Insurance companies | id, name | |
| **paymentnetwork** | Payment networks | id, networkname | |
| **bankaccount** | Bank accounts | id, accountname, bankid | |
| **save** | Cash registers | saveid, savename |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **product** | Product master | productId, productName, productCatId | |
| **storedetail** | Inventory quantities | storedetailid, storeid, productid, productquantity | |
| **productrequest** | Product requests | id, productid, quantity, status |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **branch** | System branches | branchId, branchName | |
| **user** | System users | userid, username, employeename | |
| **usergroup** | User groups | usergroupid, directSaveBills, percentageDiscount | |
| **programsettings** | System settings | programsettingsid, settingkey, settingvalue |
๐ Key Functions
1. Default Action / addview2 - Bill Creation Form
Location: Line 267
Purpose: Display bill creation form with initialization
Function Signature:
// Triggered when: do=empty, do=addview2
if (!isset($_GET['do']) || $_GET['do'] == "empty" || $_GET['do'] == "addview2")
Process Flow:
1. Generate bill number based on branch and year
2. Load dropdown data (clients, stores, insurance, etc.)
3. Handle product requests if coming from request system
4. Set direct save permissions based on user group
5. Display appropriate template (add.html or add2.html)
Bill Number Generation:
$branchId = $_SESSION['branchId'];
$today = date('y');
$billNo = $branchId . $today;
$bills = $billsEX->searchInBillNo($billNo);
if (count($bills) > 0) {
$billNo = $bills->billno + 1;
} else {
$billNo .= '00001';
}
---
2. add() - Sales Bill Creation
Location: Line 441
Purpose: Process sales bill creation with validation
Function Signature:
elseif ($_GET['do'] == "add")
Process Flow:
1. Call add(0) function from included billsfunctions.php
2. Process result for inventory warnings
3. Handle product request completion
4. Generate appropriate redirect based on success/failure
5. Update kashf (medical examination) usage if applicable
Error Handling:
if ($detailResult['flag'] == 99) {
$note = "ุฑูู
ุงููุงุชูุฑุฉ ู
ูุฌูุฏ ู
ู ูุจู";
$smarty->assign('errorNote', $note);
$smarty->display("error.html");
}
---
3. edit() - Bill Editing Interface
Location: Line 556
Purpose: Load bill for editing with all related data
Function Signature:
elseif ($_GET['do'] == "edit")
Process Flow:
1. Get bill ID from request
2. Load complete bill details via getBillDetails()
3. Load all dropdown data (products, clients, stores)
4. Display edit template with populated data
---
4. print / printbuy - Bill Printing
Location: Line 376 / 408
Purpose: Generate printable bill format
Print Types:
- โข
type=0: Normal print - โข
type=1: Insurance print only - โข
type=2: Both formats
Process Flow:
1. Load complete bill details
2. Determine print format based on type parameter
3. Display appropriate print template
4. Handle lens-specific formatting if requested
---
5. show() - Bills Listing
Location: Line 705
Purpose: Display bills with filtering and summary information
Function Signature:
elseif ($do == "show")
Process Flow:
1. Load user group permissions
2. Generate bill number lists for filtering tabs:
- All bills
- Pending insurance bills
- Approved insurance bills
- Rejected insurance bills
3. Query today's bills with totals
4. Calculate daily balance summary
5. Display tabbed interface
Daily Summary Calculation:
$totalBalance = 0;
foreach ($bills as $bill) {
if ($bill->deleted == 0) {
$totalBalance = $totalBalance + $bill->finalnetbillvalue;
}
}
---
6. billtransport - Workshop Transportation
Location: Line 757
Purpose: Manage bill transportation to workshops and branches
Process Flow:
1. Load new bills ready for transport
2. Load drivers, workshops, and branches data
3. Process bill product details and categories
4. Handle delivery orders with filtering options
5. Track order status and delays
6. Manage returned bills from workshops
Bill Status Updates:
- โข Status 0: New (ready for transport)
- โข Status 1: At workshop
- โข Status 2: Returned from workshop
- โข Status 3: Delivered to branch
- โข Status 4: Completed
---
7. toworkshop() - Send to Workshop
Location: Line 1572
Purpose: Create workshop delivery order
Function Signature:
function toworkshop()
Process Flow:
1. Generate unique order number
2. Create workshop order record
3. Link bills to order
4. Update bill status to "at workshop"
5. Track driver and delivery timeouts
6. Return order ID for printing
Order Number Generation:
do {
$unique = uniqid("0");
} while (isUnique($unique));
---
8. addBuy / updateBuy - Purchase Bill Operations
Location: Line 1125 / 1286
Purpose: Handle purchase bill creation and updates
Process Flow:
1. Generate buy bill number
2. Load supplier and bank data
3. Process purchase bill details
4. Handle inventory updates
5. Generate accounting entries
6. Manage product requests
---
9. saveDailyEntryDelete() - Accounting Integration
Location: Line 1337
Purpose: Generate reversal accounting entries for deleted bills
Accounting Structure:
// For sales bill deletion:
// Credit: Customer account (waitvalue)
// Credit: Insurance company (if applicable)
// Credit: Cash register (if cash/card)
// Debit: Sales revenue account
---
๐ Workflows
Workflow 1: Sales Bill Creation
Workflow 2: Workshop Transportation
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | |
|---|---|---|---|
| `do=` (empty) | Default form | Bill creation form (normal) | |
| `do=addview2` | Category form | Bill creation form (with categories) | |
| `do=add` | `add()` | Process sales bill creation | |
| `do=edit` | Edit interface | Load bill for editing | |
| `do=update` | `update()` | Process bill updates | |
| `do=delete` | Delete process | Mark bill as deleted | |
| `do=print` | Print interface | Generate bill printout | |
| `do=show` | Bills listing | Display bills with filters | |
| `do=billtransport` | Workshop transport | Manage workshop deliveries | |
| `do=toworkshop` | `toworkshop()` | Create workshop order | |
| `do=buybill` | Purchase form | Purchase bill creation | |
| `do=addbuybill` | `addBuy()` | Process purchase bill | |
| `do=showbuybill` | Purchase listing | Display purchase bills |
๐งฎ Calculation Methods
Bill Number Generation
$branchId = $_SESSION['branchId'];
$today = date('y');
$billNo = $branchId . $today . '00001'; // Format: [Branch][Year][Sequence]
Payment Processing
// Cash and card payments to save account
if ($bills->cash == 1 || $bills->card == 1) {
$saveValue = $bills->cashvalue + $cardRest;
}
// Insurance processing with discount
$insValue = $bills->companycarry;
$insDiscount = $insValue * ($bills->insdiscountpercent) / 100;
$insRest = $insValue - $insDiscount;
Workshop Timeout Calculations
$hours = dateTimeDiff($order->recieveBranchDate, $order->deliverBranchDate);
if ($hours > $order->drivertimeoutback) {
$order->driverdelayback = $hours;
}
---
๐ Security & Permissions
User Group Permissions
$usergroup = $UsergroupDAO->load($_SESSION['usergroupid']);
if ($userdata->directSaveBills == 1 && $usergroup->directSaveBills == 1) {
$directSave = 1; // Allow direct saving without confirmation
}
Bill Access Control
- โข Users can only access bills from their assigned stores
- โข Manager-level users can view all bills
- โข Branch-specific filtering applied automatically
---
๐ Performance Considerations
Database Optimization
1. Indexes Required:
- bills(billdate, deleted)
- billsproduct(billid, productid)
- toworkshoporder(orderStatus, orderNo)
2. Query Optimization:
- Date-based filtering for daily operations
- Status-based queries for workshop management
- Batch operations for multiple bill processing
---
๐ Common Issues & Troubleshooting
1. Duplicate Bill Numbers
Issue: Bill number already exists error
Cause: Race condition in bill number generation
Debug:
SELECT MAX(billno) FROM bills WHERE billno LIKE '[Branch][Year]%';
2. Workshop Order Tracking
Issue: Orders show wrong status
Cause: Status updates not properly synchronized
Fix: Verify status update transactions are atomic
3. Insurance Processing Errors
Issue: Insurance calculations incorrect
Cause: Percentage vs fixed amount confusion
Debug: Check discounttype field values
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข sellbillController.md - Detailed sales operations
- โข buyBillController.md - Purchase operations
- โข Database Schema Documentation - Table relationships
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When major changes occur