RA

Task Management / Documentation Portal

Architecture • Restrictions • Design • REST API
swagger.json Back to App
⚡

Interactive API Execution Flow Assistant

Unauthenticated (Token Required)

All protected endpoints below require a valid JWT Bearer token in the Authorization: Bearer <token> header. Click 1-Click Quick Authorize below to instantly authenticate Swagger UI with live seed data.

architecture.md High-Level Architecture & Scaling Live Document

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.

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.

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:

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.
restricts.md RBAC Rules & Constraint Matrix Policy Enforcement

System Restrictions & Access Control Matrix - Task Management

1. Executive Summary & Security Philosophy

The Task Management implements a multi-layered security and restriction architecture governed by the Principle of Least Privilege (PoLP). Access boundaries are enforced simultaneously at three distinct levels:

  1. HTTP & Routing Level: Middleware pipelines (auth, must_change_password, role:superadmin, role:superadmin|admin, JwtAuthenticate).
  2. Component & Controller Level: Livewire component state guards, query scopes, and API authorization checks.
  3. Database & Query Scoping Level: Multi-tenant departmental isolation and assignee constraints embedded into Eloquent queries.

2. Role-Based Access Control (RBAC) Matrix

The system defines 4 primary roles:

Feature / Module Super Admin (superadmin) Admin (admin) Team Lead (team lead) User (user)
System Dashboard Full Global Access Department Scoped Department Scoped Restricted (Redirects to Tasks)
Task Viewing All Tasks All Dept Tasks Own Dept Tasks Assigned Tasks Only
Task Creation Allowed (Global) Allowed (Global) Allowed (Own Dept) Forbidden (403)
Task Reassignment Allowed Allowed Allowed (Own Dept) Forbidden (403)
Task Status Update Full Control Full Control Full Control Allowed (Assigned Tasks)
Task Revision Request Allowed Allowed Allowed Allowed (Assigned Tasks)
Task Approval Allowed Allowed Allowed Forbidden (403)
Task Deletion Allowed Allowed Restricted Forbidden (403)
Menu Management CRUD Full Control Read Only / Configured Read Only / Configured Forbidden (No Access)
User Management Full Control (All Users) Can manage non-superadmins Department Members Only Forbidden (403)
Superadmin User Inspection Allowed Hidden / Restricted Hidden / Restricted Forbidden (403)
Department Management Full Control Full Control Read Only Forbidden (403)
Class & Subject CRUD Full Control Allowed Read Only Forbidden (403)
Access Control (Roles/Perms) Full Control Forbidden Forbidden Forbidden (403)
Activity / Audit Log Full Raw Logs Restricted Forbidden Forbidden (403)
System Settings Full Control Forbidden Forbidden Forbidden (403)
Reports Access Global (All Filters) Dept & Task Wise Dept & Team Wise Own Dept & Personal Metrics Only
Interactive API Docs Full Access Accessible Accessible Restricted Web / Read Only

3. Module-Specific Restriction Rules

3.1 Menu Management Restrictions

  • Super Admin: Has unrestricted permission to create (POST /admin/menus), update (PUT /admin/menus/{id}), delete (DELETE /admin/menus/{id}), reorder, and activate/deactivate menu links.
  • Admin & Team Lead:
    • Cannot alter sidebar menu configurations directly.
    • Can only view and navigate menus explicitly enabled and authorized by the Super Admin in the menu_roles permission registry.
  • User Role:
    • Zero access to menu management interfaces.
    • Sidebar is stripped of administrative navigation. Users can only see Tasks and My Profile.

3.2 Task Management & Lifecycle Restrictions

  • Task Visibility Scoping:
    • superadmin: Views every task in the system without constraint.
    • admin: Views tasks across departments; superadmin-authored or sensitive audit records are masked.
    • team lead: Strictly constrained to tasks belonging to their assigned department_id.
    • user: Strictly constrained to tasks where assigned_to == auth()->user()->id or tasks where they are an active subtask participant.
  • Creation & Modification Restrictions:
    • Standard user role cannot create new tasks, update core task descriptors (title, priority, due date), assign users, or delete tasks.
    • Historical task attributes (such as previous subjects or classes linked to completed tasks) are protected from accidental alteration.
  • Revision & Approval State Machine:
    • Users can submit work for review (status = 'review') and submit revision feedback.
    • Final task sign-off and approval (POST /tasks/{id}/approve or status = 'completed') requires superadmin, admin, or team lead authorization.

