# Chart of Accounts Controller Documentation

**File**: `/controllers/accountstree.php`  
**Purpose**: Manages the hierarchical chart of accounts structure for the accounting system  
**Last Updated**: December 19, 2024  
**Total Functions**: 8  
**Lines of Code**: 686

---

## 📋 Overview

The Chart of Accounts Controller manages the complete financial account structure in the ERP system. It handles:
- Hierarchical account tree management (parent-child relationships)
- Account classification (assets, liabilities, equity, revenue, expenses)
- Account nature configuration (debit/credit)
- Account ordering and layout management
- Account tree visualization and reporting
- Excel import/export for account structure
- Opening balance management integration
- Tree level configuration (up to 6 levels deep)

### Primary Functions
- [x] Display hierarchical account tree
- [x] Add new accounts with parent-child relationships
- [x] Edit account properties and classifications
- [x] Delete accounts (with restrictions)
- [x] Excel import for bulk account creation
- [x] Excel export of account structure
- [x] Account tree configuration management
- [x] Opening balance entry support
- [x] Account ordering and layout management

### Related Controllers
- [dailyentry.php](#) - Journal entries using chart accounts
- [sellbillController.php](sellbillController.md) - Sales transactions
- [buyBillController.php](buyBillController.md) - Purchase transactions
- [expensesController.php](#) - Expense management
- [saveController.php](#) - Cash management
- [bankController.php](#) - Bank account management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **accountstree** | Main chart of accounts | id, customName, parent, itemtype, itemtype2, layingOrder, theValue, accountNature, reportid, listId |
| **accountstreesetting** | Tree level configuration | levelno, nooffields |
| **programsetting** | System configuration | Program-wide settings |

### Financial Integration Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **dailyentry** | Journal entries | Uses accountstree.id |
| **dailyentrycreditor** | Credit entries | Links to accountstree.id |
| **dailyentrydebtor** | Debit entries | Links to accountstree.id |
| **sellbill** | Sales transactions | Auto-creates journal entries |
| **buybill** | Purchase transactions | Auto-creates journal entries |
| **savedaily** | Cash movements | Links to cash accounts |

### Support Tables
| Table Name | Purpose | Relationship |
|------------|---------|--------------|
| **youtubelink** | Help videos | Training materials |
| **branch** | Branch management | Multi-branch support |

---

## 🔧 Key Functions

### 1. Main Display (Default Action)
**Purpose**: Display the main chart of accounts interface  
**Line**: 124  

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Load Tree Setup │───▶│ Generate 6 Levels│───▶│ Display Tree HTML│
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                 │
                      ┌──────────▼──────────┐
                      │ Calculate Values    │
                      │ Apply Permissions   │
                      │ Check Opening Goods │
                      └─────────────────────┘
```

**Key Operations**:
- Initializes 6-level tree structure
- Loads account tree settings
- Generates HTML tree display
- Applies user permissions for client/supplier visibility

### 2. display_children($parent, $level, $itr, $itr2)
**Purpose**: Recursive function to build hierarchical account tree display  
**Line**: 310

**Parameters**:
- `$parent` (int) - Parent account ID (0 for root)
- `$level` (int) - Current tree level (0-based)
- `$itr` (string) - Iteration string without zeros
- `$itr2` (string) - Iteration string with zeros

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Get Child Accounts│───▶│ Generate Layout  │───▶│ Build HTML Output│
└─────────────────┘    └──────────────────┘    └─────────────────┘
          │                       │                       │
          ▼                       ▼                       ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Calculate Order │    │ Update DB Layout │    │ Recurse Children│
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

**Business Logic**:
- Generates hierarchical account codes based on level settings
- Updates database laying order for search optimization
- Builds interactive tree HTML with edit/delete controls
- Calculates account values for parent accounts

### 3. set()
**Purpose**: Configure chart of accounts settings  
**Line**: 177

**Parameters** (via $_POST):
- `calTreeNodes` - Enable/disable tree node calculations
- `showClientsAtTree` - Show/hide client accounts in tree
- `showSuppliersAtTree` - Show/hide supplier accounts in tree
- `level1` to `level6` - Number of digits for each tree level

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Save Cookies    │───▶│ Update Level     │───▶│ Redirect to     │
│ (20 year expiry)│    │ Settings         │    │ Main View       │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

### 4. addTreeFromExcel()
**Purpose**: Import complete chart of accounts from Excel file  
**Line**: 492

**Excel Columns**:
- Column B: Account code
- Column D: Account name (Arabic)
- Column E: Account name (English)
- Column F: Item type 3
- Column G: Parent code
- Column H: Level
- Column Q: Account nature (مدين/دائن)
- Column R: Report list (ميزانية/قائمة الدخل)

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Upload Excel    │───▶│ Truncate Existing│───▶│ Parse Rows      │
│ File            │    │ Account Tree     │    │ (Start Row 2)   │
└─────────────────┘    └──────────────────┘    └─────────────────┘
          │                                              │
          ▼                                              ▼
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Transaction     │◀───│ Insert New       │◀───│ Map Parent      │
│ Commit/Rollback │    │ Accounts         │    │ Relationships   │
└─────────────────┘    └──────────────────┘    └─────────────────┘
```

**Critical Operations**:
- Truncates existing chart of accounts
- Maps parent-child relationships by laying order codes
- Converts Arabic nature text to numeric values
- Assigns proper report classifications

### 5. exportAsExcel()
**Purpose**: Export chart of accounts to Excel format  
**Line**: 225

**Excel Output Columns**:
- A: Account Code (layingOrder)
- B: Account Name
- C: Parent Name
- D: Account Nature (مدينة/دائنة)
- E: Report Type (متاجرة/ارباح و خسائر)
- F: Statement Type (ميزانية/قائمة الدخل)

**Features**:
- Color-coded rows by tree level
- Formatted borders and fonts
- Auto-sized columns
- Arabic text support

### 6. getTheTrueValue($parent, $sum)
**Purpose**: Calculate cumulative values for parent accounts  
**Line**: 411

**Logic**:
- Recursively sums child account values
- Respects visibility settings for clients/suppliers
- Updates parent account totals dynamically

### 7. checkStartGoods()
**Purpose**: Check if opening goods entry is needed  
**Line**: 464

**Process**:
- Checks if any sales/purchase bills exist
- Sets flag for opening balance requirement
- Integrates with opening entry functionality

### 8. exportToExcel($type, $level)
**Purpose**: Format individual account row for Excel export  
**Line**: 618

**Formatting**:
- Level-based color coding
- Proper data type handling
- Arabic text formatting

---

## 🔄 Business Logic Flow

### Account Tree Structure
The system uses a 6-level hierarchical structure:

```
Level 1: Main Categories (Assets, Liabilities, etc.)
├── Level 2: Sub-categories 
    ├── Level 3: Account Groups
        ├── Level 4: Sub-groups
            ├── Level 5: Account Types
                └── Level 6: Individual Accounts
```

### Account Classification System

#### Account Types (itemtype):
- **0**: Assets (اصول)
- **1**: Liabilities (خصوم)  
- **2**: Equity (حقوق الملكية)
- **3**: Expenses (مصروفات)
- **4**: Revenue (ايرادات)
- **5**: Cost of Sales (تكلفة المبيعات)

#### Account Nature (accountNature):
- **0**: Debit Nature (مدينة)
- **1**: Credit Nature (دائنة)

#### Report Classifications (reportid/listId):
- **1**: Balance Sheet (ميزانية)
- **2**: Income Statement (قائمة الدخل)

### Double-Entry Bookkeeping Integration

```
Account Nature + Transaction Type = Effect
┌─────────────┬─────────────┬─────────────┐
│ Nature      │ Debit Entry │ Credit Entry│
├─────────────┼─────────────┼─────────────┤
│ Debit (0)   │ Increase    │ Decrease    │
│ Credit (1)  │ Decrease    │ Increase    │
└─────────────┴─────────────┴─────────────┘
```

---

## ⚠️ Common Issues

### 1. Tree Level Configuration
**Issue**: Incorrect digit allocation for account codes  
**Solution**: Configure level settings with appropriate digit counts:
```php
Level 1: 2 digits (01, 02, 03...)
Level 2: 2 digits (0101, 0102...)
Level 3: 2 digits (010101, 010102...)
```

### 2. Excel Import Failures
**Issue**: Excel import truncates existing data  
**Prevention**: 
- Always backup before import
- Verify Excel format matches template
- Test with small dataset first

### 3. Account Code Conflicts
**Issue**: Duplicate laying order codes  
**Solution**: System auto-generates codes based on tree structure

### 4. Visibility Settings
**Issue**: Accounts hidden unexpectedly  
**Check**: Cookie settings for client/supplier visibility:
- `showClientsAtTree`
- `showSuppliersAtTree`

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/config.php` - System configuration
- `../public/include_dao.php` - Database layer
- `dailyentryfun.php` - Daily entry functions
- `../library/uploadImages.php` - File upload handling
- `../library/Classes/PHPExcel/IOFactory.php` - Excel processing

### Key DAOs
- `AccountstreeDAO` - Account CRUD operations
- `AccountstreesettingDAO` - Tree configuration
- `ProgramsettingsDAO` - System settings
- `SellbillDAO` - Sales integration
- `ReturnsellbillDAO` - Returns integration

### JavaScript Integration
- Tree expansion/collapse functionality
- Account editing modals
- AJAX account operations
- Dynamic value calculations

---

## 🎯 Account Tree Configuration

### Standard Account Structure
```
1. اصول (Assets)
   ├── 11. اصول متداولة (Current Assets)
   │   ├── 111. نقدية (Cash)
   │   └── 112. عملاء (Accounts Receivable)
   └── 12. اصول ثابتة (Fixed Assets)

2. خصوم (Liabilities)  
   ├── 21. خصوم متداولة (Current Liabilities)
   │   └── 211. موردين (Accounts Payable)
   └── 22. خصوم طويلة الأجل (Long-term Liabilities)

3. حقوق الملكية (Equity)
4. ايرادات (Revenue)
5. مصروفات (Expenses)
6. تكلفة المبيعات (Cost of Sales)
```

### Special Account IDs
- **58, 60**: Client accounts (can be hidden)
- **81, 87**: Supplier accounts (can be hidden)

---

**Critical Note**: This controller manages the foundation of the entire accounting system. All financial transactions ultimately post to accounts defined here. Changes to the account structure should be made carefully and with proper backup procedures.