# Kempiala Controller Documentation

**File**: `/controllers/kempialaController.php`  
**Purpose**: Promissory notes (bills of exchange) management and tracking system  
**Last Updated**: December 20, 2024  
**Total Functions**: 20+  
**Lines of Code**: ~1,223

---

## 📋 Overview

The Kempiala Controller manages promissory notes (bills of exchange) in the ERP19 system. A "Kempiala" is an Arabic term for a promissory note or bill of exchange. This controller handles:
- Promissory note creation and management
- Client debt conversion to promissory notes
- Promissory note sales to suppliers
- Expiration tracking and management
- Financial journal entries for all transactions
- Client and supplier debt adjustments
- Transaction history and reporting

### Primary Functions
- [x] Create promissory notes from client debts
- [x] Sell promissory notes to suppliers
- [x] Track note expiration dates
- [x] Manage note lifecycle (available/sold/expired)
- [x] Generate accounting journal entries
- [x] Update client and supplier debt balances
- [x] Provide detailed transaction reporting
- [x] Handle note cancellations and reversals

### Related Controllers
- [clientController.php](clientController.md) - Customer debt management
- [supplierController.php](supplierController.md) - Supplier payment management
- [dailyentry.php](dailyentry.md) - Journal entry management
- [clientReportsController.php](clientReportsController.md) - Customer reporting

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **kempiala** | Promissory notes | id, clientID, supplierID, value, recievingdate, expiredate, selling, conditions |
| **client** | Customer accounts | clientid, clientname, clientdebt, treeId |
| **supplier** | Supplier accounts | supplierid, suppliername, suppliercurrentDebt, treeId |
| **clientdebtchange** | Client debt history | clientid, clientdebtchangeamount, clientdebtchangetype, tablename, clientdebtchangemodelid |
| **supplierdebtchange** | Supplier debt history | supplierid, supplierdebtchangeamount, supplierdebtchangetype, tablename, supplierdebtchangemodelid |

### Accounting Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **dailyentry** | Journal entries | dailyentryid, entryComment, entryDate |
| **dailyentrycreditor** | Credit entries | dailyentryid, accountstreeid, value |
| **dailyentrydebtor** | Debit entries | dailyentryid, accountstreeid, value |
| **accountstree** | Chart of accounts | accountstreeid, accountname |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **youtubelink** | Tutorial videos | youtubelinkid, title, url |
| **programsettings** | System settings | programsettingsid, companyname |
| **usergroup** | User permissions | usergroupid, usergroupname |

---

## 🔑 Key Functions

### 1. **Default Action** - Add Promissory Note Form
**Location**: Line 176  
**Purpose**: Display form to create new promissory note

**Process Flow**:
1. Check user permissions
2. Setup breadcrumb navigation
3. Set current date default
4. Display add form

**Template**: `kempialaview/add.html`

---

### 2. **add()** - Create New Promissory Note
**Location**: Line 564  
**Purpose**: Create promissory note and adjust client debt

**Function Signature**:
```php
function add() {
    // Creates promissory note from client debt
}
```

**Process Flow**:
1. **Collect Form Data**:
   ```php
   $clientID = $_POST["clientID"];
   $recievingdate = $_POST["recievingdate"];
   $expiredate = $_POST["expiredate"];
   $value = $_POST["value"];
   $clientcomment = $_POST["clientcomment"];
   ```

2. **Create Promissory Note**:
   ```php
   $Kempiala->clientID = $clientID;
   $Kempiala->value = $value;
   $Kempiala->recievingdate = $recievingdate;
   $Kempiala->expiredate = $expiredate;
   $Kempiala->selling = 0; // Not sold yet
   $kempialaid = $KempialaDAO->insert($Kempiala);
   ```

3. **Update Client Debt**:
   ```php
   $clientdata = $ClientDAO->load($clientID);
   $debtBefore = $clientdata->clientdebt;
   $Client->clientdebt = ($debtBefore - $value); // Reduce debt
   $ClientEX->updatedept($Client);
   ```

4. **Record Debt Change**:
   ```php
   $Clientdebtchange->clientdebtchangeamount = $value;
   $Clientdebtchange->clientdebtchangetype = 1; // Debt decrease
   $Clientdebtchange->tablename = "kempialaController.php";
   $Clientdebtchange->processname = "شراء كمبياله"; // Purchase promissory note
   $ClientdebtchangeDAO->insert($Clientdebtchange);
   ```

