# Employee Personal AJAX Controller Documentation

**File**: `/controllers/employeePersonalajex.php`  
**Purpose**: AJAX endpoint for employee personal financial operations including salary calculations and departmental debt management  
**Last Updated**: December 20, 2024  
**Total Functions**: 3+  
**Lines of Code**: ~188

---

## 📋 Overview

The Employee Personal AJAX Controller is a lightweight API endpoint that provides real-time employee financial data and calculations for other controllers and AJAX requests. It serves:
- Employee departmental debt tracking
- Absent employee reporting for daily operations
- Net salary calculations with all deductions and bonuses
- Real-time financial data for attendance systems
- Integration point for payroll and attendance modules
- Session-based data access with user permissions
- JSON response formatting for frontend consumption

### Primary Functions
- [x] Retrieve employee departmental debt information
- [x] List absent employees for specific dates
- [x] Calculate net salary with comprehensive deduction/bonus breakdown
- [x] Provide real-time financial data for decision making
- [x] Support attendance system integration
- [x] Handle branch-based filtering
- [x] JSON API responses for frontend integration

### Related Controllers
- [employeePersonalController.php](employeePersonalController.md) - Full employee personal management
- [employeeAttendance.php](employeeAttendance.md) - Attendance tracking integration
- [EmployeeAttendanceExcelController.php](EmployeeAttendanceExcelController.md) - Bulk attendance processing
- [employeeController.php](employeeController.md) - Employee management

---

## 🗄️ Database Tables

### Primary Tables (Read Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **employee** | Employee master data with financial info | employeeId, employeeName, employeeSalary, employeeBouns, empdept, Reward, Discount, Withdraw, Absence, Repayment, permission, allLeave |
| **employeepersonnel** | Employee financial transactions | id, empName, empValue, type, employeepersonneldate |
| **employeeclosedayhistory** | Daily attendance tracking | id, employeeid, day, isAbsent, del |

### Financial Calculation Fields
| Field Name | Purpose | Type |
|------------|---------|------|
| **employeeSalary** | Base monthly salary | Decimal |
| **employeeBouns** | Regular bonuses | Decimal |
| **empdept** | Employee debt balance | Decimal |
| **Reward** | Rewards and incentives | Decimal |
| **Discount** | Penalties and discounts | Decimal |
| **Withdraw** | Cash withdrawals/advances | Decimal |
| **Absence** | Absence penalty totals | Decimal |
| **Repayment** | Debt repayments | Decimal |
| **permission** | Permission-based deductions | Decimal |
| **allLeave** | Leave-related deductions | Decimal |

### Reference Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **save** | Cash registers and safes | saveid, savename, savevalue |
| **salaryreport** | Salary calculation summaries | id, employeeId, month, year |

---

## 🔑 Key Functions

### 1. **getdeptbefor()** - Retrieve Employee Debt
**Location**: Line 104  
**Purpose**: Get current departmental debt amount for specific employee

**Function Signature**:
```php
// Triggered when: do=getdeptbefor
$id = $_GET["id"];  // Employee ID
```

**Process Flow**:
1. Get employee ID from request parameter
2. Load employee record using DAO
3. Return departmental debt amount
4. Simple text response (not JSON)

**Implementation**:
```php
$id = $_GET["id"];
$myempdata = $empDao->load($id);
echo $myempdata->empdept;
```

**Features**:
- **Direct Access**: Simple GET parameter access
- **Fast Response**: Single database lookup
- **Lightweight**: Returns plain text value
- **Integration Ready**: Used by other controllers for debt checking

---

### 2. **absentEmploye()** - List Absent Employees
**Location**: Line 113  
**Purpose**: Return list of employees who were absent on a specific date

**Function Signature**:
```php
// Triggered when: do=absentEmploye
$id = filter_input(INPUT_POST, 'id');  // Date string
```

**Process Flow**:
1. Receive date from POST parameter
2. Query employees absent on that date
3. Format results as JSON array
4. Return employee list for processing

**Implementation**:
```php
$id = filter_input(INPUT_POST, 'id');
$employes = $empEX->queryAllFromdayhistoty($id);
echo json_encode($employes);
```

**Features**:
- **Date-based Query**: Filter employees by absence date
- **JSON Response**: Returns structured data
- **Extended DAO**: Uses extended DAO methods
- **Attendance Integration**: Supports attendance system workflows

---

### 3. **getNetSalary()** - Comprehensive Salary Calculation
**Location**: Line 122  
**Purpose**: Calculate net salary with comprehensive breakdown of all financial components

