# Employee Groups Controller Documentation

**File**: `/controllers/employeegroups.php`  
**Purpose**: Manage employee group hierarchy with attendance system integration and Ajax-powered functionality  
**Last Updated**: December 20, 2024  
**Total Functions**: 8+  
**Lines of Code**: ~279

---

## 📋 Overview

The Employee Groups Controller manages the top-level hierarchy of employee organization within the ERP system. It provides comprehensive group management with tight integration to attendance systems and supports real-time Ajax operations. Key capabilities include:
- Employee group creation and management
- Attendance system assignment and configuration
- Real-time Ajax operations for dynamic data loading
- Group-based attendance data retrieval
- Integration with employee day closure workflows
- Hierarchical employee organization support

### Primary Functions
- [x] Create and manage employee groups
- [x] Assign attendance systems to groups
- [x] Ajax-powered group selection and filtering
- [x] Real-time attendance system data retrieval
- [x] Integration with subgroup management
- [x] Support for day closure status tracking
- [x] CRUD operations with validation
- [x] YouTube tutorial integration

### Related Controllers
- [employeesubgroups.php](employeesubgroups.md) - Subgroup management
- [employeeController.php](employeeController.md) - Individual employee management
- [employeeAttendanceSystems.php](employeeAttendanceSystems.md) - Attendance system configuration
- [employeeendday.php](employeeendday.md) - Day closure integration

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **employeegroup** | Employee group definitions | id, name, employeeattendancesystemid, userid, del, sysdate |

### Related Tables (Referenced)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **employeeattendancesystem** | Attendance system configurations | id, attendanceTime, departureTime, del |
| **employeeattendancesystemweek** | Weekly attendance schedules | id, employeeattendancesystem_id, day, attendanceTime, departureTime |
| **employeesubgroup** | Subgroups within groups | id, name, employeegroupid, employeeattendancesystemid |
| **employee** | Individual employee records | employeeId, employeegroupid, employeesubgroupid, branchid |

### Status Tracking Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **employeeclosedaygroupstatus** | Group closure status tracking | id, day, employeegroupid, status, userid, sysdate |

### Configuration Tables
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **youtubelink** | Tutorial references | youtubelinkid, title, url |

---

## 🔑 Key Functions

### 1. **add()** - Create Employee Group
**Location**: Line 188-202  
**Purpose**: Create new employee group with attendance system assignment

**Function Signature**:
```php
function add()
// POST Parameters:
$name = filter_input(INPUT_POST, 'name');
$employeeattendancesystemid = (float) filter_input(INPUT_POST, 'employeeattendancesystemid');
```

**Process Flow**:
1. **Input Validation and Processing**:
   ```php
   $employeeGroup->name = filter_input(INPUT_POST, 'name');
   $employeeGroup->employeeattendancesystemid = (float) filter_input(INPUT_POST, 'employeeattendancesystemid');
   ```

2. **System Fields Assignment**:
   ```php
   $employeeGroup->userid = $_SESSION["userid"];
   $employeeGroup->del = 0; // Active status
   $employeeGroup->sysdate = date("Y-m-d H:i:s");
   ```

3. **Database Insertion**:
   ```php
   $employeeGroupDAO->insert($employeeGroup);
   ```

**Features**:
- Automatic user tracking
- Timestamp management
- Attendance system integration
- Soft delete support

---

### 2. **update()** - Modify Employee Group
**Location**: Line 204-219  
**Purpose**: Update existing employee group information

**Function Signature**:
```php
function update()
// POST Parameters:
$id = (int) filter_input(INPUT_POST, 'id');
```

**Process Flow**:
1. **Load Existing Record**:
   ```php
   $id = (int) filter_input(INPUT_POST, 'id');
   $employeeGroup = $employeeGroupDAO->load($id);
   ```

