# User Group Controller Documentation

**File**: `/controllers/usergroupController.php`  
**Purpose**: Manages user groups, roles, permissions, and access control policies  
**Last Updated**: December 19, 2024  
**Total Functions**: 12  
**Lines of Code**: ~940

---

## 📋 Overview

The User Group Controller is the core component for managing user roles and permissions in the ERP system. It handles:
- Creating and editing user groups (roles)
- Managing permission sets and access control
- Property-based permission system
- Business rule configuration
- Restaurant/POS specific permissions
- Financial and operational restrictions
- UI customization per role
- Permission inheritance and copying
- Bulk operations on user groups

### Primary Functions
- [x] Create new user groups with permissions
- [x] Edit existing user groups and permissions
- [x] Copy user groups with full permission sets
- [x] Soft delete/restore user groups
- [x] Bulk operations on multiple groups
- [x] Property-based permission management
- [x] Restaurant/kitchen specific settings
- [x] Financial control settings
- [x] UI behavior customization
- [x] Access control for different modules

### Related Controllers
- [userController.php](userController.md) - User account management
- [sellbillController.php](sellbillController.md) - Sales operations
- [buyBillController.php](buyBillController.md) - Purchase operations
- [productController.php](productController.md) - Product management
- [storeController.php](storeController.md) - Store management
- [clientController.php](clientController.md) - Customer management
- [supplierController.php](supplierController.md) - Supplier management
- [dailyentryController.php](#) - Accounting entries
- [propertiesController.php](#) - Property definitions

---

## 🗄️ Database Tables

### Primary Tables (Direct Operations)
| Table Name | Purpose | Key Columns |
|------------|---------|-------------|
| **usergroup** | User roles/groups | usergroupid, usergroupname, usergroupdescription, level, conditions |
| **relusergroupproperties** | Group permissions | relusergrouppropertiesid, usergroupid, propertyid, propertyvalue, theorder |
| **properties** | Permission definitions | propertyid, propertyname, propertyparent, propertytype |

### Permission Control Fields in usergroup Table
| Field Category | Purpose | Key Fields |
|------------|---------|-------------|
| **Business Permissions** | Core operations | clientnegative, suplliernegative, storenegative, priceupdate |
| **Financial Control** | Money operations | directDiscount, percentageDiscount, allowEditDelInBills |
| **Display Settings** | UI customization | showSellAllPrice, showSellHalfPrice, showBuyPrice, hidemenu |
| **Restaurant Features** | POS operations | autoKitchenPrint, sendKitchen, hall, takeAway, delivery |
| **Security Settings** | Access control | allowBillDelete, billDeletePassword, editUserPrivlage |
| **Report Access** | Data visibility | netprofit, showsIndexStatistics, downloadClientPhones |

### Reference Tables
| Table Name | Purpose | Relationship |
|------------|---------|-------------|
| **user** | System users | usergroup.usergroupid → user.usergroupid |
| **properties** | Permission catalog | Property-based permission system |

---

## 🔧 Key Functions

### 1. **add()** - Create New User Group
**Location**: Line 248  
**Purpose**: Create a new user group with complete permission set

**Function Signature**:
```php
function add()
```

**Parameters** (via $_POST):
- `usergroupname` - Group display name
- `usergroupdescription` - Group description
- `startpage` - Default landing page
- `level` - Permission level
- `clientnegative` - Allow negative client balances
- `suplliernegative` - Allow negative supplier balances
- `storenegative` - Allow negative stock
- `priceupdate` - Allow price modifications
- `directDiscount` - Direct discount permission
- `percentageDiscount` - Percentage discount permission
- `allowEditDelInBills` - Edit/delete bills permission
- `showSellAllPrice` - Display all prices flag
- `autoKitchenPrint` - Auto print to kitchen
- `billDeletePassword` - Password for bill deletion
- `reviewBillsAllowedTables` - Array of tables for bill review
- `itr` - Number of properties to process

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Validate Input  │───▶│ Create UserGroup │───▶│ Get Group ID    │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                                         │
┌─────────────────┐    ┌──────────────────┐             │
│ Success Response│◀───│ Save Permissions │◀────────────┘
└─────────────────┘    └──────────────────┘
                                │
                    ┌──────────────────┐
                    │ Loop Through     │
                    │ Properties (1-N) │
                    └──────────────────┘
```

### 2. **show()** - Display All User Groups
**Location**: Line 441  
**Purpose**: Retrieve and display all user groups with ordering

**Returns**: Array of user group data ordered by name

### 3. **edit()** - Load User Group for Editing
**Location**: Line 561  
**Purpose**: Load user group data and associated permissions

**Parameters**:
- `id` - User group ID from GET

**Returns**: Array containing:
- `[0]` - User group data
- `[1]` - Property data with current values
- `[2]` - Property count

### 4. **update()** - Update User Group
**Location**: Line 580  
**Purpose**: Update user group and permissions using dynamic query building

**Key Features**:
- Dynamic SQL query building via `getUpdateQuery()`
- Permission property updates
- Cache invalidation for headers
- Session updates for current user group

### 5. **copyUserGroup()** - Duplicate User Group
**Location**: Line 696  
**Purpose**: Create a copy of existing user group with all permissions

**Parameters**:
- `usergroupid` - Source group ID

**Process Flow**:
```
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Load Source     │───▶│ Create New Group │───▶│ Copy Properties │
│ Group & Props   │    │ (New ID)         │    │ (Bulk Insert)   │
└─────────────────┘    └──────────────────┘    └─────────────────┘
          │                       │                       │
┌─────────▼───────┐    ┌──────────▼──────┐    ┌──────────▼──────┐
│ Reset Group ID  │    │ Append "_NewID" │    │ Bulk SQL Insert │
│ to NULL         │    │ to Group Name   │    │ for Properties  │
└─────────────────┘    └─────────────────┘    └─────────────────┘
```

### 6. **executeOperation()** - Bulk Operations
**Location**: Line 449  
**Purpose**: Perform bulk operations on multiple user groups

**Operations**:
- `1` - Temporary delete (soft delete)
- `2` - Return delete (restore)
- `3` - Permanent delete

### 7. **tempdelete()** - Soft Delete Group
**Location**: Line 485  
**Purpose**: Temporarily disable user group (conditions = 1)

### 8. **deleteFinaly()** - Permanent Delete Group
**Location**: Line 528  
**Purpose**: Permanently remove user group with validation

**Validation**: Checks if group has associated users before deletion

### 9. **getUpdateQuery()** - Dynamic Query Builder
**Location**: Line 723  
**Purpose**: Build dynamic UPDATE SQL based on submitted form fields

**Features**:
- Over 70 different permission fields
- Conditional field updates
- SQL injection protection
- Dynamic query construction

---

## 🔄 Business Logic Flow

### Permission Management Architecture
```
┌─────────────────┐
│ Properties      │
│ (Master List)   │
└─────────┬───────┘
          │
┌─────────▼───────┐    ┌──────────────────┐
│ User Group      │───▶│ Property Values  │
│ Creation        │    │ Assignment       │
└─────────────────┘    └──────────────────┘
          │                       │
┌─────────▼───────┐               │
│ Users Assigned  │               │
│ to Group        │               │
└─────────────────┘               │
          │                       │
┌─────────▼───────┐               │
│ Permission      │◀──────────────┘
│ Inheritance     │
└─────────────────┘
```

### Restaurant/POS Permission System
```
                    ┌─────────────────┐
                    │ Restaurant      │
                    │ Operations      │
                    └─────────┬───────┘
                              │
      ┌───────────────────────┼───────────────────────┐
      │                       │                       │
┌─────▼─────┐      ┌─────────▼────────┐      ┌─────▼─────┐
│ Kitchen   │      │ Service Types    │      │ Hall      │
│ Printing  │      │ (Hall/Takeaway/  │      │ Management│
└───────────┘      │  Delivery)       │      └───────────┘
                   └──────────────────┘
```

### Financial Control Matrix
| Permission | Scope | Impact |
|------------|-------|--------|
| `clientnegative` | Customer debt | Allow negative balances |
| `suplliernegative` | Supplier debt | Allow negative balances |
| `storenegative` | Inventory | Allow negative stock |
| `directDiscount` | Sales | Direct discount entry |
| `percentageDiscount` | Sales | Percentage-based discounts |
| `priceupdate` | Products | Modify product prices |
| `allowEditDelInBills` | Bills | Edit/delete sales bills |
| `allowBillDelete` | Security | Delete bills (with password) |

---

## ⚠️ Common Issues

### Session Cache Management
**Issue**: Header cache needs clearing when permissions change
```php
// ✅ IMPLEMENTED: Line 685-686
$fh = fopen('../temp__cashedheader/cashedheader_' . $_SESSION['dbname'] . '_' . $_SESSION['userid'] . '.html', 'w');
fclose($fh);
```

### User Group Dependencies
**Issue**: Cannot delete groups with associated users
```php
// ✅ VALIDATION: Line 541-542
$userValidation = $myUserRecord->queryByUsergroupid($userGroupId);
if (count($userValidation) <= 0) {
    // Safe to delete
}
```

### Permission Property Synchronization
**Issue**: New properties don't appear in old groups
```php
// ✅ SOLUTION: Line 342 - Uses queryAllbillsettingsNotDeleted_f()
// Automatically includes new properties with default values
```

---

## 🔗 Dependencies

### Required DAOs
- `UsergroupMySqlDAO` - User group database operations  
- `UsergroupMySqlExtDAO` - Extended user group queries
- `RelusergrouppropertiesMySqlDAO` - Permission relationships
- `PropertiesMySqlDAO` - Permission definitions
- `UserMySqlDAO` - User validation for deletions

### Required Files
- `../public/impOpreation.php` - Core operations
- `../public/config.php` - Configuration
- `../public/include_dao.php` - DAO includes

### Permission Categories
1. **Basic Access** - Menu visibility, page access
2. **Financial** - Money operations, discounts, pricing
3. **Inventory** - Stock control, negative quantities
4. **Restaurant** - Kitchen, halls, service types
5. **Security** - Bill deletion, user management
6. **Reporting** - Statistics, exports, data access
7. **UI Control** - Price visibility, menu hiding

---

## 🚀 Performance Notes

- Property-based permissions require JOIN queries
- Bulk operations process multiple groups efficiently
- Cache management for header regeneration
- Session updates for real-time permission changes
- Dynamic query building reduces code duplication

The User Group Controller is the foundation of the ERP system's security model, providing fine-grained access control across all business operations.