**Function Signature**:
```php
// Triggered when: do=getNetSalary  
$id = $_GET["id"];  // Employee ID
```

**Process Flow**:
1. **Employee Data Loading**: Load complete employee financial record
2. **Null Validation**: Set null values to 0 for calculations
3. **Component Assembly**: Build all salary components
4. **Net Calculation**: Apply formula for final net salary
5. **Response Formatting**: Return net salary and current debt

**Comprehensive Null Handling**:
```php
if ($allsalarys->employeeBouns == null || $allsalarys->employeeBouns == "") {
    $allsalarys->employeeBouns = 0;
}
if ($allsalarys->empdept == null || $allsalarys->empdept == "" || $allsalarys->empdept == 0) {
    $allsalarys->empdept = 0;
}
// ... continues for all financial fields
```

**Salary Calculation Formula**:
```php
$total = (($allsalarys->employeeBouns) + ($allsalarys->Reward) + ($allsalarys->employeeSalary)) -
         (($allsalarys->Discount) + ($allsalarys->Withdraw) + ($allsalarys->Absence) + 
          ($allsalarys->Repayment) + ($allsalarys->permission) + ($allsalarys->allLeave));

$currentDebt = ($allsalarys->empdept) - ($allsalarys->Repayment);
echo $total . "*" . $currentDebt;  // Returns "netSalary*currentDebt"
```

**Financial Components**:
- **Income Components**:
  - Base salary (`employeeSalary`)
  - Regular bonuses (`employeeBouns`)
  - Rewards and incentives (`Reward`)

- **Deduction Components**:
  - Penalties and discounts (`Discount`)
  - Cash withdrawals (`Withdraw`)
  - Absence penalties (`Absence`)
  - Debt repayments (`Repayment`)
  - Permission-based deductions (`permission`)
  - Leave-related deductions (`allLeave`)

- **Debt Calculation**:
  - Current debt = Original debt - Repayments
  - Net salary excludes debt balance
  - Both values returned for frontend processing

---

## 🔄 Workflows

### Workflow 1: Real-time Debt Checking
```
┌─────────────────────────────────────────────────────────────┐
│              START: Check Employee Debt                    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Receive AJAX Request                                   │
│     - GET parameter with employee ID                        │
│     - Called from frontend forms/interfaces                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Load Employee Record                                    │
│     - Direct DAO lookup by employee ID                     │
│     - Access departmental debt field                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Return Debt Amount                                      │
│     - Plain text response for quick integration            │
│     - Used by forms to display current debt                │
│     - Enables real-time debt validation                     │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Comprehensive Salary Calculation
```
┌─────────────────────────────────────────────────────────────┐
│           START: Calculate Net Salary                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Complete Employee Financial Data                  │
│     - Get employee ID from request                         │
│     - Load all financial fields from employee table        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Validate and Normalize Data                            │
│     - Check each financial field for null/empty values     │
│     - Set null values to 0 for safe calculations           │
│     - Prepare all components for mathematical operations    │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Calculate Income Components                             │
│     - Base Salary: employeeSalary                          │
│     - Regular Bonuses: employeeBouns                       │
│     - Rewards: Reward                                      │
│     - Total Income = Salary + Bonuses + Rewards            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Calculate Deduction Components                         │
│     - Penalties: Discount                                   │
│     - Withdrawals: Withdraw                                │
│     - Absences: Absence                                    │
│     - Repayments: Repayment                                │
│     - Permission Deductions: permission                     │
│     - Leave Deductions: allLeave                           │
│     - Total Deductions = Sum of all deduction types        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Calculate Final Amounts                                │
│     - Net Salary = Total Income - Total Deductions         │
│     - Current Debt = Original Debt - Repayments            │
│     - Format: "netSalary*currentDebt"                      │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  6. Return Calculated Results                              │
│     - Send formatted string response                        │
│     - Frontend parses for display/processing               │
│     - Used for payroll and financial planning              │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| `do=getdeptbefor` | Debt lookup | Get employee departmental debt amount |
| `do=absentEmploye` | Absent list | Get employees absent on specific date |
| `do=getNetSalary` | Salary calculation | Calculate comprehensive net salary |

### Required Parameters by Action

**Get Debt** (`do=getdeptbefor`):
- `id` - Employee ID (GET parameter)

**Absent Employees** (`do=absentEmploye`):
- `id` - Date string (POST parameter)