2. **Update Fields**:
   ```php
   $employeeGroup->name = filter_input(INPUT_POST, 'name');
   $employeeGroup->employeeattendancesystemid = (float) filter_input(INPUT_POST, 'employeeattendancesystemid');
   $employeeGroup->userid = $_SESSION["userid"];
   $employeeGroup->sysdate = date("Y-m-d H:i:s");
   ```

3. **Save Changes**:
   ```php
   $employeeGroupDAO->update($employeeGroup);
   ```

**Features**:
- Maintains audit trail
- Updates modification timestamp
- Preserves record integrity

---

### 3. **getattendancesystemajax** - Ajax Attendance System Retrieval
**Location**: Line 144-148  
**Purpose**: Return attendance system ID for a specific group via Ajax

**Function Signature**:
```php
// Ajax Action: do=getattendancesystemajax
$id = (int) filter_input(INPUT_POST, 'id');
```

**Implementation**:
```php
$employeeGroup = $employeeGroupDAO->load($id);
echo $employeeGroup->employeeattendancesystemid;
```

**Usage**: Frontend JavaScript can call this to dynamically load attendance system information when group is selected.

---

### 4. **getgroups()** - Ajax Group Search and Filtering
**Location**: Line 251-278  
**Purpose**: Provide Ajax-powered group search with optional day status filtering

**Function Signature**:
```php
function getgroups()
// GET Parameters:
$name = $_GET['term']; // Search term
$day = $_GET['day']; // Optional day for status filtering
```

**Process Flow**:
1. **Dynamic Query Selection**:
   ```php
   if (isset($day) && !empty($day)) {
       $result = $employeeGroupEX->queryByNameWithDayStatue($name, $day);
   } else {
       $result = $employeeGroupEX->queryByNameEX($name);
   }
   ```

2. **Response Formatting**:
   ```php
   foreach ($result as $row) {
       $row_array['id'] = $row->id;
       $row_array['text'] = $row->name;
       $row_array['status'] = (int) $row->status; // Day closure status
       array_push($return_arr, $row_array);
   }
   ```

3. **JSON Response**:
   ```php
   echo json_encode($return_arr);
   ```

**Features**:
- Real-time search capabilities
- Day status integration for closure workflows
- Optimized for Select2 dropdown integration

---

### 5. **getgroupAttendanceData** - Comprehensive Attendance Data
**Location**: Line 152-159  
**Purpose**: Retrieve complete attendance system data including weekly schedules

**Function Signature**:
```php
// Ajax Action: do=getgroupAttendanceData
$id = (int) filter_input(INPUT_POST, 'id');
```

**Implementation**:
```php
$row = $employeeGroupDAO->load($id);
$stem = $employeeAttendanceSystemDAO->load($row->employeeattendancesystemid);
$stemweek = R::getAll('select * from employeeattendancesystemweek where employeeattendancesystem_id = ?',[$row->employeeattendancesystemid]);
echo json_encode(array($stem,$stemweek));
```

**Return Format**:
```json
[
  {
    "id": 1,
    "attendanceTime": "08:00:00", 
    "departureTime": "17:00:00"
  },
  [
    {"day": "Sunday", "attendanceTime": "08:00:00", "departureTime": "17:00:00"},
    {"day": "Monday", "attendanceTime": "08:00:00", "departureTime": "17:00:00"}
  ]
]
```

**Features**:
- Complete attendance system configuration
- Weekly schedule details
- Ready for frontend processing

---

### 6. **Standard CRUD Operations**

**Show Listing** (`do=show`):
```php
$showData = $employeeGroupDAO->queryByDel(0);
$smarty->assign("showData", $showData);
```

**Edit Form** (`do=edit`):
```php
$id = (int) $_GET['id'];
$loadData = $employeeGroupDAO->load($id);
$smarty->assign("loadData", $loadData);
```

**Delete Record** (`do=delete`):
```php
$id = (int) $_GET['id'];
$employeeGroupDAO->delete($id);
```

---

## 🔄 Workflows

