📝 Markdown Document Manager

Upload markdown files and organize them in a tree structure

Add Document
Document Tree
Delete Document
View Document

Add New Document


Or Upload Markdown File

Max file size: 2M | Supported: .md, .txt, .markdown files | Content limit: 5MB

Document Tree Structure

🗑️ Delete Document

⚠️ Warning: This action cannot be undone!

ACCOUNTSTREE_CONTROLLER_API_DOCUMENTATION

Created: 2025-08-09 00:18:58 | Updated: 2025-08-09 00:18:58

▶ Accounts Tree Controller API Documentation

■ 1. Controller Overview

  • Purpose: Complete chart of accounts management system - the backbone of financial reporting
  • Module: Financial Management / Accounting
  • File: controllers/accountstree.php (686 lines)
  • Primary Database Table: accountstree
  • Dependencies:
  • → Complex DAO/DTO pattern with multiple accounting models
  • → PHPExcel for import/export operations
  • → Daily entry system integration (dailyentryfun.php)
  • → Account tree settings management
  • → Multi-level hierarchical structure support
  • → Expense type categorization

■ 2. Business Logic Analysis

Chart of Accounts System

This controller manages the chart of accounts - the fundamental structure of the entire ERP financial system. Every financial transaction in the system (sales, purchases, payments, expenses) must map to accounts in this tree.

Key Concepts:

  1. Hierarchical Structure: Multi-level tree with parent-child relationships
  2. Account Types: Assets, Liabilities, Equity, Income, Expenses
  3. Account Nature: Debit (0) or Credit (1) balance accounts
  4. Reporting Integration: Balance Sheet vs Income Statement accounts
  5. Level Settings: 6-level maximum depth with configurable digits per level

Integration Points:

  • Client Controller: Each client gets an account in the tree (type 57)
  • Supplier Controller: Each supplier gets an account in the tree (type 80)
  • Product Controller: Inventory accounts for each product
  • Sales Bill Controller: Sales revenue accounts
  • Daily Entry System: All journal entries reference accounts tree
  • Financial Reports: Balance sheet and income statement generation

■ 3. All Controller Operations (7 Operations Total)

Operation #1: Default (empty 'do') - Display Accounts Tree

Purpose: Display the complete chart of accounts in hierarchical tree format Implementation Details:

// Line 130-176 in accountstree.php

">if (empty($do)) {
    // Set up 6-level tree structure

    $maxNoOfLevels = 6;
    for (">$i = 1; ">$i <= ">$maxNoOfLevels; $i++) {
        ">$level = $accountsTreeSettingDAO->queryByLevelno($i);
        ">if (count($level) < 1) {
            // Create level if doesn&#039;t exist

            $accountsTreeSetting->levelno = $i;
            $accountsTreeSetting->nooffields = 1;
            ">$id = $accountsTreeSettingDAO->insert($accountsTreeSetting);
        }
        ">$levelSetting[">$i] = $level;
    }
    
    // Get expense type parents for integration

    $allParents = getExtepensesTypeParents();
    
    // Generate complete tree HTML

    $outputString = display_children(0, 0, 0, 0);
    
    // Check for opening inventory

    checkStartGoods();
    
    $smarty->display("accountstreeview/add.html");
}
SQL Operations:

-- Get level settings for each tree level

SELECT * FROM accountstreesetting WHERE levelno = ?

-- Create level setting if not exists

INSERT INTO accountstreesetting (levelno, nooffields) VALUES (?, 1)

-- Get all accounts for tree display (done in display_children function)

SELECT accountstree.*, parent.name as parentName 
FROM accountstree 
LEFT JOIN accountstree as parent ON accountstree.parent = parent.id
WHERE accountstree.conditions = 0
ORDER BY accountstree.theOrder, accountstree.id

-- Get expense type parents

SELECT * FROM expensestype WHERE parent = 0 AND conditions = 0