3.3 Dashboard Restrictions

  • Super Admin: Sees global statistics across all departments, total active users, system completion ratios, and server load indicators.
  • Admin & Team Lead: Dashboard metrics are partitioned by department. Admin cannot view superadmin performance figures.
  • User: Direct access to /dashboard or / automatically redirects to /tasks. When personal summaries are rendered, users only see:
    • Personal assigned task count
    • Personal pending, in-progress, and review status breakdowns
    • Previous task summary and completion count

3.4 Reports & Analytics Restrictions

  • Super Admin: Full multi-dimensional analytics:
    • Department-wise, task-wise, employee-wise, monthly, and weekly analytics.
    • Advanced cross-filtering by role, department, and custom user sets.
  • Admin & Team Lead:
    • Department-wise and task-wise reporting within permitted departments.
    • Superadmin accounts and tasks are completely excluded from calculations and tables to prevent privilege leakage.
  • User Role:
    • Strictly restricted from organizational cross-department analytics.
    • Can only view their own departmental metrics and personal productivity metrics:
      • Days to complete tasks
      • Personal timeline events
      • Task review ratio and revision frequency
      • Extension count indicators

4. Task State Machine & Color-Coded Extension Rules

To prevent workflow bottlenecks and enforce accountability, task extensions are governed by deterministic lifecycle rules:

stateDiagram-v2
    [*] --> Pending: Created (Admin / Lead)
    Pending --> InProgress: Assignee Starts Work
    InProgress --> Review: Assignee Submits for Review
    
    Review --> RevisionRequested: Reviewer Requests Changes
    RevisionRequested --> InProgress: Extension Incremented (+1)
    
    Review --> Completed: Approved by Admin / Lead
    Completed --> [*]

Color-Coded Extension Rules:

When tasks are reviewed or completed, their visual badge and audit state reflects the number of revision extensions granted:

  1. 0 Extensions (On Time):
    • Badge: Green (bg-emerald-500/10 text-emerald-400 border-emerald-500/20)
    • Significance: Task completed within original timeline without revision penalty.
  2. 1st Extension (Moderate Delay):
    • Badge: Yellow (bg-amber-500/10 text-amber-400 border-amber-500/20)
    • Significance: Single revision required; flagged for monitoring.
  3. 2+ Extensions (Critical Delay):
    • Badge: Red (bg-rose-500/10 text-rose-400 border-rose-500/20)
    • Significance: Excessive revisions; flagged in employee performance and bottleneck reports.

5. Workload Scheduling & Date Conflict Restrictions

The system prevents assignee fatigue and schedule overlapping through automated conflict detection:

  1. Date Capacity Limit:
    • Assignees cannot be assigned concurrent critical tasks that exceed their daily capacity.
  2. Workload Check Endpoint (/api/tasks/workload & /api/tasks/user-workload/{userId}):
    • Before scheduling, managers can inspect assignee calendar density.
    • If an assignee is already booked for the target start and due dates, the system prompts with conflict warnings.

6. Authentication, Account & Session Restrictions

  1. Mandatory First-Time Password Change (must_change_password):
    • Newly created accounts have must_change_password = true.
    • The must_change_password middleware intercepts all requests to /dashboard, /tasks, and other routes, forcing redirect to /force-change-password until the user sets a secure credential.
  2. Deactivated Account Lockout (is_active = false):
    • If an administrator deactivates a user:
      • Web sessions are terminated immediately.
      • Login attempts return HTTP 403 Forbidden: Your account has been deactivated.
      • Subsequent /api/fresh-token requests for the user are rejected.
  3. Stateless API Security Restrictions:
    • Bearer token must be an access token. Passing a refresh token as a Bearer authorization header returns HTTP 401 Unauthorized.
    • Access tokens strictly expire after 86400 seconds (24 hours). Expired tokens cannot invoke endpoints and must be refreshed via /api/fresh-token.
    • Single-use Refresh Token Rotation (RTR): After the 30-second concurrency grace window, reused refresh tokens are treated as potential replay attacks.
design.md ER Schema & UI/UX Design System Reactive Components

System & UI/UX Design Specification - Task Management

1. Executive Summary & Design Philosophy

The Task Management is designed with a modern, high-density, real-time user experience that bridges productivity tooling with responsive reactive components. Built on Tailwind CSS, Livewire 4, and Alpine.js, the user interface provides instant state hydration, zero page reload transitions, and clear visual hierarchy optimized for fast decision-making.


2. UI/UX Design System & Theme Tokens