5. **Create Journal Entry**:
   ```php
   // Debit: Promissory Notes (Account 91)
   $dailyEntryDebtor->value = $value;
   $dailyEntryDebtor->accountstreeid = 91;
   
   // Credit: Customer Account
   $dailyEntryCreditor->value = $value;
   $dailyEntryCreditor->accountstreeid = $clientTreeId;
   
   insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray, 1);
   ```

**Transaction Type**: Using database transactions for data integrity

---

### 3. **addsell()** - Sell Promissory Note to Supplier
**Location**: Line 440  
**Purpose**: Sell existing promissory note to supplier

**Process Flow**:
1. **Load Promissory Note**:
   ```php
   $kempialaid = $_POST["id"];
   $kempialadata = $KempialaDAO->load($kempialaid);
   $value = $kempialadata->value;
   ```

2. **Update Note Status**:
   ```php
   $Kempiala->selling = 1; // Mark as sold
   $Kempiala->sellingdate = $today;
   $Kempiala->supplierID = $supplierid;
   $KempialaEX->updatesell($Kempiala, $suppliercomment);
   ```

3. **Adjust Supplier Debt**:
   ```php
   $supplierdata = $SupplierDAO->load($supplierid);
   $debtBefore = $supplierdata->suppliercurrentDebt;
   $Supplier->suppliercurrentDebt = ($debtBefore - $value); // Reduce what we owe
   $SupplierEX->updatedept($Supplier);
   ```

4. **Create Journal Entry**:
   ```php
   // Debit: Supplier Account (we owe them less)
   $dailyEntryDebtor->accountstreeid = $supplierTreeId;
   
   // Credit: Promissory Notes Payable (Account 91)
   $dailyEntryCreditor->accountstreeid = 91;
   ```

**Business Logic**: When selling a promissory note to a supplier, we're essentially using the note to pay down our debt to that supplier.

---

### 4. **show()** - Display Available Promissory Notes
**Location**: Line 842  
**Purpose**: Show available (unsold) promissory notes

**Function Signature**:
```php
function show($clientId) {
    // Display available promissory notes
}
```

**Features**:
- Pagination support (25 records per page)
- Client-specific filtering
- Date-based filtering
- Exclusion of expired notes

**Query Logic**:
```php
$allColums = $KempialaEX->queryAllex(0, $today); // Get available notes
if (isset($clientId) && $clientId != -1) {
    $shownData = $KempialaDAO->queryByClientID($clientId);
} else {
    $shownData = $KempialaEX->queryAlllimted($offset, $limit, 0, $today);
}
```

---

### 5. **showsold()** - Display Sold Promissory Notes
**Location**: Line 731  
**Purpose**: Show promissory notes that have been sold

**Features**:
- Pagination support
- Sold status filtering
- Transaction history

---

### 6. **showexit()** - Display Expired Promissory Notes
**Location**: Line 788  
**Purpose**: Show promissory notes that have expired

**Expiration Logic**:
```php
$today = date("Y-m-d");
$allColums = $KempialaEX->queryAllexpier(0, $today);
```

---

### 7. **delete()** - Cancel Promissory Note
**Location**: Line 891  
**Purpose**: Cancel promissory note and reverse transactions

**Process Flow**:
1. Load promissory note data
2. Mark as deleted (conditions = 1)
3. Reverse client debt adjustment
4. Record debt change
5. Reverse journal entry

**Debt Reversal**:
```php
$Client->clientdebt = ($debtBefore + $value); // Add debt back
$Clientdebtchange->clientdebtchangetype = 0; // Debt increase
$Clientdebtchange->processname = "الغاء كمبياله"; // Cancel promissory note
```

---

### 8. **deletefinal()** - Complete Promissory Note Deletion
**Location**: Line 978  
**Purpose**: Handle complex deletion scenarios including sold notes

**Complex Logic**:
- If note was sold to supplier, reverse supplier debt adjustment
- Create balancing journal entries
- Handle both client and supplier account adjustments

---

### 9. **update()** - Update Promissory Note
**Location**: Line 1167  
**Purpose**: Update promissory note expiration date and comments

**Editable Fields**:
- Expiration date
- Client comments
- Basic note information