-- Check for opening inventory account

SELECT * FROM accountstree WHERE itemtype3 = &#039;بضاعة اول المدة&#039;

API Endpoint: GET /controllers/accountstree.php Business Logic:
  • → Displays complete chart of accounts
  • → Shows account codes, names, balances
  • → Hierarchical tree visualization
  • → Integration with client/supplier accounts
  • → Cookie-based display preferences
---

Operation #2: do=set

Purpose: Save account tree level settings and display preferences Implementation Details:

// Line 177-214 in accountstree.php

">elseif ($do == "set") {
    // Set long-term cookies (20 years)

    setcookie("calTreeNodes", (int) $_POST[&#039;calTreeNodes&#039;], (time() + (20  365  24  60  60)));

    setcookie("showClientsAtTree", (int) $_POST[&#039;showClientsAtTree&#039;], (time() + (20  365  24  60  60)));

    setcookie("showSuppliersAtTree", (int) $_POST[&#039;showSuppliersAtTree&#039;], (time() + (20  365  24  60  60)));

    
    // Configure 6 levels of tree structure

    $maxNoOfLevels = 6;
    for (">$i = 1; ">$i <= ">$maxNoOfLevels; $i++) {
        ">$level = $accountsTreeSettingDAO->queryByLevelno($i);
        ">if (count($level) < 1) {
            // Create new level setting

            $accountsTreeSetting->levelno = $i;
            $accountsTreeSetting->nooffields = 1;
            ">$id = $accountsTreeSettingDAO->insert($accountsTreeSetting);
        } else {
            // Update existing level

            ">$level = $level[0];
            $leveldigits = filter_input(INPUT_POST, "level" . $i);
            ">if (!empty($leveldigits)) {
                ">$level->nooffields = $leveldigits;
                $accountsTreeSettingDAO->update($level);
            }
        }
    }
    header("location:accountstree.php");
}
SQL Operations:

-- Get existing level setting

SELECT * FROM accountstreesetting WHERE levelno = ?

-- Insert new level setting

INSERT INTO accountstreesetting (levelno, nooffields) VALUES (?, ?)

-- Update level setting

UPDATE accountstreesetting SET nooffields = ? WHERE id = ?
API Endpoint: POST /controllers/accountstree.php?do=set Request Body:

{
    "calTreeNodes": 1,
    "showClientsAtTree": 1, 
    "showSuppliersAtTree": 1,
    "level1": 2,
    "level2": 2,
    "level3": 3,
    "level4": 3,
    "level5": 3,
    "level6": 3
}
---

Operation #3: do=uploadtree

Purpose: Display Excel upload form for chart of accounts import Implementation Details:

// Line 215-216 in accountstree.php

">elseif ($do == "uploadtree") {
    $smarty->display("accountstreeview/uploadexceltree.html");
}
API Endpoint: GET /controllers/accountstree.php?do=uploadtree Business Logic: Simple form display for Excel file upload ---

Operation #4: do=addtreefromexcel

Purpose: Process Excel file and import complete chart of accounts Implementation Details:

// Line 217-224 in accountstree.php

">elseif ($do == "addtreefromexcel") {
    addTreeFromExcel();  // Complex function starting at line 492

}
Complete addTreeFromExcel() function implementation:

// Line 492-617 in accountstree.php

function addTreeFromExcel() {
    global $accountsTree, $accountsTreeDAO, $accountsTreeEX;
    
    // Upload Excel file

    ">$handle = ">new upload($_FILES[&#039;productssheet&#039;]);

    ">$excelfileName = uploadfile($handle, "../upload/products");
    $inputFileName = "../upload/products/" . $excelfileName;
    
    // Transaction for data integrity

    $mytransactions = new Transaction();
    
    // Truncate existing tree (WARNING: Deletes all accounts!)

    $accountsTreeEX->Truncate();
    
    // Process Excel file

    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    ">$objPHPExcel = $objReader->load($inputFileName);
    
    ">$sheet = $objPHPExcel->getSheet(0);
    ">$highestRow = $sheet->getHighestRow();
    
    for ($row = 2; $row <= ">$highestRow; $row++) {
        $rowData = $sheet->rangeToArray(&#039;A&#039; . $row . &#039;:&#039; . ">$highestColumn . $row, NULL, TRUE, FALSE);

        $rowData = $rowData[0];
        
        // Extract account data from Excel

        ">$code = $rowData[1];                // Account code

        ">$accountName = $rowData[3];         // Arabic name

        ">$accountNameEn = $rowData[4];       // English name

        ">$itemType3 = $rowData[5];           // Account category

        $parentCode = $rowData[6];          // Parent account code

        ">$level = $rowData[7];               // Tree level

        $accountNature = $rowData[16];      // Debit/Credit nature

        ">$listName = $rowData[17];           // Balance Sheet/Income Statement

        
        ">if (!empty($accountName)) {
            // Find parent account

            $parentId = 0;
            $parentData = $accountsTreeDAO->queryByLayingOrder($parentCode);
            ">if (count($parentData) > 0) {
                $parentId = $parentData[0]->id;
            }
            
            // Process account nature

            switch ($accountNature) {
                case &#039;مدين&#039;:  // Debit

                    $accountNature = 0;
                    break;
                case &#039;دائن&#039;:  // Credit

                    $accountNature = 1;
                    break;
            }
            
            // Process report assignment

            $listId = 0;
            switch ($listName) {
                case &#039;ميزانية&#039;:      // Balance Sheet

                    $listId = 1;
                    break;
                case &#039;قائمة الدخل&#039;:   // Income Statement

                    $listId = 2;
                    break;
            }
            
            // Create account tree entry

            $accountsTree->customName = $accountName;
            $accountsTree->name = $accountName;
            $accountsTree->customNameEn = $accountNameEn;
            $accountsTree->nameEn = $accountNameEn;
            $accountsTree->parent = $parentId;
            $accountsTree->itemtype = -1;
            $accountsTree->itemtype2 = 1;  // Final element (leaf)

            $accountsTree->itemtype3 = $itemType3;
            $accountsTree->notes = &#039;&#039;;

            $accountsTree->theOrder = 0;
            $accountsTree->layingOrder = $code;
            $accountsTree->accountNature = $accountNature;
            $accountsTree->reportid = $listId;
            $accountsTree->conditions = 0;
            $accountsTree->theValue = 0;
            
            $accountsTreeDAO->insert($accountsTree);
        }
    }
}
SQL Operations:

-- Truncate existing accounts tree (DANGEROUS!)

TRUNCATE TABLE accountstree

-- Find parent account by code

SELECT * FROM accountstree WHERE layingOrder = ? AND conditions = 0

-- Insert new account from Excel

INSERT INTO accountstree (
    customName, name, customNameEn, nameEn, parent, itemtype, itemtype2, 
    itemtype3, notes, theOrder, layingOrder, accountNature, reportid, 
    conditions, theValue
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0)
API Endpoint: POST /controllers/accountstree.php?do=addtreefromexcel Request: Multipart form with Excel file Business Logic:
  • COMPLETE CHART OF ACCOUNTS IMPORT
  • → Processes standardized Excel format
  • → Maps Arabic/English account names
  • → Establishes parent-child relationships
  • → Sets account nature (debit/credit)
  • → Assigns to financial statements
  • WARNING: Truncates existing tree
---

Operation #5: do=exportAsExcel

Purpose: Export complete chart of accounts to Excel format Implementation Details:

// Line 225-283 in accountstree.php  

">elseif ($do == "exportAsExcel") {
    // Create PHPExcel object

    ">$objPHPExcel = new PHPExcel();
    $objPHPExcel->setActiveSheetIndex(0);
    $objPHPExcel->getActiveSheet()->setTitle("شجرة الحسابات");
    
    // Set headers in Arabic

    $objPHPExcel->getActiveSheet()
        ->SetCellValue(&#039;A1&#039;, &#039;الكود&#039;)         // Code

        ->SetCellValue(&#039;B1&#039;, &#039;اسم العنصر&#039;)    // Account Name

        ->SetCellValue(&#039;C1&#039;, &#039;والد العنصر&#039;)   // Parent

        ->SetCellValue(&#039;D1&#039;, &#039;طبيعة العنصر&#039;)  // Nature

        ->SetCellValue(&#039;E1&#039;, &#039;فى تقرير&#039;)      // In Report

        ->SetCellValue(&#039;F1&#039;, &#039;القائمة&#039;);      // Statement

    
    // Style formatting

    $styleArray = array(
        &#039;font&#039; => array(

            &#039;bold&#039; => true,

            &#039;size&#039; => 12,

            &#039;color&#039; => array(&#039;rgb&#039; => &#039;blue&#039;),

            &#039;name&#039; => &#039;Verdana&#039;

        )
    );
    
    // Export all accounts with exportToExcel function

    exportToExcel(0, 2);  // Start from root level

    
    // Output Excel file

    header(&#039;Content-Type: application/vnd.ms-excel&#039;);

    header(&#039;Content-Disposition: attachment;filename="AccountsTree.xlsx"&#039;);

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, &#039;Excel2007&#039;);

    $objWriter->save(&#039;php://output&#039;);

}
SQL Operations from exportToExcel() function:

-- Get all accounts at specific level

SELECT accountstree.*, parent.name as parentName
FROM accountstree 
LEFT JOIN accountstree as parent ON accountstree.parent = parent.id
WHERE accountstree.parent = ? AND accountstree.conditions = 0
ORDER BY accountstree.theOrder, accountstree.id

-- Recursive call for child accounts

-- (Function calls itself for each child account)

API Endpoint: GET /controllers/accountstree.php?do=exportAsExcel Response: Excel file download (AccountsTree.xlsx) Business Logic:
  • → Exports complete chart of accounts
  • → Hierarchical Excel format
  • → Arabic column headers
  • → Includes all account details
  • → Recursive tree traversal
---

Operation #6: do=sucess

Purpose: Display success confirmation page Implementation Details:

// Line 284-286 in accountstree.php

">elseif ($do == "sucess") {
    $smarty->display("succes.html");
}
API Endpoint: GET /controllers/accountstree.php?do=sucess ---

Operation #7: do=error

Purpose: Display error notification page Implementation Details:

// Line 287-289 in accountstree.php

">elseif ($do == "error") {
    $smarty->display("error.html");
}
API Endpoint: GET /controllers/accountstree.php?do=error ---

■ 4. Critical Helper Functions

display_children() Function

Purpose: Recursively generates complete accounts tree HTML Key Features:
  • → Recursive tree traversal
  • → Balance calculations
  • → Client/supplier account integration
  • → Multi-level indentation
  • → Account type color coding

checkStartGoods() Function

Purpose: Ensures opening inventory account exists Business Logic: Creates "بضاعة اول المدة" (Opening Inventory) account if missing - critical for inventory accounting.

getExtepensesTypeParents() Function

Purpose: Integration with expense management system

■ 5. Database Schema

accountstree Table Structure:


CREATE TABLE accountstree (
    id INT PRIMARY KEY AUTO_INCREMENT,
    customName VARCHAR(255),           -- Arabic account name

    name VARCHAR(255),                 -- Account name  

    customNameEn VARCHAR(255),         -- English account name

    nameEn VARCHAR(255),               -- English name

    parent INT,                        -- Parent account ID

    itemtype INT,                      -- Account category (-1, 0, 1, etc.)

    itemtype2 INT,                     -- Branch (0) or Leaf (1)

    itemtype3 VARCHAR(255),            -- Account subcategory

    notes TEXT,                        -- Account notes

    theOrder INT,                      -- Display order

    layingOrder VARCHAR(50),           -- Account code

    accountNature TINYINT,             -- 0=Debit, 1=Credit

    reportid INT,                      -- 1=Balance Sheet, 2=Income Statement

    conditions TINYINT,                -- 0=Active, 1=Deleted

    theValue DECIMAL(15,2),            -- Current balance

    -- Additional fields for integration

    branchid INT,                      -- Branch assignment

    userid INT                         -- User who created

);

accountstreesetting Table Structure:


CREATE TABLE accountstreesetting (
    id INT PRIMARY KEY AUTO_INCREMENT,
    levelno INT,                       -- Tree level (1-6)

    nooffields INT                     -- Number of digits for this level

);

■ 6. Integration with Other Controllers

Client Controller Integration:

  • → Each client automatically gets an account (itemtype3 = 57)
  • → Client accounts are children of "Accounts Receivable"
  • → Balance updates when sales bills are created

Supplier Controller Integration:

  • → Each supplier gets an account (itemtype3 = 80)
  • → Supplier accounts are children of "Accounts Payable"
  • → Balance updates with purchase bills

Daily Entry System Integration:

  • → Every journal entry references accounts tree IDs
  • → Automatic balance updates
  • → Double-entry bookkeeping enforcement

Financial Reports Integration:

  • → Balance Sheet uses accounts with reportid = 1
  • → Income Statement uses accounts with reportid = 2
  • → Hierarchical reporting structure

■ 7. API Conversion Considerations

REST API Endpoints:


GET /api/v1/accounts-tree # Get complete tree
POST /api/v1/accounts-tree/settings # Update level settings
POST /api/v1/accounts-tree/import # Import from Excel
GET /api/v1/accounts-tree/export # Export to Excel
GET /api/v1/accounts-tree/{id} # Get specific account
POST /api/v1/accounts-tree # Create new account
PUT /api/v1/accounts-tree/{id} # Update account
DELETE /api/v1/accounts-tree/{id} # Delete account

Critical API Requirements:

  1. Tree Structure Validation: Prevent circular references
  2. Balance Integrity: Real-time balance calculations
  3. Multi-language Support: Arabic/English names
  4. Hierarchical Permissions: Access control by tree levels
  5. Transaction Support: Atomic operations for imports
  6. Integration Webhooks: Notify other systems of changes

■ 8. Mathematical Completeness Verification

Total Operations Documented: 7/7 (100% Complete)

  1. Default (show tree) - Fully documented with SQL
  2. set - Level settings management
  3. uploadtree - Upload form display
  4. addtreefromexcel - Complete Excel import with all SQL operations
  5. exportAsExcel - Full export functionality
  6. sucess - Success page
  7. error - Error page

Mathematical Verification:

  • → Operations in Controller: 7
  • → Operations in Documentation: 7
  • Completeness: 7/7 = 100%

■ 9. Critical Business Impact

The Accounts Tree Controller is the foundation of the entire financial system. It manages:
  1. Chart of Accounts: The backbone of all financial reporting
  2. Account Relationships: Parent-child hierarchical structure
  3. Account Types: Assets, Liabilities, Equity, Income, Expenses
  4. Financial Statement Mapping: Balance Sheet vs Income Statement accounts
  5. Integration Hub: Central point for all financial transactions
  6. Multi-language Support: Arabic/English financial reporting
  7. Excel Integration: Complete import/export capabilities
Without this controller, the entire ERP financial system cannot function. Every sale, purchase, payment, and financial report depends on the accounts tree structure managed by this controller. --- This comprehensive documentation provides complete coverage of the Accounts Tree Controller (686 lines) - the critical financial foundation that enables all accounting operations, financial reporting, and business intelligence in the ERP system.