Resturant Documentation
Restaurant (Bills) Controller Documentation
File: /controllers/resturant.php
Purpose: Comprehensive restaurant/retail billing system with POS functionality, workshop orders, and advanced payment processing
Last Updated: December 21, 2024
Total Functions: 13
Lines of Code: ~1988
---
๐ Overview
The Restaurant Controller (also known as Bills Controller) is a sophisticated point-of-sale and billing management system designed for restaurants, retail stores, or service businesses. It provides comprehensive billing functionality with advanced features including insurance billing, workshop order management, multi-payment methods, and integrated accounting. The controller handles:
- โข Complete POS billing system with product selection and pricing
- โข Insurance company integration for medical/service billing
- โข Workshop order management and tracking
- โข Multi-payment method support (cash, credit, insurance)
- โข Product request fulfillment and management
- โข Advanced bill printing with multiple templates
- โข Client and customer management integration
- โข Inventory integration with automatic stock updates
- โข Daily entry (accounting) integration for financial tracking
- โข Branch-based operations and user permissions
- โข Excel export functionality for reporting
- โข Category-based product filtering and selection
Primary Functions
- โ Complete POS billing system
- โ Insurance billing and claim processing
- โ Workshop order creation and management
- โ Multi-payment method processing
- โ Product request fulfillment
- โ Advanced bill printing (normal/insurance)
- โ Client management integration
- โ Inventory stock management
- โ Accounting entry automation
- โ Excel export and reporting
- โ Category-based product organization
- โ User permission and access control
Related Controllers
- โข billsController.php - Alternative billing interface
- โข clientController.php - Customer management
- โข productController.php - Product management
- โข workshopController.php - Workshop operations
- โข storedetailController.php - Inventory management
- โข dailyentryController.php - Accounting integration
---
๐๏ธ Database Tables
Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **bills** | Main bill records | billid, billno, clientid, userid, billdate, totalamount, insurancecompanyid | |
| **billsproducts** | Bill line items | billsproductid, billid, productid, quantity, productprice, totalproductprice | |
| **billsbuy** | Purchase bills | billsbuyid, billno, supplierid, userid, billdate, totalamount | |
| **billsproductsbuy** | Purchase line items | billsproductsbuyid, billsbuyid, productid, quantity, productprice |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **toworkshoporder** | Workshop orders | toworkshoporderid, clientid, workshopid, orderdate, orderstatus | |
| **toworkshoporderbill** | Workshop billing | toworkshoporderbillid, toworkshoporderid, billid | |
| **workshop** | Workshop details | workshopid, workshopname, workshoptype |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **product** | Product master | productId, productName, productCatId, productSellPrice | |
| **productcat** | Product categories | productCatId, productCatName, productCatParent | |
| **productrequest** | Product requests | productrequestid, productid, quantity, status, requestdate | |
| **storedetail** | Inventory levels | storedetailid, productid, storeid, productquantity |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **client** | Customer records | clientid, clientname, clientphone, clientaddress | |
| **insurancecompanie** | Insurance providers | insurancecompanyid, companyname, companytype | |
| **paymentnetwork** | Payment methods | paymentnetworkid, networkname, networktype |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **branch** | Organization branches | branchId, branchName | |
| **store** | Store locations | storeId, storeName | |
| **user** | System users | userid, employeename, usergroupid | |
| **usergroup** | User permissions | usergroupid, groupname, permissions |
๐ Key Functions
1. Default Action - Bill Creation Interface
Location: Line 267
Purpose: Display the main billing interface with product selection and payment options
Process Flow:
1. Generate unique bill number based on branch and year
2. Load client data for customer selection
3. Load insurance companies for insurance billing
4. Load payment networks for payment processing
5. Handle product requests if specified
6. Check user permissions for direct save functionality
7. Display appropriate billing template (normal or category-based)
Bill Number Generation:
$branchId = $_SESSION['branchId'];
$today = date('y');
$billNo = $branchId . $today;
$bills = $billsEX->searchInBillNo($billNo);
if (count($bills) > 0) {
$billNo = $bills->billno + 1;
if ($branchId == 0) {
$billNo = '0' . $billNo;
}
} else {
$billNo .= '00001';
}
Product Request Handling:
if ($isProductRequest == 1) {
$choosedItemArr = $_POST['choosedItem'];
foreach ($choosedItemArr as $productRequestId) {
$productRequest = $productRequestDAO->load($productRequestId);
array_push($productRequestArray, $productRequest);
$product = $productDAO->load($productRequest->productid);
$productRequest->productName = $product->productName;
$parentId = $product->productCatId;
$pathArr = getProductPath_recursive($parentId, $categories, 0);
$productRequest->productName = $product->productName . '/' . $pathArr;
}
}
---
2. add() - Bill Processing and Creation
Location: Line 441
Purpose: Process new bill creation with inventory updates and accounting integration
Process Flow:
1. Process bill data from form submission
2. Validate product availability and pricing
3. Create bill record in database
4. Create bill product line items
5. Update inventory quantities
6. Create accounting entries
7. Handle different bill types (normal, insurance, category-based)
8. Return success/failure status with bill ID
Error Handling:
if ($detailResult['flag'] == 99) {
$note = "ุฑูู
ุงููุงุชูุฑุฉ ู
ูุฌูุฏ ู
ู ูุจู";
$smarty->assign('errorNote', $note);
$smarty->display("error.html");
} else {
finishProductRequests();
if ($flag == 1) {
// Insufficient inventory
$note = "ูุง ููุฌุฏ ูู
ูุฉ ุจุงูู
ุฎุฒู ูุงููุฉ ูููุงุชูุฑุฉ";
$smarty->assign('msgnote', $note);
$smarty->display("notes2.html");
} else {
// Success - redirect based on bill type
switch ($payType) {
case "normal_bill":
header("location:?do=empty");
break;
case "cate_bill":
header("location:?do=addview2");
break;
// Additional cases...
}
}
}
---
3. print / printbuy - Bill Printing
Location: Lines 376, 408
Purpose: Generate printable bill formats for different scenarios
Print Types Supported:
- โข Normal Print (type = 0): Standard bill format
- โข Insurance Print (type = 1): Insurance company format
- โข Both Print (type = 2): Both normal and insurance formats
Process Flow:
1. Get bill ID and print type from request
2. Load bill details via getBillDetails() or getBillDetailsBuy()
3. Determine lens display option
4. Display appropriate template(s) based on print type
Template Selection:
if ($type == 2) { // Both formats
$smarty->display("billsview/print.html");
$smarty->display("billsview/printins.html");
} elseif ($type == 1) { // Insurance only
$smarty->display("billsview/printins.html");
} else { // Normal only
$smarty->display("billsview/print.html");
}
---
4. saveDailyEntryDelete() - Accounting Entry Deletion
Location: Line 1337
Purpose: Remove daily accounting entries when bills are deleted
Function Signature:
function saveDailyEntryDelete($billId)
Process Flow:
1. Load bill details for accounting reversal
2. Create reversal entries for:
- Client accounts (credit reversal)
- Cash/payment accounts (debit reversal)
- Sales revenue accounts (debit reversal)
3. Handle insurance billing reversals if applicable
4. Update account balances
---
5. saveDailyEntryDeleteBuy() - Purchase Entry Deletion
Location: Line 1458
Purpose: Remove accounting entries for deleted purchase bills
Similar to saveDailyEntryDelete() but handles purchase-side accounting
---
6. toworkshop() - Workshop Order Creation
Location: Line 1581
Purpose: Create workshop orders from bills for service processing
Function Signature:
function toworkshop()
Process Flow:
1. Get bill and workshop details from request
2. Validate workshop availability and capacity
3. Create workshop order record
4. Link bill to workshop order
5. Update workshop status and scheduling
6. Generate workshop tracking number
---
7. isUnique() - Uniqueness Validation
Location: Line 1651
Purpose: Validate bill number uniqueness
Function Signature:
function isUnique($unique)
Returns: Boolean indicating if bill number is available
---
8. tobranch() - Branch Transfer
Location: Line 1661
Purpose: Transfer bills or orders between branches
Process Flow:
1. Validate source and target branches
2. Update bill branch assignments
3. Handle inventory transfers if needed
4. Update user permissions and access
5. Create audit trail for transfer
---
9. encrypt_url() / decrypt_url() - URL Security
Location: Lines 1702, 1718
Purpose: Encrypt/decrypt sensitive data in URLs
Function Signatures:
function encrypt_url($string)
function decrypt_url($string)
Usage: Secure transmission of bill IDs and sensitive parameters in URLs
---
10. dateTimeDiff() - Date Calculation
Location: Line 1731
Purpose: Calculate time differences for bill processing
Function Signature:
function dateTimeDiff($dateTime1, $dateTime2)
Returns: Time difference for billing calculations and reporting
---
11. finishProductRequests() - Request Completion
Location: Line 1743
Purpose: Mark product requests as fulfilled after bill creation
Process Flow:
1. Get product request IDs from bill session
2. Update request status to completed
3. Link requests to created bill
4. Update inventory allocation
5. Notify requesting users/departments
---
12. getCategoryChilds() - Category Hierarchy
Location: Line 1758
Purpose: Build product category tree for filtering
Function Signature:
function getCategoryChilds($parentid = 0)
Process Flow:
1. Start with root categories (parentid = 0)
2. Recursively load child categories
3. Build hierarchical structure for display
4. Return formatted category tree
---
13. style() / styleBy() - Reporting Functions
Location: Lines 1772, 1869
Purpose: Generate various bill reports and statistics
Process Flow:
1. Parse date ranges and filters
2. Query bill data with aggregations
3. Calculate totals and statistics
4. Format data for display
5. Support multiple report formats (HTML, Excel)
---
๐ Workflows
Workflow 1: Bill Creation Process
Workflow 2: Workshop Order Creation
---
๐ URL Routes & Actions
| URL Parameter | Function Called | Description | |
|---|---|---|---|
| `do=` (empty) | Default action | Display main billing interface | |
| `do=empty` | Default action | Alternative billing interface | |
| `do=addview2` | Category billing | Category-based billing interface | |
| `do=add` | `add()` | Process new bill creation | |
| `do=print` | Print interface | Display bill for printing | |
| `do=printbuy` | Print interface | Display purchase bill for printing | |
| `do=toworkshop` | `toworkshop()` | Create workshop order | |
| `do=tobranch` | `tobranch()` | Transfer to branch | |
| `do=style` | `style()` | Generate reports | |
| `do=styleby` | `styleBy()` | Generate filtered reports |
Bill Creation (do=add):
- โข Bill details and product selections via comprehensive POST data
- โข Client information and payment methods
- โข Insurance details if applicable
Bill Printing (do=print, do=printbuy):
- โข
id- Bill ID to print (via GET) - โข
type- Print type (0=normal, 1=insurance, 2=both, via GET) - โข
go- Return URL after printing (via GET) - โข
lens- Lens display option (via GET)
Workshop Order (do=toworkshop):
- โข Bill ID and workshop selection
- โข Order requirements and scheduling
- โข Workshop-specific parameters
Reporting (do=style, do=styleby):
- โข Date ranges and filter criteria
- โข Report type and format specifications
- โข User and branch filters
---
๐งฎ Calculation Methods
Bill Totals and Pricing
// Product line total
$lineTotal = $quantity * $unitPrice;
// Apply discount
if ($discountType == 'percentage') {
$discountAmount = $lineTotal * ($discountPercent / 100);
} else {
$discountAmount = $discountValue;
}
$lineTotal -= $discountAmount;
// Calculate tax
$taxAmount = $lineTotal * ($taxRate / 100);
$lineTotalWithTax = $lineTotal + $taxAmount;
Insurance Billing Calculations
// Insurance coverage calculation
$insuranceCoverage = $billTotal * ($coveragePercent / 100);
$clientPortion = $billTotal - $insuranceCoverage;
$insuranceClaimAmount = $insuranceCoverage;
Inventory Updates
// Decrease inventory for sales
$currentQuantity = $storeDetail->productquantity;
$newQuantity = $currentQuantity - $soldQuantity;
$storeDetail->productquantity = $newQuantity;
---
๐ Security & Permissions
Authentication
include_once("../public/authentication.php");
- โข Required for all bill operations
- โข Session-based user validation
User Permissions
- โข Branch-based access control
- โข Direct save permissions per user group
- โข Percentage discount limits per user group
- โข Store access restrictions
Data Security
- โข URL encryption for sensitive parameters
- โข Bill number uniqueness validation
- โข Input sanitization via filter_input()
- โข Session-based security for user data
---
๐ Performance Considerations
Database Optimization Tips
1. Critical Indexes Required:
- bills(billno, billdate, clientid) - For bill queries
- billsproducts(billid, productid) - For line item queries
- storedetail(productid, storeid) - For inventory updates
- client(clientid) - For customer lookups
2. Query Optimization:
- Use transactions for bill creation
- Batch inventory updates
- Optimize category hierarchy queries
3. Memory Management:
- Large product catalogs can impact performance
- Consider pagination for product selection
- Optimize image loading for product displays
---
๐ Common Issues & Troubleshooting
1. Bill Number Duplication
Issue: Duplicate bill numbers generated
Cause: Concurrency issues in number generation
Solution: Add database constraints and better locking
2. Inventory Sync Issues
Issue: Inventory quantities not updating correctly
Cause: Transaction failures or rollback issues
Debug: Check transaction handling and error logging
3. Insurance Billing Errors
Issue: Insurance claims not processing
Cause: Missing insurance company setup or configuration
Solution: Verify insurance company data and billing rules
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข clientController.php - Customer management
- โข productController.php - Product management
- โข workshopController.php - Workshop operations
- โข dailyentryController.php - Accounting integration
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When major changes occur