---

## 🔄 Workflows

### Workflow 1: Promissory Note Creation
```
┌─────────────────────────────────────────────────────────────┐
│          START: Client Has Outstanding Debt                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Create Promissory Note                                  │
│     - Set client ID and amount                              │
│     - Set receiving and expiration dates                    │
│     - Add comments and terms                                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Reduce Client Debt                                      │
│     - Calculate new debt balance                            │
│     - Update client debt amount                             │
│     - Record debt change transaction                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Create Accounting Entry                                 │
│     - Debit: Promissory Notes Receivable                    │
│     - Credit: Customer Account                              │
│     - Record journal entry                                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Note Available for Sale                                 │
│     - Note status: Available                                │
│     - Track expiration date                                 │
│     - Available for supplier sale                           │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Selling Promissory Note to Supplier
```
┌─────────────────────────────────────────────────────────────┐
│        START: Available Promissory Note                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Select Supplier and Terms                               │
│     - Choose supplier to sell to                            │
│     - Set sale date                                         │
│     - Add supplier comments                                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Update Note Status                                      │
│     - Mark as sold (selling = 1)                           │
│     - Set supplier ID                                       │
│     - Record selling date                                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Adjust Supplier Debt                                    │
│     - Reduce amount owed to supplier                        │
│     - Record supplier debt change                           │
│     - Track payment via promissory note                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Create Accounting Entry                                 │
│     - Debit: Supplier Payable Account                       │
│     - Credit: Promissory Notes Payable                      │
│     - Record transaction                                    │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default action | Display add promissory note form |
| `do=add` | `add()` | Create new promissory note |
| `do=addsell` | `addsell()` | Sell promissory note to supplier |
| `do=show` | `show()` | Display available promissory notes |
| `do=showexit` | `showexit()` | Display expired promissory notes |
| `do=sell` | Edit for sale | Display sell form |
| `do=showsold` | `showsold()` | Display sold promissory notes |
| `do=delete` | `delete()` | Cancel promissory note |
| `do=edit` | `edit()` | Display edit form |
| `do=editprint` | Print view | Display print view |
| `do=deletefinal` | `deletefinal()` | Complete deletion process |
| `do=update` | `update()` | Update promissory note |

### Form Parameters
**Add Promissory Note**:
- `clientID` - Customer ID
- `recievingdate` - Note receiving date
- `expiredate` - Note expiration date
- `value` - Note amount
- `clientcomment` - Comments/terms

**Sell to Supplier**:
- `id` - Promissory note ID
- `supplierID` - Supplier ID
- `suppliercomment` - Sale comments

**Update Note**:
- `id` - Promissory note ID
- `expiredate` - New expiration date
- `clientcomment` - Updated comments

---

## 🔒 Security & Permissions

### Access Control
```php
// Authentication check on all actions
include_once("../public/authentication.php");
```

**Security Features**:
- Session-based authentication
- User ID tracking in all transactions
- Database transaction rollback on errors
- Input filtering through framework

### Permission Structure
- All logged-in users can access promissory note functions
- No role-based restrictions implemented
- User ID logged for audit trail

### Recommended Enhancements
```php
// Add permission checks
if (!hasPermission('manage_promissory_notes')) {
    throw new Exception('Access denied');
}

// Add approval workflow for high amounts
if ($value > getApprovalLimit($_SESSION['userid'])) {
    requireApproval($kempialaData);
}
```

---

## 🔢 Calculation Methods

### Client Debt Adjustment
```php
// When creating promissory note
$newDebt = $originalDebt - $promissoryNoteValue;

// When canceling promissory note  
$newDebt = $originalDebt + $promissoryNoteValue;
```

### Supplier Debt Adjustment
```php
// When selling note to supplier
$newSupplierDebt = $originalSupplierDebt - $promissoryNoteValue;

// When reversing sale
$newSupplierDebt = $originalSupplierDebt + $promissoryNoteValue;
```

### Journal Entry Logic
```php
// Creating promissory note:
// Dr. Promissory Notes Receivable (Asset)
// Cr. Customer Account (Reduce receivable)

// Selling to supplier:
// Dr. Supplier Payable (Reduce payable)
// Cr. Promissory Notes Payable (Increase liability)
```

---

## 📊 Performance Considerations

