# Check Deposit Controller Documentation

**File**: `/controllers/depositcheckController.php`  
**Purpose**: Manages check deposits from customers to bank accounts, reducing customer debt and increasing bank balances  
**Last Updated**: December 20, 2024  
**Total Functions**: 8+  
**Lines of Code**: ~1,229

---

## 📋 Overview

The Check Deposit Controller handles the process of depositing customer checks into bank accounts. This is a critical financial operation that:
- Records customer check deposits to specific bank accounts
- Reduces customer debt by the deposited amount
- Updates bank account balances and movements
- Generates proper accounting entries for the transactions
- Supports integration with premium payment systems
- Provides comprehensive tracking and reversal capabilities

### Primary Functions
- [x] Process customer check deposits to bank accounts
- [x] Update customer debt balances automatically
- [x] Track bank account balance changes
- [x] Generate accounting entries (daily entries)
- [x] Handle premium payment allocations
- [x] Support deposit reversal (cancellation)
- [x] Maintain detailed audit trails
- [x] Integrate with concurrent user protection

### Related Controllers
- [datedCheckedController.php](datedCheckedController.md) - Post-dated check management
- [clientPayedDeptController.php](#) - Customer payments
- [bankaccountController.php](#) - Bank account operations
- [accountmovementController.php](#) - Account movement tracking

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **checkdeposit** | Check deposit master records | checkdepositid, clientid, bankaccountid, checkdepositamount, checkdepositdate, conditions, dailyentryid |
| **clientdebtchange** | Customer debt transaction log | clientdebtchangeid, clientid, clientdebtchangeamount, clientdebtchangetype, clientdebtchangedate, tablename |
| **accountmovement** | Bank account movement tracking | accountmovementid, accountid, accountmovementamount, accountmovementtype, tablename, accountmovementmodelid |

### Financial Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **bankaccount** | Bank account master data | accountid, bankid, accountbeginingbalance, accountdate, treeId |
| **bank** | Bank master information | bankid, bankname |
| **client** | Customer master data | clientid, clientname, clientdebt, treeId, inUse |

### Supporting Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **premium** | Premium/installment tracking | premiumid, value, rest, payed, clientid |
| **dailyentry** | Accounting entries | dailyentryid, entryComment, entryDate |
| **accountstree** | Chart of accounts | id, name, parent, theValue |

---

## 🔑 Key Functions

### 1. **Default Action** - Add Form Display
**Location**: Line 172  
**Purpose**: Display the check deposit form with necessary dropdowns

**Process Flow**:
1. Load all banks with extended information
2. Load all customer data
3. Set today's date as default
4. Display deposit form template

**Key Variables**:
- `$bank` - All available banks
- `$allclientdata` - All customers for selection
- `$today` - Current date

---

### 2. **add()** - Process Check Deposit
**Location**: Line 480  
**Purpose**: Core function to process customer check deposits

**Function Signature**:
```php
function add()
```

**Process Flow**:
1. **Transaction Start**: Initialize transaction for data consistency
2. **Input Processing**: Extract and validate POST parameters
3. **Client Debt Management**: 
   - Lock client using concurrent access protection
   - Reduce customer debt by deposit amount
   - Log debt change in clientdebtchange table
4. **Bank Account Updates**:
   - Increase bank account balance
   - Create account movement record
5. **Check Deposit Record**: Insert main deposit record
6. **Accounting Integration**: Generate daily entry
7. **Premium Handling**: Process installment payments if applicable
8. **Transaction Commit**: Finalize all changes

**Key Variables**:
- `$clientid` - Customer making deposit
- `$accountid` - Target bank account
- `$checkwithdrawalamount` - Deposit amount
- `$checkdate` - Deposit date

---

### 3. **show()** - Display Deposits
**Location**: Line 782  
**Purpose**: Display check deposits based on various filters

**Filter Options**:
- **Date Range**: From and to dates
- **Customer**: Specific customer deposits
- **Single Deposit**: By deposit ID
- **Today Only**: Default view

**Process Flow**:
1. Parse filter parameters from request
2. Build appropriate query based on filters
3. Execute query through extended DAO
4. Assign results to template
5. Display with appropriate message

**Query Patterns**:
```php
// Date range query
$shownData = $CheckdepositEX->queryWithDateExt($from, $to);

// Customer specific query  
$shownData = $CheckdepositEX->queryWithClientIdExt($clientId);

// Single deposit query
$temp = $CheckdepositEX->loadEX($id);
```

---

### 4. **delete()** - Reverse Check Deposit
**Location**: Line 869  
**Purpose**: Reverse/cancel a check deposit transaction

**Function Signature**:
```php
function delete($id, $dailentry)
```

**Process Flow**:
1. **Transaction Start**: Begin reversal transaction
2. **Load Original Data**: Get deposit details
3. **Reverse Customer Debt**: Add back the deposit amount to customer debt
4. **Reverse Bank Account**: Subtract deposit from bank balance
5. **Log Reversal**: Create debt change and account movement records
6. **Update Status**: Mark deposit as cancelled (conditions=1)
7. **Reverse Accounting**: Call `reverseEntryWithItsID()` to reverse daily entry

**Key Features**:
- Maintains audit trail of reversal
- Supports both same-day and historical reversals
- Handles concurrent user scenarios
- Preserves original transaction data

---

### 5. **edit()** - Load Deposit for Editing
**Location**: Line 1058  
**Purpose**: Load deposit data for modification

**Process Flow**:
1. Get deposit ID from POST or GET
2. Load extended deposit information
3. Load related customer data
4. Return deposit object for template

---

### 6. **update()** - Update Deposit Details
**Location**: Line 1091  
**Purpose**: Update non-financial deposit details

**Process Flow**:
1. Extract update parameters
2. Update deposit user and note fields
3. Preserve financial data integrity

**Note**: Only updates metadata, not financial amounts

---

### 7. **execute()** - Batch Operations
**Location**: Line 1137  
**Purpose**: Process multiple deposits in batch (mainly deletions)

**Process Flow**:
1. Parse operation type and selected items
2. Loop through selected deposits
3. Execute operation (typically deletion)
4. Accumulate results and error messages
5. Display operation summary

---

### 8. **getClientDataFromClientInUseSP()** - Concurrent Access Protection
**Location**: Line 1191  
**Purpose**: Safely access customer data with locking mechanism

**Function Signature**:
```php
function getClientDataFromClientInUseSP($clientid)
```

**Process Flow**:
1. Check if customer is being used by another process
2. Wait if customer is locked (up to 15 seconds)
3. Force unlock if wait time exceeds limit
4. Return customer data when available

**Concurrency Features**:
- Prevents simultaneous debt modifications
- Automatic timeout and recovery
- Live backup logging for force unlocks

---

## 🔄 Workflows

### Workflow 1: Standard Check Deposit
```
┌─────────────────────────────────────────────────────────────┐
│              START: Customer Brings Check                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Select Customer and Bank Account                        │
│     - Choose customer from dropdown                        │
│     - Select target bank account                           │
│     - Enter check details (amount, date, number)           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Lock Customer Record                                    │
│     - Check if customer is in use by another process       │
│     - Wait if locked, force unlock after 15 seconds       │
│     - Proceed when customer record is available            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Update Customer Debt                                    │
│     - Reduce customer debt by check amount                 │
│     - Log debt change: Type=1 (decrease)                   │
│     - Record in clientdebtchange table                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Update Bank Account                                     │
│     - Increase bank account balance                        │
│     - Create account movement record                       │
│     - Log movement type=0 (increase)                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Create Check Deposit Record                             │
│     - Insert into checkdeposit table                       │
│     - Link to customer and bank account                    │
│     - Store check details and amount                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Generate Accounting Entry                               │
│     - Create daily entry                                   │
│     - Debit: Bank Account (asset increase)                 │
│     - Credit: Customer Account (receivable decrease)       │
│     - Link daily entry ID to deposit record                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  7. Process Premium Payments (if applicable)               │
│     - Check for installment payments                       │
│     - Allocate deposit to specific installments            │
│     - Update premium payment records                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  8. Finalize Transaction                                    │
│     - Commit all database changes                          │
│     - Release customer lock                                 │
│     - Return success status                                 │
└─────────────────────────────────────────────────────────────┘
```

### Workflow 2: Check Deposit Reversal
```
┌─────────────────────────────────────────────────────────────┐
│              START: Need to Cancel Deposit                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Select Deposit to Cancel                                │
│     - Choose from deposit list                             │
│     - Verify deposit is not already cancelled              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Load Original Transaction Data                          │
│     - Get customer ID and deposit amount                   │
│     - Load bank account information                        │
│     - Verify original daily entry ID                       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Reverse Customer Debt                                   │
│     - Lock customer record                                 │
│     - Add deposit amount back to customer debt             │
│     - Create reversal entry in clientdebtchange            │
│     - Type=0 (increase debt)                               │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Reverse Bank Account                                    │
│     - Subtract deposit amount from bank balance            │
│     - Create reversal account movement                     │
│     - Type=1 (decrease)                                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Update Deposit Status                                   │
│     - Mark deposit as cancelled (conditions=1)             │
│     - Preserve original data for audit                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Reverse Accounting Entry                                │
│     - Call reverseEntryWithItsID()                         │
│     - Create offsetting daily entry                        │
│     - Maintain audit trail                                 │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default | Display check deposit form |
| `do=add` | `add()` | Process new check deposit |
| `do=show` | `show()` | Display deposits with filters |
| `do=delete` | `delete()` | Cancel/reverse check deposit |
| `do=edit` | `edit()` | Load deposit for editing |
| `do=update` | `update()` | Update deposit details |
| `do=details` | `edit()` | View deposit details |
| `do=executeOperation` | `execute()` + `show()` | Batch operations on deposits |
| `do=editprint` | `edit()` | Print-friendly edit view |
| `do=editprint2` | `edit()` | Alternative print format with Arabic number conversion |

### Required Parameters by Action

**Add Deposit** (`do=add`):
- `clientid` - Customer ID
- `accountid` - Bank account ID  
- `txtAmount` - Deposit amount
- `ddlBank` - Bank ID
- `checkdate` - Deposit date

**Show Deposits** (`do=show`):
- `clientid` - Filter by customer (optional)
- `from` - Start date (optional)
- `to` - End date (optional)
- `id` - Specific deposit ID (optional)

**Delete Deposit** (`do=delete`):
- `id` - Deposit ID to cancel
- `action` - Daily entry ID for reversal

---

## 🧮 Calculation Methods

### Debt Balance Update
```php
// Reduce customer debt by deposit amount
$Client->clientdebt = ($debtBefore - $checkwithdrawalamount);

// Log the debt change
$Clientdebtchange->clientdebtchangetype = 1; // Decrease
$Clientdebtchange->clientdebtchangeamount = $checkwithdrawalamount;
$Clientdebtchange->clientdebtchangeafter = $debtBefore - $checkwithdrawalamount;
```

### Bank Account Balance Update
```php
// Increase bank account balance
$account->accountbeginingbalance = $accountBefore + $checkwithdrawalamount;

// Track account movement
$accountMove->accountmovementtype = 0; // Increase
$accountMove->accountmovementafter = $accountBefore + $checkwithdrawalamount;
```

### Premium Payment Allocation
```php
if ($dept_rest < $checkwithdrawalamount) {
    // Close current installment and apply excess to next
    $rest = $checkwithdrawalamount - $dept_rest;
    $premiumData->payed = 1;
    $premiumData->rest = $premiumData->rest + $rest;
}
```

---

## 🔒 Security & Permissions

### Authentication Requirements
```php
include_once("../public/authentication.php");
```

### User Activity Tracking
- All records include `userid` field
- Timestamp tracking on all operations
- Audit trail through clientdebtchange and accountmovement tables

### Concurrent Access Protection
```php
// Prevent simultaneous customer debt modifications
$client_data = $ClientEX->callClientInUseSP($clientid);
while ($client_data->clientdebt == 'in_use') {
    sleep(1); // Wait for other process to complete
    $noOfTries++;
    if ($noOfTries > 15) {
        // Force unlock after 15 seconds
        R::exec('UPDATE client SET inUse = 0 where clientid = ' . $clientid);
    }
}
```

---

## 📊 Performance Considerations

### Database Optimization Tips
1. **Indexes Required**:
   - `checkdeposit(clientid, checkdepositdate)`
   - `checkdeposit(bankaccountid, checkdepositdate)`
   - `clientdebtchange(clientid, clientdebtchangedate)`
   - `accountmovement(accountid, accountmovementdate)`

2. **Query Optimization**:
   - Use date filtering with proper indexes
   - Avoid SELECT * in large tables
   - Use prepared statements for repeated queries

3. **Concurrency Management**:
   - Minimal lock duration on customer records
   - Automatic timeout and recovery mechanisms
   - Live backup logging for debugging

### Known Performance Considerations
- Customer locking may cause delays under high concurrency
- Large date ranges in show() may return excessive data
- Premium payment processing adds complexity to deposit transactions

---

## 🐛 Common Issues & Troubleshooting

### 1. **Customer Lock Timeout**
**Issue**: Deposit fails with "customer in use" error  
**Cause**: Another process has locked the customer record

**Solutions**:
- Wait for automatic timeout (15 seconds)
- Check for stuck processes holding locks
- Force unlock using database direct access

### 2. **Accounting Entry Mismatch**
**Issue**: Daily entry amounts don't match deposit amounts  
**Cause**: Error in daily entry generation or account tree setup

**Debug**:
```sql
-- Check daily entry details
SELECT * FROM dailyentry WHERE dailyentryid = [ENTRY_ID];
SELECT * FROM dailyentrycreditor WHERE dailyentryid = [ENTRY_ID];
SELECT * FROM dailyentrydebtorcredit WHERE dailyentryid = [ENTRY_ID];
```

### 3. **Bank Balance Discrepancy**
**Issue**: Bank account balance doesn't match sum of movements  
**Cause**: Failed transaction or missing movement record

**Verification**:
```sql
-- Verify movement records
SELECT SUM(CASE WHEN accountmovementtype = 0 THEN accountmovementamount 
               ELSE -accountmovementamount END) as net_movement
FROM accountmovement 
WHERE accountid = [ACCOUNT_ID] AND tablename = 'depositcheckController.php';
```

### 4. **Premium Payment Allocation Errors**
**Issue**: Installment payments not properly allocated  
**Cause**: Logic error in premium processing or missing premium records

**Debug Steps**:
1. Verify premium records exist for customer
2. Check payment allocation logic
3. Ensure premium rest calculations are correct

---

## 🧪 Testing Scenarios

### Test Case 1: Basic Check Deposit
```
1. Create customer with existing debt
2. Process check deposit for partial debt amount
3. Verify customer debt reduced correctly
4. Confirm bank account balance increased
5. Check daily entry created properly
```

### Test Case 2: Concurrent Access
```
1. Start deposit process for customer A
2. Simultaneously start another process for same customer
3. Verify second process waits appropriately
4. Confirm no data corruption occurs
5. Validate final balances are correct
```

### Test Case 3: Deposit Reversal
```
1. Create and process check deposit
2. Reverse the deposit transaction
3. Verify customer debt restored to original
4. Confirm bank account balance reduced
5. Check daily entry reversal created
```

### Test Case 4: Premium Payment Integration
```
1. Set up customer with installment payments
2. Process deposit with premium allocation
3. Verify installments marked as paid
4. Check excess amount applied to next installment
5. Confirm premium payment records updated
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [datedCheckedController.md](datedCheckedController.md) - Post-dated check management
- [Database Schema Documentation](#) - Table relationships
- [Concurrent Access Protection](#) - Multi-user safety features

---

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