RedBean Kashf (Medical Examination) Controller Documentation
File: /controllers/rb_kashf.php
Purpose: Medical examination management system with comprehensive accounting integration, patient tracking, and cash register management
Last Updated: December 20, 2024
Total Functions: 12+
Lines of Code: ~896
---
๐ Overview
The RedBean Kashf Controller manages medical examination operations for optical/medical clinics. It provides comprehensive functionality for:
- โข Patient examination registration and management
- โข Doctor assignment and tracking
- โข Medical examination fee processing with accounting integration
- โข Cash register integration with automatic balance updates
- โข Client debt tracking and payment history
- โข Examination editing and deletion with transaction reversal
- โข Print-friendly examination records
- โข Complete audit trail for all medical transactions
Primary Functions
- โ Medical examination registration with patient and doctor assignment
- โ Automatic accounting journal entry creation for examination fees
- โ Cash register integration with balance validation and updates
- โ Client debt change tracking and history management
- โ Examination editing with accounting transaction reversal
- โ Doctor and patient management integration
- โ Print formatting for examination records
- โ Complete transaction audit trail and reversibility
Related Controllers
- โข clientController.php - Patient/customer management
- โข userController.php - Doctor management (user type 4)
- โข dailyentryfun.php - Accounting journal entries
- โข saveController.php - Cash register management
- โข clientdebtchangeController.php - Client debt tracking
---
๐๏ธ Database Tables
Core Medical Tables
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **kashf** | Medical examinations | id, kashfvalue, kashftype, customerid, doctorid, kashfdate, paystatus | |
| **client** | Patients/customers | clientid, clientname, clientphone, clientaddress | |
| **user** | Doctors (type 4) | userid, username, usergroupid, usertype | |
| **clientarea** | Patient area/region | clientareaid, areaname |
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **save** | Cash registers | saveid, savename, savecurrentvalue, treeId | |
| **savedaily** | Cash register transactions | saveid, savedailychangeamount, savedailychangetype, processname | |
| **clientdebtchange** | Patient payment history | clientid, clientdebtchangeamount, clientdebtchangedate, processname | |
| **dailyentry** | Accounting journal headers | id, totalcreditor, totaldebtor, entryComment | |
| **dailyentrycreditor** | Credit entries | dailyentryid, accountstreeid, value, dComment | |
| **dailyentrydebtor** | Debit entries | dailyentryid, accountstreeid, value, dComment |
๐ Key Functions
1. Default Action - Examination Registration Form
Location: Line 101
Purpose: Display examination registration form with required data
Setup Process:
$today = date('Y-m-d');
$customer = $ClientDAO->queryAll(); // All patients
$Doctor = $doctorDAOEx->loadDocotr(4); // Type 4 = doctors
$clientarea = $ClientareaDAO->queryAll(); // Patient areas
// Generate new examination ID
$kashfDetails = $kashfDAO->queryAll();
$last_obj = end($kashfDetails);
$new_id = $last_obj->id + 1;
$smarty->assign('new_id', $new_id);
2. add - Create Medical Examination
Location: Line 133
Purpose: Process new medical examination with complete financial integration
Function Logic:
function add() {
// Extract form data
$customerid = filter_input(INPUT_POST, 'client');
$datetoday = filter_input(INPUT_POST, 'kashfdate');
$docselect = filter_input(INPUT_POST, 'docselect');
$kashf_value = (float) filter_input(INPUT_POST, 'kashf_value');
$kasf_type = filter_input(INPUT_POST, 'kasf_type');
$paytype = 2; // Fixed: payment completed
// Validation checks
if ($customerid == '-1') {
// Show error: invalid customer
return;
}
if ($docselect == '-1') {
// Show error: invalid doctor
return;
}
if ($datetoday < date('Y-m-d')) {
// Show error: invalid date
return;
}
// Create examination record
$kashf->kashfvalue = $kashf_value;
$kashf->kashftype = $kasf_type;
$kashf->customerid = $customerid;
$kashf->doctorid = $docselect;
$kashf->kashfdate = $datetoday;
$kashf->paystatus = $paytype;
$kashf->entered = 0;
$kashf->dailyentryid = 0;
$kashId = $kashfDAO->insert($kashf);
}
Client Debt Tracking Integration:
// Load last client debt change for continuity
$last_client_deptchaneg = $clientDeptChangeExt->selectLastClientDept($customerid);
if (!empty($customerid)) {
// Create debt change record (no amount change for examination booking)
$clientDeptChange->clientdebtchangeafter = $last_client_deptchaneg[0]->clientdebtchangeafter;
$clientDeptChange->clientdebtchangeamount = 0; // No debt change
$clientDeptChange->clientdebtchangebefore = $last_client_deptchaneg[0]->clientdebtchangebefore;
$clientDeptChange->clientdebtchangemodelid = $kashId;
$clientDeptChange->processname = "ุฅุถุงูุฉ ูุดู ุฌุฏูุฏ";
$clientDeptChange->tablename = "rb_kashf.php";
$clientDeptChangeDAO->insert($clientDeptChange);
}
Accounting Integration:
// Create journal entry for examination income
$dailyEntry->entryComment = 'ุชู
ุญุฌุฒ ูุดู ุจุตุฑูุงุช';
// Debit: Cash Register (money received)
$dailyEntryDebtor->value = $kashf_value;
$saveid = $_SESSION['saveid'];
$dataSave = $mySaveRecord->load($saveid);
$idTreeSave = $dataSave->treeId;
$dailyEntryDebtor->accountstreeid = $idTreeSave;
// Credit: Medical Services Income Account (fixed account 273)
$dailyEntryCreditor->value = $kashf_value;
$dailyEntryCreditor->accountstreeid = 273;
// Execute journal entry
$returnDailyId = insertEntery($dailyEntry, [$dailyEntryDebtor], [$dailyEntryCreditor]);
$dailyId = $returnDailyId[1];
// Update examination with journal entry ID
$kashf->dailyentryid = $dailyId;
$kashfDAO->update($kashf);
Cash Register Update:
// Update cash register balance
$saveDatat = $mySaveRecord->load($saveid);
$mySave->savecurrentvalue = ($saveDatat->savecurrentvalue + $kashf_value);
$mySaveRecord->update($mySave);
// Log cash register transaction
$mySavedaily->savedailychangeamount = $kashf_value;
$mySavedaily->savedailychangetype = 0; // Increase
$mySavedaily->processname = 'ุชู
ุญุฌุฒ ูุดู ุจุตุฑูุงุช';
$mySavedaily->savedailymodelid = $kashId;
$mySavedaily->savedailysaveafter = ($saveDatat->savecurrentvalue + $kashf_value);
$mySavedaily->savedailysavebefore = $saveDatat->savecurrentvalue;
$mySavedaily->tablename = 'rb_kashf.php';
$mySavedailyRecord->insert($mySavedaily);
---
3. show - Display Examinations List
Location: Line 347
Purpose: Show all examinations with customer and doctor details
Data Processing:
$showkashf = $kashfDAOEx->queryAllDESC();
foreach ($showkashf as $kdata) {
$custid = $kdata->customerid;
$docid = $kdata->doctorid;
// Load customer information
$custData = $ClientDAO->load($custid);
$kdata->custname = $custData->clientname;
// Load doctor information
$docdata = $doctorDAOEx->loadDocotr2($docid, 4);
$kdata->DocData = $docdata->username;
}
---
4. update - Examination Modification
Location: Line 434
Purpose: Update examination with accounting transaction reversal and recreation
Complex Update Logic:
function update() {
$custselect = filter_input(INPUT_POST, 'custselect');
$docselect = filter_input(INPUT_POST, 'docselect');
$kashf_value = filter_input(INPUT_POST, 'kashf_value');
$kashfid = filter_input(INPUT_POST, 'kashfid');
$oldCustomer = filter_input(INPUT_POST, 'client');
if ($oldCustomer == $custselect) {
// Same customer - simple update
$loadkashf2 = $kashfDAO->load($kashfid);
$loadkashf2->kashfvalue = $kashf_value;
$loadkashf2->kashftype = $kasf_type;
$loadkashf2->doctorid = $docselect;
// Reverse old accounting entry
$dailyId1 = $loadkashf2->dailyentryid;
reverseEntryWithItsID($dailyId1);
// Create new accounting entry with updated values
$dailyEntry->entryComment = 'ุชู
ุชุนุฏูู ุงููุดู ';
$returnDailyId = insertEntery($dailyEntry, $dailyEntryDebtorArray, $dailyEntryCreditorArray);
$dailyId2 = $returnDailyId[1];
$loadkashf2->dailyentryid = $dailyId2;
$kashfDAO->update($loadkashf2);
} else {
// Customer changed - more complex update
// Full validation and re-creation process
}
}
---
5. delete - Examination Deletion
Location: Line 870
Purpose: Delete examination and reverse all associated transactions
Deletion Process:
elseif ($do == 'delete') {
// Delete examination record
$kashfDAO->delete($id);
// Reverse associated journal entry
reverseEntryWithItsID($dilEntry);
// Note: Cash register and debt changes are reversed via journal entry reversal
header('location:?do=show');
}
---
๐ Workflows
Workflow 1: Complete Medical Examination Registration
---
Workflow 2: Examination Update with Transaction Reversal
---
๐ฐ Financial Integration Details
Chart of Accounts Integration
// Cash Register Account (Dynamic - based on user's assigned register)
$saveid = $_SESSION['saveid'];
$dataSave = $mySaveRecord->load($saveid);
$cashAccountId = $dataSave->treeId;
// Medical Services Income Account (Fixed)
$medicalIncomeAccountId = 273;
// Journal Entry Structure:
// DR: Cash Register Account $examination_fee
// CR: Medical Services Account $examination_fee
Client Debt vs Cash Payment Logic
// Current Implementation: Immediate Cash Payment
$clientDeptChange->clientdebtchangeamount = 0; // No debt created
$mySave->savecurrentvalue += $kashf_value; // Cash added immediately
// Alternative: Credit/Debt System (for future implementation)
// $clientDeptChange->clientdebtchangeamount = $kashf_value; // Create debt
// Cash received only when payment made separately
Account Balance Effects
Before Examination:
- Cash Register Balance: $1,000
- Medical Income Account: $5,000
After $100 Examination:
- Cash Register Balance: $1,100 (+$100)
- Medical Income Account: $5,100 (+$100)
Journal Entry:
DR: Cash Register (Asset) $100
CR: Medical Income (Revenue) $100
---
๐ Security & Data Validation
Input Validation
// Date validation
$datetoday = filter_input(INPUT_POST, 'kashfdate');
$now = new DateTime();
$date = $now->format('Y-m-d');
if ($kashfdate < $date) {
// Show error: future dates only
}
// Amount validation
$kashf_value = (float) filter_input(INPUT_POST, 'kashf_value');
if ($kashf_value <= 0) {
// Show error: positive amounts only
}
// Entity validation
if ($customerid == '-1' || $docselect == '-1') {
// Show error: valid selections required
}
Transaction Integrity
- โข All operations wrapped in database transactions
- โข Journal entries automatically balance debit/credit
- โข Cash register updates linked to journal entries
- โข Reversal operations maintain audit trail
Access Control
- โข Requires active user session
- โข Doctor selection limited to user type 4
- โข Cash register access controlled by user assignment
---
๐ Performance Considerations
Database Optimization
1. Critical Indexes:
CREATE INDEX idx_kashf_customer ON kashf(customerid, kashfdate);
CREATE INDEX idx_kashf_doctor ON kashf(doctorid, kashfdate);
CREATE INDEX idx_savedaily_kashf ON savedaily(savedailymodelid, tablename);
CREATE INDEX idx_clientdebt_kashf ON clientdebtchange(clientdebtchangemodelid, tablename);
```
2. **Query Patterns**:
- Frequent lookups by customer and doctor
- Date range filtering for reporting
- Cash register transaction tracking
### Memory Management
- Limited result sets for dropdown lists
- Efficient object loading for edit operations
- Minimal template variable assignment
---
## ๐ Common Issues & Troubleshooting
### 1. **Journal Entry Imbalance**
**Issue**: Debits don't equal credits error
**Cause**: Currency conversion or calculation error
**Debug**:
php
echo "Debit Amount: " . $dailyEntryDebtor->value;
echo "Credit Amount: " . $dailyEntryCreditor->value;
echo "Examination Fee: " . $kashf_value;
### 2. **Cash Register Balance Issues**
**Issue**: Cash register shows incorrect balance
**Cause**: Failed transaction or reversal issue
**Debug**:
php
$saveData = $mySaveRecord->load($_SESSION['saveid']);
echo "Current Balance: " . $saveData->savecurrentvalue;
// Check recent transactions
$recentTransactions = R::getAll("SELECT * FROM savedaily
WHERE tablename = 'rb_kashf.php'
ORDER BY savedailydate DESC LIMIT 10");
### 3. **Customer/Doctor Not Loading**
**Issue**: Dropdowns show empty or wrong data
**Cause**: Query filtering or deleted records
**Debug**:
php
// Check doctor query
$doctors = $doctorDAOEx->loadDocotr(4);
echo "Doctor Count: " . count($doctors);
// Check customer query
$customers = $ClientDAO->queryAll();
echo "Customer Count: " . count($customers);
### 4. **Update Errors**
**Issue**: Examination update fails or creates duplicates
**Cause**: Transaction reversal failure
**Debug**:
php
echo "Original Journal Entry ID: " . $originalKashf->dailyentryid;
echo "New Journal Entry ID: " . $newDailyEntryId;
// Check reversal status
$originalEntry = $dailyEntryDAO->load($originalKashf->dailyentryid);
echo "Reversal Status: " . $originalEntry->reverseofid;
---
## ๐ฑ Print & Display Features
### Print Formatting
php
if ($do == 'editprint') {
// Load examination data for print format
$editkasf = $kashfDAO->load($id);
// Load related data
$custData = $ClientDAO->load($editkasf->customerid);
$docdata = $doctorDAOEx->loadDocotr2($editkasf->doctorid, 4);
// Display print template
$smarty->display('rb_kashf/kashf_editprint.html');
}
### Custom Display Variable
php
// Special template variable for kashf functionality
$smarty->assign("customKashf", 1);
// Used in templates for:
// - Special CSS styling
// - Custom navigation elements
// - Kashf-specific UI components
---
## ๐งช Testing Scenarios
### Test Case 1: Basic Examination Creation
1. Access examination form
2. Select valid patient and doctor
3. Enter examination fee and type
4. Submit form
5. Verify examination created
6. Check cash register balance increased
7. Verify journal entry created
8. Check client debt change record
### Test Case 2: Examination Update
1. Edit existing examination
2. Change examination fee amount
3. Verify original transaction reversed
4. Verify new transaction created
5. Check cash register balance adjusted correctly
6. Verify journal entries balanced
### Test Case 3: Examination Deletion
1. Delete examination record
2. Verify examination marked as deleted
3. Check journal entry reversal
4. Verify cash register balance decreased
5. Check audit trail maintained
### Test Case 4: Validation Testing
1. Submit form with invalid customer (-1)
2. Verify error message displayed
3. Submit with past date
4. Verify date validation error
5. Submit with zero amount
6. Verify amount validation error
```
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข dailyentryfun.md - Accounting journal functions
- โข clientController.php - Patient management
- โข Medical Practice Management Guide - Best practices for medical systems
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When medical examination workflow changes