# Salary Report Controller Documentation

**File**: `/controllers/salaryReportController.php`  
**Purpose**: Manages salary calculations, payroll reports, and salary payment processing  
**Last Updated**: December 19, 2024  
**Total Functions**: 10  
**Lines of Code**: ~975

---

## 📋 Overview

The Salary Report Controller is the core component for managing payroll operations in the ERP system. It handles:
- Monthly salary calculations and reports
- Employee salary entitlements and deductions
- Payroll payment processing and receipts
- Salary history tracking and management
- Integration with accounting system for payroll entries
- Cost center allocation for salary expenses
- Multi-branch payroll support
- Advanced salary calculations with bonuses, deductions, and previous balances

### Primary Functions
- [x] Generate monthly salary reports
- [x] Calculate employee net pay with all components
- [x] Process salary payments and receipts
- [x] Track salary history and changes
- [x] Generate payroll accounting entries
- [x] Handle salary advances and deductions
- [x] Print salary slips and reports
- [x] Support multi-branch payroll
- [x] Cost center allocation for payroll
- [x] Excel export capabilities

### Related Controllers
- [employeeController.php](employeeController.md) - Employee management
- [EmployeeAttendanceController.php](EmployeeAttendanceController.md) - Attendance tracking
- [employeePersonalController.php](#) - Employee loans and advances
- [dailyentry.php](dailyentry.md) - Accounting entries
- [saveController.php](saveController.md) - Cash/bank management
- [accountstree.php](accountstree.md) - Chart of accounts
- [costcenterController.php](#) - Cost center management

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `salaryreport` | Monthly salary reports | `salaryreportid`, `employeeid`, `salarymonth`, `salaryreportnet` |
| `employeepersonnel` | Employee transactions/deductions | `employeeid`, `employeepersonneltype`, `employeepersonnelvalue` |
| `employee` | Employee master data | `employeeId`, `employeeName`, `employeeSalary`, `treeId2` |
| `save` | Cash/bank accounts for payment | `saveid`, `savename`, `savevalue` |
| `savedaily` | Daily cash movements | `saveid`, `savedailychangeamount`, `savedailychangetype` |

### Related Tables (References)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `dailyentry` | Payroll accounting entries | `dailyentryid`, `entryComment`, `thedate` |
| `dailyentrycreditor` | Credit side of entries | `dailyentryid`, `accountstreeid`, `value` |
| `dailyentrydebtor` | Debit side of entries | `dailyentryid`, `accountstreeid`, `value` |
| `accountstree` | Chart of accounts | `id`, `customName`, `parentId` |
| `costcenter` | Cost center allocation | `costcenterid`, `costcentername` |
| `costcenterdetail` | Cost center details | `costcenterid`, `accountstreeid`, `value` |

### Reference Tables (Lookups)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| `programsettings` | System configuration | `settingName`, `settingValue` |
| `user` | User preferences for saves | `userid`, `saveids`, `searchinonesave` |
| `branch` | Branch-based payroll | `branchId`, `branchName` |

---

## 🔧 Key Functions

### Main Controller Actions

#### **Default Action (Salary Report View)**
```php
if (!isset($_GET['do'])) // Line 168
```
- **Purpose**: Display monthly salary calculation report
- **Parameters**: 
  - `from` (POST): Salary month (YYYY-MM format)
- **Process Flow**:
```
┌─ Load User Settings ─┐
│ • Save preferences   │
│ • Cost centers       │
└──────────────────────┘
       ▼
┌─ Calculate Salaries ─┐
│ • Base salary        │
│ • Bonuses & rewards  │
│ • Deductions & fines │
│ • Previous balance   │
└──────────────────────┘
       ▼
┌─ Format Report ─────┐
│ allEmpsalary array  │
└─────────────────────┘
```

#### **Show Finalized Salaries**
```php
elseif ($do == "show") // Line 260
```
- **Purpose**: Display employees who received their salaries
- **Function Call**: `show()`
- **Template**: `salaryReportview/showfinsh.html`

#### **Edit Print Receipt**
```php
elseif ($do == "editprint") // Line 267
```
- **Purpose**: Edit and print salary receipt
- **Function Call**: `editprint()`
- **Template**: `salaryReportview/editprint.html`

#### **Process Receipt Payment**
```php
elseif ($do == "Receipt") // Line 274
```
- **Purpose**: Process salary payment receipt
- **Function Call**: `Receipt()`
- **Support**: CURL requests and normal requests
- **Returns**: 1 on success, -1 on error

### Core Business Functions

#### **show() Function**
```php
function show() // Line 506
```
- **Purpose**: Retrieve and display finalized salary payments
- **Process Flow**:
```
┌─ Load Month Data ─┐
│ GET['from'] param │
└───────────────────┘
       ▼
┌─ Query Payments ──┐
│ SalaryreportEX->  │
│ queryAll()        │
└───────────────────┘
       ▼
┌─ Assign to View ─┐
│ Smarty template  │
└──────────────────┘
```

#### **Receipt() Function**
```php
function Receipt() // Line 584
```
- **Purpose**: Process employee salary payment with full accounting integration
- **Parameters** (from $_POST):
  - `empIds[]`: Array of employee IDs
  - `amounts[]`: Corresponding payment amounts
  - `salarymonthdate`: Payment month
  - `saveid`: Payment account ID
  - `costcenterid`: Cost center for allocation
  - `note`: Payment note/reference

- **Process Flow**:
```
┌─ Start Transaction ─┐
│ Transaction::start()│
└─────────────────────┘
       ▼
┌─ Loop Employees ────┐
│ For each empId:     │
│ • Create salary rec │
│ • Update cash acc   │
│ • Create daily entry│
└─────────────────────┘
       ▼
┌─ Create Accounting ─┐
│ • Debit: Cash/Bank  │
│ • Credit: Employee  │
│ • Daily entries     │
└─────────────────────┘
       ▼
┌─ Cost Center ──────┐
│ Allocation if set  │
└────────────────────┘
       ▼
┌─ Commit/Rollback ──┐
│ Based on success   │
└────────────────────┘
```

- **Code Example**:
```php
// Create salary record
$Salaryreport->employeeid = $empId;
$Salaryreport->salaryreportnet = $amount;
$Salaryreport->salarymonth = $salarymonthdate;
$Salaryreport->sysdate = date("Y-m-d H:i:s");
$Salaryreport->conditions = 0;
$Salaryreport->userid = $_SESSION['userid'];

// Update cash account
$saveValueBefore = getSaveValueBefore($saveid);
$saveValueAfter = $saveValueBefore - $amount;
updateSave($saveid, $saveValueAfter);

// Create daily entry
insertSavedaily($saveValueBefore, $amount, 2, $saveid, 
    "استلام مرتب $employeeName", $salaryId, $saveValueAfter, "salaryreport");
```

#### **delete() Function**
```php
function delete() // Line 827
```
- **Purpose**: Cancel salary payment and reverse transactions
- **Parameters**: 
  - `id` (GET): Salary report ID to delete
- **Process Flow**:
```
┌─ Load Salary Record ┐
│ SalaryreportDAO->   │
│ load($id)           │
└─────────────────────┘
       ▼
┌─ Reverse Payment ───┐
│ • Add back to cash  │
│ • Remove daily entry│
│ • Mark as deleted   │
└─────────────────────┘
       ▼
┌─ Update Employee ───┐
│ Remove paid status  │
└─────────────────────┘
```

#### **Salary Entitlement Entry**
```php
elseif ($do == "salaryEntitlementEntry-notFinised") // Line 306
```
- **Purpose**: Create accounting entries for salary entitlements (accruals)
- **Process Flow**:
```
┌─ Calculate Entitlements ─┐
│ • Base salaries          │
│ • Bonuses & rewards      │
│ • Deductions & penalties │
│ • Social insurance       │
│ • Work tax               │
└──────────────────────────┘
       ▼
┌─ Create Journal Entry ───┐
│ Date: Last day of month  │
│ Comment: "استحقاق مرتبات" │
└──────────────────────────┘
       ▼
┌─ Debit Employee Accounts ┐
│ Individual employee GL   │
│ accounts with amounts    │
└──────────────────────────┘
       ▼
┌─ Credit Liability Accts ─┐
│ • Salaries payable      │
│ • Bonuses payable       │
│ • Insurance payable     │
│ • Tax payable           │
└─────────────────────────┘
```

### Utility Functions

#### **getSaveValueBefore($saveid)**
```php
function getSaveValueBefore($saveid) // Line 877
```
- **Purpose**: Get current balance of cash/bank account
- **Return**: Current account balance (float)

#### **updateSave($saveid, $savevalueafter)**
```php
function updateSave($saveid, $savevalueafter) // Line 925
```
- **Purpose**: Update cash/bank account balance
- **Parameters**: Account ID and new balance

#### **insertSavedaily()**
```php
function insertSavedaily($savedailysavebefore, $savedailychangeamount, $savedailychangetype, 
    $saveid, $processname, $savedailymodelid, $savedailysaveafter, $tablename) // Line 941
```
- **Purpose**: Record cash movement transaction
- **Parameters**: Before/after balances, change amount, process details

---

## 🔄 Business Logic Flow

### Monthly Salary Calculation Workflow
```
┌─ START: Monthly Report ─┐
│                         │
▼                         │
┌─ Select Month ─────────┐│
│ User input: YYYY-MM    ││
└────────────────────────┘│
       ▼                  │
┌─ Load Employee Data ───┐│
│ • Active employees     ││
│ • Branch filtering     ││
│ • Base salaries        ││
└────────────────────────┘│
       ▼                  │
┌─ Calculate Components ─┐│
│ For each employee:     ││
│ • Base salary          ││
│ • Bonuses              ││
│ • Rewards              ││
│ • Deductions           ││
│ • Absences             ││
│ • Advances/loans       ││
│ • Previous balance     ││
└────────────────────────┘│
       ▼                  │
┌─ Apply Formulas ──────┐│
│ Net = (Salary + Bonus  ││
│ + Reward) - (Discount  ││
│ + Withdraw + Absence   ││
│ + Repayment + Leave)   ││
│ + Previous Balance     ││
└────────────────────────┘│
       ▼                  │
┌─ Generate Report ─────┐│
│ Array format for      ││
│ display/printing      ││
└────────────────────────┘│
       ▼                  │
┌─ END: Display Report ──┘
```

### Salary Payment Processing
```
┌─ START: Pay Salaries ──┐
│                        │
▼                        │
┌─ Select Employees ────┐│
│ • Checkbox selection  ││
│ • Enter amounts       ││
│ • Choose payment acc  ││
└───────────────────────┘│
       ▼                 │
┌─ Validate Data ──────┐│
│ • Employee exists     ││
│ • Amount > 0          ││
│ • Account has funds   ││
└───────────────────────┘│
       ▼                 │
┌─ Start Transaction ──┐│
│ Database transaction  ││
│ for atomicity         ││
└───────────────────────┘│
       ▼                 │
┌─ Process Each Employee┐│
│ For each selected:    ││
│ • Create salary record││
│ • Deduct from account ││
│ • Create daily entry  ││
└───────────────────────┘│
       ▼                 │
┌─ Generate Accounting ─┐│
│ Dr: Cash/Bank Account ││
│ Cr: Employee Account  ││
└───────────────────────┘│
       ▼                 │
┌─ Cost Center Alloc ───┐│
│ If specified, allocate││
│ to cost center        ││
└───────────────────────┘│
       ▼                 │
┌─ Commit Transaction ──┐│
│ Save all changes      ││
└───────────────────────┘│
       ▼                 │
┌─ END: Success/Error ───┘
```

### Salary Component Calculations
```
Base Components:
┌─ Basic Salary ────┐
├─ Housing Allowance┤
├─ Transport Allow ─┤
├─ Other Allowances─┤
└─ Bonuses ────────┘

Additions:
┌─ Performance Bonus┐
├─ Overtime Pay ───┤
├─ Rewards ────────┤
└─ Retroactive Pay─┘

Deductions:
┌─ Absences ───────┐
├─ Late Penalties ─┤
├─ Loan Repayments┤
├─ Advances ──────┤
├─ Social Insurance┤
├─ Work Tax ──────┤
└─ Other Discounts┘

Net Calculation:
Net Salary = (Base + Additions) - Deductions + Previous Balance
```

---

## ⚠️ Common Issues

### Known Bugs & Limitations

1. **Transaction Safety**
   - **Issue**: Some operations lack proper transaction wrapping
   - **Location**: Various functions
   - **Impact**: Data inconsistency if operations fail mid-process
   - **Solution**: Add transaction management to all multi-table operations

2. **Duplicate Object Creation**
   - **Issue**: Same objects created multiple times
   - **Location**: Lines 54-57, 123-125 (Savedaily objects)
   - **Impact**: Memory waste and confusion
   - **Solution**: Remove duplicate object creation

3. **Array Index Safety**
   - **Issue**: Direct array access without isset() checks
   - **Location**: Receipt() function processing $_POST arrays
   - **Impact**: PHP warnings for missing indices
   - **Solution**: Add proper array validation

4. **Date Format Validation**
   - **Issue**: No validation for date format inputs
   - **Location**: Month parameter processing
   - **Impact**: SQL errors or incorrect calculations
   - **Solution**: Add date format validation

### PHP 8.2 Compatibility

1. **Object Initialization**
   - All stdClass objects properly initialized before property assignment
   - No "attempt to assign property on null" errors

2. **Type Casting**
   - Proper float casting for salary calculations
   - Safe array handling for employee data

---

## 🔗 Dependencies

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/config.php` - Database configuration
- `../public/include_dao.php` - DAO includes
- `dailyentryfun.php` - Daily entry functions

### Required DAOs
- `EmployeepersonnelDAO` - Employee transactions
- `SalaryreportDAO` - Salary report operations
- `SaveDAO` - Cash/bank account management
- `SavedailyDAO` - Daily cash movements
- `EmployeeDAO` - Employee data access
- `CostcenterDAO` - Cost center management
- `DailyentryDAO` - Accounting entries
- `ProgramsettingsDAO` - System settings

### Related Controllers
- Must coordinate with employee management for data consistency
- Integrates with daily entry system for accounting
- Works with save management for payment processing
- Connects to cost center allocation system

### Template Files
- `salaryReportview/show.html` - Monthly salary report
- `salaryReportview/showfinsh.html` - Finalized payments
- `salaryReportview/editprint.html` - Edit/print receipts
- `succes.html` - Success message
- `error.html` - Error message

### Key Payroll Features
- **Multi-Component Calculation**: Base salary + allowances + bonuses - deductions
- **Previous Balance Integration**: Carries forward negative balances from previous months
- **Full Accounting Integration**: Automatic journal entries for all transactions
- **Cost Center Allocation**: Department-wise expense allocation
- **Branch Support**: Multi-branch payroll processing
- **Transaction Safety**: Database transaction support for data integrity
- **Flexible Payment Methods**: Multiple cash/bank account support
- **Audit Trail**: Complete history of all salary transactions
- **Real-time Balance Updates**: Immediate cash account balance updates