# System Architecture

## Overview

Qaya HRM is a comprehensive multitenant Human Resource Management System built on Laravel 12, designed to handle multiple organizations within a single application instance while maintaining complete data isolation.

---

## Technology Stack

### Backend
- **Framework**: Laravel 12.x
- **PHP Version**: 8.2+
- **Database**: MySQL/MariaDB
- **Authentication**: Laravel Sanctum + Custom Multi-auth
- **Authorization**: Spatie Laravel Permission
- **PDF Generation**: DomPDF (barryvdh/laravel-dompdf)
- **Excel/CSV**: Maatwebsite Excel

### Frontend
- **CSS Framework**: Bootstrap 5
- **Icons**: Bootstrap Icons
- **JavaScript**: Vanilla JS + Vite
- **Calendar**: FullCalendar
- **Build Tool**: Vite 7.x

### Additional Libraries
- **QR Code**: bacon/bacon-qr-code (Two-Factor Auth)
- **Tailwind CSS**: v4.0 (Optional styling)

---

## Application Architecture

### Three-Tier Architecture

```
┌─────────────────────────────────────────────────────────┐
│                    Presentation Layer                    │
│  (Blade Templates, Bootstrap 5, JavaScript, FullCalendar)│
└─────────────────────────────────────────────────────────┘
                            │
┌─────────────────────────────────────────────────────────┐
│                     Application Layer                    │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│  │ Controllers  │  │  Services    │  │  Policies    │  │
│  └──────────────┘  └──────────────┘  └──────────────┘  │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│  │ Middleware   │  │  Requests    │  │  Events      │  │
│  └──────────────┘  └──────────────┘  └──────────────┘  │
└─────────────────────────────────────────────────────────┘
                            │
┌─────────────────────────────────────────────────────────┐
│                       Data Layer                         │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
│  │   Models     │  │ Repositories │  │  Database    │  │
│  └──────────────┘  └──────────────┘  └──────────────┘  │
└─────────────────────────────────────────────────────────┘
```

---

## Multi-Tenancy Architecture

### Tenant Isolation Strategy

**Single Database with Organization Scoping**

```
┌──────────────────────────────────────────────────────────┐
│                    Application Instance                   │
├──────────────────────────────────────────────────────────┤
│  Organization A          Organization B          Org C   │
│  ┌──────────────┐       ┌──────────────┐       ┌─────┐  │
│  │ Users        │       │ Users        │       │Users│  │
│  │ Employees    │       │ Employees    │       │Emps │  │
│  │ Departments  │       │ Departments  │       │Dpts │  │
│  │ Payroll      │       │ Payroll      │       │Pay  │  │
│  └──────────────┘       └──────────────┘       └─────┘  │
└──────────────────────────────────────────────────────────┘
                            │
                    ┌───────┴───────┐
                    │  MySQL Database│
                    │  (Single DB)   │
                    └────────────────┘
```

### Key Components

1. **HasTenantScope Trait**
   - Automatically filters queries by `organization_id`
   - Applied to all tenant-scoped models
   - Location: `app/Traits/HasTenantScope.php`

2. **TenantScope Middleware**
   - Ensures users can only access their organization's data
   - Validates organization context on every request
   - Location: `app/Http/Middleware/TenantScope.php`

3. **Organization Model**
   - Central tenant entity
   - Manages organization settings and metadata
   - Location: `app/Models/Organization.php`

---

## User Authentication System

### Dual Authentication Paths

```
┌─────────────────────────────────────────────────────────┐
│                    Authentication Flow                   │
├─────────────────────────────────────────────────────────┤
│                                                          │
│  /systemadmin/login  ──────►  SystemAdmin Dashboard     │
│  (is_system_admin = true)     (Manage all orgs)         │
│                                                          │
│  /login  ──────────────────►  Organization Dashboard    │
│  (organization_id set)        (Scoped to org)           │
│                                                          │
└─────────────────────────────────────────────────────────┘
```

### User Types

1. **SystemAdmin**
   - `is_system_admin = true`
   - No organization_id
   - Full system access
   - Manages organizations