### Workflow 1: Employee Group Creation
```
┌─────────────────────────────────────────────────────────────┐
│                START: Create Employee Group                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Add Form                                           │
│     - Load all active attendance systems                    │
│     - Display group creation form                          │
│     - Provide attendance system dropdown                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Process Form Submission                                 │
│     - Validate group name                                   │
│     - Validate attendance system selection                 │
│     - Set system fields (user, date, status)              │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Create Group Record                                     │
│     - Insert into employeegroup table                      │
│     - Link to selected attendance system                   │
│     - Maintain audit trail                                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Success Confirmation                                    │
│     - Redirect to success page                             │
│     - Display confirmation message                         │
│     - Provide navigation options                           │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Ajax Group Selection with Status
```
┌─────────────────────────────────────────────────────────────┐
│           START: User Types in Group Search                 │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Ajax Request Processing                                 │
│     - Receive search term from frontend                    │
│     - Check for optional day parameter                     │
│     - Determine query type needed                          │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Query Database                                          │
│     IF Day Parameter Present:                               │
│       │ - Query groups with day status                     │
│       │ - Include closure status information               │
│     ELSE:                                                   │
│       │ - Query groups by name only                        │
│       │ - Return basic group information                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Format Response                                         │
│     - Create Select2-compatible JSON structure             │
│     - Include group ID, name, and status                   │
│     - Apply result limiting (performance)                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Return JSON Response                                    │
│     - Send formatted data to frontend                      │
│     - Enable dynamic dropdown population                   │
│     - Support cascading selections                         │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description | Ajax |
|---------------|----------------|-------------|------|
| (empty) | Default display | Show group creation form | No |
| `do=add` | `add()` | Create new employee group | No |
| `do=show` | Show listing | Display all employee groups | No |
| `do=delete` | Delete operation | Remove employee group | No |
| `do=edit` | Edit form | Show group edit form | No |
| `do=update` | `update()` | Save group changes | No |
| `do=getattendancesystemajax` | Ajax attendance system | Get attendance system ID | Yes |
| `do=getsubgroups` | `getsubgroups()` | Load subgroups for group | Yes |
| `do=getgroups` | `getgroups()` | Search groups with filtering | Yes |
| `do=getgroupAttendanceData` | Ajax attendance data | Get complete attendance config | Yes |
| `do=sucess` | Success page | Display success message | No |
| `do=error` | Error page | Display error message | No |

### Required Parameters by Action

**Create Group** (`do=add`):
- `name` - Group name (required)
- `employeeattendancesystemid` - Attendance system ID (required)

**Update Group** (`do=update`):
- `id` - Group ID (required)
- `name` - Updated group name
- `employeeattendancesystemid` - Updated attendance system ID

**Ajax Operations**:
- `getattendancesystemajax`: `id` (group ID)
- `getgroups`: `term` (search term), `day` (optional)
- `getgroupAttendanceData`: `id` (group ID)

---

## 🔒 Security & Permissions

### Authentication Requirements
```php
include_once("../public/authentication.php");
```
- All non-Ajax operations require authentication
- Session-based user identification
- User tracking in all operations

### Input Validation
```php
$id = (int) filter_input(INPUT_POST, 'id');
$name = filter_input(INPUT_POST, 'name');
$employeeattendancesystemid = (float) filter_input(INPUT_POST, 'employeeattendancesystemid');
```

**Security Features**:
- Input filtering using `filter_input()`
- Type casting for numeric values
- SQL injection prevention via DAO layer
- Session validation for user operations

### Ajax Security
```php
$ajaxDoArr = array('getattendancesystemajax', 'getsubgroups', 'getgroups', 'getgroupAttendanceData');
if (!in_array($do, $ajaxDoArr)) {
    include("../public/impOpreation.php");
}
```

**Ajax Protection**:
- Selective authentication for Ajax operations
- Input validation on all Ajax endpoints
- Limited data exposure in responses

---

## 🐛 Common Issues & Troubleshooting

