# Dated Check Controller Documentation

**File**: `/controllers/datedCheckedController.php`  
**Purpose**: Manages post-dated checks (PDCs) for both customers and suppliers, including check endorsements, payments, and cancellations  
**Last Updated**: December 20, 2024  
**Total Functions**: 25+  
**Lines of Code**: ~2,130

---

## 📋 Overview

The Dated Checked Controller is the central hub for managing post-dated checks (PDCs) in the ERP system. It handles:
- Post-dated check creation for customers and suppliers
- Check payment processing to cash or bank accounts
- Check endorsement between customers and suppliers
- Check cancellation and reason tracking
- Integration with cash management, bank accounts, and accounting entries
- Daily entry generation for all check transactions

### Primary Functions
- [x] Create post-dated checks for customers/suppliers
- [x] Process check payments (cash/bank)
- [x] Endorse checks between parties
- [x] Cancel checks with reason tracking
- [x] Integrate with cash registers (safes)
- [x] Integrate with bank account management
- [x] Generate daily accounting entries
- [x] Track payment history and debt changes

### Related Controllers
- [depositcheckController.php](depositcheckController.md) - Check deposits
- [clientPayedDeptController.php](#) - Customer payments
- [saveController.php](#) - Cash register management
- [bankaccountController.php](#) - Bank account operations

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **datedchecked** | Post-dated check master | datedCheckedID, clientNum, bankName, accountNo, checkValue, checkNo, dueDate, done, addType, paperType |
| **clientdebtchange** | Customer debt transaction log | clientdebtchangeid, clientid, clientdebtchangeamount, clientdebtchangetype, clientdebtchangedate, tablename |
| **supplierdebtchange** | Supplier debt transaction log | supplierdebtchangeid, supplierid, supplierdebtchangeamount, supplierdebtchangetype, supplierdebtchangedate, tablename |

### Financial Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **save** | Cash registers/safes | saveid, savename, savecurrentvalue, userid |
| **savedaily** | Cash register movements | savedailyid, saveid, savedailychangeamount, savedailychangetype, savedailymodelid, tablename |
| **checkdeposit** | Check deposits to bank | checkdepositid, clientid, bankaccountid, checkdepositamount, checkdepositdate |
| **bankaccount** | Bank account master | accountid, bankid, accountbeginingbalance, treeId |
| **accountmovement** | Bank account movements | accountmovementid, accountid, accountmovementamount, accountmovementtype, tablename |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **client** | Customer master data | clientid, clientname, clientdebt, treeId |
| **supplier** | Supplier master data | supplierid, suppliername, suppliercurrentDebt, treeId |
| **bank** | Bank master data | bankid, bankname |
| **dailyentry** | Accounting entries | dailyentryid, entryComment, entryDate |

---

## 🔑 Key Functions

### 1. **selectCustomer** - Choose Check Type
**Location**: Line 203  
**Purpose**: Display form to select whether creating check for customer (paytype=0) or supplier (paytype=1)

**Process Flow**:
1. Load all banks for dropdown
2. Set today's date for default
3. If customer type: Load all clients and show client form
4. If supplier type: Load all suppliers and show supplier form

---

### 2. **add()** - Create New Post-Dated Check
**Location**: Line 814  
**Purpose**: Core function to create new post-dated checks for customers or suppliers

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

**Process Flow**:
1. **Input Validation**: Extract POST parameters (client/supplier ID, bank details, check amount, dates)
2. **Check Record Creation**: Insert into `datedchecked` table
3. **Debt Management**: Update client/supplier debt based on check type
4. **Debt Change Logging**: Insert transaction record into debt change tables
5. **Accounting Entry**: Create daily entry with appropriate debit/credit accounts
6. **Return**: Success indicator (0 for customer, 1 for supplier)

**Key Variables**:
- `$paytype` - 0 for customer, 1 for supplier
- `$paperType` - 1 for payable check, 0 for receivable check
- `$checkValue` - Check amount
- `$clientNum` - Customer or supplier ID
- `$dueDate` - Check due date

---

### 3. **payCheck** / **payCheckForSup** - Process Check Payment
**Location**: Lines 304, 586  
**Purpose**: Display payment form and process check payment to cash or bank

**Process Flow**:
1. Load check details by ID
2. Load customer/supplier information
3. Load available cash registers and bank accounts
4. Display payment form with options (cash=0, bank=1)
5. Process payment based on selected method

---

### 4. **payment** / **paymentSupplier** - Execute Payment
**Location**: Lines 364, 644  
**Purpose**: Execute the actual payment processing

**Payment Types**:
- **Cash Payment (paytype=0)**: Calls `insertSaveAndSaveDaily()` to add to cash register
- **Bank Payment (paytype=1)**: Calls `addInBankDeposit()` to deposit in bank account

**Process Flow**:
1. Validate payment type and amount
2. Update cash register or bank account balance
3. Mark check as done (`done=1`)
4. Generate accounting entries
5. Update account movements table

---

### 5. **insertSaveAndSaveDaily()** - Cash Register Payment
**Location**: Line 1163  
**Purpose**: Process check payment to cash register

**Process Flow**:
1. Load current cash register balance
2. Calculate new balance (current + check amount)
3. Insert movement record in `savedaily` table
4. Update cash register current value
5. Generate daily entry: Debit Cash, Credit Checks Receivable

---

### 6. **addInBankDeposit()** - Bank Deposit Payment  
**Location**: Line 1391  
**Purpose**: Process check payment to bank account

**Process Flow**:
1. Insert record in `checkdeposit` table
2. Update bank account balance
3. Insert account movement record
4. Generate daily entry: Debit Bank, Credit Checks Receivable
5. Handle both customer and supplier scenarios

---

### 7. **addEndorse()** - Check Endorsement
**Location**: Line 2022  
**Purpose**: Endorse check from one party to another

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

**Process Flow**:
1. Load check and endorsement details
2. Update check status to endorsed (`done=3`)
3. Set endorsement date and person ID
4. Reduce supplier debt by check amount
5. Insert supplier debt change record
6. Generate daily entry for endorsement transaction

---

### 8. **checkCancledForClient()** / **checkCancelSup()** - Cancel Checks
**Location**: Lines 1717, 1941  
**Purpose**: Cancel checks and reverse transactions

**Process Flow**:
1. Load check details and current debt
2. Calculate reversed debt amount
3. Update client/supplier debt (reverse original transaction)
4. Insert debt change record for cancellation
5. Reverse original daily entry using `reverseEntryWithItsID()`
6. Update check with cancellation reason

---

## 🔄 Workflows

### Workflow 1: Customer Check Creation
```
┌─────────────────────────────────────────────────────────────┐
│              START: Customer Owes Money                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Select Check Type                                       │
│     - Choose "Customer" (paytype=0)                        │
│     - Load customer list and bank list                     │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Fill Check Details                                      │
│     - Customer ID, Bank Name, Account Number               │
│     - Check Number, Amount, Due Date                       │
│     - Paper Type (1=payable, 0=receivable)                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Create Check Record                                     │
│     - Insert into datedchecked table                       │
│     - Update customer debt (+/- based on paper type)       │
│     - Log debt change in clientdebtchange                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Generate Accounting Entry                               │
│     - IF Payable: Debit Checks Payable, Credit Customer    │
│     - IF Receivable: Debit Customer, Credit Checks Recv    │
│     - Link daily entry ID to check record                  │
└─────────────────────────────────────────────────────────────┘
```

### Workflow 2: Check Payment Processing
```
┌─────────────────────────────────────────────────────────────┐
│              START: Check Due Date Arrives                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Select Check for Payment                                │
│     - Choose check from pending list                       │
│     - Load check details and party information             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Choose Payment Method                                   │
│     ├─→ Cash Payment (paytype=0)                           │
│     │   └─ Select cash register                            │
│     └─→ Bank Payment (paytype=1)                           │
│         └─ Select bank account                             │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Process Payment                                         │
│     ├─→ Cash: Update register balance + movement record     │
│     └─→ Bank: Create deposit + update account balance       │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Complete Transaction                                    │
│     - Mark check as done (done=1)                          │
│     - Generate accounting entry                             │
│     - Update account movements table                        │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=` (empty) | Default view | Start page - select check type |
| `do=selectCustomer` | Customer/supplier selection | Show form to choose customer or supplier |
| `do=add` | `add()` | Create new post-dated check |
| `do=showClient` | Client check listing | Show all customer checks |
| `do=showSupllier` | Supplier check listing | Show all supplier checks |
| `do=payCheck` | Payment form | Display check payment form |
| `do=payment` | Payment processing | Process customer check payment |
| `do=payCheckForSup` | Supplier payment form | Display supplier check payment form |
| `do=paymentSupplier` | Supplier payment processing | Process supplier check payment |
| `do=details` | Check details view | Show detailed check information |
| `do=endorse` | Endorsement form | Show check endorsement form |
| `do=addEndorse` | `addEndorse()` | Process check endorsement |
| `do=checkCancledForClient` | Cancellation form | Show client check cancellation form |
| `do=checkCancledForSupplier` | Supplier cancellation form | Show supplier check cancellation form |

---

## 🔒 Security & Permissions

### Authentication Requirements
```php
include_once("../public/authentication.php");
```
- All major operations require user authentication
- Session-based user identification (`$_SESSION['userid']`)

### User Activity Tracking
- All records include `userid` for audit trail
- Date stamps on all operations (`operationDate`, `clientdebtchangedate`)
- Reason tracking for cancellations (`resonForRefused`)

### Transaction Safety
```php
$mytransactions = new Transaction();
try {
    // Operations here
    $mytransactions->commit();
} catch (Exception $ex) {
    $mytransactions->rollback();
}
```

---

## 📊 Performance Considerations

### Database Optimization Tips
1. **Indexes Required**:
   - `datedchecked(clientNum, dueDate, done)`
   - `clientdebtchange(clientid, clientdebtchangedate)`
   - `supplierdebtchange(supplierid, supplierdebtchangedate)`

2. **Query Patterns**:
   - Frequent queries by customer/supplier ID
   - Date range filtering on due dates
   - Status filtering (done=0 for pending checks)

3. **Memory Considerations**:
   - Check listing may return large datasets
   - Consider pagination for high-volume users

---

## 🐛 Common Issues & Troubleshooting

### 1. **Check Payment Fails**
**Issue**: Payment process returns error or doesn't update balances  
**Cause**: Insufficient balance in target account or transaction rollback

**Debug Steps**:
```sql
-- Check current account balance
SELECT * FROM save WHERE saveid = [ID];
SELECT * FROM bankaccount WHERE accountid = [ID];

-- Check for failed transactions
SELECT * FROM datedchecked WHERE done = 0 AND dueDate < NOW();
```

### 2. **Missing Daily Entries**
**Issue**: Check transactions don't appear in accounting reports  
**Cause**: Daily entry generation failed or was not linked

**Fix**:
```sql
-- Find checks without daily entries
SELECT * FROM datedchecked WHERE dailyentryid = 0 OR dailyentryid IS NULL;
```

### 3. **Debt Calculation Errors**
**Issue**: Customer/supplier debt doesn't match check amounts  
**Cause**: Incorrect debt type calculation or missing debt change records

**Debug**:
```sql
-- Verify debt change records
SELECT SUM(CASE WHEN clientdebtchangetype = 0 THEN clientdebtchangeamount 
               ELSE -clientdebtchangeamount END) as calculated_debt
FROM clientdebtchange 
WHERE clientid = [ID] AND tablename = 'datedCheckedController.php';
```

### 4. **Endorsement Issues**
**Issue**: Check endorsement doesn't transfer properly  
**Cause**: Missing supplier debt update or incorrect accounting entry

**Verification**:
```sql
-- Check endorsement status
SELECT * FROM datedchecked WHERE done = 3 AND endorsePersonId IS NOT NULL;
```

---

## 🧪 Testing Scenarios

### Test Case 1: Customer Check Creation
```
1. Create customer receivable check
2. Verify customer debt increases by check amount
3. Confirm daily entry created (Dr: Customer, Cr: Checks Receivable)
4. Check debt change record in clientdebtchange table
```

### Test Case 2: Check Payment to Cash
```
1. Create check and process payment to cash register
2. Verify cash register balance increases
3. Check movement record in savedaily table
4. Confirm check marked as done (done=1)
```

### Test Case 3: Check Endorsement
```
1. Create customer check
2. Endorse to supplier
3. Verify supplier debt decreases
4. Check endorsement fields updated
5. Confirm daily entry for endorsement transaction
```

### Test Case 4: Check Cancellation
```
1. Create check
2. Cancel with reason
3. Verify debt reversal
4. Check original daily entry is reversed
5. Confirm cancellation reason recorded
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [depositcheckController.md](depositcheckController.md) - Check deposits
- [Database Schema Documentation](#) - Table relationships
- [Daily Entry System Documentation](#) - Accounting integration

---

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