2. **Organization Admin**
   - Has `org_admin` role
   - Belongs to specific organization
   - Manages organization users and data

3. **Staff Users**
   - Regular employees
   - Role-based permissions
   - Self-service features

---

## Directory Structure

```
qaya-hrm/
├── app/
│   ├── Http/
│   │   ├── Controllers/
│   │   │   ├── Auth/              # Authentication
│   │   │   ├── Web/               # Web controllers
│   │   │   ├── Api/               # API controllers
│   │   │   ├── Admin/             # Admin controllers
│   │   │   ├── Organization/      # Org-specific
│   │   │   └── SystemAdmin/       # System admin
│   │   ├── Middleware/            # Custom middleware
│   │   └── Requests/              # Form requests
│   ├── Models/                    # Eloquent models
│   ├── Services/                  # Business logic
│   │   ├── PayrollService.php
│   │   ├── KenyaTaxCalculator.php
│   │   ├── SecurityService.php
│   │   └── TenantContext.php
│   ├── Policies/                  # Authorization
│   ├── Traits/                    # Reusable traits
│   │   ├── HasTenantScope.php
│   │   └── Auditable.php
│   └── Providers/                 # Service providers
├── database/
│   ├── migrations/                # Database migrations
│   ├── seeders/                   # Database seeders
│   └── factories/                 # Model factories
├── resources/
│   ├── views/                     # Blade templates
│   │   ├── layouts/
│   │   ├── employees/
│   │   ├── payroll/
│   │   ├── attendance/
│   │   └── ...
│   └── js/                        # JavaScript files
├── routes/
│   ├── web.php                    # Web routes
│   ├── api.php                    # API routes
│   └── audit.php                  # Audit routes
├── public/                        # Public assets
├── storage/                       # File storage
└── tests/                         # Tests
```

---

## Core Services

### 1. PayrollService
**Purpose**: Handles payroll calculations and generation

**Key Methods**:
- `calculatePayroll($employee, $month, $year)`
- `generateBulkPayroll($organizationId, $month, $year)`
- `processPayroll($payrollId)`

**Location**: `app/Services/PayrollService.php`

### 2. KenyaTaxCalculator
**Purpose**: Calculates PAYE, NHIF, NSSF, and housing levy

**Key Methods**:
- `calculatePAYE($grossSalary)`
- `calculateNHIF($grossSalary)`
- `calculateNSSF($grossSalary)`
- `calculateHousingLevy($grossSalary)`

**Location**: `app/Services/KenyaTaxCalculator.php`

### 3. SecurityService
**Purpose**: Manages security features and monitoring

**Key Methods**:
- `logSecurityEvent($type, $details)`
- `checkIpWhitelist($ip)`
- `detectSuspiciousActivity($userId)`

**Location**: `app/Services/SecurityService.php`

### 4. TenantContext
**Purpose**: Manages current tenant context

**Key Methods**:
- `setOrganization($organizationId)`
- `getOrganization()`
- `clearContext()`

**Location**: `app/Services/TenantContext.php`

---

## Database Design Principles

### 1. Tenant Isolation
- All tenant-scoped tables include `organization_id`
- Foreign keys maintain referential integrity
- Global scopes enforce automatic filtering

### 2. Soft Deletes
- Most models use soft deletes
- Maintains data history
- Allows data recovery

### 3. Audit Trail
- `Auditable` trait tracks changes
- Stores old/new values
- Records user and timestamp

### 4. Polymorphic Relations
- Documents can belong to multiple entities
- Flexible attachment system

---

## Security Architecture

### Authentication Layers

1. **Session-Based Auth**
   - Laravel's built-in authentication
   - CSRF protection enabled
   - Secure session management

2. **Two-Factor Authentication (2FA)**
   - TOTP-based (Time-based One-Time Password)
   - QR code generation
   - Recovery codes

3. **Password Security**
   - Bcrypt hashing
   - Password reset with tokens
   - Rate limiting on auth attempts

### Authorization Layers

1. **Role-Based Access Control (RBAC)**
   - Spatie Permission package
   - Roles: Administrator, HR Manager, Accountant, etc.
   - 32+ granular permissions

