# System Architecture Specification - Task Management ## 1. Executive Summary & Architecture Overview The **Task Management** is an enterprise-grade Task Management and Workflow Automation Platform built on **Laravel 12**, **Livewire 4**, **Tailwind CSS**, **Redis**, and **Pusher WebSockets**. The system is engineered to provide seamless real-time task lifecycle tracking, multi-tenant departmental segmentation, role-based access control (RBAC), intelligent workload balancing, and a comprehensive RESTful API for external and mobile client integrations. ```mermaid graph TD subgraph ClientLayer["Client & Presentation Layer"] Browser["Modern Web Browser (Blade + Livewire 4 + Tailwind)"] MobileApp["Mobile / External Client (Flutter / React Native)"] SwaggerUI["Interactive API Documentation Portal (Swagger 3.0)"] end subgraph GatewayLayer["Traffic & Security Gateway"] Nginx["Nginx Reverse Proxy / SSL Termination"] RateLimiter["Rate Limiting & Throttle Gate"] CorsMiddleware["CORS & Security Headers Middleware"] end subgraph AppLayer["Application & Controller Layer"] WebKernel["Laravel 12 HTTP Kernel"] LivewireEng["Livewire Reactive Engine (State Hydration)"] ApiController["REST API Controllers (JSON Contracts)"] AuthMiddleware["Auth Guards (Web Session & JWT Authenticate)"] RbacMiddleware["RBAC Guard (Spatie)"] end subgraph ServiceLayer["Business Logic & Service Layer"] WorkloadService["Workload & Capacity Engine"] TaskStateMachine["Task Lifecycle & State Machine"] PusherBroadcaster["Real-time Pusher Event Broadcaster"] JwtService["JWT & Refresh Token Rotation (RTR) Service"] ActivityLogger["Audit & Activity Logging Engine"] NotificationEngine["Database & Webhook Notification Engine"] end subgraph StorageLayer["Data & Persistence Layer"] PrimaryDB[("Primary Relational DB (MySQL / PostgreSQL / SQLite)")] RedisCache[("Redis 7.x (Cache, Tags, RTR Lock & Concurrency Window)")] RedisQueue[("Redis Queue & Horizon Worker Daemons")] PublicStorage["Local / S3 Storage (Profile Photos & Attachments)"] end Browser --> Nginx MobileApp --> Nginx SwaggerUI --> Nginx Nginx --> RateLimiter --> CorsMiddleware --> WebKernel WebKernel --> AuthMiddleware --> RbacMiddleware RbacMiddleware --> LivewireEng RbacMiddleware --> ApiController LivewireEng --> ServiceLayer ApiController --> ServiceLayer ServiceLayer --> PrimaryDB ServiceLayer --> RedisCache ServiceLayer --> RedisQueue ServiceLayer --> PusherBroadcaster ServiceLayer --> PublicStorage ``` --- ## 2. Multi-Tier Architectural Layers ### 2.1 Presentation Layer (Web & Client) - **Livewire 4 Reactive Components**: Full-page and embedded components (`TaskManager`, `TaskKanbanView`, `TaskCalendarView`, `TaskListView`, `UserManager`, `DepartmentManager`, `ClassManager`, `AccessControlManager`, `ReportManager`, `SystemSettings`, `NotificationBell`, `AuditLogManager`). - **Tailwind CSS & Blade Layouts**: Responsive UI with dark mode, custom slate accents, glassmorphic modals, and dynamic data-binding without heavy SPA build overhead. - **Client-Side Event Bus**: Pusher JS and Laravel Echo listeners subscribed to private and public broadcast channels to mutate local DOM state on real-time server events. ### 2.2 Application & Routing Layer - **Web Routes (`routes/web.php`)**: - Public & Guest Routes: `/login`, `/forgot-password`, `/reset-password`. - Authenticated & Password-Protected Routes: Enforced by `auth` and `must_change_password` middleware. - Role-Scoped Routes: Protected by Spatie `role:superadmin|admin`. - Documentation Routes: High-performance public routes (`/docs`, `/api-docs`, `/swagger.json`) bypassing unnecessary session overhead. - **API Routes (`routes/api.php`)**: - Stateless JSON endpoints secured by custom `JwtAuthenticate` middleware. - Public authentication endpoints: `/api/login`, `/api/register`, `/api/fresh-token`. ### 2.3 Service & Business Logic Layer - **`JwtService`**: - Issues HMAC-SHA256 access tokens (default TTL: 24 hours / 86400 seconds) and cryptographically distinct refresh tokens (default TTL: 30 days). - Implements **Refresh Token Rotation (RTR)**: Every refresh operation invalidates the old refresh token and issues a new pair. - Incorporates a **Concurrency Grace Window (30 seconds)** in Redis to eliminate race conditions from parallel mobile app requests. - **`ActivityLogger`**: - Asynchronously tracks user actions across system modules (Authentication, Task Lifecycle, Role Sync, User Management). - Records Actor ID, Actor Name, Action, Module, IP Address, User-Agent, and polymorphic target entities. - **Workload & Capacity Engine**: - Aggregates assignee date workloads across overlapping task date ranges. - Detects resource overcommitments and enforces scheduling capacity thresholds. - **Real-Time Notification Pipeline**: - Dispatches `TaskAssignedNotification` and `SystemAlertEvent` through Pusher WebSockets and Laravel's database notifications table. ### 2.4 Data Persistence & Cache Layer - **Relational Database**: - Normalized schema with strict foreign key constraints, indexes on lookup fields (`mobile_number`, `email`, `status`, `assigned_to`, `department_id`), and UUIDs for external/class references. - **Redis Cache & Queues**: - In-memory key-value caching for system settings and permission hierarchies. - Background asynchronous execution handled by Redis queue drivers and monitored via **Laravel Horizon**. --- ## 3. Real-Time WebSockets & Event-Driven Architecture The platform uses **Pusher WebSockets** with Laravel event broadcasting to deliver sub-second updates across clients without polling. ```mermaid sequenceDiagram autonumber actor Admin as Admin / Team Lead participant System as Task Management Server participant Pusher as Pusher WebSocket Gateway actor Assignee as Assignee (Browser / Mobile) actor Team as Team Members Admin->>System: Assign Task (POST /tasks or PATCH /api/tasks/{id}/assign) System->>System: Persist Task & Insert ActivityLog System->>System: Trigger TaskAssignedNotification System->>Pusher: Broadcast TaskAssignedEvent (Channel: private-user.{id}) System->>Pusher: Broadcast TaskUpdatedEvent (Channel: task-updates) Pusher-->>Assignee: Push Desktop Alert & Sound Notification Pusher-->>Team: Push Kanban & Calendar DOM Re-render System-->>Admin: Return HTTP 200 / Livewire Response ``` ### Channel Architecture: 1. **`private-user.{id}`**: Authenticated private channel per user for notifications, assigned tasks, and personal alerts. 2. **`task-updates`**: Channel broadcasting task status shifts (`pending` $\rightarrow$ `in_progress` $\rightarrow$ `review` $\rightarrow$ `completed`), date alterations, and comment additions. 3. **`system-alerts`**: Public broadcast channel for system-wide announcements and emergency administrative alerts. --- ## 4. Authentication, OAuth 2.0 & Token Lifecycle Architecture Task Management supports a dual authentication pipeline: ```mermaid flowchart TD Req["Incoming HTTP Request"] --> IsApi{"Path starts with /api/?"} IsApi -- Yes --> IsPublic{"Public Endpoint? (/login, /register, /fresh-token)"} IsPublic -- Yes --> HandlePublicApi["Execute Controller & Issue JWT Pair"] IsPublic -- No --> JwtAuthFilter["JwtAuthenticate Middleware"] JwtAuthFilter --> ValidateHmac["Validate HMAC-SHA256 Signature"] ValidateHmac -- Invalid --> Ret401["HTTP 401 Unauthorized"] ValidateHmac -- Valid --> CheckType{"Token Type == 'access'?"} CheckType -- No (Refresh token used as Bearer) --> Ret401Type["HTTP 401: Refresh token cannot be used as Bearer"] CheckType -- Yes --> CheckExp{"Token Expired?"} CheckExp -- Yes --> Ret401Exp["HTTP 401: Access token expired"] CheckExp -- No --> AttachUser["Hydrate Request with Authenticated User"] AttachUser --> EnforceActive{"User is_active == 1?"} EnforceActive -- No --> Ret403Deactive["HTTP 403: Account Deactivated"] EnforceActive -- Yes --> ExecApiEndpoint["Execute Protected API Action"] IsApi -- No --> WebSessionAuth["Laravel Session Auth ('web' guard)"] WebSessionAuth --> CheckWebAuth{"Auth::check()?"} CheckWebAuth -- No --> RedirectLogin["Redirect to /login"] CheckWebAuth -- Yes --> ForcePwdCheck{"must_change_password == 1?"} ForcePwdCheck -- Yes --> ForcePwdRedirect["Redirect to /force-change-password"] ForcePwdCheck -- No --> ExecWebAction["Execute Livewire / Web View"] ``` ### Refresh Token Rotation (RTR) & Grace Window: When a client requests `/api/fresh-token`: 1. Signature and token type (`refresh`) are validated against the application key. 2. If the refresh token was already consumed within the last **30 seconds** (the grace window), the cached token pair is returned to avoid failure caused by simultaneous asynchronous HTTP requests in mobile frameworks. 3. If an expired or replayed token is detected outside the grace window, the request is immediately rejected to prevent token replay attacks. 4. A brand-new access token and rotated refresh token are issued. --- ## 5. Security & Isolation Architecture 1. **Role Scoping & Middleware Guarding**: - `role:superadmin`: Restricts destructive system configurations, menu schema creation, and raw audit log access exclusively to Super Administrators. 2. **Data-Level Tenancy Scoping**: - Livewire queries and Eloquent repository calls enforce scope isolation: - `user`: Filtered strictly by `assigned_to == auth()->id()`. - `team lead`: Filtered strictly by `department_id == auth()->user()->department_id`. - `admin`: Scoped to department and team hierarchies, hiding superadmin identities and operational records. - `superadmin`: Unfiltered global visibility. 3. **Database Security**: - Parameterized queries and Eloquent ORM eliminate SQL Injection vulnerabilities. - Password hashing strictly uses `bcrypt` with robust work factors. - Cross-Site Request Forgery (CSRF) protection on all web mutations. --- ## 6. Infrastructure & Deployment Architecture - **Web Server**: Nginx with HTTP/2 and gzip/brotli compression for static and compiled assets (`public/build`). - **PHP Runtime**: PHP 8.2+ FPM configured with OPcache enabled for maximum throughput. - **Process Supervisor**: Supervisor monitoring `php artisan queue:listen` and `php artisan horizon` workers. - **Monitoring & Health Checks**: Dedicated `/health` endpoint providing continuous uptime inspection of app status, database connectivity, Redis connection, and public storage symbolic links.