TaskView is a self-hosted project and task management platform focused on clarity, ownership, and control. TaskView is built for teams that want a transparent, self-hosted alternative to SaaS task managers.
TypeScript graphviewkanban-boardnodejsproductivityproject-managementself-hostedtasktask-managementtask-managertodoapp
wip: time tracking
Nikolai Gimand08143651945
diff --git a/api/src/core/AppUser.ts b/api/src/core/AppUser.tsindex 07e03c1..89ef2e9 100644--- a/api/src/core/AppUser.ts+++ b/api/src/core/AppUser.ts@@ -13,6 +13,7 @@ import { OrganizationManager } from '../tv-modules/organizations/OrganizationManimport { SsoManager } from '../tv-modules/sso/SsoManager';import { AnalyticsManager } from '../tv-modules/analytics/AnalyticsManager';import { TasksManager } from '../tv-modules/tasks/TasksManager';+import { TimeTrackingManager } from '../tv-modules/time-tracking/TimeTrackingManager';import type { UserDbRecord, UserJwtPayload } from '../types/auth.types';import { GoalPermissionsFetcher } from './GoalPermissionsFetcher';@@ -39,6 +40,7 @@ export class AppUser {public readonly organizationManager: OrganizationManager;public readonly ssoManager: SsoManager;public readonly analyticsManager: AnalyticsManager;+ public readonly timeTrackingManager: TimeTrackingManager;constructor(userData?: UserJwtPayload) {this.userData = userData;@@ -58,6 +60,7 @@ export class AppUser {this.organizationManager = new OrganizationManager(this);this.ssoManager = new SsoManager(this);this.analyticsManager = new AnalyticsManager(this);+ this.timeTrackingManager = new TimeTrackingManager(this);}getTokenId(): number | undefined {diff --git a/api/src/core/EventBus.ts b/api/src/core/EventBus.tsindex af843a6..c7ff0bc 100644--- a/api/src/core/EventBus.ts+++ b/api/src/core/EventBus.ts@@ -1,5 +1,5 @@import { EventEmitter } from 'node:events';-import type { TasksSchemaTypeForSelect } from 'taskview-db-schemas';+import type { TasksSchemaTypeForSelect, TimeEntriesSchemaTypeForSelect } from 'taskview-db-schemas';import { $logger } from '../modules/logget';export interface AppEvents {@@ -10,6 +10,11 @@ export interface AppEvents {'collaboration.userAdded': { goalId: number; email: string; initiatorId: number };'collaboration.userRemoved': { goalId: number; collaborationUserId: number; initiatorId: number };'collaboration.rolesChanged': { goalId: number; collaborationUserId: number; initiatorId: number };+ 'time-entry.started': { entry: TimeEntriesSchemaTypeForSelect; taskId: number; userId: number; goalId: number };+ 'time-entry.stopped': { entry: TimeEntriesSchemaTypeForSelect; taskId: number; userId: number; goalId: number; durationSeconds: number };+ 'time-entry.created': { entry: TimeEntriesSchemaTypeForSelect; initiatorId: number };+ 'time-entry.updated': { entry: TimeEntriesSchemaTypeForSelect; changes: Record<string, unknown>; initiatorId: number };+ 'time-entry.deleted': { entryId: number; taskId: number; goalId: number; userId: number; initiatorId: number };}type EventName = keyof AppEvents;diff --git a/api/src/core/all-events.ts b/api/src/core/all-events.tsindex dd46126..ef54491 100644--- a/api/src/core/all-events.ts+++ b/api/src/core/all-events.ts@@ -3,11 +3,13 @@ import type { Dispatcher } from './Dispatcher';import { NotificationDispatcher } from '../tv-modules/notifications/NotificationDispatcher';import { RealtimeDispatcher } from '../tv-modules/realtime/RealtimeDispatcher';import { WebhooksDispatcher } from '../tv-modules/webhooks/WebhooksDispatcher';+import { TimeTrackingDispatcher } from '../tv-modules/time-tracking/TimeTrackingDispatcher';const dispatchers: Dispatcher[] = [new NotificationDispatcher(),new RealtimeDispatcher(),new WebhooksDispatcher(),+ new TimeTrackingDispatcher(),];export function registerAllEventHandlers() {diff --git a/api/src/migrations/taskview/migrate.json b/api/src/migrations/taskview/migrate.jsonindex ea13db0..2ba3624 100644--- a/api/src/migrations/taskview/migrate.json+++ b/api/src/migrations/taskview/migrate.json@@ -507,5 +507,24 @@"Add partial index on tasks.goals(organization_id) WHERE archive = 0 for analytics goal lookup","Add partial index on tasks.tasks(goal_id) WHERE complete IS NOT TRUE for open-task analytics queries"]+ },+ "41": {+ "version": "1.48.0",+ "name": "Release 1.48.0",+ "releaseDate": "20260511",+ "scripts": [+ "/1.48.0/0.create-time-entries.sql",+ "/1.48.0/1.create-time-entries-history.sql",+ "/1.48.0/2.alter-organizations-add-autostop.sql",+ "/1.48.0/3.add-timetracking-permissions.sql",+ "/1.48.0/all-triggers.sql"+ ],+ "description": [+ "Added time-tracking module: tasks.time_entries with one-active-timer-per-user partial unique index",+ "Added history.time_entries audit table with FK ON DELETE CASCADE to time_entries (history removed with the entry)",+ "Added time_tracking_autostop_hours column to tv_auth.organizations (default 24, NULL = disabled)",+ "Added timetracking_can_log and timetracking_can_manage_all goal-level permissions (granted to new projects only, matching the 1.46.0 analytics convention)",+ "all-triggers.sql: updated add_roles_and_permissions function with new permissions; added log_changes_time_entries trigger (BEFORE UPDATE writes JSONB snapshot to history.time_entries)"+ ]}}\ No newline at end of filediff --git a/api/src/migrations/taskview/sql/1.48.0/0.create-time-entries.sql b/api/src/migrations/taskview/sql/1.48.0/0.create-time-entries.sqlnew file mode 100644index 0000000..f91abd9--- /dev/null+++ b/api/src/migrations/taskview/sql/1.48.0/0.create-time-entries.sql@@ -0,0 +1,29 @@+CREATE TABLE IF NOT EXISTS tasks.time_entries (+ id SERIAL PRIMARY KEY,+ task_id INTEGER NOT NULL REFERENCES tasks.tasks(id) ON DELETE CASCADE,+ goal_id INTEGER NOT NULL REFERENCES tasks.goals(id) ON DELETE CASCADE,+ user_id INTEGER NOT NULL REFERENCES tv_auth.users(id) ON DELETE CASCADE,+ started_at TIMESTAMP NOT NULL DEFAULT NOW(),+ ended_at TIMESTAMP NULL,+ duration_seconds INTEGER NULL,+ description VARCHAR(500) NULL,+ source SMALLINT NOT NULL DEFAULT 0,+ billable BOOLEAN NOT NULL DEFAULT TRUE,+ auto_stopped BOOLEAN NOT NULL DEFAULT FALSE,+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),+ edited_at TIMESTAMP NOT NULL DEFAULT NOW(),+ CONSTRAINT time_entries_end_after_start CHECK (ended_at IS NULL OR ended_at > started_at),+ CONSTRAINT time_entries_duration_non_negative CHECK (duration_seconds IS NULL OR duration_seconds >= 0)+);++CREATE INDEX IF NOT EXISTS idx_time_entries_user_started+ ON tasks.time_entries(user_id, started_at DESC);++CREATE INDEX IF NOT EXISTS idx_time_entries_goal_started+ ON tasks.time_entries(goal_id, started_at DESC);++CREATE INDEX IF NOT EXISTS idx_time_entries_task+ ON tasks.time_entries(task_id);++CREATE UNIQUE INDEX IF NOT EXISTS uq_time_entries_active_per_user+ ON tasks.time_entries(user_id) WHERE ended_at IS NULL;diff --git a/api/src/migrations/taskview/sql/1.48.0/1.create-time-entries-history.sql b/api/src/migrations/taskview/sql/1.48.0/1.create-time-entries-history.sqlnew file mode 100644index 0000000..73d0bab--- /dev/null+++ b/api/src/migrations/taskview/sql/1.48.0/1.create-time-entries-history.sql@@ -0,0 +1,11 @@+CREATE SCHEMA IF NOT EXISTS history;++CREATE TABLE IF NOT EXISTS history.time_entries (+ id SERIAL PRIMARY KEY,+ entry_id INTEGER NOT NULL REFERENCES tasks.time_entries(id) ON DELETE CASCADE,+ edit_date TIMESTAMP NOT NULL DEFAULT NOW(),+ entry JSONB NOT NULL+);++CREATE INDEX IF NOT EXISTS idx_history_time_entries_entry+ ON history.time_entries(entry_id, edit_date DESC);diff --git a/api/src/migrations/taskview/sql/1.48.0/2.alter-organizations-add-autostop.sql b/api/src/migrations/taskview/sql/1.48.0/2.alter-organizations-add-autostop.sqlnew file mode 100644index 0000000..383ba7e--- /dev/null+++ b/api/src/migrations/taskview/sql/1.48.0/2.alter-organizations-add-autostop.sql@@ -0,0 +1,2 @@+ALTER TABLE tv_auth.organizations+ ADD COLUMN IF NOT EXISTS time_tracking_autostop_hours INTEGER DEFAULT 24;diff --git a/api/src/migrations/taskview/sql/1.48.0/3.add-timetracking-permissions.sql b/api/src/migrations/taskview/sql/1.48.0/3.add-timetracking-permissions.sqlnew file mode 100644index 0000000..85287f6--- /dev/null+++ b/api/src/migrations/taskview/sql/1.48.0/3.add-timetracking-permissions.sql@@ -0,0 +1,21 @@+INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)+VALUES+ (+ 'timetracking_can_view',+ 'View all time entries on this project — both own and other members''',+ 2,+ '{"en": "View time entries. User can see all time entries on this project — both own and other members''. Does not grant logging or editing.", "ru": "Просмотр записей времени. Пользователь видит все записи проекта — свои и других участников. Логировать и редактировать нельзя."}'::jsonb+ ),+ (+ 'timetracking_can_log',+ 'Start/stop timer and create/edit/delete OWN time entries on this project',+ 2,+ '{"en": "Track time. User can start/stop the timer, add manual entries, and edit/delete OWN time entries. Does not grant viewing the project log or managing others'' entries.", "ru": "Учёт времени. Пользователь может запускать/останавливать таймер, добавлять записи вручную и редактировать/удалять СВОИ записи. Не даёт права просматривать журнал проекта и управлять чужими записями."}'::jsonb+ ),+ (+ 'timetracking_can_manage_all',+ 'Edit/delete time entries of other project members (implies view)',+ 2,+ '{"en": "Manage all time entries. User can edit/delete time entries of any project member. Includes viewing the full project log.", "ru": "Управление чужими записями времени. Пользователь может редактировать/удалять записи любого участника проекта. Включает просмотр всех записей проекта."}'::jsonb+ )+ON CONFLICT (name) DO NOTHING;diff --git a/api/src/migrations/taskview/sql/1.48.0/all-triggers.sql b/api/src/migrations/taskview/sql/1.48.0/all-triggers.sqlnew file mode 100644index 0000000..d125e3b--- /dev/null+++ b/api/src/migrations/taskview/sql/1.48.0/all-triggers.sql@@ -0,0 +1,635 @@+--1.+--Trigger set previous version+create or replace function app.trigger_set_previous_version()+ returns trigger as+$date_complete$+begin+ new.prev_version = old.version;+ return new;+end;+$date_complete$+ language plpgsql;++drop trigger if exists trigger_set_previous_version on app.version;+create trigger trigger_set_previous_version+ before insert+ on app.version+ for each row+execute procedure app.trigger_set_previous_version();++--2.+--Trigger for adding owner for taskList from goal+create or replace function tasks.trigger_set_owner_for_component()+ returns trigger as+$date_complete$+begin+ new.owner = (select owner from tasks.goals where id = new.goal_id);+ return new;+end;+$date_complete$+ language plpgsql;++drop trigger if exists trigger_set_owner_for_component on tasks.goal_lists;+create trigger trigger_set_owner_for_component+ before insert+ on tasks.goal_lists+ for each row+execute procedure tasks.trigger_set_owner_for_component();++--3.+--Trigger for updating date_complete for task+create or replace function tasks.update_date_complete()+ returns trigger as+$date_complete$+begin+ if new.complete != old.complete+ then+ if new.complete = true+ then+ update tasks.tasks set date_complete = now() where id = old.id;+ else+ update tasks.tasks set date_complete = null where id = old.id;+ end if;+ end if;+ return new;+end;+$date_complete$+ language plpgsql;++drop trigger if exists tr_update_date_complete on tasks.tasks;+create trigger tr_update_date_complete+ after update+ on tasks.tasks+ for each row+execute procedure tasks.update_date_complete();++--4.+-- Delete user from collaboration if not assigned to any goal+create or replace function collaboration.delete_user_if_not_assigned_to_goal()+returns trigger as $$+declare+ count int;+begin+ if not exists (+ select 1+ from collaboration.users_to_goals+ where user_id = old.user_id+ limit 1+ ) then+ delete from collaboration.users where id = old.user_id;+ end if;++ return old;+end;+$$ language plpgsql;++drop trigger if exists trigger_delete_user_if_not_assigned_to_goal on collaboration.users_to_goals;+create trigger trigger_delete_user_if_not_assigned_to_goal+ after delete+ on collaboration.users_to_goals+ for each row+execute function collaboration.delete_user_if_not_assigned_to_goal();++--5.+--Trigger for checking task graph relation goal to avoid connection between tasks from different goals+create or replace function tasks.check_task_graph_relation_goal()+returns trigger as $$+declare+ from_goal int;+ to_goal int;+begin+ select goal_id into from_goal from tasks.tasks where id = new.from_task_id;+ select goal_id into to_goal from tasks.tasks where id = new.to_task_id;++ if from_goal is null or to_goal is null then+ raise exception 'Invalid task reference in relation';+ end if;++ if from_goal <> to_goal then+ raise exception 'Relation goal_id must match both tasks'' goal_id';+ end if;++ new.goal_id := from_goal;++ return new;+end;+$$ language plpgsql;++drop trigger if exists trigger_task_relation_goal on tasks.task_relations;+create trigger trigger_task_relation_goal+before insert or update on tasks.task_relations+for each row execute function tasks.check_task_graph_relation_goal();++--6.+--Trigger for logging changes in taskList to history table+create or replace function tasks.log_changes_tasks_goal_lists()+ returns trigger as+$body$+begin+ if tg_op = 'DELETE' then+ insert into history.tasks_goal_lists (goal_list_id, edit_date, task, deleted) values (old.id, now(), to_jsonb(old), 1);+ return old;+ elseif tg_op = 'UPDATE' then+ insert into history.tasks_goal_lists (goal_list_id, edit_date, task, deleted)+ VALUES (old.id, new.date_creation, to_jsonb(old), 0);+ new.edit_date = now();+ return new;+ end if;+end+$body$+ language plpgsql;++drop trigger if exists trigger_log_changes_tasks_goal_lists on tasks.goal_lists;+create trigger trigger_log_changes_tasks_goal_lists+ before update or delete+ on tasks.goal_lists+ for each row+execute procedure tasks.log_changes_tasks_goal_lists();++--7.+--Trigger for logging changes in goal to history table+create or replace function tasks.log_changes_tasks_goals()+ returns trigger as+$body$+begin+ if tg_op = 'DELETE' then+ insert into history.tasks_goals (goal_id, edit_date, task, deleted) values (old.id, now(), to_jsonb(old), 1);+ return old;+ elseif tg_op = 'UPDATE' then+ insert into history.tasks_goals (goal_id, edit_date, task, deleted)+ VALUES (old.id, new.date_creation, to_jsonb(old), 0);+ new.edit_date = now();+ return new;+ end if;+end+$body$+ language plpgsql;++drop trigger if exists trigger_log_changes_tasks_goals on tasks.goals;+create trigger trigger_log_changes_tasks_goals+ before update or delete+ on tasks.goals+ for each row+execute procedure tasks.log_changes_tasks_goals();++--8.+--Trigger for logging changes in task to history table+create or replace function tasks.log_changes_tasks_tasks()+ returns trigger as+$body$+begin+ if tg_op = 'DELETE' then+ insert into history.tasks_tasks (task_id, edit_date, task, deleted) values (old.id, now(), to_jsonb(old), 1);+ return old;+ elseif tg_op = 'UPDATE' then+ insert into history.tasks_tasks (task_id, edit_date, task, deleted)+ VALUES (old.id, new.date_creation, to_jsonb(old), 0);+ new.edit_date = now();+ return new;+ end if;+end+$body$+ language plpgsql;++drop trigger if exists trigger_log_changes_tasks_tasks on tasks.tasks;+create trigger trigger_log_changes_tasks_tasks+ before update or delete+ on tasks.tasks+ for each row+execute procedure tasks.log_changes_tasks_tasks();++--9.+--Trigger for setting goal_id default for task+CREATE OR REPLACE FUNCTION tasks.set_goal_id_default_for_task()+ RETURNS TRIGGER AS+$$+DECLARE+ goal_id INT;+BEGIN++ SELECT gl.goal_id+ INTO goal_id+ FROM tasks.goal_lists gl+ WHERE gl.id = NEW.goal_list_id;++ IF goal_id IS NOT NULL THEN+ NEW.goal_id := goal_id;+ END IF;++ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++drop trigger if exists before_insert_set_goal_id_for_task on tasks.tasks;++CREATE TRIGGER before_insert_set_goal_id_for_task+ BEFORE INSERT OR UPDATE+ ON tasks.tasks+ FOR EACH ROW+EXECUTE FUNCTION tasks.set_goal_id_default_for_task();+++--10.+--Trigger for adding default roles and permissions for goal+CREATE OR REPLACE FUNCTION tasks.add_roles_and_permissions()+ RETURNS TRIGGER AS+$$+DECLARE+ editor_role_id INTEGER;+ executor_role_id INTEGER;+BEGIN+ -- 1. Create role "editor"+ INSERT INTO collaboration.roles (name, goal_id)+ VALUES ('editor', NEW.id)+ RETURNING id INTO editor_role_id;++ -- 2. Create role "executor"+ INSERT INTO collaboration.roles (name, goal_id)+ VALUES ('executor', NEW.id)+ RETURNING id INTO executor_role_id;++ -- 3. Add permissions for role "editor"+ INSERT INTO collaboration.permissions_to_role (role_id, permission_id)+ SELECT editor_role_id, id+ FROM tv_auth.permissions+ WHERE name IN (+ 'goal_can_watch_content',+ 'goal_can_edit',+ 'goal_can_add_task_list',+ 'goal_can_manage_users',+ 'component_can_watch_content',+ 'component_can_edit',+ 'component_can_delete',+ 'component_can_add_tasks',+ 'task_can_edit_deadline',+ 'task_can_watch_subtasks',+ 'task_can_watch_note',+ 'task_can_recovery_history',+ 'task_can_watch_assigned_users',+ 'task_can_edit_priority',+ 'task_can_delete',+ 'task_can_watch_details',+ 'task_can_assign_users',+ 'task_can_add_subtasks',+ 'task_can_watch_tags',+ 'task_can_watch_priority',+ 'task_can_access_history',+ 'task_can_edit_tags',+ 'task_can_edit_description',+ 'task_can_edit_status',+ 'task_can_edit_note',+ 'kanban_can_manage',+ 'kanban_can_view',+ 'graph_can_manage',+ 'graph_can_view',+ 'timetracking_can_view',+ 'timetracking_can_manage_all'+ );++ -- 4. Add permissions for role "viewver"+ INSERT INTO collaboration.permissions_to_role (role_id, permission_id)+ SELECT executor_role_id, id+ FROM tv_auth.permissions+ WHERE name IN (+ 'goal_can_watch_content',+ 'component_can_watch_content',+ 'component_can_add_tasks',+ 'task_can_watch_subtasks',+ 'task_can_watch_note',+ 'task_can_watch_assigned_users',+ 'task_can_watch_details',+ 'task_can_add_subtasks',+ 'task_can_watch_tags',+ 'task_can_watch_priority',+ 'timetracking_can_view',+ 'timetracking_can_log'+ );++ RETURN NEW;+END;+$$ LANGUAGE plpgsql;+++drop trigger if exists add_roles_after_insert on tasks.goals;++CREATE TRIGGER add_roles_after_insert+ AFTER INSERT+ ON tasks.goals+ FOR EACH ROW+EXECUTE FUNCTION tasks.add_roles_and_permissions();+++--11.+--Trigger for adjusting start and end dates for task+CREATE OR REPLACE FUNCTION tasks.adjust_start_and_end_dates()+ RETURNS TRIGGER AS+$$+DECLARE+ start_timestamp TIMESTAMPTZ;+ end_timestamp TIMESTAMPTZ;+BEGIN+ -- If start_date is NULL, then start_time should be NULL+ IF NEW.start_date IS NULL THEN+ NEW.start_time := NULL;+ END IF;++ -- If end_date is NULL, then end_time should be NULL+ IF NEW.end_date IS NULL THEN+ NEW.end_time := NULL;+ END IF;++ -- If both dates are set+ IF NEW.start_date IS NOT NULL AND NEW.end_date IS NOT NULL THEN+ -- Adjust dates+ IF NEW.start_date > NEW.end_date THEN+ -- If start_date is greater than end_date, set end_date to start_date+ NEW.end_date := NEW.start_date;+ -- end_time remains unchanged+ ELSIF NEW.end_date < NEW.start_date THEN+ -- If end_date is less than start_date, set start_date to end_date+ NEW.start_date := NEW.end_date;+ -- start_time remains unchanged+ END IF;++ -- Prepare timestamps for comparison+ start_timestamp := (NEW.start_date::text || ' ' || COALESCE(NEW.start_time::text, '00:00:00+00'))::timestamptz;+ end_timestamp := (NEW.end_date::text || ' ' || COALESCE(NEW.end_time::text, '00:00:00+00'))::timestamptz;++ -- If start_timestamp is greater than end_timestamp, adjust end_date and end_time+ IF start_timestamp > end_timestamp THEN+ NEW.end_date := NEW.start_date;+ -- Assign end_time only if start_time is not NULL+ IF NEW.start_time IS NOT NULL AND NEW.end_time IS NOT NULL THEN+ NEW.end_time := NEW.start_time;+ END IF;+ END IF;+ END IF;++ RETURN NEW;+END;+$$ LANGUAGE plpgsql;+++drop trigger if exists adjust_dates_and_times_trigger on tasks.tasks;+CREATE TRIGGER adjust_dates_and_times_trigger+ BEFORE INSERT OR UPDATE+ ON tasks.tasks+ FOR EACH ROW+EXECUTE FUNCTION tasks.adjust_start_and_end_dates();++--12.+--Trigger for adding self/owner to collaboration table to be able to assign tasks to self+create or replace function tasks.add_self_to_collaboration()+returns trigger as $$+DECLARE+ owner_email TEXT;+BEGIN++ select email into owner_email+ from tv_auth.users+ where id = NEW.owner;++ if owner_email is not null then+ insert into collaboration.users (email) values (owner_email) ON CONFLICT (email) DO NOTHING;+ insert into collaboration.users_to_goals (goal_id, user_id) values (NEW.id, (select id from collaboration.users where email = owner_email));+ end if;++ return NEW;+END;+$$ language plpgsql;++drop trigger if exists add_selt_to_collaboration_trg on tasks.goals;++create trigger add_selt_to_collaboration_trg+ after insert on tasks.goals+ for each row+ execute function tasks.add_self_to_collaboration();++--13.+--Trigger for adding default kanban columns for new goal+CREATE OR REPLACE FUNCTION tasks.kanban_add_default_columns()+RETURNS TRIGGER AS $$+BEGIN+ -- Add default columns for new goal+ INSERT INTO tasks.statuses (name, goal_id, view_order)+ VALUES+ ('TODO', NEW.id, 1),+ ('In Progress', NEW.id, 2),+ ('Done', NEW.id, 3);+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++DROP TRIGGER IF EXISTS kanban_add_default_columns_trg ON tasks.goals;++CREATE TRIGGER kanban_add_default_columns_trg+AFTER INSERT ON tasks.goals+FOR EACH ROW+EXECUTE FUNCTION tasks.kanban_add_default_columns();++--14.+--Trigger for validating the correct statusId for the inserted value. To avoid assigning a status that does not belong to the goal.+CREATE OR REPLACE FUNCTION tasks.check_task_status_goal()+RETURNS TRIGGER AS $$+BEGIN+ -- Check if there is a record in tasks.statuses with the same goal_id+ IF NOT EXISTS (+ SELECT 1 FROM tasks.statuses s+ WHERE s.id = NEW.status_id AND s.goal_id = NEW.goal_id+ ) THEN+ RAISE EXCEPTION 'Status ID % is not valid for goal ID %', NEW.status_id, NEW.goal_id;+ END IF;+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++drop trigger if exists enforce_task_status_goal on tasks.tasks;++CREATE TRIGGER enforce_task_status_goal+BEFORE INSERT OR UPDATE ON tasks.tasks+FOR EACH ROW+WHEN (NEW.status_id IS NOT NULL)+EXECUTE FUNCTION tasks.check_task_status_goal();++--15.+--Trigger for setting default orders value for task+CREATE OR REPLACE FUNCTION tasks.set_order_value()+RETURNS TRIGGER AS $$+BEGIN+ IF NEW.task_order IS NULL THEN+ NEW.task_order := NEW.id;+ END IF;+ IF NEW.kanban_order IS NULL THEN+ NEW.kanban_order := NEW.id;+ END IF;+ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++drop trigger if exists set_order_trigger on tasks.tasks;+CREATE TRIGGER set_order_trigger+BEFORE INSERT ON tasks.tasks+FOR EACH ROW+EXECUTE FUNCTION tasks.set_order_value();++--16.+--Trigger for setting default view order for new status+CREATE OR REPLACE FUNCTION tasks.status_set_default_view_order()+RETURNS TRIGGER AS $$+DECLARE+ new_view_order INT;+BEGIN+ -- Determine the next view_order for the given goal_id+ SELECT COALESCE(MAX(view_order), 0) + 1 INTO new_view_order+ FROM tasks.statuses+ WHERE goal_id = NEW.goal_id;++ -- Assign the calculated value to the view_order field+ NEW.view_order := new_view_order;++ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++drop trigger if exists set_default_status_view_order on tasks.statuses;++CREATE TRIGGER set_default_status_view_order+BEFORE INSERT ON tasks.statuses+FOR EACH ROW+EXECUTE FUNCTION tasks.status_set_default_view_order();++--17.+--Trigger for validating the correct user_id for the inserted value. To avoid assigning a user that does not belong to the goal.+CREATE OR REPLACE FUNCTION tasks_auth.control_user_id_is_from_same_goal_as_task()+RETURNS TRIGGER AS $$+DECLARE+ user_exists BOOLEAN;+BEGIN+ SELECT EXISTS (+ SELECT 1+ FROM tasks.tasks tt+ LEFT JOIN collaboration.users_to_goals utg ON utg.goal_id = tt.goal_id+ WHERE tt.id = NEW.task_id AND utg.user_id = NEW.collab_user_id+ ) INTO user_exists;++ IF NOT user_exists THEN+ RAISE EXCEPTION 'User % is not associated with the goal of task %', NEW.collab_user_id, NEW.task_id;+ END IF;++ RETURN NEW;+END;+$$ LANGUAGE plpgsql;++drop trigger if exists trigger_control_user_id_is_from_same_goal_as_task on tasks_auth.task_assignee;++CREATE TRIGGER trigger_control_user_id_is_from_same_goal_as_task+BEFORE INSERT ON tasks_auth.task_assignee+FOR EACH ROW+EXECUTE FUNCTION tasks_auth.control_user_id_is_from_same_goal_as_task();++--18.+--Trigger for adding owner for task, extend owner from goal or taskList++--delete old function with wrong name+drop trigger if exists trigger_set_owner_for_task on tasks.tasks;+drop function if exists tasks.trigger_set_owner_for_task();++CREATE OR REPLACE FUNCTION tasks.fn_set_owner_for_task()+RETURNS TRIGGER AS+$body$+BEGIN+ NEW.owner := COALESCE(+ (SELECT owner FROM tasks.goal_lists WHERE id = NEW.goal_list_id),+ (SELECT owner FROM tasks.goals WHERE id = NEW.goal_id)+ );++ IF NEW.owner IS NULL THEN+ RAISE EXCEPTION 'Can not insert task without owner';+ END IF;++ RETURN NEW;+END;+$body$+LANGUAGE plpgsql;++drop trigger if exists trigger_set_owner_for_task on tasks.tasks;+create trigger trigger_set_owner_for_task+ before insert+ on tasks.tasks+ for each row+execute procedure tasks.fn_set_owner_for_task();++--19.+--Trigger for validating that tag and task belong to the same project (goal_id)+drop trigger if exists trigger_check_tag_task_same_goal on tasks.tasks_to_tags;+drop function if exists tasks.check_tag_task_same_goal();++create or replace function tasks.check_tag_task_same_goal()+returns trigger as $$+declare+ v_tag_goal_id integer;+ v_task_goal_id integer;+begin+ select goal_id into v_tag_goal_id from tasks.tags where id = new.tag_id;+ select goal_id into v_task_goal_id from tasks.tasks where id = new.task_id;++ if v_tag_goal_id is null or v_tag_goal_id != v_task_goal_id then+ raise exception 'Tag (id=%) and task (id=%) belong to different projects', new.tag_id, new.task_id;+ end if;++ return new;+end;+$$ language plpgsql;++drop trigger if exists trigger_check_tag_task_same_goal on tasks.tasks_to_tags;+create trigger trigger_check_tag_task_same_goal+ before insert on tasks.tasks_to_tags+ for each row+execute function tasks.check_tag_task_same_goal();++--20.+-- Remove user from task assignees when removed from project collaboration++drop trigger if exists trigger_remove_user_from_task_assignees on collaboration.users_to_goals;+drop function if exists collaboration.remove_user_from_task_assignees();+++CREATE OR REPLACE FUNCTION collaboration.remove_user_from_task_assignees()+RETURNS TRIGGER AS $$+BEGIN+ DELETE FROM tasks_auth.task_assignee+ WHERE collab_user_id = OLD.user_id+ AND task_id IN (SELECT id FROM tasks.tasks WHERE goal_id = OLD.goal_id);++ RETURN OLD;+END;+$$ LANGUAGE plpgsql;++DROP TRIGGER IF EXISTS trigger_remove_user_from_task_assignees ON collaboration.users_to_goals;++CREATE TRIGGER trigger_remove_user_from_task_assignees+ BEFORE DELETE+ ON collaboration.users_to_goals+ FOR EACH ROW+EXECUTE FUNCTION collaboration.remove_user_from_task_assignees();++--21.+--Trigger for logging changes in time_entries to history table+create or replace function tasks.log_changes_time_entries()+ returns trigger as+$body$+begin+ insert into history.time_entries (entry_id, edit_date, entry)+ values (old.id, now(), to_jsonb(old));+ new.edited_at = now();+ return new;+end+$body$+ language plpgsql;++drop trigger if exists trigger_log_changes_time_entries on tasks.time_entries;+create trigger trigger_log_changes_time_entries+ before update+ on tasks.time_entries+ for each row+execute procedure tasks.log_changes_time_entries();diff --git a/api/src/routes/index.ts b/api/src/routes/index.tsindex 578623d..147ecee 100644--- a/api/src/routes/index.ts+++ b/api/src/routes/index.ts@@ -17,6 +17,7 @@ import OrganizationRoutes from '../tv-modules/organizations/OrganizationRoutes';import SsoRoutes from '../tv-modules/sso/SsoRoutes';import ScimRoutes from '../tv-modules/scim/ScimRoutes';import AnalyticsRoutes from '../tv-modules/analytics/AnalyticsRoutes';+import TimeTrackingRoutes from '../tv-modules/time-tracking/TimeTrackingRoutes';import type { Routable } from '../types/routable.type';type RoutableConstructor = new (...args: any[]) => Routable;@@ -40,6 +41,7 @@ const routes: Record<string, RoutableConstructor> = {'/module/organizations': OrganizationRoutes,'/module/sso': SsoRoutes,'/module/analytics': AnalyticsRoutes,+ '/module/time-tracking': TimeTrackingRoutes,'/scim/v2': ScimRoutes,};diff --git a/api/src/tv-modules/time-tracking/TimeTrackingController.ts b/api/src/tv-modules/time-tracking/TimeTrackingController.tsnew file mode 100644index 0000000..f334d75--- /dev/null+++ b/api/src/tv-modules/time-tracking/TimeTrackingController.ts@@ -0,0 +1,101 @@+import type { Request, Response } from 'express'+import { ArkErrors } from 'arktype'+import { logError } from '../../utils/api'+import {+ TimeEntryArkTypeCreate,+ TimeEntryArkTypeDelete,+ TimeEntryArkTypeFetchEntries,+ TimeEntryArkTypeHistory,+ TimeEntryArkTypeStart,+ TimeEntryArkTypeStop,+ TimeEntryArkTypeSummaryByGoal,+ TimeEntryArkTypeSummaryByTask,+ TimeEntryArkTypeUpdate,+} from './types'++export class TimeTrackingController {+ start = async (req: Request, res: Response) => {+ const data = TimeEntryArkTypeStart(req.body)+ if (data instanceof ArkErrors) return res.status(400).send(data.summary)++ const result = await req.appUser.timeTrackingManager.start(data).catch(logError)+ if (!result) return res.status(403).end()+ return res.tvJson(result)+ }++ stop = async (req: Request, res: Response) => {+ const data = TimeEntryArkTypeStop(req.body ?? {})+ if (data instanceof ArkErrors) return res.status(400).send(data.summary)++ const entry = await req.appUser.timeTrackingManager.stop(data).catch(logError)+ if (!entry) return res.status(404).end()+ return res.tvJson(entry)+ }++ active = async (req: Request, res: Response) => {+ const entry = await req.appUser.timeTrackingManager.getActive().catch(logError)+ return res.tvJson(entry ?? null)+ }++ createManual = async (req: Request, res: Response) => {+ const data = TimeEntryArkTypeCreate(req.body)+ if (data instanceof ArkErrors) return res.status(400).send(data.summary)++ const entry = await req.appUser.timeTrackingManager.createManual(data).catch(logError)+ if (!entry) return res.status(400).end()+ return res.tvJson(entry)+ }++ update = async (req: Request, res: Response) => {+ const data = TimeEntryArkTypeUpdate({ ...req.body, id: Number(req.params.id) })+ if (data instanceof ArkErrors) return res.status(400).send(data.summary)++ const entry = await req.appUser.timeTrackingManager.update(data).catch(logError)+ if (!entry) return res.status(403).end()+ return res.tvJson(entry)+ }++ delete = async (req: Request, res: Response) => {+ const data = TimeEntryArkTypeDelete({ id: req.params.id })+ if (data instanceof ArkErrors) return res.status(400).send(data.summary)++ const ok = await req.appUser.timeTrackingManager.delete(data.id).catch(logError)+ if (!ok) return res.status(403).end()+ return res.tvJson({ deleted: true })+ }++ fetchEntries = async (req: Request, res: Response) => {+ const data = TimeEntryArkTypeFetchEntries(req.query)+ if (data instanceof ArkErrors) return res.status(400).send(data.summary)++ const entries = await req.appUser.timeTrackingManager.fetchEntries(data).catch(logError)+ return res.tvJson(entries ?? [])+ }++ summaryByTask = async (req: Request, res: Response) => {+ const data = TimeEntryArkTypeSummaryByTask({ taskId: req.params.taskId })+ if (data instanceof ArkErrors) return res.status(400).send(data.summary)++ const summary = await req.appUser.timeTrackingManager.summaryByTask(data.taskId).catch(logError)+ if (!summary) return res.status(403).end()+ return res.tvJson(summary)+ }++ summaryByGoal = async (req: Request, res: Response) => {+ const data = TimeEntryArkTypeSummaryByGoal({ goalId: req.params.goalId })+ if (data instanceof ArkErrors) return res.status(400).send(data.summary)++ const summary = await req.appUser.timeTrackingManager.summaryByGoal(data.goalId).catch(logError)+ if (!summary) return res.status(403).end()+ return res.tvJson(summary)+ }++ fetchHistory = async (req: Request, res: Response) => {+ const data = TimeEntryArkTypeHistory({ id: req.params.id })+ if (data instanceof ArkErrors) return res.status(400).send(data.summary)++ const history = await req.appUser.timeTrackingManager.fetchHistory(data.id).catch(logError)+ if (!history) return res.status(403).end()+ return res.tvJson(history)+ }+}diff --git a/api/src/tv-modules/time-tracking/TimeTrackingDispatcher.ts b/api/src/tv-modules/time-tracking/TimeTrackingDispatcher.tsnew file mode 100644index 0000000..5cd5a7e--- /dev/null+++ b/api/src/tv-modules/time-tracking/TimeTrackingDispatcher.ts@@ -0,0 +1,89 @@+import { getCentrifugoClient } from '../../core/CentrifugoClient'+import type { Dispatcher } from '../../core/Dispatcher'+import { eventBus, type AppEvents } from '../../core/EventBus'+import { getJobQueue } from '../../core/JobQueue'+import { $logger } from '../../modules/logget'+import { TimeTrackingRepository } from './TimeTrackingRepository'++const AUTOSTOP_JOB = 'time-tracking-autostop'++export class TimeTrackingDispatcher implements Dispatcher {+ private readonly repository = new TimeTrackingRepository()++ register(): void {+ eventBus.on('time-entry.started', (data) => this.onStarted(data))+ eventBus.on('time-entry.stopped', (data) => this.onStopped(data))+ eventBus.on('time-entry.created', (data) => this.onCreated(data))+ eventBus.on('time-entry.updated', (data) => this.onUpdated(data))+ eventBus.on('time-entry.deleted', (data) => this.onDeleted(data))+ }++ async registerWorkers(): Promise<void> {+ const boss = getJobQueue()+ await boss.createQueue(AUTOSTOP_JOB)+ await boss.schedule(AUTOSTOP_JOB, '0 * * * *')+ await boss.work(AUTOSTOP_JOB, async () => {+ await this.runAutostop()+ })+ }++ private async runAutostop(): Promise<void> {+ const stoppedEntries = await this.repository.autoStopOverdue()+ if (stoppedEntries.length === 0) return++ for (const entry of stoppedEntries) {+ eventBus.emit('time-entry.stopped', {+ entry,+ taskId: entry.taskId,+ userId: entry.userId,+ goalId: entry.goalId,+ durationSeconds: entry.durationSeconds ?? 0,+ })+ }++ $logger.info({ count: stoppedEntries.length }, '[TimeTracking] Autostop completed')+ }++ private async onStarted(data: AppEvents['time-entry.started']): Promise<void> {+ await this.publish(data.userId, 'time-entry.started', { entry: data.entry })+ }++ private async onStopped(data: AppEvents['time-entry.stopped']): Promise<void> {+ await this.publish(data.userId, 'time-entry.stopped', {+ entry: data.entry,+ durationSeconds: data.durationSeconds,+ })+ }++ private async onCreated(data: AppEvents['time-entry.created']): Promise<void> {+ await this.publish(data.entry.userId, 'time-entry.created', { entry: data.entry })+ }++ private async onUpdated(data: AppEvents['time-entry.updated']): Promise<void> {+ await this.publish(data.entry.userId, 'time-entry.updated', {+ entry: data.entry,+ changes: data.changes,+ })+ if (data.initiatorId !== data.entry.userId) {+ await this.publish(data.initiatorId, 'time-entry.updated', {+ entry: data.entry,+ changes: data.changes,+ })+ }+ }++ private async onDeleted(data: AppEvents['time-entry.deleted']): Promise<void> {+ await this.publish(data.userId, 'time-entry.deleted', { entryId: data.entryId, taskId: data.taskId })+ if (data.initiatorId !== data.userId) {+ await this.publish(data.initiatorId, 'time-entry.deleted', {+ entryId: data.entryId,+ taskId: data.taskId,+ })+ }+ }++ private async publish(userId: number, event: string, payload: Record<string, unknown>): Promise<void> {+ const centrifugo = getCentrifugoClient()+ await centrifugo.publishToUser(userId, event, payload)+ }+}diff --git a/api/src/tv-modules/time-tracking/TimeTrackingManager.ts b/api/src/tv-modules/time-tracking/TimeTrackingManager.tsnew file mode 100644index 0000000..11313a6--- /dev/null+++ b/api/src/tv-modules/time-tracking/TimeTrackingManager.ts@@ -0,0 +1,261 @@+import type { TimeEntriesSchemaTypeForSelect } from 'taskview-db-schemas'+import type { AppUser } from '../../core/AppUser'+import { eventBus } from '../../core/EventBus'+import { TimeTrackingRepository } from './TimeTrackingRepository'+import {+ TIME_ENTRY_SOURCE,+ type TimeEntryArgCreate,+ type TimeEntryArgFetchEntries,+ type TimeEntryArgStart,+ type TimeEntryArgStop,+ type TimeEntryArgUpdate,+ type TimeEntryStartResult,+ type TimeEntryUpdateParams,+} from './types'++export class TimeTrackingManager {+ public readonly repository: TimeTrackingRepository+ private readonly user: AppUser++ constructor(user: AppUser) {+ this.user = user+ this.repository = new TimeTrackingRepository()+ }++ private getCurrentUserId(): number | null {+ return this.user.getUserData()?.id ?? null+ }++ private computeDuration(startedAt: Date, endedAt: Date): number {+ return Math.max(0, Math.round((endedAt.getTime() - startedAt.getTime()) / 1000))+ }++ async getActive(): Promise<TimeEntriesSchemaTypeForSelect | null> {+ const userId = this.getCurrentUserId()+ if (!userId) return null+ return this.repository.findActiveForUser(userId)+ }++ async start(data: TimeEntryArgStart): Promise<TimeEntryStartResult | null> {+ const userId = this.getCurrentUserId()+ if (!userId) return null++ const task = await this.repository.fetchTaskWithGoal(data.taskId)+ if (!task) return null++ for (let attempt = 0; attempt < 2; attempt++) {+ const autoStoppedEntry = await this.closeActiveTimer(userId)++ const insertResult = await this.repository.tryInsertActiveTimer({+ taskId: task.id,+ goalId: task.goalId,+ userId,+ description: data.description ?? null,+ source: TIME_ENTRY_SOURCE.TIMER,+ })++ if (insertResult.entry) {+ const entry = insertResult.entry+ eventBus.emit('time-entry.started', {+ entry,+ taskId: entry.taskId,+ userId: entry.userId,+ goalId: entry.goalId,+ })+ return { entry, autoStoppedEntry }+ }++ if (!insertResult.conflict) return null+ }++ return null+ }++ private async closeActiveTimer(userId: number): Promise<TimeEntriesSchemaTypeForSelect | null> {+ const active = await this.repository.findActiveForUser(userId)+ if (!active) return null++ const endedAt = new Date()+ const stopped = await this.repository.updateById(active.id, {+ endedAt,+ durationSeconds: this.computeDuration(active.startedAt, endedAt),+ })+ if (!stopped) return null++ eventBus.emit('time-entry.stopped', {+ entry: stopped,+ taskId: stopped.taskId,+ userId: stopped.userId,+ goalId: stopped.goalId,+ durationSeconds: stopped.durationSeconds ?? 0,+ })++ return stopped+ }++ async stop(data: TimeEntryArgStop): Promise<TimeEntriesSchemaTypeForSelect | null> {+ const userId = this.getCurrentUserId()+ if (!userId) return null++ const target = data.entryId+ ? await this.repository.findById(data.entryId)+ : await this.repository.findActiveForUser(userId)++ if (!target || target.endedAt) return null++ const endedAt = new Date()+ const stopped = await this.repository.updateById(target.id, {+ endedAt,+ durationSeconds: this.computeDuration(target.startedAt, endedAt),+ })+ if (!stopped) return null++ eventBus.emit('time-entry.stopped', {+ entry: stopped,+ taskId: stopped.taskId,+ userId: stopped.userId,+ goalId: stopped.goalId,+ durationSeconds: stopped.durationSeconds ?? 0,+ })++ return stopped+ }++ async createManual(data: TimeEntryArgCreate): Promise<TimeEntriesSchemaTypeForSelect | null> {+ const userId = this.getCurrentUserId()+ if (!userId) return null++ if (data.endedAt.getTime() <= data.startedAt.getTime()) return null++ const task = await this.repository.fetchTaskWithGoal(data.taskId)+ if (!task) return null++ const entry = await this.repository.insert({+ taskId: task.id,+ goalId: task.goalId,+ userId,+ startedAt: data.startedAt,+ endedAt: data.endedAt,+ durationSeconds: this.computeDuration(data.startedAt, data.endedAt),+ description: data.description ?? null,+ source: TIME_ENTRY_SOURCE.MANUAL,+ billable: data.billable,+ })+ if (!entry) return null++ eventBus.emit('time-entry.created', { entry, initiatorId: userId })+ return entry+ }++ async update(data: TimeEntryArgUpdate): Promise<TimeEntriesSchemaTypeForSelect | null> {+ const userId = this.getCurrentUserId()+ if (!userId) return null++ const existing = await this.repository.findById(data.id)+ if (!existing) return null++ if (existing.endedAt === null) {+ const onlyDescription =+ data.description !== undefined &&+ data.startedAt === undefined &&+ data.endedAt === undefined &&+ data.billable === undefined+ if (!onlyDescription) return null+ }++ const updates: TimeEntryUpdateParams = {}+ const startedAt = data.startedAt ?? existing.startedAt+ const endedAt = data.endedAt ?? existing.endedAt++ if (data.startedAt !== undefined) updates.startedAt = data.startedAt+ if (data.endedAt !== undefined) updates.endedAt = data.endedAt+ if (data.description !== undefined) updates.description = data.description+ if (data.billable !== undefined) updates.billable = data.billable++ if (endedAt && (data.startedAt !== undefined || data.endedAt !== undefined)) {+ if (endedAt.getTime() <= startedAt.getTime()) return null+ updates.durationSeconds = this.computeDuration(startedAt, endedAt)+ }++ const updated = await this.repository.updateById(existing.id, updates)+ if (!updated) return null++ eventBus.emit('time-entry.updated', {+ entry: updated,+ changes: updates as Record<string, unknown>,+ initiatorId: userId,+ })++ return updated+ }++ async delete(id: number): Promise<boolean> {+ const userId = this.getCurrentUserId()+ if (!userId) return false++ const existing = await this.repository.findById(id)+ if (!existing) return false++ const deleted = await this.repository.deleteById(id)+ if (!deleted) return false++ eventBus.emit('time-entry.deleted', {+ entryId: existing.id,+ taskId: existing.taskId,+ goalId: existing.goalId,+ userId: existing.userId,+ initiatorId: userId,+ })++ return true+ }++ async fetchEntries(filters: TimeEntryArgFetchEntries): Promise<TimeEntriesSchemaTypeForSelect[]> {+ const userId = this.getCurrentUserId()+ if (!userId) return []++ let goalId = filters.goalId+ if (goalId === undefined && filters.taskId !== undefined) {+ const task = await this.repository.fetchTaskWithGoal(filters.taskId)+ if (!task) return []+ goalId = task.goalId+ }++ return this.repository.fetchEntries({+ goalId,+ taskId: filters.taskId,+ userId: filters.userId ?? userId,+ from: filters.from,+ to: filters.to,+ limit: filters.limit,+ offset: filters.offset,+ })+ }++ async summaryByTask(taskId: number) {+ const userId = this.getCurrentUserId()+ if (!userId) return null++ const task = await this.repository.fetchTaskWithGoal(taskId)+ if (!task) return null++ return this.repository.sumByTask(taskId)+ }++ async summaryByGoal(goalId: number) {+ const userId = this.getCurrentUserId()+ if (!userId) return null++ return this.repository.sumByGoal(goalId)+ }++ async fetchHistory(entryId: number) {+ const userId = this.getCurrentUserId()+ if (!userId) return null++ const existing = await this.repository.findById(entryId)+ if (!existing) return null++ return this.repository.fetchHistory(entryId)+ }+}diff --git a/api/src/tv-modules/time-tracking/TimeTrackingRepository.ts b/api/src/tv-modules/time-tracking/TimeTrackingRepository.tsnew file mode 100644index 0000000..30e8231--- /dev/null+++ b/api/src/tv-modules/time-tracking/TimeTrackingRepository.ts@@ -0,0 +1,246 @@+import { and, desc, eq, gte, isNull, lte, sql, type SQL } from 'drizzle-orm'+import {+ TimeEntriesSchema,+ TimeEntriesHistorySchema,+ TasksSchema,+ type TimeEntriesSchemaTypeForSelect,+ type TimeEntriesHistorySchemaTypeForSelect,+} from 'taskview-db-schemas'+import { Database } from '../../modules/db'+import { $logger } from '../../modules/logget'+import { callWithCatch } from '../../utils/helpers'++const PG_UNIQUE_VIOLATION = '23505'+import type {+ TimeEntryFilters,+ TimeEntryGoalSummary,+ TimeEntryInsertParams,+ TimeEntryTaskSummary,+ TimeEntryUpdateParams,+} from './types'++export class TimeTrackingRepository {+ private readonly db: Database++ constructor() {+ this.db = Database.getInstance()+ }++ async fetchTaskWithGoal(taskId: number): Promise<{ id: number; goalId: number } | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({ id: TasksSchema.id, goalId: TasksSchema.goalId })+ .from(TasksSchema)+ .where(eq(TasksSchema.id, taskId)),+ )+ return result?.[0] ?? null+ }++ async findActiveForUser(userId: number): Promise<TimeEntriesSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(TimeEntriesSchema)+ .where(and(eq(TimeEntriesSchema.userId, userId), isNull(TimeEntriesSchema.endedAt))),+ )+ return result?.[0] ?? null+ }++ async findById(id: number): Promise<TimeEntriesSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.select().from(TimeEntriesSchema).where(eq(TimeEntriesSchema.id, id)),+ )+ return result?.[0] ?? null+ }++ async insert(data: TimeEntryInsertParams): Promise<TimeEntriesSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .insert(TimeEntriesSchema)+ .values({+ taskId: data.taskId,+ goalId: data.goalId,+ userId: data.userId,+ startedAt: data.startedAt,+ endedAt: data.endedAt ?? null,+ durationSeconds: data.durationSeconds ?? null,+ description: data.description ?? null,+ source: data.source,+ billable: data.billable ?? true,+ })+ .returning(),+ )+ return result?.[0] ?? null+ }++ async tryInsertActiveTimer(+ data: TimeEntryInsertParams,+ ): Promise<{ entry: TimeEntriesSchemaTypeForSelect | null; conflict: boolean }> {+ try {+ const result = await this.db.dbDrizzle+ .insert(TimeEntriesSchema)+ .values({+ taskId: data.taskId,+ goalId: data.goalId,+ userId: data.userId,+ startedAt: data.startedAt,+ endedAt: data.endedAt ?? null,+ durationSeconds: data.durationSeconds ?? null,+ description: data.description ?? null,+ source: data.source,+ billable: data.billable ?? true,+ })+ .returning()+ return { entry: result?.[0] ?? null, conflict: false }+ } catch (error) {+ const code = (error as { code?: string } | null)?.code+ if (code === PG_UNIQUE_VIOLATION) {+ return { entry: null, conflict: true }+ }+ $logger.error(error, 'TimeTrackingRepository.tryInsertActiveTimer')+ return { entry: null, conflict: false }+ }+ }++ async updateById(id: number, data: TimeEntryUpdateParams): Promise<TimeEntriesSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .update(TimeEntriesSchema)+ .set(data)+ .where(eq(TimeEntriesSchema.id, id))+ .returning(),+ )+ return result?.[0] ?? null+ }++ async deleteById(id: number): Promise<boolean> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.delete(TimeEntriesSchema).where(eq(TimeEntriesSchema.id, id)),+ )+ return !!result?.rowCount+ }++ async fetchEntries(filters: TimeEntryFilters): Promise<TimeEntriesSchemaTypeForSelect[]> {+ const conditions: SQL[] = []+ if (filters.goalId !== undefined) conditions.push(eq(TimeEntriesSchema.goalId, filters.goalId))+ if (filters.taskId !== undefined) conditions.push(eq(TimeEntriesSchema.taskId, filters.taskId))+ if (filters.userId !== undefined) conditions.push(eq(TimeEntriesSchema.userId, filters.userId))+ if (filters.from !== undefined) conditions.push(gte(TimeEntriesSchema.startedAt, filters.from))+ if (filters.to !== undefined) conditions.push(lte(TimeEntriesSchema.startedAt, filters.to))++ const limit = Math.min(filters.limit ?? 50, 500)+ const offset = filters.offset ?? 0++ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(TimeEntriesSchema)+ .where(conditions.length > 0 ? and(...conditions) : undefined)+ .orderBy(desc(TimeEntriesSchema.startedAt))+ .limit(limit)+ .offset(offset),+ )+ return result ?? []+ }++ async sumByTask(taskId: number): Promise<TimeEntryTaskSummary> {+ const total = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({ total: sql<number>`coalesce(sum(${TimeEntriesSchema.durationSeconds}), 0)::int` })+ .from(TimeEntriesSchema)+ .where(eq(TimeEntriesSchema.taskId, taskId)),+ )++ const byUser = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({+ userId: TimeEntriesSchema.userId,+ seconds: sql<number>`coalesce(sum(${TimeEntriesSchema.durationSeconds}), 0)::int`,+ })+ .from(TimeEntriesSchema)+ .where(eq(TimeEntriesSchema.taskId, taskId))+ .groupBy(TimeEntriesSchema.userId),+ )++ return {+ totalSeconds: total?.[0]?.total ?? 0,+ byUser: byUser ?? [],+ }+ }++ async sumByGoal(goalId: number): Promise<TimeEntryGoalSummary> {+ const total = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({ total: sql<number>`coalesce(sum(${TimeEntriesSchema.durationSeconds}), 0)::int` })+ .from(TimeEntriesSchema)+ .where(eq(TimeEntriesSchema.goalId, goalId)),+ )++ const byUser = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({+ userId: TimeEntriesSchema.userId,+ seconds: sql<number>`coalesce(sum(${TimeEntriesSchema.durationSeconds}), 0)::int`,+ })+ .from(TimeEntriesSchema)+ .where(eq(TimeEntriesSchema.goalId, goalId))+ .groupBy(TimeEntriesSchema.userId),+ )++ const byTask = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({+ taskId: TimeEntriesSchema.taskId,+ seconds: sql<number>`coalesce(sum(${TimeEntriesSchema.durationSeconds}), 0)::int`,+ })+ .from(TimeEntriesSchema)+ .where(eq(TimeEntriesSchema.goalId, goalId))+ .groupBy(TimeEntriesSchema.taskId),+ )++ return {+ totalSeconds: total?.[0]?.total ?? 0,+ byUser: byUser ?? [],+ byTask: byTask ?? [],+ }+ }++ async fetchHistory(entryId: number): Promise<TimeEntriesHistorySchemaTypeForSelect[]> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(TimeEntriesHistorySchema)+ .where(eq(TimeEntriesHistorySchema.entryId, entryId))+ .orderBy(desc(TimeEntriesHistorySchema.editDate)),+ )+ return result ?? []+ }++ async autoStopOverdue(): Promise<TimeEntriesSchemaTypeForSelect[]> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .update(TimeEntriesSchema)+ .set({+ endedAt: sql`now()`,+ autoStopped: true,+ durationSeconds: sql<number>`extract(epoch from (now() - ${TimeEntriesSchema.startedAt}))::int`,+ })+ .where(+ and(+ isNull(TimeEntriesSchema.endedAt),+ sql`${TimeEntriesSchema.id} IN (+ SELECT te.id+ FROM tasks.time_entries te+ JOIN tasks.goals g ON g.id = te.goal_id+ JOIN tv_auth.organizations o ON o.id = g.organization_id+ WHERE te.ended_at IS NULL+ AND o.time_tracking_autostop_hours IS NOT NULL+ AND te.started_at < now() - (o.time_tracking_autostop_hours || ' hours')::interval+ )`,+ ),+ )+ .returning(),+ )+ return result ?? []+ }+}diff --git a/api/src/tv-modules/time-tracking/TimeTrackingRoutes.ts b/api/src/tv-modules/time-tracking/TimeTrackingRoutes.tsnew file mode 100644index 0000000..8ca59f4--- /dev/null+++ b/api/src/tv-modules/time-tracking/TimeTrackingRoutes.ts@@ -0,0 +1,39 @@+import { Router } from 'express'+import type { Routable } from '../../types/routable.type'+import { IsLoggedIn } from '../auth/middlewares/is-logged-in'+import { TimeTrackingController } from './TimeTrackingController'+import { canLogTimeOnTask } from './middlewares/can-log-time-on-task'+import { canStopTimer } from './middlewares/can-stop-timer'+import { canAccessTimeEntry } from './middlewares/can-access-time-entry'+import { canFetchTimeEntries } from './middlewares/can-fetch-time-entries'+import { canViewTimeStats } from './middlewares/can-view-time-stats'++export default class TimeTrackingRoutes implements Routable {+ private readonly router: ReturnType<typeof Router>+ private readonly controller: TimeTrackingController++ constructor() {+ this.router = Router()+ this.controller = new TimeTrackingController()+ this.initRoutes()+ }++ getRouter() {+ return this.router+ }++ private initRoutes() {+ this.router.post('/start', [IsLoggedIn, canLogTimeOnTask], this.controller.start)+ this.router.post('/stop', [IsLoggedIn, canStopTimer], this.controller.stop)+ this.router.get('/active', [IsLoggedIn], this.controller.active)++ this.router.post('/entries', [IsLoggedIn, canLogTimeOnTask], this.controller.createManual)+ this.router.patch('/entries/:id', [IsLoggedIn, canAccessTimeEntry('edit')], this.controller.update)+ this.router.delete('/entries/:id', [IsLoggedIn, canAccessTimeEntry('edit')], this.controller.delete)+ this.router.get('/entries', [IsLoggedIn, canFetchTimeEntries], this.controller.fetchEntries)+ this.router.get('/entries/:id/history', [IsLoggedIn, canAccessTimeEntry('view')], this.controller.fetchHistory)++ this.router.get('/summary/task/:taskId', [IsLoggedIn, canViewTimeStats({ kind: 'task', param: 'taskId' })], this.controller.summaryByTask)+ this.router.get('/summary/goal/:goalId', [IsLoggedIn, canViewTimeStats({ kind: 'goal', param: 'goalId' })], this.controller.summaryByGoal)+ }+}diff --git a/api/src/tv-modules/time-tracking/middlewares/can-access-time-entry.ts b/api/src/tv-modules/time-tracking/middlewares/can-access-time-entry.tsnew file mode 100644index 0000000..7b7df82--- /dev/null+++ b/api/src/tv-modules/time-tracking/middlewares/can-access-time-entry.ts@@ -0,0 +1,41 @@+import type { NextFunction, Request, Response } from 'express'+import { $logger } from '../../../modules/logget'+import { GoalPermissions } from '../../../types/auth.types'+import { logError } from '../../../utils/api'++type Action = 'view' | 'edit'++export const canAccessTimeEntry = (action: Action) => async (req: Request, res: Response, next: NextFunction) => {+ const entryId = Number(req.params.id)+ if (!entryId) return res.status(400).end()++ const userId = req.appUser.getUserData()!.id++ const entry = await req.appUser.timeTrackingManager.repository.findById(entryId).catch(logError)+ if (!entry) return res.status(404).end()++ const checker = await req.appUser.permissionsFetcher+ .getCheckerForGoal(entry.goalId)+ .catch(logError)++ if (!checker) {+ $logger.error('Can not get permissions for canAccessTimeEntry middleware')+ return res.status(500).end()+ }++ if (action === 'view') {+ if (+ checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_VIEW) ||+ checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL)+ ) {+ return next()+ }+ return res.status(403).end()+ }++ const isOwn = entry.userId === userId+ if (isOwn && checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_LOG)) return next()+ if (checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL)) return next()++ return res.status(403).end()+}diff --git a/api/src/tv-modules/time-tracking/middlewares/can-fetch-time-entries.ts b/api/src/tv-modules/time-tracking/middlewares/can-fetch-time-entries.tsnew file mode 100644index 0000000..4397d72--- /dev/null+++ b/api/src/tv-modules/time-tracking/middlewares/can-fetch-time-entries.ts@@ -0,0 +1,32 @@+import type { NextFunction, Request, Response } from 'express'+import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher'+import { $logger } from '../../../modules/logget'+import { GoalPermissions } from '../../../types/auth.types'+import { logError } from '../../../utils/api'++export const canFetchTimeEntries = async (req: Request, res: Response, next: NextFunction) => {+ const goalIdRaw = req.query.goalId+ const taskIdRaw = req.query.taskId++ if (!goalIdRaw && !taskIdRaw) return next()++ const checker = goalIdRaw+ ? await req.appUser.permissionsFetcher.getCheckerForGoal(Number(goalIdRaw)).catch(logError)+ : await req.appUser.permissionsFetcher+ .getPermissionsForType(Number(taskIdRaw), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)+ .catch(logError)++ if (!checker) {+ $logger.error('Can not get permissions for canFetchTimeEntries middleware')+ return res.status(500).end()+ }++ if (+ checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_VIEW) ||+ checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL)+ ) {+ return next()+ }++ return res.status(403).end()+}diff --git a/api/src/tv-modules/time-tracking/middlewares/can-log-time-on-task.ts b/api/src/tv-modules/time-tracking/middlewares/can-log-time-on-task.tsnew file mode 100644index 0000000..07ec980--- /dev/null+++ b/api/src/tv-modules/time-tracking/middlewares/can-log-time-on-task.ts@@ -0,0 +1,28 @@+import type { NextFunction, Request, Response } from 'express'+import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher'+import { $logger } from '../../../modules/logget'+import { GoalPermissions } from '../../../types/auth.types'+import { logError } from '../../../utils/api'++export const canLogTimeOnTask = async (req: Request, res: Response, next: NextFunction) => {+ const taskId = Number(req.body?.taskId)+ if (!taskId) return res.status(400).end()++ const checker = await req.appUser.permissionsFetcher+ .getPermissionsForType(taskId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)+ .catch(logError)++ if (!checker) {+ $logger.error('Can not get permissions for canLogTimeOnTask middleware')+ return res.status(500).end()+ }++ if (+ checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_LOG) ||+ checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL)+ ) {+ return next()+ }++ return res.status(403).end()+}diff --git a/api/src/tv-modules/time-tracking/middlewares/can-stop-timer.ts b/api/src/tv-modules/time-tracking/middlewares/can-stop-timer.tsnew file mode 100644index 0000000..7d456da--- /dev/null+++ b/api/src/tv-modules/time-tracking/middlewares/can-stop-timer.ts@@ -0,0 +1,31 @@+import type { NextFunction, Request, Response } from 'express'+import { $logger } from '../../../modules/logget'+import { GoalPermissions } from '../../../types/auth.types'+import { logError } from '../../../utils/api'++export const canStopTimer = async (req: Request, res: Response, next: NextFunction) => {+ const userId = req.appUser.getUserData()!.id++ const repo = req.appUser.timeTrackingManager.repository+ const entryIdRaw = req.body?.entryId+ const target = entryIdRaw+ ? await repo.findById(Number(entryIdRaw)).catch(logError)+ : await repo.findActiveForUser(userId).catch(logError)++ if (!target || target.endedAt) return res.status(404).end()++ const checker = await req.appUser.permissionsFetcher+ .getCheckerForGoal(target.goalId)+ .catch(logError)++ if (!checker) {+ $logger.error('Can not get permissions for canStopTimer middleware')+ return res.status(500).end()+ }++ const isOwn = target.userId === userId+ if (isOwn && checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_LOG)) return next()+ if (checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL)) return next()++ return res.status(403).end()+}diff --git a/api/src/tv-modules/time-tracking/middlewares/can-view-time-stats.ts b/api/src/tv-modules/time-tracking/middlewares/can-view-time-stats.tsnew file mode 100644index 0000000..892a2c2--- /dev/null+++ b/api/src/tv-modules/time-tracking/middlewares/can-view-time-stats.ts@@ -0,0 +1,34 @@+import type { NextFunction, Request, Response } from 'express'+import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher'+import { $logger } from '../../../modules/logget'+import { GoalPermissions } from '../../../types/auth.types'+import { logError } from '../../../utils/api'++type Source = { kind: 'goal'; param: string } | { kind: 'task'; param: string }++export const canViewTimeStats = (source: Source) => async (req: Request, res: Response, next: NextFunction) => {+ const idRaw = req.params[source.param] ?? req.query[source.param]+ const id = Number(idRaw)+ if (!id) return res.status(400).end()++ const checker =+ source.kind === 'task'+ ? await req.appUser.permissionsFetcher+ .getPermissionsForType(id, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)+ .catch(logError)+ : await req.appUser.permissionsFetcher.getCheckerForGoal(id).catch(logError)++ if (!checker) {+ $logger.error('Can not get permissions for canViewTimeStats middleware')+ return res.status(500).end()+ }++ if (+ checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_VIEW) ||+ checker.hasPermissions(GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL)+ ) {+ return next()+ }++ return res.status(403).end()+}diff --git a/api/src/tv-modules/time-tracking/types.ts b/api/src/tv-modules/time-tracking/types.tsnew file mode 100644index 0000000..27360e5--- /dev/null+++ b/api/src/tv-modules/time-tracking/types.ts@@ -0,0 +1,129 @@+import { type } from 'arktype'+import type { TimeEntriesSchemaTypeForSelect } from 'taskview-db-schemas'++const NumberFromString = type('string|number').pipe((v) => Number(v))+const OptionalNumberFromString = type('string|number|undefined').pipe((v) => v === undefined ? undefined : Number(v))+const DateFromString = type('string|Date').pipe((v) => v instanceof Date ? v : new Date(v))+const OptionalDateFromString = type('string|Date|undefined').pipe((v) => v === undefined ? undefined : v instanceof Date ? v : new Date(v))++const DESCRIPTION_MAX = 500+const Description = type('string').narrow((v, ctx) => {+ const codepoints = [...v].length+ return codepoints <= DESCRIPTION_MAX || ctx.mustBe(`at most ${DESCRIPTION_MAX} characters (got ${codepoints})`)+})++export const TimeEntryArkTypeStart = type({+ taskId: 'number',+ 'description?': Description,+})+export type TimeEntryArgStart = typeof TimeEntryArkTypeStart.infer++export const TimeEntryArkTypeStop = type({+ 'entryId?': 'number',+})+export type TimeEntryArgStop = typeof TimeEntryArkTypeStop.infer++export const TimeEntryArkTypeCreate = type({+ taskId: 'number',+ startedAt: DateFromString,+ endedAt: DateFromString,+ 'description?': Description,+ 'billable?': 'boolean',+})+export type TimeEntryArgCreate = typeof TimeEntryArkTypeCreate.infer++export const TimeEntryArkTypeUpdate = type({+ id: 'number',+ 'startedAt?': OptionalDateFromString,+ 'endedAt?': OptionalDateFromString,+ 'description?': Description,+ 'billable?': 'boolean',+})+export type TimeEntryArgUpdate = typeof TimeEntryArkTypeUpdate.infer++export const TimeEntryArkTypeDelete = type({+ id: NumberFromString,+})+export type TimeEntryArgDelete = typeof TimeEntryArkTypeDelete.infer++export const TimeEntryArkTypeFetchEntries = type({+ 'goalId?': OptionalNumberFromString,+ 'taskId?': OptionalNumberFromString,+ 'userId?': OptionalNumberFromString,+ 'from?': OptionalDateFromString,+ 'to?': OptionalDateFromString,+ 'limit?': OptionalNumberFromString,+ 'offset?': OptionalNumberFromString,+})+export type TimeEntryArgFetchEntries = typeof TimeEntryArkTypeFetchEntries.infer++export const TimeEntryArkTypeSummaryByGoal = type({+ goalId: NumberFromString,+})+export type TimeEntryArgSummaryByGoal = typeof TimeEntryArkTypeSummaryByGoal.infer++export const TimeEntryArkTypeSummaryByTask = type({+ taskId: NumberFromString,+})+export type TimeEntryArgSummaryByTask = typeof TimeEntryArkTypeSummaryByTask.infer++export const TimeEntryArkTypeHistory = type({+ id: NumberFromString,+})+export type TimeEntryArgHistory = typeof TimeEntryArkTypeHistory.infer++export const TIME_ENTRY_SOURCE = {+ TIMER: 0,+ MANUAL: 1,+} as const++export type TimeEntrySource = typeof TIME_ENTRY_SOURCE[keyof typeof TIME_ENTRY_SOURCE]++export type TimeEntryInsertParams = {+ taskId: number+ goalId: number+ userId: number+ source: TimeEntrySource+ startedAt?: Date+ endedAt?: Date | null+ durationSeconds?: number | null+ description?: string | null+ billable?: boolean+}++export type TimeEntryUpdateParams = Partial<{+ startedAt: Date+ endedAt: Date | null+ durationSeconds: number | null+ description: string | null+ billable: boolean+ autoStopped: boolean+}>++export type TimeEntryFilters = {+ goalId?: number+ taskId?: number+ userId?: number+ from?: Date+ to?: Date+ limit?: number+ offset?: number+}++export type TimeEntryStartResult = {+ entry: TimeEntriesSchemaTypeForSelect+ autoStoppedEntry: TimeEntriesSchemaTypeForSelect | null+}++export type TimeEntryUserSeconds = { userId: number; seconds: number }++export type TimeEntryTaskSummary = {+ totalSeconds: number+ byUser: TimeEntryUserSeconds[]+}++export type TimeEntryGoalSummary = {+ totalSeconds: number+ byUser: TimeEntryUserSeconds[]+ byTask: { taskId: number; seconds: number }[]+}diff --git a/api/src/types/auth.types.ts b/api/src/types/auth.types.tsindex f8165c1..18d48c4 100644--- a/api/src/types/auth.types.ts+++ b/api/src/types/auth.types.ts@@ -128,6 +128,10 @@ export const GoalPermissions = {INTEGRATIONS_CAN_VIEW: 'integrations_can_view',ANALYTICS_CAN_VIEW: 'analytics_can_view',++ TIMETRACKING_CAN_VIEW: 'timetracking_can_view',+ TIMETRACKING_CAN_LOG: 'timetracking_can_log',+ TIMETRACKING_CAN_MANAGE_ALL: 'timetracking_can_manage_all',} as const;export type PermissionsEntityType =diff --git a/taskview-packages/taskview-api/src/api/permissions.ts b/taskview-packages/taskview-api/src/api/permissions.tsindex 9c4e90a..1620a58 100644--- a/taskview-packages/taskview-api/src/api/permissions.ts+++ b/taskview-packages/taskview-api/src/api/permissions.ts@@ -130,6 +130,22 @@ export const TvPermissions: Record<Uppercase<keyof GoalPermissions>, keyof GoalP* Can view analytics dashboards and KPIs for this goal*/ANALYTICS_CAN_VIEW: 'analytics_can_view',++ /**+ * View all time entries on this project — both own and other members'.+ * Does not grant logging or editing.+ */+ TIMETRACKING_CAN_VIEW: 'timetracking_can_view',+ /**+ * Start/stop timer and create/edit/delete OWN time entries on this project.+ * Does not grant viewing the project log or managing others' entries.+ */+ TIMETRACKING_CAN_LOG: 'timetracking_can_log',+ /**+ * Edit/delete time entries of other project members. Includes viewing the+ * full project log.+ */+ TIMETRACKING_CAN_MANAGE_ALL: 'timetracking_can_manage_all',} as const;export type GoalPermissions = {@@ -174,4 +190,8 @@ export type GoalPermissions = {integrations_can_view?: true;analytics_can_view?: true;++ timetracking_can_view?: true;+ timetracking_can_log?: true;+ timetracking_can_manage_all?: true;};\ No newline at end of filediff --git a/taskview-packages/taskview-api/src/api/time-tracking.ts b/taskview-packages/taskview-api/src/api/time-tracking.tsnew file mode 100644index 0000000..c886b42--- /dev/null+++ b/taskview-packages/taskview-api/src/api/time-tracking.ts@@ -0,0 +1,69 @@+import TvApiBase from './base'+import type { AppResponse } from '@/api/base.types'+import type {+ TimeEntryCreateManualArg,+ TimeEntryFetchFilters,+ TimeEntryHistoryItem,+ TimeEntryItem,+ TimeEntryStartArg,+ TimeEntryStartResult,+ TimeEntryStopArg,+ TimeEntrySummaryByGoal,+ TimeEntrySummaryByTask,+ TimeEntryUpdateArg,+} from './time-tracking.types'++export default class TvTimeTrackingApi extends TvApiBase {+ protected moduleUrl = '/module/time-tracking'++ public async start(data: TimeEntryStartArg) {+ return this.request(this.$axios.post<AppResponse<TimeEntryStartResult>>(`${this.moduleUrl}/start`, data))+ }++ public async stop(data: TimeEntryStopArg = {}) {+ return this.request(this.$axios.post<AppResponse<TimeEntryItem>>(`${this.moduleUrl}/stop`, data))+ }++ public async getActive() {+ return this.request(this.$axios.get<AppResponse<TimeEntryItem | null>>(`${this.moduleUrl}/active`))+ }++ public async createManual(data: TimeEntryCreateManualArg) {+ return this.request(this.$axios.post<AppResponse<TimeEntryItem>>(`${this.moduleUrl}/entries`, data))+ }++ public async update(data: TimeEntryUpdateArg) {+ const { id, ...rest } = data+ return this.request(this.$axios.patch<AppResponse<TimeEntryItem>>(`${this.moduleUrl}/entries/${id}`, rest))+ }++ public async delete(id: number) {+ return this.request(+ this.$axios.delete<AppResponse<{ deleted: boolean }>>(`${this.moduleUrl}/entries/${id}`),+ )+ }++ public async fetchEntries(filters: TimeEntryFetchFilters = {}) {+ return this.request(+ this.$axios.get<AppResponse<TimeEntryItem[]>>(`${this.moduleUrl}/entries`, { params: filters }),+ )+ }++ public async summaryByTask(taskId: number) {+ return this.request(+ this.$axios.get<AppResponse<TimeEntrySummaryByTask>>(`${this.moduleUrl}/summary/task/${taskId}`),+ )+ }++ public async summaryByGoal(goalId: number) {+ return this.request(+ this.$axios.get<AppResponse<TimeEntrySummaryByGoal>>(`${this.moduleUrl}/summary/goal/${goalId}`),+ )+ }++ public async fetchHistory(entryId: number) {+ return this.request(+ this.$axios.get<AppResponse<TimeEntryHistoryItem[]>>(`${this.moduleUrl}/entries/${entryId}/history`),+ )+ }+}diff --git a/taskview-packages/taskview-api/src/api/time-tracking.types.ts b/taskview-packages/taskview-api/src/api/time-tracking.types.tsnew file mode 100644index 0000000..7e82992--- /dev/null+++ b/taskview-packages/taskview-api/src/api/time-tracking.types.ts@@ -0,0 +1,78 @@+export type TimeEntryItem = {+ id: number+ taskId: number+ goalId: number+ userId: number+ startedAt: string+ endedAt: string | null+ durationSeconds: number | null+ description: string | null+ source: 0 | 1+ billable: boolean+ autoStopped: boolean+ createdAt: string+ editedAt: string+}++export type TimeEntryStartArg = {+ taskId: number+ description?: string+}++export type TimeEntryStartResult = {+ entry: TimeEntryItem+ autoStoppedEntry: TimeEntryItem | null+}++export type TimeEntryStopArg = {+ entryId?: number+}++export type TimeEntryCreateManualArg = {+ taskId: number+ startedAt: string | Date+ endedAt: string | Date+ description?: string+ billable?: boolean+}++export type TimeEntryUpdateArg = {+ id: number+ startedAt?: string | Date+ endedAt?: string | Date+ description?: string+ billable?: boolean+}++export type TimeEntryFetchFilters = {+ goalId?: number+ taskId?: number+ userId?: number+ from?: string | Date+ to?: string | Date+ limit?: number+ offset?: number+}++export type TimeEntrySummaryByTask = {+ totalSeconds: number+ byUser: { userId: number; seconds: number }[]+}++export type TimeEntrySummaryByGoal = {+ totalSeconds: number+ byUser: { userId: number; seconds: number }[]+ byTask: { taskId: number; seconds: number }[]+}++export type TimeEntryHistoryItem = {+ id: number+ entryId: number+ editDate: string+ entry: TimeEntryItem+}++export const TIME_ENTRY_SOURCE = {+ TIMER: 0,+ MANUAL: 1,+} as constdiff --git a/taskview-packages/taskview-api/src/index.ts b/taskview-packages/taskview-api/src/index.tsindex 51e81c8..8c5973e 100644--- a/taskview-packages/taskview-api/src/index.ts+++ b/taskview-packages/taskview-api/src/index.ts@@ -16,4 +16,5 @@ export * from '@/api/api-tokens.types';export * from '@/api/sessions.types';export * from '@/api/organizations.types';export * from '@/api/sso.types';-export * from '@/api/analytics.types';\ No newline at end of file+export * from '@/api/analytics.types';+export * from '@/api/time-tracking.types';\ No newline at end of filediff --git a/taskview-packages/taskview-api/src/tv.ts b/taskview-packages/taskview-api/src/tv.tsindex d4053cc..0a317a5 100644--- a/taskview-packages/taskview-api/src/tv.ts+++ b/taskview-packages/taskview-api/src/tv.ts@@ -14,6 +14,7 @@ import TvSessions from "./api/sessions";import TvOrganizationsApi from "./api/organizations";import TvSsoApi from "./api/sso";import TvAnalyticsApi from "./api/analytics";+import TvTimeTrackingApi from "./api/time-tracking";export class TvApi {@@ -49,6 +50,8 @@ export class TvApi {public analytics: TvAnalyticsApi;+ public timeTracking: TvTimeTrackingApi;+constructor($axios: AxiosInstance) {this.$axios = $axios;@@ -81,6 +84,8 @@ export class TvApi {this.sso = new TvSsoApi(this.$axios);this.analytics = new TvAnalyticsApi(this.$axios);++ this.timeTracking = new TvTimeTrackingApi(this.$axios);}public setBaseUrl(baseUrl: string) {diff --git a/taskview-packages/taskview-db-schemas/src/index.ts b/taskview-packages/taskview-db-schemas/src/index.tsindex e0af58c..326a750 100644--- a/taskview-packages/taskview-db-schemas/src/index.ts+++ b/taskview-packages/taskview-db-schemas/src/index.ts@@ -17,3 +17,5 @@ export * from './schemas/api-tokens.schema';export * from './schemas/user-tokens.schema';export * from './schemas/organizations.schema';export * from './schemas/sso.schema';+export * from './schemas/time-entries.schema';+export * from './schemas/time-entries-history.schema';diff --git a/taskview-packages/taskview-db-schemas/src/schemas/organizations.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/organizations.schema.tsindex 895008d..54e7f30 100644--- a/taskview-packages/taskview-db-schemas/src/schemas/organizations.schema.ts+++ b/taskview-packages/taskview-db-schemas/src/schemas/organizations.schema.ts@@ -9,6 +9,7 @@ export const OrganizationsSchema = pgSchema('tv_auth').table('organizations', {logoUrl: varchar('logo_url'),isPersonal: integer('is_personal').notNull().default(0),plan: varchar().notNull().default('free'),+ timeTrackingAutostopHours: integer('time_tracking_autostop_hours').default(24),createdAt: timestamp('created_at').defaultNow(),updatedAt: timestamp('updated_at').defaultNow(),})diff --git a/taskview-packages/taskview-db-schemas/src/schemas/time-entries-history.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/time-entries-history.schema.tsnew file mode 100644index 0000000..da8001a--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/time-entries-history.schema.ts@@ -0,0 +1,12 @@+import { integer, jsonb, pgSchema, timestamp } from 'drizzle-orm/pg-core'+import { TimeEntriesSchema } from './time-entries.schema'++export const TimeEntriesHistorySchema = pgSchema('history').table('time_entries', {+ id: integer().primaryKey().generatedAlwaysAsIdentity(),+ entryId: integer('entry_id').notNull().references(() => TimeEntriesSchema.id, { onDelete: 'cascade' }),+ editDate: timestamp('edit_date').notNull().defaultNow(),+ entry: jsonb().notNull(),+})++export type TimeEntriesHistorySchemaTypeForSelect = typeof TimeEntriesHistorySchema.$inferSelect+export type TimeEntriesHistorySchemaTypeForInsert = typeof TimeEntriesHistorySchema.$inferInsertdiff --git a/taskview-packages/taskview-db-schemas/src/schemas/time-entries.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/time-entries.schema.tsnew file mode 100644index 0000000..47c3343--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/time-entries.schema.ts@@ -0,0 +1,26 @@+import { boolean, integer, pgSchema, smallint, timestamp, varchar } from 'drizzle-orm/pg-core'+import { createInsertSchema } from 'drizzle-arktype'+import { TasksSchema } from './tasks.schema'+import { GoalsSchema } from './goals.schema'+import { UsersSchema } from './users.schema'++export const TimeEntriesSchema = pgSchema('tasks').table('time_entries', {+ id: integer().primaryKey().generatedAlwaysAsIdentity(),+ taskId: integer('task_id').notNull().references(() => TasksSchema.id, { onDelete: 'cascade' }),+ goalId: integer('goal_id').notNull().references(() => GoalsSchema.id, { onDelete: 'cascade' }),+ userId: integer('user_id').notNull().references(() => UsersSchema.id, { onDelete: 'cascade' }),+ startedAt: timestamp('started_at').notNull().defaultNow(),+ endedAt: timestamp('ended_at'),+ durationSeconds: integer('duration_seconds'),+ description: varchar({ length: 500 }),+ source: smallint().$type<0 | 1>().notNull().default(0),+ billable: boolean().notNull().default(true),+ autoStopped: boolean('auto_stopped').notNull().default(false),+ createdAt: timestamp('created_at').notNull().defaultNow(),+ editedAt: timestamp('edited_at').notNull().defaultNow(),+})++export type TimeEntriesSchemaTypeForSelect = typeof TimeEntriesSchema.$inferSelect+export type TimeEntriesSchemaTypeForInsert = typeof TimeEntriesSchema.$inferInsert++export const TimeEntriesSchemaArkTypeInsert = createInsertSchema(TimeEntriesSchema)diff --git a/taskview-packages/taskview-mcp/src/server.ts b/taskview-packages/taskview-mcp/src/server.tsindex 54c2d76..a04effc 100644--- a/taskview-packages/taskview-mcp/src/server.ts+++ b/taskview-packages/taskview-mcp/src/server.ts@@ -9,6 +9,7 @@ import { registerCollaborationTools } from './tools/collaboration.js'import { registerGraphTools } from './tools/graph.js'import { registerNotificationsTools } from './tools/notifications.js'import { registerOrganizationsTools } from './tools/organizations.js'+import { registerTimeTrackingTools } from './tools/time-tracking.js'export function createMcpServer(api: TvApi) {const server = new McpServer({@@ -25,6 +26,7 @@ export function createMcpServer(api: TvApi) {registerGraphTools(server, api)registerNotificationsTools(server, api)registerOrganizationsTools(server, api)+ registerTimeTrackingTools(server, api)return server}diff --git a/taskview-packages/taskview-mcp/src/tools/time-tracking.ts b/taskview-packages/taskview-mcp/src/tools/time-tracking.tsnew file mode 100644index 0000000..a090538--- /dev/null+++ b/taskview-packages/taskview-mcp/src/tools/time-tracking.ts@@ -0,0 +1,159 @@+import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'+import type { TvApi } from 'taskview-api'+import { z } from 'zod'+import { ok, err } from './helpers.js'++export function registerTimeTrackingTools(server: McpServer, api: TvApi) {+ server.registerTool(+ 'start_timer',+ {+ description: 'Start a timer for the given task. Returns {entry, autoStoppedEntry} — autoStoppedEntry is the previous active timer that was stopped (null if there was no active timer).',+ inputSchema: {+ taskId: z.coerce.number().describe('Task ID to track time for'),+ description: z.string().optional().describe('Optional description of the work'),+ },+ },+ async (params) => {+ try {+ const result = await api.timeTracking.start({+ taskId: params.taskId,+ description: params.description,+ })+ return ok(result)+ } catch (e) { return err(e) }+ },+ )++ server.registerTool(+ 'stop_timer',+ {+ description: 'Stop the active timer (or specific entry by id) and return the closed entry.',+ inputSchema: {+ entryId: z.coerce.number().optional().describe('Specific entry ID; if omitted, stops the user\'s active timer'),+ },+ },+ async (params) => {+ try {+ const entry = await api.timeTracking.stop(params.entryId ? { entryId: params.entryId } : {})+ return ok(entry)+ } catch (e) { return err(e) }+ },+ )++ server.registerTool(+ 'get_active_timer',+ {+ description: 'Get the user\'s currently running timer (if any).',+ },+ async () => {+ try {+ const entry = await api.timeTracking.getActive()+ return ok(entry)+ } catch (e) { return err(e) }+ },+ )++ server.registerTool(+ 'log_time',+ {+ description: 'Log a manual time entry retroactively (no time-period restrictions).',+ inputSchema: {+ taskId: z.coerce.number().describe('Task ID'),+ startedAt: z.string().describe('ISO 8601 start timestamp'),+ endedAt: z.string().describe('ISO 8601 end timestamp (must be after startedAt)'),+ description: z.string().optional().describe('Optional description'),+ billable: z.boolean().optional().describe('Whether the time is billable (default true)'),+ },+ },+ async (params) => {+ try {+ const entry = await api.timeTracking.createManual({+ taskId: params.taskId,+ startedAt: params.startedAt,+ endedAt: params.endedAt,+ description: params.description,+ billable: params.billable,+ })+ return ok(entry)+ } catch (e) { return err(e) }+ },+ )++ server.registerTool(+ 'list_time_entries',+ {+ description: 'List time entries with optional filters (goalId, taskId, userId, date range).',+ inputSchema: {+ goalId: z.coerce.number().optional().describe('Filter by project'),+ taskId: z.coerce.number().optional().describe('Filter by task'),+ userId: z.coerce.number().optional().describe('Filter by user (requires manage_all permission)'),+ from: z.string().optional().describe('ISO 8601 start of range'),+ to: z.string().optional().describe('ISO 8601 end of range'),+ limit: z.coerce.number().optional().describe('Max entries (default 50, max 500)'),+ offset: z.coerce.number().optional().describe('Pagination offset'),+ },+ },+ async (params) => {+ try {+ const entries = await api.timeTracking.fetchEntries(params)+ return ok(entries)+ } catch (e) { return err(e) }+ },+ )++ server.registerTool(+ 'get_time_summary',+ {+ description: 'Get aggregated time summary for a task or a project (goal).',+ inputSchema: {+ scope: z.enum(['task', 'goal']).describe('Aggregation scope'),+ id: z.coerce.number().describe('Task ID (if scope=task) or goal ID (if scope=goal)'),+ },+ },+ async (params) => {+ try {+ const summary =+ params.scope === 'task'+ ? await api.timeTracking.summaryByTask(params.id)+ : await api.timeTracking.summaryByGoal(params.id)+ return ok(summary)+ } catch (e) { return err(e) }+ },+ )++ server.registerTool(+ 'update_time_entry',+ {+ description: 'Update fields of an existing time entry (cannot edit started/ended of a running timer).',+ inputSchema: {+ id: z.coerce.number().describe('Time entry ID'),+ startedAt: z.string().optional().describe('New start time (ISO 8601)'),+ endedAt: z.string().optional().describe('New end time (ISO 8601)'),+ description: z.string().optional().describe('New description'),+ billable: z.boolean().optional().describe('New billable flag'),+ },+ },+ async (params) => {+ try {+ const entry = await api.timeTracking.update(params)+ return ok(entry)+ } catch (e) { return err(e) }+ },+ )++ server.registerTool(+ 'delete_time_entry',+ {+ description: 'Delete a time entry (writes a record to history.time_entries before deletion).',+ inputSchema: {+ id: z.coerce.number().describe('Time entry ID'),+ },+ },+ async (params) => {+ try {+ const result = await api.timeTracking.delete(params.id)+ return ok(result)+ } catch (e) { return err(e) }+ },+ )+}diff --git a/web/src/components/ActiveTimerIndicator.vue b/web/src/components/ActiveTimerIndicator.vuenew file mode 100644index 0000000..d878781--- /dev/null+++ b/web/src/components/ActiveTimerIndicator.vue@@ -0,0 +1,56 @@+<template>+ <UTooltip+ v-if="active"+ :text="tooltipText"+ >+ <button+ type="button"+ class="flex items-center gap-1.5 px-2 py-1 rounded-md bg-primary/10 text-primary hover:bg-primary/20 transition-colors"+ @click="goToTask"+ >+ <span class="relative flex size-2">+ <span class="absolute inline-flex h-full w-full rounded-full bg-primary opacity-75 animate-ping" />+ <span class="relative inline-flex rounded-full size-2 bg-primary" />+ </span>+ <span class="font-mono text-xs tabular-nums">{{ elapsedFormatted }}</span>+ <UIcon+ name="i-lucide-square"+ class="size-3.5 cursor-pointer hover:opacity-80"+ @click.stop="onStop"+ />+ </button>+ </UTooltip>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useRouter } from 'vue-router'+import { useI18n } from 'vue-i18n'+import { useTimer } from '@/composables/useTimer'+import { useTimeTrackingStore } from '@/stores/time-tracking.store'+import { useOrganizationStore } from '@/stores/organization.store'++const router = useRouter()+const { t } = useI18n()+const store = useTimeTrackingStore()+const orgStore = useOrganizationStore()+const { active, elapsedFormatted } = useTimer()++const tooltipText = computed(() => t('timeTracking.activeTimerTooltip'))++const goToTask = () => {+ if (!active.value) return+ router.push({+ name: 'user',+ params: {+ orgSlug: orgStore.currentOrgSlug,+ projectId: String(active.value.goalId),+ taskId: String(active.value.taskId),+ },+ })+}++const onStop = async () => {+ await store.stop()+}+</script>diff --git a/web/src/components/features/tasks/TaskDetailPanel.vue b/web/src/components/features/tasks/TaskDetailPanel.vueindex 8dd2306..f5a45d4 100644--- a/web/src/components/features/tasks/TaskDetailPanel.vue+++ b/web/src/components/features/tasks/TaskDetailPanel.vue@@ -112,6 +112,12 @@class="flex-1"/>+ <!-- Time tracking -->+ <TaskTimeTracking+ :task-id="task.id"+ class="flex-1"+ />+<!-- History --><TaskHistory:task-id="task.id"@@ -144,6 +150,7 @@ import TaskAssigneeSelect from '@/components/features/tasks/parts/TaskAssigneeSeimport TaskListSelect from '@/components/features/tasks/parts/TaskListSelect.vue'import TaskKanbanStatusSelect from '@/components/features/tasks/parts/TaskKanbanStatusSelect.vue'import TaskAmountEditor from '@/components/features/tasks/parts/TaskAmountEditor.vue'+import TaskTimeTracking from '@/components/features/tasks/parts/TaskTimeTracking.vue'import TaskHistory from '@/components/features/tasks/parts/TaskHistory.vue'import TaskDeadline from '@/components/features/tasks/parts/TaskDeadline.vue'import TaskSubtasks from '@/components/features/tasks/parts/TaskSubtasks.vue'diff --git a/web/src/components/features/tasks/parts/TaskTimeTracking.vue b/web/src/components/features/tasks/parts/TaskTimeTracking.vuenew file mode 100644index 0000000..6d7bb46--- /dev/null+++ b/web/src/components/features/tasks/parts/TaskTimeTracking.vue@@ -0,0 +1,192 @@+<template>+ <div+ v-if="canViewTimeTracking || canLogTime"+ class="flex flex-col gap-3 p-3 rounded-lg border border-default"+ >+ <div class="flex items-center justify-between gap-2">+ <div class="flex items-center gap-2">+ <UIcon+ name="i-lucide-timer"+ class="size-5 text-muted"+ />+ <span class="font-medium">{{ t('timeTracking.title') }}</span>+ <UBadge+ v-if="totalSeconds > 0"+ :label="formatDuration(totalSeconds)"+ color="neutral"+ variant="subtle"+ size="sm"+ />+ </div>++ <div class="flex items-center gap-2">+ <span+ v-if="isActiveOnThisTask"+ class="font-mono text-sm tabular-nums text-primary"+ >+ {{ elapsedFormatted }}+ </span>+ <UButton+ v-if="canLogTime && !isActiveOnThisTask"+ :label="t('timeTracking.start')"+ icon="i-lucide-play"+ color="primary"+ size="sm"+ @click="onStart"+ />+ <UButton+ v-else-if="canLogTime"+ :label="t('timeTracking.stop')"+ icon="i-lucide-square"+ color="error"+ size="sm"+ @click="store.stop()"+ />+ </div>+ </div>++ <div+ v-if="canLogTime && otherActiveWarning"+ class="flex items-center gap-2 text-xs text-warning"+ >+ <UIcon+ name="i-lucide-alert-triangle"+ class="size-4 shrink-0"+ />+ <span>{{ t('timeTracking.willStopOther') }}</span>+ </div>++ <div class="flex flex-col gap-2">+ <TaskTimeTrackingEntry+ v-for="entry in entries"+ :key="entry.id"+ :entry="entry"+ @delete="onDelete"+ @update="onUpdate"+ />+ </div>++ <div+ v-if="canLogTime"+ class="flex flex-col gap-2 pt-2 border-t border-default"+ >+ <UButton+ v-if="!manualOpen"+ :label="t('timeTracking.addManual')"+ icon="i-lucide-plus"+ color="neutral"+ variant="ghost"+ size="sm"+ block+ @click="manualOpen = true"+ />+ <TaskTimeTrackingForm+ v-else+ @submit="onSubmitManual"+ @cancel="manualOpen = false"+ />+ </div>++ <TaskTimeTrackingDeleteModal+ v-model:open="deleteModalOpen"+ @confirm="onConfirmDelete"+ />+ </div>+</template>++<script setup lang="ts">+import { computed, onMounted, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import { storeToRefs } from 'pinia'+import { useEventListener } from '@vueuse/core'+import { useTimeTrackingStore } from '@/stores/time-tracking.store'+import { useTimer } from '@/composables/useTimer'+import { formatDuration } from '@/helpers/formatDuration'+import TaskTimeTrackingEntry from './TaskTimeTrackingEntry.vue'+import TaskTimeTrackingForm, { type TimeEntryFormPayload } from './TaskTimeTrackingForm.vue'+import TaskTimeTrackingDeleteModal from './TaskTimeTrackingDeleteModal.vue'+import { useGoalPermissions } from '@/composables/useGoalPermissions'++const props = defineProps<{+ taskId: number+}>()++const { t } = useI18n()+const toast = useToast()+const store = useTimeTrackingStore()+const { canViewTimeTracking, canLogTime } = useGoalPermissions()+const { entriesByTask, active } = storeToRefs(store)+const { elapsedFormatted } = useTimer()++const manualOpen = ref(false)+const deleteModalOpen = ref(false)+const pendingDeleteId = ref<number | null>(null)++const entries = computed(() => entriesByTask.value[props.taskId] ?? [])+const totalSeconds = computed(() =>+ entries.value.reduce((sum, e) => sum + (e.durationSeconds ?? 0), 0),+)+const isActiveOnThisTask = computed(() => active.value?.taskId === props.taskId)+const otherActiveWarning = computed(+ () => active.value !== null && active.value.taskId !== props.taskId,+)++const onStart = async () => {+ const result = await store.start(props.taskId)+ if (result?.autoStoppedEntry) {+ toast.add({+ title: t('timeTracking.previousStopped'),+ description: t('timeTracking.previousStoppedDescription', {+ duration: formatDuration(result.autoStoppedEntry.durationSeconds ?? 0),+ }),+ color: 'warning',+ })+ }+}++const onDelete = (entryId: number) => {+ pendingDeleteId.value = entryId+ deleteModalOpen.value = true+}++const onConfirmDelete = () => {+ if (pendingDeleteId.value !== null) {+ store.deleteEntry(pendingDeleteId.value, props.taskId)+ pendingDeleteId.value = null+ }+}++const onUpdate = (payload: TimeEntryFormPayload & { id: number }) =>+ store.update({+ id: payload.id,+ startedAt: payload.startedAt,+ endedAt: payload.endedAt,+ description: payload.description || undefined,+ })++const onSubmitManual = async (payload: TimeEntryFormPayload) => {+ const created = await store.createManual({+ taskId: props.taskId,+ startedAt: payload.startedAt,+ endedAt: payload.endedAt,+ description: payload.description || undefined,+ })+ if (created) manualOpen.value = false+}++watch(+ () => props.taskId,+ (id) => {+ if (id) store.fetchEntriesForTask(id)+ },+ { immediate: true },+)++onMounted(() => {+ if (!active.value) store.fetchActive()+})++useEventListener(document, 'visibilitychange', () => {+ if (!document.hidden && props.taskId) store.fetchEntriesForTask(props.taskId)+})+</script>diff --git a/web/src/components/features/tasks/parts/TaskTimeTrackingDeleteModal.vue b/web/src/components/features/tasks/parts/TaskTimeTrackingDeleteModal.vuenew file mode 100644index 0000000..31f4fe5--- /dev/null+++ b/web/src/components/features/tasks/parts/TaskTimeTrackingDeleteModal.vue@@ -0,0 +1,55 @@+<template>+ <UModal+ v-model:open="open"+ :fullscreen="isMobile"+ :ui="{ content: 'max-w-md' }"+ >+ <template #content>+ <UCard>+ <template #header>+ <h3 class="font-semibold">+ {{ t('timeTracking.deleteConfirmTitle') }}+ </h3>+ </template>+ <p class="text-sm text-muted">+ {{ t('timeTracking.deleteConfirm') }}+ </p>+ <template #footer>+ <div class="flex justify-end gap-2">+ <UButton+ :label="t('timeTracking.cancel')"+ color="neutral"+ variant="ghost"+ @click="open = false"+ />+ <UButton+ :label="t('timeTracking.delete')"+ icon="i-lucide-trash-2"+ color="error"+ @click="onConfirm"+ />+ </div>+ </template>+ </UCard>+ </template>+ </UModal>+</template>++<script setup lang="ts">+import { useI18n } from 'vue-i18n'+import { useTaskView } from '@/composables/useTaskView'++const open = defineModel<boolean>('open', { default: false })++const emit = defineEmits<{+ confirm: []+}>()++const { t } = useI18n()+const { isMobile } = useTaskView()++const onConfirm = () => {+ open.value = false+ emit('confirm')+}+</script>diff --git a/web/src/components/features/tasks/parts/TaskTimeTrackingEntry.vue b/web/src/components/features/tasks/parts/TaskTimeTrackingEntry.vuenew file mode 100644index 0000000..45973f0--- /dev/null+++ b/web/src/components/features/tasks/parts/TaskTimeTrackingEntry.vue@@ -0,0 +1,91 @@+<template>+ <div class="flex flex-col gap-1 px-2 py-1.5 rounded bg-elevated/50 text-sm">+ <div class="flex items-center justify-between gap-2">+ <div class="flex flex-col min-w-0 flex-1">+ <span class="font-mono text-xs text-muted">+ {{ formattedStarted }}+ </span>+ <span+ v-if="entry.description"+ class="truncate"+ >{{ entry.description }}</span>+ </div>+ <div class="flex items-center gap-2 shrink-0">+ <UBadge+ v-if="entry.endedAt"+ :label="formatDuration(entry.durationSeconds ?? 0)"+ color="neutral"+ variant="subtle"+ size="xs"+ />+ <UBadge+ v-else+ :label="t('timeTracking.running')"+ color="primary"+ variant="subtle"+ size="xs"+ />+ <UButton+ v-if="entry.endedAt && !editing && canEdit"+ icon="i-lucide-pencil"+ color="neutral"+ variant="ghost"+ size="xs"+ @click="editing = true"+ />+ <UButton+ v-if="entry.endedAt && !editing && canEdit"+ icon="i-lucide-trash-2"+ color="error"+ variant="ghost"+ size="xs"+ @click="emit('delete', entry.id)"+ />+ </div>+ </div>++ <TaskTimeTrackingForm+ v-if="editing"+ :initial-started-at="entry.startedAt"+ :initial-ended-at="entry.endedAt ?? undefined"+ :initial-description="entry.description ?? ''"+ class="border-t border-default"+ @submit="onSubmit"+ @cancel="editing = false"+ />+ </div>+</template>++<script setup lang="ts">+import { computed, ref } from 'vue'+import { useI18n } from 'vue-i18n'+import type { TimeEntryItem } from 'taskview-api'+import { formatDuration } from '@/helpers/formatDuration'+import TaskTimeTrackingForm, { type TimeEntryFormPayload } from './TaskTimeTrackingForm.vue'+import { useGoalPermissions } from '@/composables/useGoalPermissions'+import { useUserStore } from '@/stores/user.store'++const props = defineProps<{+ entry: TimeEntryItem+}>()++const emit = defineEmits<{+ delete: [entryId: number]+ update: [payload: TimeEntryFormPayload & { id: number }]+}>()++const { t } = useI18n()+const editing = ref(false)+const userStore = useUserStore()+const { canLogTime, canManageAllTime } = useGoalPermissions()++const isOwn = computed(() => userStore.payloadData?.id === props.entry.userId)+const canEdit = computed(() => (isOwn.value ? canLogTime.value : canManageAllTime.value))++const formattedStarted = computed(() => new Date(props.entry.startedAt).toLocaleString())++const onSubmit = (payload: TimeEntryFormPayload) => {+ emit('update', { id: props.entry.id, ...payload })+ editing.value = false+}+</script>diff --git a/web/src/components/features/tasks/parts/TaskTimeTrackingForm.vue b/web/src/components/features/tasks/parts/TaskTimeTrackingForm.vuenew file mode 100644index 0000000..bef24fc--- /dev/null+++ b/web/src/components/features/tasks/parts/TaskTimeTrackingForm.vue@@ -0,0 +1,159 @@+<template>+ <div class="flex flex-col gap-2 pt-2">+ <div class="flex gap-2">+ <UPopover v-model:open="startOpen">+ <UButton+ :label="formattedStart"+ icon="i-lucide-calendar"+ color="neutral"+ variant="outline"+ size="sm"+ class="flex-1 justify-start"+ />+ <template #content>+ <div class="p-2 flex flex-col gap-2">+ <UCalendar+ v-model="startDate"+ :max-value="endDate"+ />+ <UInputTime+ v-model="startTime"+ :hour-cycle="24"+ />+ </div>+ </template>+ </UPopover>++ <UPopover v-model:open="endOpen">+ <UButton+ :label="formattedEnd"+ icon="i-lucide-calendar-check"+ color="neutral"+ variant="outline"+ size="sm"+ class="flex-1 justify-start"+ />+ <template #content>+ <div class="p-2 flex flex-col gap-2">+ <UCalendar+ v-model="endDate"+ :min-value="startDate"+ />+ <UInputTime+ v-model="endTime"+ :hour-cycle="24"+ />+ </div>+ </template>+ </UPopover>+ </div>++ <UFormField :label="t('timeTracking.description')">+ <UInput+ v-model="description"+ size="sm"+ class="w-full"+ />+ </UFormField>++ <div class="flex justify-end gap-2">+ <UButton+ :label="t('timeTracking.cancel')"+ color="neutral"+ variant="ghost"+ size="sm"+ @click="emit('cancel')"+ />+ <UButton+ :label="submitLabel ?? t('timeTracking.save')"+ color="primary"+ size="sm"+ :disabled="!isValid"+ @click="onSubmit"+ />+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed, ref, shallowRef } from 'vue'+import { useI18n } from 'vue-i18n'+import { useDateFormat } from '@vueuse/core'+import { CalendarDate, Time } from '@internationalized/date'++export type TimeEntryFormPayload = {+ startedAt: string+ endedAt: string+ description: string+}++const props = defineProps<{+ initialStartedAt?: string+ initialEndedAt?: string+ initialDescription?: string+ submitLabel?: string+}>()++const emit = defineEmits<{+ submit: [TimeEntryFormPayload]+ cancel: []+}>()++const { t } = useI18n()++const fromIso = (iso: string | undefined): { date?: CalendarDate; time?: Time } => {+ if (!iso) return {}+ const d = new Date(iso)+ return {+ date: new CalendarDate(d.getFullYear(), d.getMonth() + 1, d.getDate()),+ time: new Time(d.getHours(), d.getMinutes()),+ }+}++const initialStart = fromIso(props.initialStartedAt)+const initialEnd = fromIso(props.initialEndedAt)++const startDate = shallowRef<CalendarDate | undefined>(initialStart.date)+const endDate = shallowRef<CalendarDate | undefined>(initialEnd.date)+const startTime = shallowRef<Time | undefined>(initialStart.time)+const endTime = shallowRef<Time | undefined>(initialEnd.time)+const description = ref(props.initialDescription ?? '')++const startOpen = ref(false)+const endOpen = ref(false)++const toJsDate = (date: CalendarDate | undefined, time: Time | undefined): Date | null => {+ if (!date) return null+ return new Date(date.year, date.month - 1, date.day, time?.hour ?? 0, time?.minute ?? 0)+}++const startJs = computed(() => toJsDate(startDate.value, startTime.value))+const endJs = computed(() => toJsDate(endDate.value, endTime.value))++const isValid = computed(() => {+ if (!startJs.value || !endJs.value) return false+ return endJs.value.getTime() > startJs.value.getTime()+})++const formatPair = (date: CalendarDate | undefined, time: Time | undefined, placeholder: string) => {+ if (!date) return placeholder+ const js = new Date(date.year, date.month - 1, date.day)+ const datePart = useDateFormat(js, 'DD MMM').value+ if (!time) return datePart+ const h = String(time.hour).padStart(2, '0')+ const m = String(time.minute).padStart(2, '0')+ return `${datePart} ${h}:${m}`+}++const formattedStart = computed(() => formatPair(startDate.value, startTime.value, t('timeTracking.startedAt')))+const formattedEnd = computed(() => formatPair(endDate.value, endTime.value, t('timeTracking.endedAt')))++const onSubmit = () => {+ if (!isValid.value || !startJs.value || !endJs.value) return+ emit('submit', {+ startedAt: startJs.value.toISOString(),+ endedAt: endJs.value.toISOString(),+ description: description.value,+ })+}+</script>diff --git a/web/src/composables/useCentrifugo/handlers/index.ts b/web/src/composables/useCentrifugo/handlers/index.tsindex 0cd61c2..49eb282 100644--- a/web/src/composables/useCentrifugo/handlers/index.ts+++ b/web/src/composables/useCentrifugo/handlers/index.ts@@ -1,8 +1,20 @@import type { RealtimeEventMap, RealtimeHandler } from '../types'import { handleNotification } from './notification'import { handleGoalsChanged } from './goals-changed'+import {+ handleTimeEntryCreated,+ handleTimeEntryDeleted,+ handleTimeEntryStarted,+ handleTimeEntryStopped,+ handleTimeEntryUpdated,+} from './time-entry'export const eventHandlers: { [K in keyof RealtimeEventMap]: RealtimeHandler<K> } = {'notification': handleNotification,'goals.changed': handleGoalsChanged,+ 'time-entry.started': handleTimeEntryStarted,+ 'time-entry.stopped': handleTimeEntryStopped,+ 'time-entry.created': handleTimeEntryCreated,+ 'time-entry.updated': handleTimeEntryUpdated,+ 'time-entry.deleted': handleTimeEntryDeleted,}diff --git a/web/src/composables/useCentrifugo/handlers/time-entry.ts b/web/src/composables/useCentrifugo/handlers/time-entry.tsnew file mode 100644index 0000000..21d9dd1--- /dev/null+++ b/web/src/composables/useCentrifugo/handlers/time-entry.ts@@ -0,0 +1,26 @@+import { useTimeTrackingStore } from '@/stores/time-tracking.store'+import type { RealtimeEventMap } from '../types'++export function handleTimeEntryStarted(data: RealtimeEventMap['time-entry.started']) {+ useTimeTrackingStore().handleRealtimeStarted(data.entry)+}++export function handleTimeEntryStopped(data: RealtimeEventMap['time-entry.stopped']) {+ useTimeTrackingStore().handleRealtimeStopped(data.entry)+}++export function handleTimeEntryCreated(data: RealtimeEventMap['time-entry.created']) {+ useTimeTrackingStore().handleRealtimeCreated(data.entry)+}++export function handleTimeEntryUpdated(data: RealtimeEventMap['time-entry.updated']) {+ const store = useTimeTrackingStore()+ store.replaceInTask(data.entry)+ if (store.active?.id === data.entry.id) {+ store.active = data.entry.endedAt ? null : data.entry+ }+}++export function handleTimeEntryDeleted(data: RealtimeEventMap['time-entry.deleted']) {+ useTimeTrackingStore().handleRealtimeDeleted({ entryId: data.entryId, taskId: data.taskId })+}diff --git a/web/src/composables/useCentrifugo/types.ts b/web/src/composables/useCentrifugo/types.tsindex d10e911..aa26e1e 100644--- a/web/src/composables/useCentrifugo/types.ts+++ b/web/src/composables/useCentrifugo/types.ts@@ -1,4 +1,4 @@-import type { Notification } from 'taskview-api'+import type { Notification, TimeEntryItem } from 'taskview-api'export type RealtimeEventMap = {'notification': {@@ -11,6 +11,29 @@ export type RealtimeEventMap = {event: 'goals.changed'goalId: number}+ 'time-entry.started': {+ event: 'time-entry.started'+ entry: TimeEntryItem+ }+ 'time-entry.stopped': {+ event: 'time-entry.stopped'+ entry: TimeEntryItem+ durationSeconds: number+ }+ 'time-entry.created': {+ event: 'time-entry.created'+ entry: TimeEntryItem+ }+ 'time-entry.updated': {+ event: 'time-entry.updated'+ entry: TimeEntryItem+ changes: Record<string, unknown>+ }+ 'time-entry.deleted': {+ event: 'time-entry.deleted'+ entryId: number+ taskId: number+ }}export type RealtimeEvent = RealtimeEventMap[keyof RealtimeEventMap]diff --git a/web/src/composables/useGoalPermissions.ts b/web/src/composables/useGoalPermissions.tsindex b0eb120..dbc29a1 100644--- a/web/src/composables/useGoalPermissions.ts+++ b/web/src/composables/useGoalPermissions.ts@@ -80,6 +80,10 @@ export const useGoalPermissions = () => {const canViewIntegrations = computed(() => permissions.INTEGRATIONS_CAN_VIEW || permissions.INTEGRATIONS_CAN_MANAGE)const canManageIntegrations = computed(() => permissions.INTEGRATIONS_CAN_MANAGE)+ const canViewTimeTracking = computed(() => permissions.TIMETRACKING_CAN_VIEW || permissions.TIMETRACKING_CAN_MANAGE_ALL)+ const canLogTime = computed(() => permissions.TIMETRACKING_CAN_LOG || permissions.TIMETRACKING_CAN_MANAGE_ALL)+ const canManageAllTime = computed(() => permissions.TIMETRACKING_CAN_MANAGE_ALL)+return {permissions,canDeleteGoal,@@ -114,5 +118,8 @@ export const useGoalPermissions = () => {canManageGraph,canViewIntegrations,canManageIntegrations,+ canViewTimeTracking,+ canLogTime,+ canManageAllTime,}}diff --git a/web/src/composables/useTimer.ts b/web/src/composables/useTimer.tsnew file mode 100644index 0000000..c3b5398--- /dev/null+++ b/web/src/composables/useTimer.ts@@ -0,0 +1,24 @@+import { computed } from 'vue'+import { storeToRefs } from 'pinia'+import { useNow } from '@vueuse/core'+import { useTimeTrackingStore } from '@/stores/time-tracking.store'+import { formatDuration } from '@/helpers/formatDuration'++export function useTimer() {+ const { active } = storeToRefs(useTimeTrackingStore())+ const now = useNow({ interval: 1000 })++ const elapsedSeconds = computed(() => {+ if (!active.value) return 0+ const startedMs = new Date(active.value.startedAt).getTime()+ return Math.max(0, Math.floor((now.value.getTime() - startedMs) / 1000))+ })++ const elapsedFormatted = computed(() => formatDuration(elapsedSeconds.value))++ return {+ active,+ elapsedSeconds,+ elapsedFormatted,+ }+}diff --git a/web/src/helpers/formatDuration.ts b/web/src/helpers/formatDuration.tsnew file mode 100644index 0000000..dda052e--- /dev/null+++ b/web/src/helpers/formatDuration.ts@@ -0,0 +1,9 @@+export function formatDuration(seconds: number): string {+ if (!Number.isFinite(seconds) || seconds < 0) return '00:00'+ const total = Math.floor(seconds)+ const h = Math.floor(total / 3600)+ const m = Math.floor((total % 3600) / 60)+ const s = total % 60+ if (h > 0) return `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`+ return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`+}diff --git a/web/src/layouts/UserLayout.vue b/web/src/layouts/UserLayout.vueindex f72064a..a876365 100644--- a/web/src/layouts/UserLayout.vue+++ b/web/src/layouts/UserLayout.vue@@ -22,6 +22,7 @@>{{ t('main') }}</TvGoalLikeItem>+ <ActiveTimerIndicator /><NotificationBell /></div>@@ -42,6 +43,7 @@<script setup lang="ts">import { onMounted, watch } from 'vue'import { useRoute, useRouter } from 'vue-router'+import { useEventListener } from '@vueuse/core'import { App } from '@capacitor/app'import { CapacitorUpdater } from '@capgo/capacitor-updater'import { useDashboard } from '@/composables/useDashboard'@@ -51,18 +53,30 @@ import { useI18n } from 'vue-i18n'import ConnectionStatusBanner from '@/components/ConnectionStatusBanner.vue'import ProjectsSidebar from '@/components/features/projects/ProjectsSidebar.vue'import NotificationBell from '@/components/NotificationBell.vue'+import ActiveTimerIndicator from '@/components/ActiveTimerIndicator.vue'import { useCentrifugo } from '@/composables/useCentrifugo'import { usePushNotifications } from '@/composables/usePushNotifications'import { useGoalsStore } from '@/stores/goals.store'import { useOrganizationStore } from '@/stores/organization.store'+import { useTimeTrackingStore } from '@/stores/time-tracking.store'const { isSidebarOpen, isSidebarCollapsed } = useDashboard()const { connect: connectCentrifugo } = useCentrifugo()const { init: initPush } = usePushNotifications()const { t } = useI18n()+const toast = useToast()const appStore = useAppStore()const goalsStore = useGoalsStore()const orgStore = useOrganizationStore()+const timeTrackingStore = useTimeTrackingStore()++watch(+ () => timeTrackingStore.lastError,+ (err) => {+ if (!err) return+ toast.add({ title: t(err.key), color: 'error' })+ },+)const route = useRoute()const router = useRouter()@@ -124,6 +138,11 @@ onMounted(async () => {}await goalsStore.fetchGoals()+ timeTrackingStore.fetchActive()++ useEventListener(document, 'visibilitychange', () => {+ if (!document.hidden) timeTrackingStore.fetchActive()+ })await CapacitorUpdater.notifyAppReady()console.log('notifyAppReady', APP_VERSION)diff --git a/web/src/locales/en.ts b/web/src/locales/en.tsindex c53d9ae..9f61477 100644--- a/web/src/locales/en.ts+++ b/web/src/locales/en.ts@@ -677,4 +677,32 @@ export default {restored: 'Connection restored',reload: 'Reload',},+ timeTracking: {+ title: 'Time tracking',+ start: 'Start',+ stop: 'Stop',+ running: 'Running',+ addManual: 'Add manually',+ startedAt: 'Started at',+ endedAt: 'Ended at',+ description: 'Description',+ save: 'Save',+ cancel: 'Cancel',+ willStopOther: 'Starting will stop your current timer on another task',+ previousStopped: 'Previous timer stopped',+ previousStoppedDescription: 'Your previous timer was running for {duration} and has been stopped',+ activeTimerTooltip: 'Click to open task — square icon to stop',+ autostopHours: 'Auto-stop timers after (hours)',+ autostopHint: 'Leave empty to disable',+ delete: 'Delete',+ deleteConfirmTitle: 'Delete time entry?',+ deleteConfirm: 'This action cannot be undone.',+ errors: {+ generic: 'Time tracking action failed',+ forbidden: 'You don\'t have permission for this action',+ notFound: 'Time entry not found',+ validation: 'Invalid input data',+ network: 'Network error. Check your connection.',+ },+ },}diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.tsindex 2120174..00d6f0a 100644--- a/web/src/locales/ru.ts+++ b/web/src/locales/ru.ts@@ -609,4 +609,32 @@ export default {restored: 'Соединение восстановлено',reload: 'Обновить',},+ timeTracking: {+ title: 'Учёт времени',+ start: 'Запустить',+ stop: 'Остановить',+ running: 'Идёт',+ addManual: 'Добавить вручную',+ startedAt: 'Начало',+ endedAt: 'Окончание',+ description: 'Описание',+ save: 'Сохранить',+ cancel: 'Отмена',+ willStopOther: 'Запуск остановит ваш текущий таймер на другой задаче',+ previousStopped: 'Предыдущий таймер остановлен',+ previousStoppedDescription: 'Предыдущий таймер работал {duration} и был остановлен',+ activeTimerTooltip: 'Клик — открыть задачу; квадрат — остановить',+ autostopHours: 'Автостоп таймеров через (часов)',+ autostopHint: 'Оставьте пустым, чтобы отключить',+ delete: 'Удалить',+ deleteConfirmTitle: 'Удалить запись времени?',+ deleteConfirm: 'Действие необратимо.',+ errors: {+ generic: 'Не удалось выполнить действие',+ forbidden: 'У вас нет прав на это действие',+ notFound: 'Запись времени не найдена',+ validation: 'Некорректные данные',+ network: 'Ошибка сети. Проверьте подключение.',+ },+ },}diff --git a/web/src/stores/time-tracking.store.ts b/web/src/stores/time-tracking.store.tsnew file mode 100644index 0000000..ccedc9f--- /dev/null+++ b/web/src/stores/time-tracking.store.ts@@ -0,0 +1,239 @@+import { defineStore } from 'pinia'+import axios from 'axios'+import type {+ TimeEntryCreateManualArg,+ TimeEntryFetchFilters,+ TimeEntryHistoryItem,+ TimeEntryItem,+ TimeEntryStartResult,+ TimeEntrySummaryByGoal,+ TimeEntrySummaryByTask,+ TimeEntryUpdateArg,+} from 'taskview-api'+import { $tvApi } from '@/plugins/axios'++interface TimeTrackingState {+ active: TimeEntryItem | null+ entriesByTask: Record<number, TimeEntryItem[]>+ summaryByTask: Record<number, TimeEntrySummaryByTask>+ taskRecency: number[]+ loadingActive: boolean+ loadingByTaskId: number | null+ lastError: { key: string; ts: number } | null+}++const TASK_CACHE_LIMIT = 10++function resolveErrorKey(err: unknown): string {+ if (axios.isAxiosError(err)) {+ const status = err.response?.status+ if (status === 403) return 'timeTracking.errors.forbidden'+ if (status === 404) return 'timeTracking.errors.notFound'+ if (status === 400) return 'timeTracking.errors.validation'+ if (status === undefined) return 'timeTracking.errors.network'+ }+ return 'timeTracking.errors.generic'+}++export const useTimeTrackingStore = defineStore('timeTracking', {+ state: (): TimeTrackingState => ({+ active: null,+ entriesByTask: {},+ summaryByTask: {},+ taskRecency: [],+ loadingActive: false,+ loadingByTaskId: null,+ lastError: null,+ }),+ actions: {+ setError(err: unknown): void {+ this.lastError = { key: resolveErrorKey(err), ts: Date.now() }+ },++ touchTaskCache(taskId: number): void {+ this.taskRecency = this.taskRecency.filter((id) => id !== taskId)+ this.taskRecency.push(taskId)+ while (this.taskRecency.length > TASK_CACHE_LIMIT) {+ const evicted = this.taskRecency.shift()+ if (evicted !== undefined) {+ delete this.entriesByTask[evicted]+ delete this.summaryByTask[evicted]+ }+ }+ },++ async fetchActive(): Promise<void> {+ this.loadingActive = true+ try {+ const result = await $tvApi.timeTracking.getActive()+ this.active = result ?? null+ } catch (err) {+ this.setError(err)+ } finally {+ this.loadingActive = false+ }+ },++ async start(taskId: number, description?: string): Promise<TimeEntryStartResult | null> {+ try {+ const result = await $tvApi.timeTracking.start({ taskId, description })+ if (!result) return null+ if (result.autoStoppedEntry) this.replaceInTask(result.autoStoppedEntry)+ this.active = result.entry+ this.appendToTask(result.entry)+ return result+ } catch (err) {+ this.setError(err)+ return null+ }+ },++ async stop(entryId?: number): Promise<TimeEntryItem | null> {+ try {+ const entry = await $tvApi.timeTracking.stop(entryId ? { entryId } : {})+ if (!entry) return null+ if (this.active?.id === entry.id) this.active = null+ this.replaceInTask(entry)+ return entry+ } catch (err) {+ this.setError(err)+ return null+ }+ },++ async createManual(data: TimeEntryCreateManualArg): Promise<TimeEntryItem | null> {+ try {+ const entry = await $tvApi.timeTracking.createManual(data)+ if (!entry) return null+ this.appendToTask(entry)+ return entry+ } catch (err) {+ this.setError(err)+ return null+ }+ },++ async update(data: TimeEntryUpdateArg): Promise<TimeEntryItem | null> {+ try {+ const entry = await $tvApi.timeTracking.update(data)+ if (!entry) return null+ this.replaceInTask(entry)+ if (this.active?.id === entry.id) {+ this.active = entry.endedAt ? null : entry+ }+ return entry+ } catch (err) {+ this.setError(err)+ return null+ }+ },++ async deleteEntry(id: number, taskId: number): Promise<boolean> {+ try {+ const result = await $tvApi.timeTracking.delete(id)+ if (!result?.deleted) return false+ const list = this.entriesByTask[taskId]+ if (list) this.entriesByTask[taskId] = list.filter((e) => e.id !== id)+ if (this.active?.id === id) this.active = null+ return true+ } catch (err) {+ this.setError(err)+ return false+ }+ },++ async fetchEntriesForTask(taskId: number): Promise<void> {+ this.loadingByTaskId = taskId+ try {+ const result = await $tvApi.timeTracking.fetchEntries({ taskId })+ this.entriesByTask[taskId] = result ?? []+ this.touchTaskCache(taskId)+ } catch (err) {+ this.setError(err)+ } finally {+ this.loadingByTaskId = null+ }+ },++ async fetchEntries(filters: TimeEntryFetchFilters): Promise<TimeEntryItem[]> {+ try {+ const result = await $tvApi.timeTracking.fetchEntries(filters)+ return result ?? []+ } catch (err) {+ this.setError(err)+ return []+ }+ },++ async fetchSummaryByTask(taskId: number): Promise<TimeEntrySummaryByTask | null> {+ try {+ const result = await $tvApi.timeTracking.summaryByTask(taskId)+ if (result) {+ this.summaryByTask[taskId] = result+ this.touchTaskCache(taskId)+ }+ return result ?? null+ } catch (err) {+ this.setError(err)+ return null+ }+ },++ async fetchSummaryByGoal(goalId: number): Promise<TimeEntrySummaryByGoal | null> {+ try {+ return await $tvApi.timeTracking.summaryByGoal(goalId) ?? null+ } catch (err) {+ this.setError(err)+ return null+ }+ },++ async fetchHistory(entryId: number): Promise<TimeEntryHistoryItem[]> {+ try {+ const result = await $tvApi.timeTracking.fetchHistory(entryId)+ return result ?? []+ } catch (err) {+ this.setError(err)+ return []+ }+ },++ handleRealtimeStarted(entry: TimeEntryItem): void {+ this.active = entry+ this.appendToTask(entry)+ },++ handleRealtimeStopped(entry: TimeEntryItem): void {+ if (this.active?.id === entry.id) this.active = null+ this.replaceInTask(entry)+ },++ handleRealtimeCreated(entry: TimeEntryItem): void {+ this.appendToTask(entry)+ },++ handleRealtimeDeleted(payload: { entryId: number; taskId: number }): void {+ const list = this.entriesByTask[payload.taskId]+ if (list) this.entriesByTask[payload.taskId] = list.filter((e) => e.id !== payload.entryId)+ if (this.active?.id === payload.entryId) this.active = null+ },++ appendToTask(entry: TimeEntryItem): void {+ const list = this.entriesByTask[entry.taskId] ?? []+ const idx = list.findIndex((e) => e.id === entry.id)+ if (idx === -1) {+ this.entriesByTask[entry.taskId] = [entry, ...list]+ } else {+ list[idx] = entry+ }+ this.touchTaskCache(entry.taskId)+ },++ replaceInTask(entry: TimeEntryItem): void {+ const list = this.entriesByTask[entry.taskId]+ if (!list) return+ const idx = list.findIndex((e) => e.id === entry.id)+ if (idx !== -1) list[idx] = entry+ },+ },+})