# Timeline Architecture

## Overview

The Timeline system provides a visual representation of project tasks and employee assignments over time. It is built using a React-based frontend (using the SVAR React Gantt library) and a Laravel API backend.

## System Components

### 1. API Backend (`src/App/Http/Controllers/Api/v1/TimelineController.php`)

The Timeline uses a versioned API (`v1`) for all data interactions. This controller follows the project's standardized API architecture (`BaseApiController`), ensuring consistent JSON responses.

**Key Endpoints:**
- `POST /api/v1/timeline/tasks`: Retrieves filtered tasks grouped by employee.
- `POST /api/v1/timeline/date-ranges`: Calculates the dynamic viewport range based on filters.
- `POST /api/v1/timeline/open-task`: Persists the expanded/collapsed state of an employee's task list.
- `PUT /api/v1/timeline/tasks/{id}`: Updates task dates, status, or assignment (drag & drop).

### 2. Shared Services (`src/App/Services/Timeline/`)

To ensure consistency between the web view and the API, core logic is encapsulated in shared services:

- **`TimelineTasksService.php`**: 
  - Handles the complex SQL querying of `projecttasks` joined with `assignees`, `employees`, and `projects`.
  - Applies multi-level filtering (Project, Employee, Status, Dates).
  - Formats raw database records into the hierarchical structure required by the Gantt component.
  - Implements the "last 1 year" guardrail (applied only when user dates are not specified).

- **`TimelineDateRangesService.php`**:
  - Calculates the start and end dates for the Gantt viewport.
  - Automatically adjusts the range based on the filtered task set to ensure the viewport is centered on relevant data.

### 3. Frontend Architecture (`resources/js/Timeline/`)

The frontend is a decoupled React application organized into components, hooks, and utilities.

- **`page/Timeline.jsx`**: The main entry point that manages the global state (filters, search, data loading).
- **`components/GanttChart.jsx`**: A wrapper around the `GanttChartRenderer` that integrates with custom hooks for operations.
- **`hooks/`**: Encapsulates logic for specific operations:
  - `useTaskOperations.js`: CRUD actions (update, move, open).
  - `useTaskResize.js`: Handles start/end date changes via dragging.
  - `useVisualTaskDrag.js`: Manages the UI feedback during drag-and-drop.
- **`ZoomControl.jsx`**: Manages zoom levels (Hour, Day, Week, Month, Quarter, Year) and fetches dynamic ranges from the backend.

## Data Flow

1. **Initialization**: The initial page load (`TimelineController@index`) provides the base HTML and initial filter metadata via Blade templates.
2. **Data Fetching**: The React component fetches task data via `POST /api/v1/timeline/tasks`. Filters are sent in a grouped format:
   ```json
   {
     "filters": {
       "projecttask": { "startdate": "...", "enddate": "..." },
       "project": { "refid": [...] },
       "employee": { "refid": [...] }
     }
   }
   ```
3. **Viewport Management**: Whenever filters change, the `ZoomControl` requests new date ranges to ensure the timeline displays the correct time window.
4. **Persistence**: User actions (resizing a task, moving it to another employee) trigger `PUT` requests to the API, which updates the database and returns the refreshed task set.

## Real-time Synchronization

The Timeline integrates with the project's broadcasting system. When a task is updated via the Timeline, a `ProjectTaskUpdated` event is broadcasted. This allows other users viewing the same project to receive instant notifications or updates.

For detailed information on broadcasting, see: [Gantt Real-Time Broadcast Architecture](./broadcasting/gantt.md).

## Key Implementation Details

- **Multi-Tenancy**: All database queries explicitly use the `tenant_connection` to ensure data isolation.
- **Task Identification**: The frontend uses `externalId` (which maps to the database `refid`) for identifying tasks in most API operations.
- **Date Handling**: Dates are processed using `Carbon` on the backend and native `Date` objects on the frontend, with a consistent `YYYY-MM-DD` format for API communication.

## Debugging Guide

- **Backend Issues**: Check `storage/logs/laravel.log` for SQL errors or validation failures. The API endpoints log filter parameters for easier reproduction.
- **Frontend Issues**: Use React Developer Tools to inspect the `updateData` state in `TimelineIndex`.
- **Query Performance**: The `TimelineTasksService` uses complex joins; use Laravel Telescope or `DB::listen` to analyze query execution times if the timeline feels slow.
