# Employee Subgroups Controller Documentation

**File**: `/controllers/employeesubgroups.php`  
**Purpose**: Manage employee subgroup hierarchy with dual attendance system inheritance and organizational structure  
**Last Updated**: December 20, 2024  
**Total Functions**: 4+  
**Lines of Code**: ~200

---

## 📋 Overview

The Employee Subgroups Controller manages the second-level hierarchy in employee organization, sitting between employee groups and individual employees. It provides sophisticated subgroup management with dual attendance system assignment capabilities, allowing for flexible workforce organization and attendance rule inheritance.

### Key Capabilities
- Hierarchical subgroup management within employee groups
- Dual attendance system assignment (group-inherited and subgroup-specific)
- CRUD operations for employee subgroups
- Integration with parent employee groups
- Attendance system inheritance and override capabilities
- YouTube tutorial integration for user guidance

### Primary Functions
- [x] Create and manage employee subgroups within groups
- [x] Assign attendance systems at subgroup level (can override group settings)
- [x] Maintain hierarchical relationships with parent groups
- [x] Support CRUD operations with validation
- [x] Provide attendance system flexibility for specialized teams
- [x] Integration with employee day closure workflows

### Related Controllers
- [employeegroups.php](employeegroups.md) - Parent group 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 |
|------------|---------|-------------|
| **employeesubgroup** | Employee subgroup definitions | id, name, employeegroupid, employeeattendancesystemid, userid, del, sysdate |

### Related Tables (Referenced)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **employeegroup** | Parent employee groups | id, name, employeeattendancesystemid, userid, del |
| **employeeattendancesystem** | Attendance system configurations | id, attendanceTime, departureTime, userid, del |
| **employee** | Individual employee records | employeeId, employeesubgroupid, employeegroupid, branchid |

### Status Tracking Tables  
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **employeeclosedaysubgroupstatus** | Subgroup closure status tracking | id, day, employeesubgroupid, status, userid, sysdate, conditions |

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

---

## 🔑 Key Functions

### 1. **add()** - Create Employee Subgroup
**Location**: Line 165-180  
**Purpose**: Create new employee subgroup with group assignment and attendance system configuration

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

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

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

3. **Database Insertion**:
   ```php
   $employeeSubGroupDAO->insert($employeeSubGroup);
   ```

**Key Features**:
- Hierarchical assignment to parent group
- Specific attendance system assignment (can differ from group)
- Automatic user and timestamp tracking
- Support for specialized team configurations

---

### 2. **update()** - Modify Employee Subgroup
**Location**: Line 182-198  
**Purpose**: Update existing employee subgroup information and assignments

**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');
   $employeeSubGroup = $employeeSubGroupDAO->load($id);
   ```

2. **Update Fields**:
   ```php
   $employeeSubGroup->name = filter_input(INPUT_POST, 'name');
   $employeeSubGroup->employeegroupid = (float) filter_input(INPUT_POST, 'employeegroupid');
   $employeeSubGroup->employeeattendancesystemid = (float) filter_input(INPUT_POST, 'employeeattendancesystemid');
   ```

3. **System Fields Update**:
   ```php
   $employeeSubGroup->userid = $_SESSION["userid"];
   $employeeSubGroup->del = 0;
   $employeeSubGroup->sysdate = date("Y-m-d H:i:s");
   ```

4. **Save Changes**:
   ```php
   $employeeSubGroupDAO->update($employeeSubGroup);
   ```

**Features**:
- Group reassignment capability
- Attendance system modification
- Audit trail maintenance
- Relationship integrity preservation

---

### 3. **Standard CRUD Operations**

**Default Display** (empty $do):
```php
$employeeAttendanceSystem = $employeeAttendanceSystemDAO->queryByDel(0);
$smarty->assign('employeeAttendanceSystem', $employeeAttendanceSystem);

$employeeGroup = $employeeGroupDAO->queryByDel(0);
$smarty->assign('employeeGroup', $employeeGroup);
```
- Loads all active attendance systems for selection
- Loads all active employee groups for hierarchy selection
- Displays subgroup creation form

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

$youtubes = $youtubeLinkDAO->queryAll();
$smarty->assign("youtubes", $youtubes);
```
- Lists all active employee subgroups
- Integrates YouTube tutorial links
- Provides management interface

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

$employeeGroup = $employeeGroupDAO->queryByDel(0);
$smarty->assign('employeeGroup', $employeeGroup);

