# 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
- [x] Sales bill CRUD operations
- [x] Purchase bill management
- [x] Workshop transportation orders
- [x] Bill printing and export
- [x] Insurance claim processing  
- [x] Payment network integration
- [x] Product request fulfillment
- [x] Branch delivery management
- [x] Accounting entry generation
- [x] Multi-store inventory management

### Related Controllers
- [sellbillController.php](sellbillController.md) - Detailed sales operations
- [buyBillController.php](buyBillController.md) - Purchase operations
- [clientController.php](clientController.md) - Customer management
- [productController.php](productController.md) - 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 |

### Workshop Management Tables
| 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 |

### Client & Supplier Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **client** | Customer master | clientid, clientname, clientdebt |
| **supplier** | Supplier master | supplierid, suppliername |
| **clientarea** | Customer areas/regions | id, name |

### Payment & Insurance Tables
| 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 |

### Product & Inventory Tables  
| 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 |

### System Tables
| 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**:
```php
// 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**:
```php
$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**:
```php
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**:
```php
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**:
```php
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**:
```php
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**:
```php
$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**:
```php
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**:
```php
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**:
```php
// 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
```
┌─────────────────────────────────────────────────────────────┐
│              START: Create Sales Bill                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Initialize Bill Form                                    │
│     - Generate bill number                                  │
│     - Load customer dropdown                                │
│     - Load store and product data                           │
│     - Set user permissions                                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. User Fills Bill Details                                 │
│     - Select customer                                       │
│     - Add products and quantities                           │
│     - Set payment terms                                     │
│     - Configure insurance if applicable                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Validate and Process Bill                               │
│     - Check product availability                            │
│     - Validate bill number uniqueness                       │
│     - Calculate totals and taxes                            │
│     - Process payment allocations                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Update Inventory and Accounts                           │
│     - Decrease product quantities                           │
│     - Update customer debt                                  │
│     - Generate daily accounting entries                     │
│     - Process insurance claims                              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Complete and Output                                     │
│     - Save bill to database                                 │
│     - Mark product requests as fulfilled                    │
│     - Generate print output or redirect                     │
│     - Send for workshop processing if needed                │
└─────────────────────────────────────────────────────────────┘
```

### Workflow 2: Workshop Transportation
```
┌─────────────────────────────────────────────────────────────┐
│              START: Workshop Transportation                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Prepare Bills for Workshop                              │
│     - Select bills with status "new"                        │
│     - Group by product categories                           │
│     - Choose driver and workshop                            │
│     - Set delivery timeouts                                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Create Delivery Order                                   │
│     - Generate unique order number                          │
│     - Link selected bills to order                          │
│     - Update bill status to "at workshop"                   │
│     - Set delivery dates and timeouts                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Track Workshop Processing                               │
│     - Monitor delivery timeouts                             │
│     - Track workshop completion                             │
│     - Handle delays and exceptions                          │
│     - Prepare for return delivery                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Manage Return Process                                   │
│     - Assign return driver                                  │
│     - Update bill status to "returned"                      │
│     - Track return delivery times                           │
│     - Complete order fulfillment                            │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 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
```php
$branchId = $_SESSION['branchId'];
$today = date('y');
$billNo = $branchId . $today . '00001'; // Format: [Branch][Year][Sequence]
```

### Payment Processing
```php
// 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
```php
$hours = dateTimeDiff($order->recieveBranchDate, $order->deliverBranchDate);
if ($hours > $order->drivertimeoutback) {
    $order->driverdelayback = $hours;
}
```

---

## 🔒 Security & Permissions

### User Group Permissions
```php
$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**:
```sql
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](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [sellbillController.md](sellbillController.md) - Detailed sales operations  
- [buyBillController.md](buyBillController.md) - Purchase operations
- [Database Schema Documentation](#) - Table relationships

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When major changes occur