**Net Salary** (`do=getNetSalary`):
- `id` - Employee ID (GET parameter)

---

## 🧮 Calculation Methods

### Debt Amount Retrieval
```php
$myempdata = $empDao->load($id);
echo $myempdata->empdept;  // Direct field access
```

### Net Salary Formula
```php
// Income components
$income = $employeeSalary + $employeeBouns + $Reward;

// Deduction components  
$deductions = $Discount + $Withdraw + $Absence + $Repayment + $permission + $allLeave;

// Final calculation
$netSalary = $income - $deductions;
$currentDebt = $empdept - $Repayment;

// Response format
echo $netSalary . "*" . $currentDebt;
```

### Null Value Normalization
```php
$value = ($field == null || $field == "" || $field == 0) ? 0 : $field;
```

---

## 🔒 Security & Permissions

### Session Management
- **Session Start**: Manual session start at controller level
- **Session Data**: Access to user session for permissions
- **Output Buffering**: `ob_start()` for response control

### Input Validation
- **Filter Input**: Uses `filter_input()` for POST parameters
- **Type Casting**: Direct GET parameter access (simple values)
- **DAO Security**: Database access through secure DAO layer

### Data Access
- **Read-Only**: Controller only reads data, no modifications
- **Employee Scope**: Access limited to specific employee data
- **No Authentication Check**: Relies on session state from calling controller

---

## 📊 Performance Considerations

### Database Optimization
1. **Single Queries**: Each function performs one targeted query
2. **Direct Loads**: Uses DAO load() method for ID-based access
3. **No Joins**: Simple table access without complex joins

### Response Efficiency
1. **Lightweight Responses**: Plain text or minimal JSON
2. **No Template Processing**: Direct echo responses
3. **Fast Calculations**: In-memory mathematical operations

### Known Performance Issues
- **No Caching**: Employee data loaded fresh each request
- **Session Overhead**: Manual session management
- **No Connection Pooling**: New database connection per request

---

## 🐛 Common Issues & Troubleshooting

### 1. **Empty/Null Salary Components**
**Issue**: Calculation returns NaN or incorrect values  
**Cause**: Database fields containing NULL or empty strings

**Solution**: Comprehensive null checking implemented:
```php
if ($allsalarys->employeeBouns == null || $allsalarys->employeeBouns == "") {
    $allsalarys->employeeBouns = 0;
}
```

### 2. **Session Not Available**
**Issue**: Session data not accessible to AJAX calls  
**Cause**: Session not properly started or expired

**Debug**:
```php
session_start();
if (!isset($_SESSION['userid'])) {
    echo "Session expired";
    exit;
}
```

### 3. **Employee Not Found**
**Issue**: DAO load returns null/empty object  
**Cause**: Invalid employee ID or deleted employee

**Protection**:
```php
$myempdata = $empDao->load($id);
if (!$myempdata) {
    echo "0";  // Return safe default
    exit;
}
```

### 4. **Calculation Overflow**
**Issue**: Very large salary amounts cause calculation errors  
**Solution**: Use appropriate data types and validation:
```php
$total = (float) $income - (float) $deductions;
```

---

## 🧪 Testing Scenarios

### Test Case 1: Debt Amount Retrieval
```
1. Create employee with known debt amount
2. Call getdeptbefor with employee ID
3. Verify returned value matches database
4. Test with employee ID = 0 (invalid)
5. Test with non-existent employee ID
```

### Test Case 2: Absent Employee Listing  
```
1. Create test employees with attendance records
2. Mark some as absent for specific date
3. Call absentEmploye with test date
4. Verify JSON response contains correct employees
5. Test with date having no absences
6. Test with invalid date format
```

### Test Case 3: Net Salary Calculation
```
1. Create employee with all salary components populated
2. Test calculation with positive values
3. Test with null/empty fields
4. Test with negative values (debt scenarios)
5. Verify response format (netSalary*currentDebt)
6. Test edge cases (very large numbers)
```

### Test Case 4: Session and Security
```
1. Test calls without valid session
2. Verify session data access
3. Test with expired sessions
4. Check SQL injection protection
5. Validate input parameter handling
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [employeePersonalController.md](employeePersonalController.md) - Full employee personal management
- [employeeAttendance.md](employeeAttendance.md) - Attendance integration
- [EmployeeAttendanceExcelController.md](EmployeeAttendanceExcelController.md) - Bulk operations

---

**Documented By**: AI Assistant  
**Review Status**: ✅ Complete  
**Next Review**: When major changes occur