$employeeAttendanceSystem = $employeeAttendanceSystemDAO->queryByDel(0);
$smarty->assign('employeeAttendanceSystem', $employeeAttendanceSystem);
```
- Loads existing subgroup data
- Provides dropdowns for group and attendance system selection
- Maintains relationship context

**Delete Record** (`do=delete`):
```php
$id = (int) $_GET['id'];
$employeeSubGroupDAO->delete($id);
```
- Soft delete implementation
- Maintains referential integrity
- Preserves audit trail

---

## 🔄 Workflows

### Workflow 1: Employee Subgroup Creation
```
┌─────────────────────────────────────────────────────────────┐
│              START: Create Employee Subgroup                │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Load Creation Form Dependencies                         │
│     - Load all active employee groups                      │
│     - Load all active attendance systems                   │
│     - Display subgroup creation form                       │
│     - Provide hierarchy selection options                  │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  2. Process Form Submission                                 │
│     - Validate subgroup name                                │
│     - Validate parent group selection                      │
│     - Validate attendance system assignment                │
│     - Check for naming conflicts                           │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Create Hierarchical Relationships                      │
│     - Assign to selected parent group                      │
│     - Set specific attendance system (may override group)  │
│     - Establish organizational structure                   │
│     - Set system fields (user, timestamp, status)         │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  4. Database Insertion                                      │
│     - Insert into employeesubgroup table                   │
│     - Maintain referential integrity                       │
│     - Create audit trail                                   │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  5. Success Confirmation                                    │
│     - Redirect to success page                             │
│     - Display confirmation message                         │
│     - Provide navigation options                           │
└─────────────────────────────────────────────────────────────┘
```

---

### Workflow 2: Attendance System Assignment Logic
```
┌─────────────────────────────────────────────────────────────┐
│         START: Determine Attendance System Rules            │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼
┌─────────────────────────────────────────────────────────────┐
│  1. Check Subgroup-Specific Assignment                     │
│     - Query employeesubgroup.employeeattendancesystemid    │
│     - Check if subgroup has specific system assigned       │
│     - Validate assignment is active                        │
└────────────────────┬────────────────────────────────────────┘
                     │
                     ▼ (if subgroup has specific system)
┌─────────────────────────────────────────────────────────────┐
│  2A. Use Subgroup-Specific System                          │
│     - Load subgroup's attendance system configuration      │
│     - Apply subgroup-specific rules                        │
│     - Override parent group settings                       │
└────────────────────┬────────────────────────────────────────┘
                     │                     │
                     │                     ▼ (if no specific system)
                     │   ┌─────────────────────────────────────────────────────────────┐
                     │   │  2B. Inherit from Parent Group                             │
                     │   │     - Query parent group's attendance system               │
                     │   │     - Load group-level attendance configuration            │
                     │   │     - Apply inherited rules                                │
                     │   └─────────────────────┬───────────────────────────────────────┘
                     │                         │
                     ▼                         ▼
┌─────────────────────────────────────────────────────────────┐
│  3. Apply Attendance Rules                                  │
│     - Load attendance times and departure times            │
│     - Apply discount rules for late arrivals               │
│     - Configure absence handling                           │
│     - Set permission and early departure rules             │
└─────────────────────────────────────────────────────────────┘
```

---

## 🌐 URL Routes & Actions

| URL Parameter | Function Called | Description |
|---------------|----------------|-------------|
| (empty) | Default display | Show subgroup creation form |
| `do=add` | `add()` | Create new employee subgroup |
| `do=show` | Show listing | Display all employee subgroups |
| `do=delete` | Delete operation | Remove employee subgroup |
| `do=edit` | Edit form | Show subgroup edit form |
| `do=update` | `update()` | Save subgroup changes |
| `do=sucess` | Success page | Display success message |
| `do=error` | Error page | Display error message |

### Required Parameters by Action

**Create Subgroup** (`do=add`):
- `name` - Subgroup name (required)
- `employeegroupid` - Parent group ID (required)
- `employeeattendancesystemid` - Attendance system ID (required)

**Update Subgroup** (`do=update`):
- `id` - Subgroup ID (required)
- `name` - Updated subgroup name
- `employeegroupid` - Updated parent group ID
- `employeeattendancesystemid` - Updated attendance system ID

**Edit/Delete Operations**:
- `id` - Subgroup ID (required via GET parameter)

---

## 🧮 Attendance System Inheritance Logic

### Subgroup vs Group Attendance Systems
```php
// Subgroup-specific attendance system assignment
$employeeSubGroup->employeeattendancesystemid = (float) filter_input(INPUT_POST, 'employeeattendancesystemid');