### Database Optimization
1. **Indexes Required**:
   ```sql
   CREATE INDEX idx_kempiala_client ON kempiala(clientID, conditions);
   CREATE INDEX idx_kempiala_supplier ON kempiala(supplierID, selling);
   CREATE INDEX idx_kempiala_expiry ON kempiala(expiredate, conditions);
   CREATE INDEX idx_kempiala_status ON kempiala(selling, conditions, expiredate);
   ```

2. **Query Optimization**:
   - Date-based filtering for expiration
   - Status-based filtering for available/sold notes
   - Client/supplier relationship joins

### Transaction Management
```php
// All financial operations use transactions
$mytransactions = new Transaction();
try {
    // Multiple database operations
    $mytransactions->commit();
} catch (Exception $ex) {
    $mytransactions->rollback();
}
```

---

## 🐛 Common Issues & Troubleshooting

### 1. **Debt Calculation Errors**
**Issue**: Client debt not updating correctly  
**Cause**: Concurrent transactions or rollback failures

**Debug**:
```php
// Check debt before and after
echo "Client debt before: " . $clientdata->clientdebt . "<br>";
echo "Promissory note value: " . $value . "<br>";
echo "Expected new debt: " . ($clientdata->clientdebt - $value) . "<br>";

// Verify debt change record
$debtChanges = $ClientdebtchangeEX->queryByClientAndDate($clientID, date('Y-m-d'));
print_r($debtChanges);
```

### 2. **Journal Entry Imbalance**
**Issue**: Accounting entries don't balance  
**Cause**: Missing or incorrect account IDs

**Debug**:
```php
// Check account tree IDs
echo "Client tree ID: " . $clientTreeId . "<br>";
echo "Supplier tree ID: " . $supplierTreeId . "<br>";
echo "Promissory notes account: 91<br>";

// Verify journal entry creation
$journalEntry = $dailyEntryDAO->load($journalEntryId);
print_r($journalEntry);
```

### 3. **Expiration Date Issues**
**Issue**: Notes not appearing in expired list  
**Cause**: Date format or timezone problems

**Fix**:
```php
// Standardize date comparison
$today = date('Y-m-d');
$expiredNotes = $KempialaEX->queryAllexpier(0, $today . ' 23:59:59');

// Debug date comparison
echo "Today: {$today}<br>";
echo "Note expiry: {$noteData->expiredate}<br>";
echo "Is expired: " . ($noteData->expiredate < $today ? 'Yes' : 'No');
```

### 4. **Transaction Rollback Issues**
**Issue**: Partial updates when errors occur  
**Cause**: Missing transaction boundaries

**Fix**:
```php
// Ensure all operations are in transaction
$mytransactions = new Transaction();
try {
    // Start transaction explicitly
    $mytransactions->begin();
    
    // All database operations here
    $kempialaId = $KempialaDAO->insert($Kempiala);
    $ClientEX->updatedept($Client);
    $ClientdebtchangeDAO->insert($Clientdebtchange);
    
    // Commit all changes
    $mytransactions->commit();
} catch (Exception $ex) {
    // Rollback on any error
    $mytransactions->rollback();
    throw $ex;
}
```

---

## 🧪 Testing Scenarios

### Test Case 1: Promissory Note Creation
```
1. Create client with known debt amount
2. Create promissory note for partial debt
3. Verify client debt reduced correctly
4. Check debt change history
5. Verify journal entry created
6. Confirm note appears in available list
```

### Test Case 2: Supplier Sale Process
```
1. Create available promissory note
2. Sell to supplier with known debt
3. Verify supplier debt reduced
4. Check supplier debt change history
5. Verify journal entries
6. Confirm note appears in sold list
```

### Test Case 3: Expiration Handling
```
1. Create promissory note with past expiry date
2. Verify appears in expired list
3. Test date boundary conditions
4. Check exclusion from available list
```

### Test Case 4: Cancellation Process
```
1. Create and cancel promissory note
2. Verify debt restoration
3. Check reversal journal entries
4. Confirm note marked as deleted
5. Test complex cancellation scenarios
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [clientController.php](clientController.md) - Customer management
- [supplierController.php](supplierController.md) - Supplier management
- [dailyentry.php](dailyentry.md) - Journal entry system
- [clientReportsController.php](clientReportsController.md) - Customer reporting

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When promissory note workflows change