# Daily Entry (Journal Entry) Controller Documentation

**File**: `/controllers/dailyentry.php`  
**Purpose**: Manages journal entries for double-entry bookkeeping system  
**Last Updated**: December 19, 2024  
**Total Functions**: 8  
**Lines of Code**: 755

---

## 📋 Overview

The Daily Entry Controller is the core component for managing journal entries in the double-entry bookkeeping system. It handles:
- Manual journal entry creation and management
- Automated journal entries from sales/purchase transactions
- Entry reversal and correction functionality
- Opening balance entries
- Multi-branch journal entry support
- Account balance calculations and updates
- Cost center allocation
- Debit/credit balance validation
- Entry search and filtering
- Journal entry reporting and printing

### Primary Functions
- [x] Create manual journal entries (debit/credit)
- [x] Display journal entry listing with filters
- [x] Reverse journal entries with automatic posting
- [x] Opening balance entry management
- [x] Multi-branch support
- [x] Cost center integration
- [x] Account balance updates
- [x] Entry printing and reporting
- [x] Date range filtering
- [x] Account-specific filtering

### Related Controllers
- [accountstree.php](accountstree.md) - Chart of accounts structure
- [sellbillController.php](sellbillController.md) - Auto journal entries from sales
- [buyBillController.php](buyBillController.md) - Auto journal entries from purchases
- [expensesController.php](#) - Expense journal entries
- [saveController.php](#) - Cash transaction entries
- [bankController.php](#) - Bank transaction entries

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **dailyentry** | Main journal entries | id, thedate, totalcreditor, totaldebtor, entryComment, userid, branchid, related, reverseofid |
| **dailyentrycreditor** | Credit side entries | dailyentryid, accountstreeid, value, dComment, costcenterid |
| **dailyentrydebtor** | Debit side entries | dailyentryid, accountstreeid, value, dComment, costcenterid |

### Integration Tables  
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **accountstree** | Chart of accounts | Referenced by creditor/debtor entries |
| **costcenter** | Cost centers | Referenced by creditor/debtor entries |
| **branch** | Branch management | Multi-branch support |
| **programsetting** | System configuration | Entry behavior settings |

### Financial Impact Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **savedaily** | Cash movements | Auto-posted from cash entries |
| **accountmovement** | Account movements | Auto-posted from bank entries |
| **sellbill** | Sales transactions | Generate automatic entries |
| **buybill** | Purchase transactions | Generate automatic entries |

---

## 🔧 Key Functions

### 1. Main Display (Default Action)
**Purpose**: Display journal entry interface with entry listing  
**Line**: 214  

**Parameters** (via $_POST):
- `dailyentryid` - Specific entry ID(s) to display
- `datefrom` - Start date filter
- `dateto` - End date filter
- `layingOrder` - Account filter
- `branchid` - Branch filter

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Update Branch   │───▶│ Load Filters &   │───▶│ Generate Entry  │
│ IDs for Users   │    │ User Data        │    │ Listing Table   │
└─────────────────┘    └──────────────────┘    └─────────────────┘
          │                       │                       │
          ▼                       ▼                       ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Load Cost       │    │ Default to       │    │ Display Main    │
│ Centers         │    │ Today's Date     │    │ Entry Form      │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

**Business Logic**:
- Updates branch IDs for entries without branches
- Loads cost centers for allocation
- Applies date filters (defaults to today)
- Generates comprehensive entry listing

### 2. DrawTableNew($dailyentryid, $startDate, $endDate, $layingOrder, $branchid, $print)
**Purpose**: Generate journal entry listing table with advanced formatting  
**Line**: 341

**Parameters**:
- `$dailyentryid` (string) - Comma-separated entry IDs
- `$startDate` (date) - Filter start date
- `$endDate` (date) - Filter end date  
- `$layingOrder` (string) - Account code filter
- `$branchid` (int) - Branch ID filter
- `$print` (int) - Print mode flag (0=screen, 1=print)

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Build Query     │───▶│ Get Daily Entry  │───▶│ Load Credit/    │
│ Filters         │    │ Records          │    │ Debit Details   │
└─────────────────┘    └──────────────────┘    └─────────────────┘
          │                       │                       │
          ▼                       ▼                       ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Format for      │    │ Merge Entry      │    │ Assign to       │
│ Print/Screen    │    │ Data Structure   │    │ Smarty Template │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

**Advanced Features**:
- Optimized SQL queries with proper joins
- Memory-efficient array indexing
- Print-friendly date formatting
- Integrated debit/credit display

### 3. reverse()
**Purpose**: Reverse a journal entry by creating opposite entry  
**Line**: 591

**URL**: `?do=reverse&id={entry_id}`

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Load Original   │───▶│ Check Reverse    │───▶│ Create New      │
│ Entry Data      │    │ Status           │    │ Entry Header    │
└─────────────────┘    └──────────────────┘    └─────────────────┘
          │                       │                       │
          ▼                       ▼                       ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Reverse Debit   │◀───│ Update Account   │◀───│ Swap Debit/     │
│ Entries to      │    │ Balances         │    │ Credit Sides    │
│ Credit          │    │                  │    │                 │
└─────────────────┘    └──────────────────┘    └─────────────────┘
          │                       │                       │
          ▼                       ▼                       ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Reverse Credit  │    │ Apply Plugin     │    │ Mark Original   │
│ Entries to      │    │ Effects          │    │ as Reversed     │
│ Debit           │    │                  │    │ (reverseofid=-10)│
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

**Critical Business Rules**:
- Can only reverse entries once (reverseofid != -10)
- Creates new entry with swapped debit/credit sides
- Updates account balances automatically
- Applies plugin effects for cash/bank accounts
- Links reversal to original entry

### 4. affectAccount($CreditorOrDebtorObj, $type)
**Purpose**: Update account balances based on journal entry  
**Line**: 668

**Parameters**:
- `$CreditorOrDebtorObj` - Credit or debit entry object
- `$type` - Entry type (0=debit, 1=credit)

**Double-Entry Logic**:
```
Account Type + Entry Side = Balance Effect
┌─────────────┬─────────────┬─────────────┐
│ Account     │ Debit Entry │ Credit Entry│
│ Type        │ Effect      │ Effect      │
├─────────────┼─────────────┼─────────────┤
│ Assets (0)  │ Increase    │ Decrease    │
│ Liabilities │ Decrease    │ Increase    │
│ (1)         │             │             │
│ Equity (2)  │ Decrease    │ Increase    │
│ Expenses(3) │ Increase    │ Decrease    │
│ Revenue (4) │ Decrease    │ Increase    │
│ Cost (5)    │ Increase    │ Decrease    │
└─────────────┴─────────────┴─────────────┘
```

### 5. whatToDo($accountType, $numSign, $type)
**Purpose**: Determine if account balance should increase or decrease  
**Line**: 691

**Parameters**:
- `$accountType` (int) - Account classification (0-5)
- `$numSign` (string) - Always 'positive'
- `$type` (int) - Entry type (0=debit, 1=credit)

**Returns**: 'increase' or 'decrease'

### 6. openingentry
**Purpose**: Display opening balance entry form  
**Line**: 286

**Process**:
- Loads all leaf accounts (final level accounts)
- Applies visibility filters for clients/suppliers
- Displays opening balance entry interface

### 7. openingbalance  
**Purpose**: Display opening balance management interface  
**Line**: 307

**Process**:
- Similar to opening entry but for balance management
- Supports bulk opening balance entry

### 8. print
**Purpose**: Generate printable journal entry report  
**Line**: 264

**Process**:
- Uses same filtering as main display
- Formats for print layout
- Generates printer-friendly output

---

## 🔄 Business Logic Flow

### Journal Entry Creation Workflow
```
User Input
    │
    ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Validate        │───▶│ Create Daily     │───▶│ Create Debit    │
│ Debit = Credit  │    │ Entry Header     │    │ Side Entries    │
└─────────────────┘    └──────────────────┘    └─────────────────┘
    │                           │                       │
    ▼                           ▼                       ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Error if        │    │ Set Entry Date   │    │ Create Credit   │
│ Unbalanced      │    │ & User Info      │    │ Side Entries    │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                │                       │
                                ▼                       ▼
                    ┌──────────────────┐    ┌─────────────────┐
                    │ Update Account   │    │ Apply Plugin    │
                    │ Balances         │    │ Effects         │
                    └──────────────────┘    └─────────────────┘
```

### Entry Reversal Workflow
```
Reversal Request
    │
    ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Check if        │───▶│ Mark Original    │───▶│ Create Reverse  │
│ Already Reversed│    │ as Reversed      │    │ Entry Header    │
└─────────────────┘    └──────────────────┘    └─────────────────┘
    │                           │                       │
    ▼                           ▼                       ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Exit if         │    │ reverseofid=-10  │    │ Swap Debit/     │
│ Already         │    │                  │    │ Credit Amounts  │
│ Reversed        │    │                  │    │                 │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

### Double-Entry Bookkeeping Rules

**Fundamental Equation**: Assets = Liabilities + Equity

**Entry Rules**:
1. **Every entry must balance** (Total Debits = Total Credits)
2. **Account nature determines effect**:
   - Debit increases: Assets, Expenses, Cost of Sales
   - Credit increases: Liabilities, Equity, Revenue
3. **Journal entries auto-update account balances**
4. **Reversals create exact opposite entries**

---

## ⚠️ Common Issues

### 1. Unbalanced Entries
**Issue**: Total debits ≠ total credits  
**Prevention**: Client-side validation before submission  
**Fix**: System should reject unbalanced entries

### 2. Branch Assignment
**Issue**: Entries created without branch assignment  
**Solution**: System auto-updates entries with user's branch ID:
```php
// Auto-update branch IDs for entries without branches
$allnothavebranch = $dailyEntryEX->queryAllnothavebranch();
foreach ($allnothavebranch as $entry) {
    $dailyEntryEX->updatebranchid($entry->value, $entry->id);
}
```

### 3. Account Balance Corruption
**Issue**: Manual balance changes cause inconsistency  
**Prevention**: Only update balances through journal entries  
**Fix**: Rebuild balances from journal entry history

### 4. Reversal Chain Issues
**Issue**: Attempting to reverse already reversed entries  
**Prevention**: Check reverseofid status before reversal:
```php
if ($olddailyEntry->reverseofid != -10) {
    // Proceed with reversal
}
```

### 5. Cost Center Allocation
**Issue**: Missing cost center assignments  
**Solution**: Validate cost center requirements for expense accounts

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/authentication.php` - Security
- `affectplugins.php` - Plugin system integration
- `dailyentryfun.php` - Daily entry utilities
- `../models/sql/Transaction.class.php` - Database transactions

### Critical DAOs
- `DailyentryDAO` - Main entry operations
- `DailyentrycreditorDAO` - Credit side management
- `DailyentrydebtorDAO` - Debit side management
- `AccountstreeDAO` - Account balance updates
- `CostcenterDAO` - Cost center operations

### Plugin Integration
The system includes `affectplugins.php` which handles:
- Cash register updates for cash accounts
- Bank account balance synchronization
- Supplier/client balance updates
- Inventory valuation adjustments

---

## 🎯 Entry Types and Status Codes

### Entry Status (condition)
- **0**: Active entry
- **1**: Draft entry (not posted)

### Reverse Status (reverseofid)
- **0**: Normal entry (not reversed/reversal)
- **Positive number**: Entry ID this is a reversal of
- **-10**: Entry has been reversed (cannot be reversed again)

### Entry Source (fromFlag)
- **0**: Manual journal entry
- **1**: Auto-generated from sales
- **2**: Auto-generated from purchases
- **3**: Auto-generated from expenses
- **4**: Auto-generated from cash transactions
- **5**: Auto-generated from bank transactions

### Related Entry Grouping (related)
- Groups related entries together (e.g., multiple entries from one transaction)

---

## 🎲 Best Practices

### 1. Entry Creation
- Always validate debit/credit balance before saving
- Include meaningful entry comments
- Assign appropriate cost centers for tracking
- Use consistent date formatting

### 2. Account Selection
- Use leaf accounts only (not parent accounts)
- Verify account nature matches entry intention
- Check account permissions for user access

### 3. Reversal Management
- Add clear reversal reasons in comments
- Check reversal permissions before allowing
- Maintain audit trail of all reversals

### 4. Multi-Branch Support
- Ensure proper branch assignment
- Filter entries by user branch permissions
- Maintain branch-specific reporting

---

**Critical Note**: This controller is the heart of the accounting system. All financial transactions flow through journal entries. Any modifications should preserve the double-entry bookkeeping integrity and maintain proper audit trails.