2.1 Color Palette & Visual Foundations

  • Background Canvas: Deep Slate (#090d16 to #0f172a), creating a distraction-free dark interface that reduces eye fatigue during extended planning sessions.
  • Surface & Cards: Semi-transparent Slate (rgba(30, 41, 59, 0.7)), elevated with subtle 1px border borders (rgba(255, 255, 255, 0.08)) and soft ambient shadows.
  • Brand & Accent Colors:
    • Primary Accent: Vibrant Indigo / Crimson Red (#4f46e5 / #ef4444) for primary actions, active navigation items, and attention triggers.
    • Success State: Emerald (#10b981) for completed tasks, 0-extension deliveries, and positive indicators.
    • Warning State: Amber (#f59e0b) for pending reviews, upcoming deadlines, and 1st-extension tasks.
    • Danger / Urgent State: Rose (#f43f5e) for overdue deadlines, 2+ extensions, and critical errors.
  • Typography: Clean sans-serif system stack (system-ui, -apple-system, BlinkMacSystemFont, Inter, Segoe UI) with strict typographic scaling (xs, sm, base, lg, xl, 2xl).

2.2 Layout & Navigation Design

  • Collapsible Sidebar:
    • Displays dynamic tenant menus filtered by authenticated user role.
    • Features quick-glance user badge, notification alerts, and instant logout action.
  • Header Bar:
    • Global Search bar with debounce filtering.
    • Real-time NotificationBell with unread count indicator and audio/desktop alerts.
    • User identity avatar and shortcut to Profile management.
  • Workspace Views (Three-Way Task Perspective):
    1. Calendar View (TaskCalendarView): Interactive monthly grid displaying date-wise task blocks, day-level inspection popups, and overdue markers.
    2. Kanban View (TaskKanbanView): Agile 4-column board (Pending, In Progress, Review, Completed) with interactive status transitions and priority badges.
    3. List View (TaskListView): High-density table featuring column sorting, bulk actions, priority tags, and quick-access action drawers.

3. Entity-Relationship (ER) & Database Design

erDiagram
    USERS ||--o{ TASKS : "creates / assigned_to"
    USERS }o--|| DEPARTMENTS : "belongs to"
    USERS }o--o| CLASSES : "enrolled in"
    USERS }o--o| SUBJECTS : "specializes in"
    USERS ||--o{ ACTIVITY_LOGS : "triggers"
    USERS ||--o{ NOTIFICATIONS : "receives"

    TASKS ||--o{ TASK_SUBTASKS : "contains"
    TASKS ||--o{ TASK_COMMENTS : "has"
    TASKS }o--o| VIDEOS : "references"
    TASKS }o--|| DEPARTMENTS : "assigned to department"

    MENUS ||--o{ MENU_ROLES : "configured for"
    ROLES ||--o{ MENU_ROLES : "grants access to"

    USERS {
        uuid id PK
        string name
        string email UK
        string mobile_number UK
        string password
        uuid class_id FK
        bigint department_id FK
        bigint subject_id FK
        string profile_photo_path
        boolean is_active
        boolean must_change_password
        timestamp last_login_at
        string last_login_ip
        timestamps created_at_updated_at
    }

    TASKS {
        bigint id PK
        string title
        text description
        string status "pending, in_progress, review, completed, revision"
        string priority "low, medium, high, urgent"
        uuid created_by FK
        uuid assigned_to FK
        bigint department_id FK
        bigint video_id FK
        date start_date
        date due_date
        time reminder_time
        integer extension_count
        timestamp completed_at
        timestamps created_at_updated_at
    }

    TASK_SUBTASKS {
        bigint id PK
        bigint task_id FK
        uuid assigned_to FK
        string title
        boolean is_completed
        integer order
        timestamps created_at_updated_at
    }

    TASK_COMMENTS {
        bigint id PK
        bigint task_id FK
        uuid user_id FK
        text comment
        string attachment_path
        timestamps created_at_updated_at
    }

    DEPARTMENTS {
        bigint id PK
        string name UK
        string code
        text description
        boolean is_active
        timestamps created_at_updated_at
    }

    CLASSES {
        uuid id PK
        string name
        string section
        boolean is_active
        timestamps created_at_updated_at
    }

    SUBJECTS {
        bigint id PK
        string name
        string code
        bigint publisher_id FK
        boolean is_active
        timestamps created_at_updated_at
    }

    ACTIVITY_LOGS {
        bigint id PK
        string action
        string module
        uuid user_id FK
        string user_name
        json payload
        string loggable_type
        bigint loggable_id
        timestamps created_at_updated_at
    }

    SYSTEM_SETTINGS {
        bigint id PK
        string key UK
        text value
        string type
        timestamps created_at_updated_at
    }

4. Component Hierarchy & Reactive Architecture

graph TD
    AppLayout["App Layout (resources/views/layouts/app.blade.php)"]
    Sidebar["Sidebar Component (views/components/sidebar.blade.php)"]
    Header["Navbar / NotificationBell (Livewire/NotificationBell.php)"]
    
    AppLayout --> Sidebar
    AppLayout --> Header
    AppLayout --> MainOutlet["Main Page Router Outlet"]

    MainOutlet --> TaskManager["TaskManager (Livewire/TaskManager.php)"]
    MainOutlet --> UserManager["UserManager (Livewire/UserManager.php)"]
    MainOutlet --> ReportManager["ReportManager (Livewire/ReportManager.php)"]
    MainOutlet --> DepartmentManager["DepartmentManager (Livewire/DepartmentManager.php)"]
    MainOutlet --> ClassManager["ClassManager (Livewire/ClassManager.php)"]
    MainOutlet --> AccessControlManager["AccessControlManager (Livewire/AccessControlManager.php)"]
    MainOutlet --> AuditLogManager["AuditLogManager (Livewire/AuditLogManager.php)"]
    MainOutlet --> SystemSettings["SystemSettings (Livewire/SystemSettings.php)"]

    TaskManager --> TaskCalendarView["TaskCalendarView (Monthly Grid)"]
    TaskManager --> TaskKanbanView["TaskKanbanView (4 Status Lanes)"]
    TaskManager --> TaskListView["TaskListView (Searchable Data Table)"]
    TaskManager --> TaskModal["Task Creation / Edit Modal (4-Person Subtasks)"]
    TaskManager --> TaskCommentDrawer["Task Comments & Discussion Drawer"]
    TaskManager --> TaskTimelineDrawer["Task Timeline & Audit Events Drawer"]

5. RESTful API Contract & Standardization

All REST endpoints follow a standardized, predictable JSON response envelope:

5.1 Success Response Schema

{
  "success": true,
  "message": "Operation completed successfully.",
  "responseMessage": "Operation completed successfully.",
  "data": { ... },
  "userDetails": { ... },
  "token": "eyJ0eXAiOiJKV1QiLC..."
}

5.2 Error Response Schema

{
  "success": false,
  "message": "Validation failed for one or more fields.",
  "errors": {
    "mobile_number": ["The mobile number has already been taken."]
  }
}

5.3 HTTP Status Codes Standard:

  • 200 OK: Request succeeded with data payload.
  • 201 Created: Resource (task, comment, user) successfully created.
  • 400 Bad Request: Malformed payload or business logic constraint violation.
  • 401 Unauthorized: Missing, invalid, or expired JWT Bearer token.
  • 403 Forbidden: Authenticated user lacks required role/permission (e.g. user accessing admin APIs).
  • 404 Not Found: Target entity not found in database.
  • 422 Unprocessable Entity: Request validation failed.
  • 500 Internal Server Error: Unhandled server exception with sanitized public response.

6. Workflows & State Progression Diagrams

6.1 Task Creation & 4-Person Subtask Allocation

sequenceDiagram
    autonumber
    actor Creator as Admin / Team Lead
    participant TM as TaskManager (Livewire / API)
    participant DB as Relational Database
    participant Echo as Pusher WebSockets
    actor Workers as 4 Assigned Subtask Workers

    Creator->>TM: Fill Task Details + 4 Assignees + Video URL
    TM->>DB: Begin Database Transaction
    TM->>DB: Insert Task Record
    TM->>DB: Insert 4 TaskSubtask Records
    TM->>DB: Commit Transaction
    TM->>DB: Write ActivityLog Entry
    TM->>Echo: Broadcast TaskAssignedNotification to each assignee
    Echo-->>Workers: Real-time Alert & Notification Bell Badge Update
    TM-->>Creator: Flash Success & Render in Calendar/Kanban

6.2 Task Revision & Extension Increment Loop

sequenceDiagram
    autonumber
    actor Worker as Assignee / Worker
    participant System as Task Management
    actor Reviewer as Reviewer (Team Lead / Admin)

    Worker->>System: Submit Task for Review (status = 'review')
    System->>Reviewer: Send Review Ready Notification
    Reviewer->>System: Reject with Feedback (POST /tasks/{id}/revision)
    System->>System: Increment extension_count by 1
    System->>System: Set status = 'in_progress' or 'revision'
    System->>System: Update color badge (Yellow if 1st, Red if 2+)
    System->>Worker: Notify Revision Requested with Comments
    Worker->>System: Re-submit Revision
    Reviewer->>System: Approve Task (POST /tasks/{id}/approve)
    System->>System: Set status = 'completed', completed_at = now()
    System->>System: Update Final Report Metrics
API_DOCUMENTATION.md Endpoints, Payloads & OAuth RTR Bearer Auth

Task Management - REST API Documentation

This document describes all REST API endpoints available in the Task Management, with special focus on authentication, role-based access control, task lifecycle management, date-wise assignee workload scheduling, and conflict detection.


1. Overview & Interactive Documentation

  • Interactive Swagger UI: GET /api/docs (served directly via api-docs.html)
  • OpenAPI 3.0 Specification: GET /api/swagger.json (served directly via swagger.json)
  • Base API URL: /api

Authentication Scheme

All protected endpoints require a JWT Bearer token in the Authorization header:

Authorization: Bearer <your-jwt-token>

2. Authentication Endpoints

2.1 Register

  • Endpoint: POST /api/register or POST /api/register/bulk

  • Access: Public

  • Single User Payload:

    {
      "name": "John Doe",
      "email": "johndoe@example.com",
      "mobile_number": "9876543210",
      "password": "password123",
      "department_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "class_id": "optional-uuid",
      "subject_id": "optional-uuid",
      "roles": ["user"]
    }
    

    (Accepts mobile_number or mobileNumber)

  • Multiple Users Payload (with Shared Department):

    {
      "department_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "users": [
        {
          "name": "User One",
          "email": "user1@example.com",
          "mobile_number": "9876543210",
          "password": "password123"
        },
        {
          "name": "User Two",
          "email": "user2@example.com",
          "mobile_number": "9876543211",
          "password": "password123",
          "department_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6"
        }
      ]
    }
    

    (Also accepts a raw JSON array of users [ { ... }, { ... } ])

  • Single User Response 201 Created:

    {
      "success": true,
      "message": "Registration successful.",
      "token": "eyJ0eXAiOiJKV1QiLC...",
      "token_type": "Bearer",
      "expires_in": 86400,
      "refresh_token": "...",
      "userDetails": {
        "id": "9a1b2c3d-...",
        "name": "John Doe",
        "email": "johndoe@example.com",
        "mobile_number": "9876543210",
        "department_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
        "roles": ["user"]
      }
    }
    
  • Multiple Users Response 201 Created:

    {
      "success": true,
      "message": "2 users registered successfully.",
      "count": 2,
      "users": [
        {
          "token": "eyJ0eXAiOiJKV1QiLC...",
          "token_type": "Bearer",
          "expires_in": 86400,
          "refresh_token": "...",
          "userDetails": {
            "id": "uuid-1",
            "name": "User One",
            "email": "user1@example.com",
            "mobile_number": "9876543210",
            "department_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
            "roles": ["user"]
          }
        },
        {
          "token": "eyJ0eXAiOiJKV1QiLC...",
          "token_type": "Bearer",
          "expires_in": 86400,
          "refresh_token": "...",
          "userDetails": {
            "id": "uuid-2",
            "name": "User Two",
            "email": "user2@example.com",
            "mobile_number": "9876543211",
            "department_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
            "roles": ["user"]
          }
        }
      ],
      "data": [...]
    }
    

2.2 Login

  • Endpoint: POST /api/login
  • Access: Public
  • Payload:
    {
      "mobileNumber": "9999999999",
      "password": "password123"
    }
    
    (Accepts email or mobileNumber interchangeably)
  • Response 200 OK:
    {
      "success": true,
      "message": "Login successful.",
      "token": "eyJ0eXAiOiJKV1QiLC...",
      "userDetails": {
        "id": "9a1b2c3d-...",
        "name": "Admin User",
        "email": "admin@eveapplication.com",
        "mobile_number": "9999999999",
        "roles": ["admin"]
      }
    }
    

2.3 Fresh Token / Refresh Token (OAuth 2.0 Flow)

  • Endpoint: POST /api/fresh-token (Aliases: POST /api/refresh-token, POST /api/refresh)
  • Access: Public (requires valid refresh_token)
  • Headers:
    Content-Type: application/json
    X-Refresh-Token: <optional-refresh-token-in-header>
    
  • Payload:
    {
      "refresh_token": "eyJ0eXAiOiJKV1QiLC..."
    }
    
    (Accepts refresh_token, camelCase refreshToken, X-Refresh-Token header, or Authorization: Bearer <refresh_token>)
  • Response 200 OK:
    {
      "success": true,
      "message": "Token refreshed successfully.",
      "responseMessage": "Token refreshed successfully.",
      "token": "eyJ0eXAiOiJKV1QiLC...<new-access-token>",
      "access_token": "eyJ0eXAiOiJKV1QiLC...<new-access-token>",
      "token_type": "Bearer",
      "expires_in": 86400,
      "refresh_token": "eyJ0eXAiOiJKV1QiLC...<new-rotated-refresh-token>",
      "userDetails": { ... },
    }
    
  • Security Features & Best Practices:
    • Token Type Isolation: Refresh tokens cannot be used to call protected APIs; access tokens cannot be used to refresh.
    • Refresh Token Rotation (RTR): Upon every refresh, a new refresh token is issued and the old one is invalidated.
    • Replay Attack Detection: If a previously consumed or revoked refresh token is re-submitted, it is blocked immediately.
    • Concurrency Grace Window: Parallel requests (common in React & Flutter when multiple widgets fire simultaneously) share the same fresh token pair within a 30-second window, preventing race-condition 401 logouts.

2.4 Current User

  • Endpoint: GET /api/me
  • Access: Authenticated (Bearer <token>)
  • Response 200 OK: Returns authenticated user profile, assigned roles, and relations.

2.5 Logout

  • Endpoint: POST /api/logout
  • Access: Authenticated (Bearer <token>)
  • Response 200 OK:
    {
      "success": true,
      "message": "Successfully logged out."
    }
    

3. Tasks & Date-Wise Workload Management

3.1 List Tasks

  • Endpoint: GET /api/tasks
  • Query Parameters:
    • status (pending, in_progress, revision, review, completed, approved, cancelled)
    • priority (low, medium, high, urgent)
    • assigned_to (UUID)
    • department_id (Integer)
    • search (String)
    • start_date (YYYY-MM-DD, exact start date match)
    • start_date_from (YYYY-MM-DD, tasks starting on or after)
    • start_date_to (YYYY-MM-DD, tasks starting on or before)
    • due_date_from (YYYY-MM-DD, tasks due on or after)
    • due_date_to (YYYY-MM-DD, tasks due on or before)

3.2 Create Task

  • Endpoint: POST /api/tasks
  • Payload:
    {
      "title": "Color Grading Physics Class 10",
      "description": "Adjust color grading and tone curve.",
      "assigned_to": "9a1b2c3d-0000-0000-0000-000000000001",
      "department_id": 1,
      "priority": "urgent",
      "status": "pending",
      "start_date": "2026-10-05 4:20 P.M",
      "due_date": "2026-10-15 4:25 P.M"
    }
    

3.3 Date-Wise Assignee Workload & Conflict Schedule (New ✨)

Provides real-time date-wise task assignment schedule for an assignee, total active/overdue task counters, and collision detection against a chosen due date.

Option A: Path Parameter with Date Query

  • Endpoint: GET /api/tasks/user-workload/{userId}?date=2026-09-30
  • Parameters:
    • userId (Path, UUID, required): Target user ID
    • date (Query, YYYY-MM-DD, optional): Target due date for conflict calculation
  • Response 200 OK:
    {
      "success": true,
      "message": "User workload retrieved successfully.",
      "data": {
        "user": {
          "id": "9a1b2c3d-0000-0000-0000-000000000001",
          "name": "Nilanjan Mondal",
          "email": "nilanjan@eveapplication.com",
          "department": "Video Production"
        },
        "summary": {
          "total_assigned": 8,
          "active_tasks": 4,
          "completed_tasks": 3,
          "overdue_tasks": 1
        },
        "conflict_check": {
          "checked_date": "2026-09-30",
          "has_conflict": true,
          "conflict_count": 2,
          "tasks_on_date": [
            {
              "id": 12,
              "title": "Intro Montage Animation",
              "priority": "high",
              "status": "in_progress",
              "due_date": "2026-09-30 14:00:00"
            },
            {
              "id": 15,
              "title": "Audio Mastering Chapter 2",
              "priority": "medium",
              "status": "pending",
              "due_date": "2026-09-30 17:30:00"
            }
          ]
        },
        "datewise_tasks": {
          "2026-09-29": {
            "date": "2026-09-29",
            "date_formatted": "Sep 29, 2026 (Tue)",
            "task_count": 1,
            "active_count": 1,
            "tasks": [ ... ]
          },
          "2026-09-30": {
            "date": "2026-09-30",
            "date_formatted": "Sep 30, 2026 (Wed)",
            "task_count": 2,
            "active_count": 2,
            "tasks": [ ... ]
          }
        }
      }
    }
    

Option B: Query Parameters

  • Endpoint: GET /api/tasks/workload?user_id={userId}&date=2026-09-30

3.4 Single API: User Tasks & Subtasks in One Call (New ✨)

Retrieve all tasks (with nested subtasks) and all direct subtasks assigned to a specific user, complete with department details and aggregate KPI counters.

  • Endpoint: GET /api/user/{userId}/tasks (Alias: GET /api/users/{userId}/tasks)
  • Parameters:
    • userId (Path, UUID, required): Target user ID
    • status (Query, string, optional): pending, in_progress, revision, review, completed, approved, cancelled
  • Response 200 OK:
    {
      "success": true,
      "message": "User tasks and subtasks retrieved successfully.",
      "user": {
        "id": "9d36a992-0bca-4b08-9df2-51a44e548232",
        "name": "Nilanjan Mondal",
        "email": "nilanjan@example.com",
        "department": { "id": "uuid", "name": "Editorial Department", "code": "EDIT" }
      },
      "summary": {
        "tasks": { "total": 5, "pending": 1, "in_progress": 3, "completed": 1, "overdue": 0 },
        "subtasks": { "total": 8, "pending": 2, "in_progress": 4, "completed": 2 }
      },
      "tasks": [ ... ],
      "subtasks": [ ... ]
    }
    

3.5 Quick Status & Quick Assign

  • Endpoint: PATCH /api/tasks/{id}/status
    • Payload: {"status": "in_progress"}
  • Endpoint: PATCH /api/tasks/{id}/assign
    • Payload: {"assigned_to": "9a1b2c3d-..."}
  • Endpoint: PATCH /api/tasks/{id}/workflow-stage
    • Transition task directly to a specific workflow section/stage.
    • Payload: {"stage": "Quality Check"}
  • Endpoint: POST /api/tasks/{id}/advance-stage
    • Advance task sequentially to the next workflow stage in its assigned pipeline.
  • Endpoint: PATCH /api/tasks/{id}/workflow
    • Assign or reassign workflow pipeline to task.
    • Payload: {"workflow_id": 1}

4. Multi-Person Subtasks & Comments

4.1 Subtasks

  • GET /api/tasks/{taskId}/subtasks - List subtasks for a task (filterable by page_no, assigned_to, department_id, status, search, and per_page)
  • GET /api/tasks/{taskId}/subtasks/{subtaskId} - Retrieve single subtask details
  • POST /api/tasks/subtasks or POST /api/tasks/{taskId}/subtasks - Create subtasks with page_no and JSON due_date:
    {
      "task_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "subtasks": [
        {
          "title": "Audio Sync & Sound Design",
          "description": "Sync audio tracks with video timeline and balance audio levels.",
          "page_no": "12-15",
          "assigned_to": [
            "3fa85f64-5717-4562-b3fc-2c963f66afa6"
          ],
          "status": "pending",
          "due_date": {
            "from": "2026-07-02",
            "to": "2026-07-04"
          }
        },
        {
          "title": "Color Grading",
          "description": "Balance saturation, match camera profiles, and export LUT.",
          "page_no": "16-20",
          "assigned_to": [
            "3fa85f64-5717-4562-b3fc-2c963f66afa6"
          ],
          "status": "pending",
          "due_date": {
            "from": "2026-10-15",
            "to": "2026-10-15"
          }
        }
      ]
    }
    
  • POST /api/tasks/subtasks/bulk - Bulk create subtasks across multiple parent tasks (with page_no)
  • PUT /api/tasks/{taskId}/subtasks/{subtaskId} or PATCH /api/tasks/{taskId}/subtasks/{subtaskId} - Unified Subtask Management (One API):
    • Update standard fields (title, description, page_no, assigned_to, due_date, status)
    • Request Revision: Pass { "revision_date": "2026-10-25 18:00:00", "revision_notes": "Color correction needed" } to automatically set status: "revision", increment extension_count, and update schedule deadlines.
    • Approve Subtask: Pass { "status": "approved" } or { "action": "approve" } to set approved_at: now(), approved_by: <user_id>, and finalize subtask.
    • Update Revision Notes/Extensions: Directly update revision_notes or extension_count.
  • POST /api/tasks/{taskId}/subtasks/{subtaskId}/revision - Dedicated subtask revision request endpoint (revision_date required, revision_notes optional)
  • POST /api/tasks/{taskId}/subtasks/{subtaskId}/approve - Dedicated subtask approve endpoint
  • PATCH /api/tasks/{taskId}/subtasks/{subtaskId}/toggle - Toggle subtask completion status
  • DELETE /api/tasks/{taskId}/subtasks/{subtaskId} - Remove subtask

4.2 Comments & Audit Trail

  • GET /api/tasks/{taskId}/comments - Discussion comments & system change audit logs
  • POST /api/tasks/{taskId}/comments - Post comment
  • DELETE /api/tasks/{taskId}/comments/{commentId} - Delete comment

5. Workflows Master API

The Workflow Master entity enables organizations to define structured, multi-section lifecycle pipelines with custom sequential stages (e.g., Drafting -> Review -> Proofing -> Final Approval -> Completed).

5.1 Endpoints

  • GET /api/workflows - List all workflows with search and department filtering
  • POST /api/workflows - Create a new workflow pipeline with custom stages/sections
    {
      "name": "Video Production Pipeline",
      "code": "VIDEO_PIPELINE",
      "description": "Multi-stage video editing and QA pipeline",
      "department_id": 2,
      "stages": [
        "1. Audio Prep & Sound Sync",
        "2. Color Grading & Tone",
        "3. Voiceover & Subtitles",
        "4. Quality Inspection",
        "5. Final Sign-off & Delivery"
      ],
      "is_active": true
    }
    
  • GET /api/workflows/{id} - Retrieve details of a workflow
  • PUT /api/workflows/{id} - Update a workflow pipeline and its stages
  • DELETE /api/workflows/{id} - Delete a workflow (unlinks associated tasks safely)
  • GET /api/workflows/{id}/stages - Get ordered stages array for dropdowns/steppers

6. Task Types Master API

The Task Types Master entity manages task classifications (such as Book, Video, Audio Podcast, etc.). Allows listing with associated task counts, creating, updating via dedicated or unified save endpoints, and safely deleting task types with auto-nullification of references on existing tasks.

6.1 Endpoints

  • GET /api/task-types - List all task types with optional keyword search and is_active filter
  • POST /api/task-types - Create a new task type
  • POST /api/task-types/save - Unified Save API: Create new task type or update existing if id is provided in payload
  • GET /api/task-types/{id} - Retrieve details of a task type by UUID or unique code
  • PUT /api/task-types/{id} or PATCH /api/task-types/{id} - Update a task type
  • DELETE /api/task-types/{id} - Delete a task type (safely disassociates tasks by setting task_type_id: null)
{
  "name": "Audio Podcast",
  "code": "audio_podcast",
  "description": "Podcast production and sound engineering",
  "is_active": true
}

7. Other Modular Resources

Section Endpoints Key Capabilities
Task Types /api/task-types (GET, POST), /api/task-types/save (POST), /api/task-types/{id} (GET, PUT, PATCH, DELETE) Master categories (Book, Video, etc.) with task counts & safe delete
Workflows /api/workflows (GET, POST, PUT, DELETE), /api/workflows/{id}/stages Multi-section lifecycle pipelines and stages
Departments /api/departments (GET, POST), /api/departments/tree (GET), /api/departments/parent/{parentId} (GET), /api/departments/{id}/sub-departments (GET), /api/departments/{id} (GET, PUT, DELETE) Manage parent departments & sub-departments, parent-wise tree, direct child sub-departments, circular check & team leads
Classes /api/classes (GET, POST, PUT, DELETE) Academic classes breakdown
Subjects /api/subjects (GET, POST, PUT, DELETE) Curriculum subjects under classes
Access Control /api/roles (GET, POST), /api/roles/{id} (GET, PUT, PATCH, DELETE), /api/roles/{id}/toggle-status (PATCH), /api/roles/{id}/status (PUT, PATCH), /api/permissions (GET), /api/roles/{id}/permissions (POST), /api/users/{id}/roles (POST) RBAC synchronization, role active/deactive status management (is_active filter & toggle, superadmin protection), and user role assignment
Settings /api/settings (GET, POST) System configuration key-value storage
Audit Logs /api/audit-logs (GET), /api/audit-logs/{id} (GET) Full audit trail and change inspector
Dashboard /api/dashboard/stats, /api/reports/analytics High-level metrics and workload charts
Menus /api/menus (GET, POST, PUT, DELETE) Navigation hierarchies and role permissions
Notifications /api/notifications, /api/notifications/{id}/read, /api/notifications/mark-all-read User notifications
Resource Attachment /api/attach_resources (POST, aliases: /api/attach_respurces, /api/attach-resources), /api/detach_resources (POST), /api/attached_resources (GET) Attach and detach multiple polymorphic resources (departments, subjects) to/from users and models (user_id, resource_id, department, subject)