### 1. **Attendance System Assignment Issues**
**Issue**: Groups created without valid attendance system assignments  
**Cause**: Invalid attendance system IDs or deleted systems

**Debug Steps**:
```sql
-- Check for orphaned group records
SELECT eg.id, eg.name, eg.employeeattendancesystemid 
FROM employeegroup eg 
LEFT JOIN employeeattendancesystem eas ON eg.employeeattendancesystemid = eas.id 
WHERE eas.id IS NULL AND eg.del = 0;
```

**Fix**: Validate attendance system exists before assignment

### 2. **Ajax Response Issues**
**Issue**: Ajax calls return no data or malformed JSON  
**Common Causes**:
- PHP errors before JSON output
- Incorrect parameter names
- Session issues in Ajax context

**Debug**:
```php
// Add at start of Ajax functions
error_log("Ajax call: " . $_GET['do'] . " with params: " . print_r($_REQUEST, true));
```

### 3. **Group Deletion Cascade Issues**
**Issue**: Deleting groups with associated subgroups/employees  
**Solution**: Implement cascade checking:
```php
function delete($id) {
    // Check for dependent subgroups
    $subgroups = $employeeSubGroupDAO->queryByEmployeegroupid($id);
    if (count($subgroups) > 0) {
        throw new Exception("Cannot delete group with existing subgroups");
    }
    
    // Check for dependent employees
    $employees = $employeeDAO->queryByEmployeegroupid($id);
    if (count($employees) > 0) {
        throw new Exception("Cannot delete group with existing employees");
    }
    
    $employeeGroupDAO->delete($id);
}
```

### 4. **Performance Issues with Large Groups**
**Issue**: Slow loading when many groups exist  
**Optimization**:
- Implement pagination on listing pages
- Add search functionality to reduce result sets
- Index frequently queried columns

---

## 📊 Performance Considerations

### Database Optimization
1. **Essential Indexes**:
   ```sql
   CREATE INDEX idx_employeegroup_del ON employeegroup(del);
   CREATE INDEX idx_employeegroup_attendance ON employeegroup(employeeattendancesystemid);
   CREATE INDEX idx_employeegroup_name ON employeegroup(name);
   CREATE INDEX idx_employeegroup_userid ON employeegroup(userid);
   ```

2. **Query Optimization**:
   - Use `queryByDel(0)` to filter active records efficiently
   - Implement proper LIMIT clauses in Ajax searches
   - Cache attendance system data for repeated access

### Ajax Performance
- Implement debouncing on search inputs
- Use result caching where appropriate
- Limit result sets to manageable sizes (50-100 records)

### Memory Management
- Proper variable cleanup in loops
- Efficient JSON encoding
- Connection management for database operations

---

## 🧪 Testing Scenarios

### Test Case 1: Group CRUD Operations
```
1. Create new group with valid attendance system
2. Verify group appears in listing
3. Edit group name and attendance system
4. Confirm changes saved correctly
5. Test deletion (ensure no dependencies)
6. Verify soft delete functionality
```

### Test Case 2: Ajax Functionality
```
1. Test getgroups with search term
2. Verify JSON response format
3. Test with day parameter for status filtering
4. Check getgroupAttendanceData returns complete config
5. Validate getattendancesystemajax returns correct ID
```

### Test Case 3: Attendance System Integration
```
1. Create group with specific attendance system
2. Verify system assignment saved correctly
3. Test Ajax retrieval of attendance data
4. Check weekly schedule data inclusion
5. Validate system changes affect group properly
```

### Test Case 4: Error Handling
```
1. Test with invalid attendance system IDs
2. Try to delete group with dependencies
3. Submit forms with missing required fields
4. Test Ajax calls with invalid parameters
5. Verify error pages display correctly
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [employeesubgroups.md](employeesubgroups.md) - Subgroup management
- [employeeController.md](employeeController.md) - Individual employee management
- [employeeAttendanceSystems.md](employeeAttendanceSystems.md) - Attendance system configuration

---

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