// This can be different from the parent group's attendance system
// Allowing for specialized teams within larger groups
```

### Inheritance Hierarchy
1. **Employee Level**: Individual employees inherit from their subgroup
2. **Subgroup Level**: Subgroups can have specific attendance systems
3. **Group Level**: Groups provide default attendance systems
4. **System Level**: Fallback to system defaults if needed

### Use Cases for Dual Assignment
- **Management Teams**: Different schedules within same department
- **Shift Workers**: Multiple shifts within same functional group  
- **Special Projects**: Temporary teams with unique attendance requirements
- **Regional Variations**: Different office hours for same job function

---

## 🔒 Security & Permissions

### Authentication Requirements
```php
include_once("../public/authentication.php");
```
- All operations require valid user session
- User tracking in all create/update operations
- Session-based access control

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

**Security Features**:
- Input filtering using `filter_input()` function
- Type casting for numeric values (int, float)
- SQL injection prevention via DAO layer
- Referential integrity through foreign key relationships

### Data Integrity
- Soft delete implementation preserves audit trails
- User and timestamp tracking on all operations
- Referential integrity with parent groups and attendance systems

---

## 🐛 Common Issues & Troubleshooting

### 1. **Orphaned Subgroups**
**Issue**: Subgroups with invalid parent group references  
**Cause**: Parent groups deleted without cascading updates

**Debug Query**:
```sql
-- Find subgroups with invalid parent groups
SELECT es.id, es.name, es.employeegroupid 
FROM employeesubgroup es 
LEFT JOIN employeegroup eg ON es.employeegroupid = eg.id 
WHERE eg.id IS NULL AND es.del = 0;
```

**Prevention**: Implement cascade checking before group deletion

### 2. **Invalid Attendance System Assignments**
**Issue**: Subgroups assigned to deleted or inactive attendance systems  
**Solution**: Validate attendance system before assignment:
```php
function validateAttendanceSystem($systemId) {
    global $employeeAttendanceSystemDAO;
    $system = $employeeAttendanceSystemDAO->load($systemId);
    return ($system && $system->del == 0);
}
```

### 3. **Duplicate Subgroup Names**
**Issue**: Multiple subgroups with same name in same group  
**Enhancement**: Add unique constraint validation:
```php
function checkDuplicateName($name, $groupId, $excludeId = null) {
    global $employeeSubGroupEX;
    $existing = $employeeSubGroupEX->queryByNameAndGroup($name, $groupId);
    if ($excludeId) {
        $existing = array_filter($existing, function($item) use ($excludeId) {
            return $item->id != $excludeId;
        });
    }
    return count($existing) > 0;
}
```

### 4. **Cascading Updates for Employees**
**Issue**: Employees not updated when subgroup attendance system changes  
**Note**: Attendance system changes affect employees through inheritance, ensure proper change propagation in employee day closure processes.

---

## 📊 Performance Considerations

### Database Optimization
1. **Essential Indexes**:
   ```sql
   -- Subgroup queries
   CREATE INDEX idx_employeesubgroup_del ON employeesubgroup(del);
   CREATE INDEX idx_employeesubgroup_group ON employeesubgroup(employeegroupid, del);
   CREATE INDEX idx_employeesubgroup_attendance ON employeesubgroup(employeeattendancesystemid);
   CREATE INDEX idx_employeesubgroup_name ON employeesubgroup(name, employeegroupid);
   
   -- Employee assignment queries
   CREATE INDEX idx_employee_subgroup ON employee(employeesubgroupid, conditions);
   ```

2. **Query Optimization**:
   - Use `queryByDel(0)` for efficient active record filtering
   - Implement JOIN queries for hierarchical data loading
   - Cache attendance system configurations

### Memory Management
- Efficient loading of dropdown data
- Proper variable cleanup in processing functions
- Optimized template data assignment

### Scalability Considerations
- Implement pagination for large subgroup lists
- Consider materialized views for complex hierarchical queries
- Cache frequently accessed parent group data

---

## 🧪 Testing Scenarios

### Test Case 1: Subgroup CRUD Operations
```
1. Create subgroup with valid parent group and attendance system
2. Verify subgroup appears in listings
3. Edit subgroup name, group, and attendance system
4. Confirm changes saved correctly
5. Test deletion and soft delete verification
6. Check referential integrity maintained
```

### Test Case 2: Attendance System Assignment
```
1. Create subgroup with specific attendance system (different from group)
2. Verify subgroup uses its own attendance rules
3. Create subgroup inheriting from parent group system
4. Test attendance system change propagation
5. Validate system deletion impact on subgroups
```

### Test Case 3: Hierarchical Relationships
```
1. Create multiple subgroups within same parent group
2. Verify hierarchy maintained correctly
3. Test parent group changes affecting subgroups
4. Check employee assignment to subgroups
5. Validate day closure workflows with subgroups
```

### Test Case 4: Error Handling
```
1. Try creating subgroup with invalid parent group
2. Test with deleted attendance system assignment
3. Submit forms with missing required fields
4. Test duplicate name handling
5. Verify proper error messages displayed
```

---

## 📚 Related Documentation

- [CLAUDE.md](/Applications/AMPPS/www/erp19/CLAUDE.md) - PHP 8.2 migration guide
- [employeegroups.md](employeegroups.md) - Parent group 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