2. **Policy-Based Authorization**
   - Laravel Policies for model authorization
   - Fine-grained access control
   - Automatic policy discovery

3. **Middleware Protection**
   - `auth` - Requires authentication
   - `tenant_scope` - Enforces organization isolation
   - `system_admin` - System admin only
   - `permission:xxx` - Permission-based access

### Data Protection

1. **Input Sanitization**
   - XSS prevention
   - SQL injection protection (Eloquent ORM)
   - CSRF tokens

2. **Output Encoding**
   - Blade automatic escaping
   - Safe HTML rendering

3. **File Upload Security**
   - Type validation
   - Size limits
   - Secure storage paths

---

## Performance Optimization

### Database Optimization
- Indexed foreign keys
- Eager loading relationships
- Query result caching
- Database connection pooling

### Application Optimization
- Route caching
- Config caching
- View caching
- Opcache enabled

### Asset Optimization
- Vite for bundling
- CSS/JS minification
- Image optimization
- CDN-ready structure

---

## Scalability Considerations

### Horizontal Scaling
- Stateless application design
- Session storage in database/Redis
- File storage on shared filesystem/S3

### Vertical Scaling
- Optimized queries
- Efficient indexing
- Background job processing

### Queue System
- Laravel Queue for async tasks
- Email sending
- Report generation
- Bulk operations

---

## API Architecture

### RESTful API Design
- Resource-based endpoints
- Standard HTTP methods
- JSON responses
- API versioning support

### API Authentication
- Sanctum token-based auth
- API rate limiting
- CORS configuration

---

## Deployment Architecture

### Recommended Stack

```
┌─────────────────────────────────────────────────────────┐
│                      Load Balancer                       │
│                     (Nginx/HAProxy)                      │
└─────────────────────────────────────────────────────────┘
                            │
        ┌───────────────────┼───────────────────┐
        │                   │                   │
┌───────▼────────┐  ┌───────▼────────┐  ┌──────▼─────────┐
│  App Server 1  │  │  App Server 2  │  │  App Server N  │
│  (PHP-FPM)     │  │  (PHP-FPM)     │  │  (PHP-FPM)     │
└────────────────┘  └────────────────┘  └────────────────┘
        │                   │                   │
        └───────────────────┼───────────────────┘
                            │
        ┌───────────────────┼───────────────────┐
        │                   │                   │
┌───────▼────────┐  ┌───────▼────────┐  ┌──────▼─────────┐
│  MySQL Master  │  │  Redis Cache   │  │  File Storage  │
│  (Database)    │  │  (Sessions)    │  │  (S3/NFS)      │
└────────────────┘  └────────────────┘  └────────────────┘
```

---

## Integration Points

### Email Integration
- SMTP configuration
- Queue-based sending
- Email templates

### SMS Integration (Future)
- SMS gateway integration
- Notification system
- Bulk SMS support

### Payment Integration (Future)
- Payroll disbursement
- Bank file generation
- Payment gateway integration

---

## Monitoring & Logging

### Application Logging
- Laravel Log channels
- Error tracking
- Debug logging

### Audit Logging
- User activity tracking
- Data change history
- Security event logging

### Performance Monitoring
- Query performance
- Response times
- Resource usage

---

## Backup & Recovery

### Database Backups
- Automated daily backups
- Point-in-time recovery
- Backup retention policy

### File Backups
- Document storage backups
- Photo/attachment backups
- Backup verification

---

## Development Workflow

### Version Control
- Git-based workflow
- Feature branches
- Pull request reviews

### Testing Strategy
- Unit tests
- Feature tests
- Integration tests
- Manual QA

### Deployment Process
- Staging environment
- Production deployment
- Rollback procedures

---

## Future Architecture Considerations

### Microservices Migration
- Service decomposition
- API gateway
- Event-driven architecture

### Cloud-Native Features
- Container orchestration (Kubernetes)
- Serverless functions
- Auto-scaling

### Advanced Analytics
- Data warehouse integration
- Business intelligence tools
- Predictive analytics

---

**Last Updated**: February 2026
