Daily Entry Functions Controller Documentation
File: /controllers/dailyentryfun.php
Purpose: Core accounting utility functions for managing daily journal entries, accounts tree, and accounting operations
Last Updated: December 20, 2024
Total Functions: 25+
Lines of Code: ~858
---
๐ Overview
The Daily Entry Functions Controller serves as the backbone of the accounting system, providing essential utility functions for:
- โข Daily journal entry management (debit/credit transactions)
- โข Chart of accounts (accounts tree) management
- โข Account balance calculations and updates
- โข Double-entry bookkeeping enforcement
- โข Transaction reversal and correction
- โข Cost center detail tracking
- โข Account value affection based on account type
Primary Functions
- โ Insert complex journal entries with multiple debits/credits
- โ Manage accounts tree structure (add/delete/restore elements)
- โ Enforce accounting equation balance (debits = credits)
- โ Reverse journal entries by ID or comment
- โ Calculate running account balances
- โ Handle cost center allocations
- โ Support transaction rollback on errors
- โ Validate unique account names within parent groups
- โ Automatic account value updates based on account type
Related Controllers
- โข dailyentrymany.php - Bulk daily entry creation
- โข sellbillController.php - Sales transaction entries
- โข buyBillController.php - Purchase transaction entries
- โข clientPayedDeptController.php - Customer payment entries
- โข expensesController.php - Expense transaction entries
---
๐๏ธ Database Tables
Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns | |
|---|---|---|---|
| **accountstree** | Chart of accounts master | id, name, parent, itemtype, itemtype2, theValue, userid, reportid | |
| **dailyentry** | Journal entry headers | id, totalcreditor, totaldebtor, thedate, userid, entryComment, operationId | |
| **dailyentrycreditor** | Credit side entries | id, dailyentryid, accountstreeid, value, dComment, costcenterid | |
| **dailyentrydebtor** | Debit side entries | id, dailyentryid, accountstreeid, value, dComment, costcenterid | |
| **costcenter** | Cost center master data | id, name, description | |
| **costcenterdetail** | Cost center allocations | id, costcenterid, costamount, modelid, tablename, type |
| Type | Description | Nature | |
|---|---|---|---|
| **0** | ู ุตุฑููุงุช (Expenses) | Debit balance | |
| **1** | ุฎุตูู (Liabilities) | Credit balance | |
| **2** | ุฅูุฑุงุฏุงุช (Income) | Credit balance | |
| **3** | ุฃุตูู (Assets) | Debit balance | |
| **4** | ุญููู ุงูู ูููุฉ (Equity) | Credit balance | |
| **5** | ู ุณุญูุจุงุช (Drawings) | Debit balance |
๐ Key Functions
1. addTreeElement() - Add Account to Chart
Location: Line 94
Purpose: Add new account to the chart of accounts with validation
Function Signature:
function addTreeElement($name, $parent, $itemtype, $itemfrom, $itemtype2, $notes = '', $theOrder = 0, $theValue = 0, $reportid = 0)
Parameters:
- โข
$name- Account name (required, must be unique within parent) - โข
$parent- Parent account ID (0 = root level) - โข
$itemtype- Account type (0-5, see table above) - โข
$itemfrom- Source (0=program, 1=tree only) - โข
$itemtype2- Level (0=parent, 1=leaf account) - โข
$notes- Optional description - โข
$theOrder- Display order - โข
$theValue- Initial balance (for leaf accounts) - โข
$reportid- Report group ID
Return Values:
- โข
{id}- Success, returns new account ID - โข
-1- Error, duplicate name
Validation:
- โข Checks name uniqueness within parent using
isUniqueName() - โข Inherits parent's account nature and list ID
- โข Sets default report ID (2 for expenses/income)
---
2. insertEntery() - Create Journal Entry
Location: Line 337
Purpose: Insert complete double-entry journal transaction with validation
Function Signature:
function insertEntery($dailyEntryObj = NULL, $dailyEntryDebtorArray, $dailyEntryCreditorArray, $stopEntryTransaction = 0, $operationId = 0, $operationDetailLink = '')
Process Flow:
1. Validation: Ensure total debits = total credits and โ 0
2. Entry Header: Create dailyentry record with totals and metadata
3. Debit Entries: Process each debit line item
- Insert dailyentrydebtor record
- Update account balance via affectAccount()
- Handle cost center allocation if specified
- Execute plugin effects if fromFlag = 2
4. Credit Entries: Process each credit line item (same pattern)
5. Transaction Control: Commit on success, rollback on failure
Return Values:
- โข
[1, {entryId}]- Success with new entry ID - โข
[-1, 0]- Error: debits โ credits or zero amount - โข
[-2, 0]- Error: database exception
Features:
- โข Automatic transaction wrapping (unless nested)
- โข Cost center detail creation
- โข Plugin system integration
- โข Account balance updates
- โข Branch assignment from session
---
3. reverseEntryWithItsID() - Reverse Journal Entry
Location: Line 495
Purpose: Create reversing entry to cancel out original transaction
Function Signature:
function reverseEntryWithItsID($id, $stopEntryTransaction = 0)
Process Flow:
1. Load original entry and validate not already reversed
2. Mark original entry as reversed (reverseofid = -10)
3. Create new entry with reversed debits/credits:
- Original debits โ new credits
- Original credits โ new debits
4. Update account balances with reversed amounts
5. Set comment: "ุชู ุนูุณ ุงูููุฏ ุฑูู {id}"
Reversal Status Codes:
- โข
0- Normal entry - โข
{positive}- This entry reverses entry #{positive} - โข
-9- Manually marked as reversed - โข
-10- Automatically reversed by system
---
4. affectAccount() - Update Account Balance
Location: Line 759
Purpose: Update account balance based on transaction type and account nature
Function Signature:
function affectAccount($CreditorOrDebtorObj, $type)
Account Effect Logic:
// For Assets (3), Expenses (0), Drawings (5):
if ($type == 0) { // Debit side
$operation = 'increase'; // Normal balance side
} else { // Credit side
$operation = 'decrease'; // Contra balance side
}
// For Liabilities (1), Income (2), Equity (4):
if ($type == 0) { // Debit side
$operation = 'decrease'; // Contra balance side
} else { // Credit side
$operation = 'increase'; // Normal balance side
}
Parameters:
- โข
$CreditorOrDebtorObj- Entry line object with accountstreeid, value - โข
$type- 0=debit entry, 1=credit entry
---
5. insertCostCenterDetail() - Track Cost Allocations
Location: Line 820
Purpose: Record cost center allocation for management reporting
Function Signature:
function insertCostCenterDetail($Costcenterid, $val, $dailyentryid, $comment, $controllerName, $costCenterType = -1)
Purpose: Links specific amounts to cost centers for:
- โข Project cost tracking
- โข Department expense analysis
- โข Activity-based costing
- โข Management reporting
---
๐ Workflows
Workflow 1: Complete Journal Entry Creation
---
Workflow 2: Account Tree Management
---
๐ Usage Examples
Example 1: Simple Expense Entry
// Record office supplies expense paid from cash
$dailyEntry = new Dailyentry();
$dailyEntry->entryComment = 'Office supplies purchase';
// Debit: Office Supplies Expense
$debitEntry = new Dailyentrydebtor();
$debitEntry->accountstreeid = 150; // Office Supplies account
$debitEntry->value = 500.00;
$debitEntry->dComment = 'Printer paper and pens';
// Credit: Cash Account
$creditEntry = new Dailyentrycreditor();
$creditEntry->accountstreeid = 101; // Cash account
$creditEntry->value = 500.00;
$creditEntry->dComment = 'Payment for supplies';
$result = insertEntery($dailyEntry, [$debitEntry], [$creditEntry]);
// Returns: [1, 1234] where 1234 is the new entry ID
Example 2: Sales Transaction Entry
// Record cash sale with multiple accounts affected
$dailyEntry = new Dailyentry();
$dailyEntry->entryComment = 'Cash sale - invoice #12345';
$dailyEntry->operationId = 12345;
$dailyEntry->operationDetailLink = 'sellbillController.php?id=12345';
// Debit entries
$debitEntries = [];
// Cash received
$cashDebit = new Dailyentrydebtor();
$cashDebit->accountstreeid = 101; // Cash
$cashDebit->value = 1150.00;
$debitEntries[] = $cashDebit;
// Credit entries
$creditEntries = [];
// Sales revenue
$salesCredit = new Dailyentrycreditor();
$salesCredit->accountstreeid = 201; // Sales Revenue
$salesCredit->value = 1000.00;
$creditEntries[] = $salesCredit;
// Sales tax
$taxCredit = new Dailyentrycreditor();
$taxCredit->accountstreeid = 210; // Sales Tax Payable
$taxCredit->value = 150.00;
$creditEntries[] = $taxCredit;
$result = insertEntery($dailyEntry, $debitEntries, $creditEntries);
---
๐ Security & Permissions
User Access Control
- โข All functions respect
$_SESSION['userid']for audit trail - โข Account access controlled by user permissions
- โข Branch-level data separation via
$_SESSION['branchId']
Data Validation
- โข Account name uniqueness enforced within parent groups
- โข Numeric validation on amounts (no negative values in core functions)
- โข Account tree integrity maintained (parent-child relationships)
- โข Double-entry validation (debits = credits) strictly enforced
Transaction Safety
- โข Database transactions wrap multi-table operations
- โข Automatic rollback on any failure
- โข Reversal entries maintain audit trail
- โข No direct balance updates without journal entries
---
๐ Performance Considerations
Database Optimization
1. Indexes Required:
- accountstree(parent, del, name)
- accountstree(parent, del, customName)
- dailyentry(operationId)
- dailyentrycreditor(dailyentryid)
- dailyentrydebtor(dailyentryid)
2. Query Patterns:
- Frequent parent-child traversal in accounts tree
- Entry detail lookups by dailyentryid
- Account balance updates (single row updates)
Memory Management
- โข Large journal entries with many line items require adequate PHP memory
- โข Cost center processing adds overhead for each line item
- โข Plugin system execution can be resource-intensive
---
๐ Common Issues & Troubleshooting
1. "ูุงุจุฏ ุงู ูููู ู ุฌู ูุน ู ุฏูู ูุณุงูู ู ุฌู ูุน ุฏุงุฆู" Error
Issue: Debits don't equal credits validation failure
Cause: Rounding errors or incorrect amount calculation
Debug:
$totalDebits = getTotal($dailyEntryDebtorArray);
$totalCredits = getTotal($dailyEntryCreditorArray);
echo "Debits: $totalDebits, Credits: $totalCredits";
2. "ุงุณู ุงูุนูุตุฑ ู ูุฑุฑ" Error
Issue: Account name already exists in parent group
Cause: Trying to create duplicate account name
Fix:
// Check before creating
$isUnique = isUniqueName($accountName, $parentId);
if (!$isUnique) {
// Handle duplicate - maybe append suffix or use different name
}
3. Account Balance Calculation Errors
Issue: Account balances don't match expected values
Cause: Missing entries or incorrect account type logic
Debug:
// Check account type and recent entries
$account = $accountsTreeDAO->load($accountId);
echo "Account Type: " . $account->itemtype;
echo "Current Balance: " . $account->theValue;
// Check recent entries affecting this account
$recentDebits = $dailyEntryDebtorDAO->queryByAccountstreeid($accountId);
$recentCredits = $dailyEntryCreditorDAO->queryByAccountstreeid($accountId);
4. Transaction Rollback Issues
Issue: Partial entries created despite errors
Cause: Nested transaction handling or missing try-catch
Fix:
// Always use transaction wrapper
$transaction = new Transaction();
try {
// Your journal entry operations
insertEntery($entry, $debits, $credits, 1); // stopEntryTransaction = 1
$transaction->commit();
} catch (Exception $e) {
$transaction->rollback();
// Handle error appropriately
}
---
๐งช Testing Scenarios
Test Case 1: Basic Double-Entry Validation
1. Create entry with unbalanced debits/credits
2. Verify function returns [-1, 0]
3. Create entry with balanced amounts
4. Verify function returns [1, {id}]
5. Check database for correct entry creation
Test Case 2: Account Tree Hierarchy
1. Create parent account (itemtype2 = 0)
2. Create child accounts under parent
3. Test name uniqueness within parent
4. Verify inheritance of parent properties
5. Test account deletion and restoration
Test Case 3: Reversal Functionality
1. Create normal journal entry
2. Record original entry ID
3. Reverse the entry using reverseEntryWithItsID()
4. Verify original marked as reversed (reverseofid = -10)
5. Verify new reversing entry created
6. Check account balances return to pre-entry state
Test Case 4: Cost Center Integration
1. Create entry with cost center assignments
2. Verify costcenterdetail records created
3. Check cost allocation amounts match entry amounts
4. Test cost center reporting accuracy
---
๐ Related Documentation
- โข CLAUDE.md - PHP 8.2 migration guide
- โข dailyentrymany.md - Bulk entry operations
- โข Database Schema Documentation - Complete table relationships
- โข Accounting Principles Guide - Double-entry bookkeeping rules
---
Documented By: AI Assistant
Review Status: โ Complete
Next Review: When accounting logic changes occur