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
feat: sprints
Nikolai Giman673cc868f8af
diff --git a/api/src/core/AppUser.ts b/api/src/core/AppUser.tsindex fb8964c..d952207 100644--- a/api/src/core/AppUser.ts+++ b/api/src/core/AppUser.ts@@ -15,6 +15,7 @@ import { AnalyticsManager } from '../tv-modules/analytics/AnalyticsManager';import { TasksManager } from '../tv-modules/tasks/TasksManager';import { TimeTrackingManager } from '../tv-modules/time-tracking/TimeTrackingManager';import { UiPreferencesManager } from '../tv-modules/ui-preferences/UiPreferencesManager';+import { SprintsManager } from '../tv-modules/sprints/SprintsManager';import type { UserDbRecord, UserJwtPayload } from '../types/auth.types';import { GoalPermissionsFetcher } from './GoalPermissionsFetcher';@@ -43,6 +44,7 @@ export class AppUser {public readonly analyticsManager: AnalyticsManager;public readonly timeTrackingManager: TimeTrackingManager;public readonly uiPreferencesManager: UiPreferencesManager;+ public readonly sprintsManager: SprintsManager;constructor(userData?: UserJwtPayload) {this.userData = userData;@@ -64,6 +66,7 @@ export class AppUser {this.analyticsManager = new AnalyticsManager(this);this.timeTrackingManager = new TimeTrackingManager(this);this.uiPreferencesManager = new UiPreferencesManager(this);+ this.sprintsManager = new SprintsManager(this);}getTokenId(): number | undefined {diff --git a/api/src/core/EventBus.ts b/api/src/core/EventBus.tsindex b3138a5..47aef33 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 { SprintsSchemaTypeForSelect, TasksSchemaTypeForSelect } from 'taskview-db-schemas';import type { TimeEntryWithUser } from '../tv-modules/time-tracking/types';import { $logger } from '../modules/logget';@@ -16,6 +16,21 @@ export interface AppEvents {'time-entry.created': { entry: TimeEntryWithUser; initiatorId: number };'time-entry.updated': { entry: TimeEntryWithUser; changes: Record<string, unknown>; initiatorId: number };'time-entry.deleted': { entryId: number; taskId: number; goalId: number; userId: number; initiatorId: number };+ 'sprint.created': { sprint: SprintsSchemaTypeForSelect; initiatorId: number };+ 'sprint.updated': { sprint: SprintsSchemaTypeForSelect; changes: Record<string, unknown>; initiatorId: number };+ 'sprint.activated': { sprintId: number; goalId: number; initiatorId: number | null };+ 'sprint.reviewStarted': { sprintId: number; goalId: number; initiatorId: number };+ 'sprint.completed': { sprintId: number; goalId: number; initiatorId: number };+ 'sprint.paused': { sprintId: number; goalId: number; initiatorId: number };+ 'sprint.resumed': { sprintId: number; goalId: number; initiatorId: number };+ 'sprint.deleted': { sprintId: number; goalId: number; initiatorId: number };+ 'task.assignedToSprint': {+ taskId: number;+ sprintId: number | null;+ prevSprintId: number | null;+ goalId: number;+ initiatorId: number;+ };}type EventName = keyof AppEvents;diff --git a/api/src/core/FetchTasksQueryBuilder.ts b/api/src/core/FetchTasksQueryBuilder.tsindex e269f6b..81dfad3 100644--- a/api/src/core/FetchTasksQueryBuilder.ts+++ b/api/src/core/FetchTasksQueryBuilder.ts@@ -45,6 +45,11 @@ export class FetchTasksQueryBuilder {args.push(this.data.filters.priority);}+ if (this.data.filters.sprintId !== undefined) {+ query += ` AND t.sprint_id = $${args.length + 1}`;+ args.push(this.data.filters.sprintId);+ }+if (this.limit !== null) {if (this.data.showCompleted === 0) {query += ` AND t.complete = $${args.length + 1}`;diff --git a/api/src/core/all-events.ts b/api/src/core/all-events.tsindex ef54491..74a9241 100644--- a/api/src/core/all-events.ts+++ b/api/src/core/all-events.ts@@ -4,12 +4,14 @@ import { NotificationDispatcher } from '../tv-modules/notifications/Notificationimport { RealtimeDispatcher } from '../tv-modules/realtime/RealtimeDispatcher';import { WebhooksDispatcher } from '../tv-modules/webhooks/WebhooksDispatcher';import { TimeTrackingDispatcher } from '../tv-modules/time-tracking/TimeTrackingDispatcher';+import { SprintsDispatcher } from '../tv-modules/sprints/SprintsDispatcher';const dispatchers: Dispatcher[] = [new NotificationDispatcher(),new RealtimeDispatcher(),new WebhooksDispatcher(),new TimeTrackingDispatcher(),+ new SprintsDispatcher(),];export function registerAllEventHandlers() {diff --git a/api/src/migrations/taskview/migrate.json b/api/src/migrations/taskview/migrate.jsonindex 21f4624..9c7ab26 100644--- a/api/src/migrations/taskview/migrate.json+++ b/api/src/migrations/taskview/migrate.json@@ -572,5 +572,33 @@"description": ["Added tv_auth.ui_preferences table: per-user JSONB storage of UI customization choices (which analytics charts and task detail fields are shown and in what order). One row per user keyed by user_id."]+ },+ "46": {+ "version": "1.53.0",+ "name": "Release 1.53.0",+ "releaseDate": "20260528",+ "scripts": [+ "/1.53.0/0.create-sprints.sql",+ "/1.53.0/1.create-sprint-task-outcomes.sql",+ "/1.53.0/2.create-sprint-user-capacity.sql",+ "/1.53.0/3.create-sprint-retros.sql",+ "/1.53.0/4.alter-tasks-add-sprint.sql",+ "/1.53.0/5.alter-notifications-add-sprint-id.sql",+ "/1.53.0/6.add-sprint-permissions.sql",+ "/1.53.0/7.alter-goals-add-estimate-unit.sql",+ "/1.53.0/8.alter-sprint-task-outcomes-add-estimate.sql",+ "/1.53.0/9.create-sprint-cadence.sql",+ "/1.53.0/all-triggers.sql"+ ],+ "description": [+ "Added tasks.goals.estimate_unit ('hours' | 'points', default 'points') — per-project unit for sprint estimates & capacity display.",+ "Sprints feature. tasks.sprints: sprint container with lifecycle draft/planned/active/review/completed; one active-or-review sprint per project enforced by a partial unique index.",+ "tasks.sprint_task_outcomes: per-task result decided at close (accepted/carried-over/dropped/incomplete). tasks.sprint_user_capacity: per-user capacity. tasks.sprint_retros: went well/bad/action items. Sprint capacity column is `capacity` (story points, unitless).",+ "Extended tasks.tasks with sprint_id (FK SET NULL) and estimate_value (task estimate in story points, unitless), and tasks.notifications with sprint_id. Sprint availability is governed by the sprint_can_view permission (RBAC), not a per-project flag. Sprint burndown reuses the existing trigger-maintained tasks.date_complete column (no new completion column added).",+ "Added permission group 5 'sprints' and permissions sprint_can_view, sprint_can_manage, sprint_can_assign_tasks, sprint_can_view_analytics; backfilled grants for existing projects' editor/executor roles.",+ "all-triggers.sql: re-applies all triggers idempotently (drop+create) and updates tasks.add_roles_and_permissions() so NEW projects grant sprint permissions to editor (all four) and executor (view + assign).",+ "Added tasks.sprint_task_outcomes.estimate_value — story-points snapshot captured at sprint close so a closed sprint's velocity is frozen (unaffected by later estimate edits or moving the task to another sprint).",+ "Added tasks.sprint_cadence — per-project sprint auto-generation config (Linear-style): enabled, length_days, start_date anchor, lookahead, name_template, last_generated_date. A background job keeps current + lookahead future sprints created."+ ]}}\ No newline at end of filediff --git a/api/src/migrations/taskview/sql/1.53.0/0.create-sprints.sql b/api/src/migrations/taskview/sql/1.53.0/0.create-sprints.sqlnew file mode 100644index 0000000..4a90f69--- /dev/null+++ b/api/src/migrations/taskview/sql/1.53.0/0.create-sprints.sql@@ -0,0 +1,26 @@+CREATE TABLE IF NOT EXISTS tasks.sprints (+ id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,+ goal_id INTEGER NOT NULL REFERENCES tasks.goals(id) ON DELETE CASCADE,+ name VARCHAR(255) NOT NULL,+ goal_text VARCHAR(2000),+ goal_achieved BOOLEAN,+ status VARCHAR(20) NOT NULL DEFAULT 'draft',+ start_date DATE NOT NULL,+ end_date DATE NOT NULL,+ capacity NUMERIC(10, 2),+ paused_at TIMESTAMP,+ creator_id INTEGER REFERENCES tv_auth.users(id),+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),+ edited_at TIMESTAMP NOT NULL DEFAULT NOW(),+ review_started_at TIMESTAMP,+ completed_at TIMESTAMP,+ CONSTRAINT sprint_dates_valid CHECK (end_date >= start_date)+);++CREATE INDEX IF NOT EXISTS idx_sprints_goal_status ON tasks.sprints(goal_id, status);++-- At most one active OR in-review sprint per project, enforced at the DB level+-- (no race). 'review' also holds the slot: the previous sprint must be closed+-- before the next can start.+CREATE UNIQUE INDEX IF NOT EXISTS idx_one_active_sprint_per_goal+ ON tasks.sprints(goal_id) WHERE status IN ('active', 'review');diff --git a/api/src/migrations/taskview/sql/1.53.0/1.create-sprint-task-outcomes.sql b/api/src/migrations/taskview/sql/1.53.0/1.create-sprint-task-outcomes.sqlnew file mode 100644index 0000000..2d64683--- /dev/null+++ b/api/src/migrations/taskview/sql/1.53.0/1.create-sprint-task-outcomes.sql@@ -0,0 +1,12 @@+CREATE TABLE IF NOT EXISTS tasks.sprint_task_outcomes (+ sprint_id INTEGER NOT NULL REFERENCES tasks.sprints(id) ON DELETE CASCADE,+ task_id INTEGER NOT NULL REFERENCES tasks.tasks(id) ON DELETE CASCADE,+ outcome VARCHAR(20) NOT NULL,+ -- 'accepted' | 'carried-over' | 'dropped' | 'incomplete'+ carried_over_to INTEGER REFERENCES tasks.sprints(id) ON DELETE SET NULL,+ decided_by INTEGER REFERENCES tv_auth.users(id),+ decided_at TIMESTAMP NOT NULL DEFAULT NOW(),+ PRIMARY KEY (sprint_id, task_id)+);++CREATE INDEX IF NOT EXISTS idx_sprint_outcomes_task ON tasks.sprint_task_outcomes(task_id);diff --git a/api/src/migrations/taskview/sql/1.53.0/2.create-sprint-user-capacity.sql b/api/src/migrations/taskview/sql/1.53.0/2.create-sprint-user-capacity.sqlnew file mode 100644index 0000000..6583a2d--- /dev/null+++ b/api/src/migrations/taskview/sql/1.53.0/2.create-sprint-user-capacity.sql@@ -0,0 +1,6 @@+CREATE TABLE IF NOT EXISTS tasks.sprint_user_capacity (+ sprint_id INTEGER NOT NULL REFERENCES tasks.sprints(id) ON DELETE CASCADE,+ user_id INTEGER NOT NULL REFERENCES tv_auth.users(id) ON DELETE CASCADE,+ hours NUMERIC(10, 2) NOT NULL,+ PRIMARY KEY (sprint_id, user_id)+);diff --git a/api/src/migrations/taskview/sql/1.53.0/3.create-sprint-retros.sql b/api/src/migrations/taskview/sql/1.53.0/3.create-sprint-retros.sqlnew file mode 100644index 0000000..facff01--- /dev/null+++ b/api/src/migrations/taskview/sql/1.53.0/3.create-sprint-retros.sql@@ -0,0 +1,8 @@+CREATE TABLE IF NOT EXISTS tasks.sprint_retros (+ sprint_id INTEGER PRIMARY KEY REFERENCES tasks.sprints(id) ON DELETE CASCADE,+ went_well TEXT,+ went_bad TEXT,+ action_items TEXT,+ edited_at TIMESTAMP NOT NULL DEFAULT NOW(),+ edited_by INTEGER REFERENCES tv_auth.users(id)+);diff --git a/api/src/migrations/taskview/sql/1.53.0/4.alter-tasks-add-sprint.sql b/api/src/migrations/taskview/sql/1.53.0/4.alter-tasks-add-sprint.sqlnew file mode 100644index 0000000..55469ea--- /dev/null+++ b/api/src/migrations/taskview/sql/1.53.0/4.alter-tasks-add-sprint.sql@@ -0,0 +1,6 @@+ALTER TABLE tasks.tasks+ ADD COLUMN IF NOT EXISTS sprint_id INTEGER REFERENCES tasks.sprints(id) ON DELETE SET NULL,+ ADD COLUMN IF NOT EXISTS estimate_value NUMERIC(10, 2);+ -- estimate_value: task estimate in story points (unitless).++CREATE INDEX IF NOT EXISTS idx_tasks_sprint_id ON tasks.tasks(sprint_id) WHERE sprint_id IS NOT NULL;diff --git a/api/src/migrations/taskview/sql/1.53.0/5.alter-notifications-add-sprint-id.sql b/api/src/migrations/taskview/sql/1.53.0/5.alter-notifications-add-sprint-id.sqlnew file mode 100644index 0000000..12c20e7--- /dev/null+++ b/api/src/migrations/taskview/sql/1.53.0/5.alter-notifications-add-sprint-id.sql@@ -0,0 +1,4 @@+ALTER TABLE tasks.notifications+ ADD COLUMN IF NOT EXISTS sprint_id INTEGER REFERENCES tasks.sprints(id) ON DELETE CASCADE;+ -- Lets the client deep-link a notification to "open sprint N" without+ -- stuffing metadata into the body.diff --git a/api/src/migrations/taskview/sql/1.53.0/6.add-sprint-permissions.sql b/api/src/migrations/taskview/sql/1.53.0/6.add-sprint-permissions.sqlnew file mode 100644index 0000000..5f2b974--- /dev/null+++ b/api/src/migrations/taskview/sql/1.53.0/6.add-sprint-permissions.sql@@ -0,0 +1,35 @@+-- Permission group 5 = sprints (shown in the role editor; group 1 'app' is hidden there)+INSERT INTO tv_auth.permissions_group (id, name)+VALUES (5, 'sprints')+ON CONFLICT (id) DO NOTHING;++-- New sprint permissions+INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)+VALUES+ ('sprint_can_view', 'View sprints of the project', 5,+ '{"en": "View sprints. See the project sprints, their dates and contents.", "ru": "Просмотр спринтов. Видеть спринты проекта, их даты и состав."}'::jsonb),+ ('sprint_can_manage', 'Create, edit, activate, close sprints, save retro', 5,+ '{"en": "Manage sprints. Create, edit, activate, run review and close sprints; save retros.", "ru": "Управление спринтами. Создавать, редактировать, активировать, проводить ревью и закрывать спринты; сохранять ретро."}'::jsonb),+ ('sprint_can_assign_tasks', 'Move tasks in and out of sprints', 5,+ '{"en": "Assign tasks to sprints. Move tasks into and out of sprints.", "ru": "Назначение задач в спринты. Перемещать задачи в спринты и из них."}'::jsonb),+ ('sprint_can_view_analytics', 'View sprint burndown and velocity', 5,+ '{"en": "View sprint analytics. See burndown and velocity charts.", "ru": "Аналитика спринтов. Видеть burndown и velocity."}'::jsonb)+ON CONFLICT (name) DO NOTHING;++-- Backfill existing projects: grant sprint permissions to their editor/executor roles.+-- (NEW projects get them via tasks.add_roles_and_permissions() — see all-triggers.sql.)+INSERT INTO collaboration.permissions_to_role (role_id, permission_id)+SELECT r.id, p.id+FROM collaboration.roles r+CROSS JOIN tv_auth.permissions p+WHERE r.name = 'editor'+ AND p.name IN ('sprint_can_view', 'sprint_can_manage', 'sprint_can_assign_tasks', 'sprint_can_view_analytics')+ON CONFLICT DO NOTHING;++INSERT INTO collaboration.permissions_to_role (role_id, permission_id)+SELECT r.id, p.id+FROM collaboration.roles r+CROSS JOIN tv_auth.permissions p+WHERE r.name = 'executor'+ AND p.name IN ('sprint_can_view', 'sprint_can_assign_tasks')+ON CONFLICT DO NOTHING;diff --git a/api/src/migrations/taskview/sql/1.53.0/7.alter-goals-add-estimate-unit.sql b/api/src/migrations/taskview/sql/1.53.0/7.alter-goals-add-estimate-unit.sqlnew file mode 100644index 0000000..3fbd272--- /dev/null+++ b/api/src/migrations/taskview/sql/1.53.0/7.alter-goals-add-estimate-unit.sql@@ -0,0 +1,3 @@+ALTER TABLE tasks.goals+ ADD COLUMN IF NOT EXISTS estimate_unit VARCHAR(10) NOT NULL DEFAULT 'points';+ -- 'hours' | 'points' — unit the project measures sprint estimates & capacity in.diff --git a/api/src/migrations/taskview/sql/1.53.0/8.alter-sprint-task-outcomes-add-estimate.sql b/api/src/migrations/taskview/sql/1.53.0/8.alter-sprint-task-outcomes-add-estimate.sqlnew file mode 100644index 0000000..a276080--- /dev/null+++ b/api/src/migrations/taskview/sql/1.53.0/8.alter-sprint-task-outcomes-add-estimate.sql@@ -0,0 +1,6 @@+ALTER TABLE tasks.sprint_task_outcomes+ ADD COLUMN IF NOT EXISTS estimate_value NUMERIC(10, 2);+ -- Snapshot of tasks.estimate_value taken AT sprint close. Sprint history is+ -- frozen: later edits to the task's estimate, or moving it to another sprint,+ -- must NOT change a closed sprint's velocity. Velocity reads this snapshot,+ -- not the live task estimate.diff --git a/api/src/migrations/taskview/sql/1.53.0/9.create-sprint-cadence.sql b/api/src/migrations/taskview/sql/1.53.0/9.create-sprint-cadence.sqlnew file mode 100644index 0000000..5e0490a--- /dev/null+++ b/api/src/migrations/taskview/sql/1.53.0/9.create-sprint-cadence.sql@@ -0,0 +1,15 @@+CREATE TABLE IF NOT EXISTS tasks.sprint_cadence (+ goal_id INTEGER PRIMARY KEY REFERENCES tasks.goals(id) ON DELETE CASCADE,+ enabled BOOLEAN NOT NULL DEFAULT FALSE,+ length_days INTEGER NOT NULL DEFAULT 14,+ start_date DATE NOT NULL,+ lookahead INTEGER NOT NULL DEFAULT 2,+ name_template VARCHAR(100) NOT NULL DEFAULT 'Sprint {n}',+ last_generated_date DATE,+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),+ edited_at TIMESTAMP NOT NULL DEFAULT NOW()+);+-- Per-project sprint cadence (Linear-style auto-generation). A background job+-- keeps the current + `lookahead` future sprints created, every `length_days`+-- starting from `start_date`. `last_generated_date` = start_date of the last+-- auto-created sprint, so generation is idempotent and only moves forward.diff --git a/api/src/migrations/taskview/sql/1.53.0/all-triggers.sql b/api/src/migrations/taskview/sql/1.53.0/all-triggers.sqlnew file mode 100644index 0000000..1a8973a--- /dev/null+++ b/api/src/migrations/taskview/sql/1.53.0/all-triggers.sql@@ -0,0 +1,641 @@+--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',+ 'sprint_can_view',+ 'sprint_can_manage',+ 'sprint_can_assign_tasks',+ 'sprint_can_view_analytics'+ );++ -- 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',+ 'sprint_can_view',+ 'sprint_can_assign_tasks'+ );++ 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 ccbe4e5..3dcb145 100644--- a/api/src/routes/index.ts+++ b/api/src/routes/index.ts@@ -19,6 +19,7 @@ import ScimRoutes from '../tv-modules/scim/ScimRoutes';import AnalyticsRoutes from '../tv-modules/analytics/AnalyticsRoutes';import TimeTrackingRoutes from '../tv-modules/time-tracking/TimeTrackingRoutes';import UiPreferencesRoutes from '../tv-modules/ui-preferences/UiPreferencesRoutes';+import SprintsRoutes from '../tv-modules/sprints/SprintsRoutes';import type { Routable } from '../types/routable.type';type RoutableConstructor = new (...args: any[]) => Routable;@@ -44,6 +45,7 @@ const routes: Record<string, RoutableConstructor> = {'/module/analytics': AnalyticsRoutes,'/module/time-tracking': TimeTrackingRoutes,'/module/ui-preferences': UiPreferencesRoutes,+ '/module/sprints': SprintsRoutes,'/scim/v2': ScimRoutes,};diff --git a/api/src/tv-modules/goals/GoalsRepository.ts b/api/src/tv-modules/goals/GoalsRepository.tsindex cfabc2e..f2782cf 100644--- a/api/src/tv-modules/goals/GoalsRepository.ts+++ b/api/src/tv-modules/goals/GoalsRepository.ts@@ -156,6 +156,7 @@ export class GoalsRepository {archive: GoalsSchema.archive,backlogVersion: GoalsSchema.backlogVersion,organizationId: GoalsSchema.organizationId,+ estimateUnit: GoalsSchema.estimateUnit,}).from(GoalsSchema).leftJoin(CollaborationUsersToGoalsSchema, eq(GoalsSchema.id, CollaborationUsersToGoalsSchema.goalId))diff --git a/api/src/tv-modules/goals/types.ts b/api/src/tv-modules/goals/types.tsindex 0bb8fe0..0fb88a9 100644--- a/api/src/tv-modules/goals/types.ts+++ b/api/src/tv-modules/goals/types.ts@@ -16,6 +16,7 @@ export const GoalsArkTypeUpdate = type({'name?': 'string | null','description?': 'string | null','color?': 'string | null',+ "estimateUnit?": "'hours' | 'points'",});export type GoalsArgUpdate = typeof GoalsArkTypeUpdate.infer;diff --git a/api/src/tv-modules/kanban/types.ts b/api/src/tv-modules/kanban/types.tsindex 1a2f0bc..45058df 100644--- a/api/src/tv-modules/kanban/types.ts+++ b/api/src/tv-modules/kanban/types.ts@@ -69,9 +69,15 @@ const NumberArrayFromCommaSeparatedString = type('string|undefined').pipe((v) =>return v.split(',').map(Number).filter((n) => !isNaN(n));});+const SprintFilterFromString = type('string|number').pipe((v) => {+ const n = Number(v);+ return isNaN(n) ? undefined : n;+});+export const KanbanArkTypeFilters = type({'listIds?': NumberArrayFromCommaSeparatedString,'assigneeIds?': NumberArrayFromCommaSeparatedString,+ 'sprintId?': SprintFilterFromString,});export type KanbanArgFilters = typeof KanbanArkTypeFilters.infer;diff --git a/api/src/tv-modules/sprints/SprintScheduler.ts b/api/src/tv-modules/sprints/SprintScheduler.tsnew file mode 100644index 0000000..57a2240--- /dev/null+++ b/api/src/tv-modules/sprints/SprintScheduler.ts@@ -0,0 +1,84 @@+import { getJobQueue } from '../../core/JobQueue';+import { $logger } from '../../modules/logget';+import { SprintsRepository } from './SprintsRepository';++export const SPRINT_CADENCE_JOB = 'sprint-cadence-generate';++export class SprintScheduler {+ private readonly repo = new SprintsRepository();++ /**+ * Ensure the current + `lookahead` future sprints exist for a goal whose+ * cadence is enabled. Windows run every `length_days` from `start_date`.+ * Idempotent: skips windows whose start date already has a live (non-completed)+ * sprint, so manual sprints and repeated runs never duplicate. All generated+ * sprints are created as `planned` — activation is always manual.+ * Returns the number of sprints created.+ */+ async generateCadenceForGoal(goalId: number): Promise<number> {+ const cadence = await this.repo.getCadence(goalId);+ if (!cadence || !cadence.enabled) return 0;++ const lengthDays = cadence.lengthDays > 0 ? cadence.lengthDays : 14;+ const lookahead = cadence.lookahead >= 0 ? cadence.lookahead : 0;+ const today = new Date().toISOString().slice(0, 10);++ const offset = this.daysBetween(cadence.startDate, today);+ const currentIdx = offset < 0 ? 0 : Math.floor(offset / lengthDays);+ const lastIdx = currentIdx + lookahead;++ let created = 0;+ let maxStart = cadence.lastGeneratedDate ?? null;++ for (let idx = currentIdx; idx <= lastIdx; idx++) {+ const winStart = this.addDays(cadence.startDate, idx * lengthDays);+ const winEnd = this.addDays(winStart, lengthDays - 1);++ const existing = await this.repo.findByGoalAndStartDate({ goalId, startDate: winStart });+ if (existing) {+ if (!maxStart || winStart > maxStart) maxStart = winStart;+ continue;+ }++ const name = cadence.nameTemplate.includes('{n}')+ ? cadence.nameTemplate.replace('{n}', String(idx + 1))+ : `${cadence.nameTemplate} ${idx + 1}`;++ const sprint = await this.repo.createCadenceSprint({ goalId, name, startDate: winStart, endDate: winEnd });+ if (!sprint) continue;+ created++;+ if (!maxStart || winStart > maxStart) maxStart = winStart;+ }++ if (maxStart) await this.repo.setCadenceLastGenerated({ goalId, lastGeneratedDate: maxStart });+ $logger.info(`[SprintScheduler] cadence goal=${goalId} created=${created} windows=[${currentIdx}..${lastIdx}]`);+ return created;+ }++ async registerCadenceWorker(): Promise<void> {+ const boss = getJobQueue();+ await boss.createQueue(SPRINT_CADENCE_JOB);+ await boss.schedule(SPRINT_CADENCE_JOB, '0 1 * * *');++ await boss.work(SPRINT_CADENCE_JOB, async () => {+ const cadences = await this.repo.getEnabledCadences();+ for (const c of cadences) {+ await this.generateCadenceForGoal(c.goalId).catch((e) =>+ $logger.error(e, `[SprintScheduler] cadence sweep goal=${c.goalId}`)+ );+ }+ });+ }++ private addDays(dateStr: string, days: number): string {+ const d = new Date(`${dateStr}T00:00:00Z`);+ d.setUTCDate(d.getUTCDate() + days);+ return d.toISOString().slice(0, 10);+ }++ private daysBetween(from: string, to: string): number {+ const a = new Date(`${from}T00:00:00Z`).getTime();+ const b = new Date(`${to}T00:00:00Z`).getTime();+ return Math.floor((b - a) / 86_400_000);+ }+}diff --git a/api/src/tv-modules/sprints/SprintsController.ts b/api/src/tv-modules/sprints/SprintsController.tsnew file mode 100644index 0000000..e26ea30--- /dev/null+++ b/api/src/tv-modules/sprints/SprintsController.ts@@ -0,0 +1,152 @@+import { type } from 'arktype';+import type { Request, Response } from 'express';+import type { SprintStatus } from 'taskview-db-schemas';+import { logError } from '../../utils/api';+import {+ SprintArkTypeClose,+ SprintArkTypeCreate,+ SprintArkTypeGoalIdParam,+ SprintArkTypeListQuery,+ SprintArkTypePlanningQuery,+ SprintArkTypeSaveRetro,+ SprintArkTypeSetCadence,+ SprintArkTypeSetTask,+ SprintArkTypeSprintIdParam,+ SprintArkTypeUpdate,+ SprintArkTypeVelocityQuery,+} from './types';+import type { SprintErrorCode, SprintResult } from './types';++const codeToStatus: Record<SprintErrorCode, number> = {+ not_found: 404,+ conflict: 409,+ invalid_state: 400,+ forbidden: 403,+};++const VALID_STATUSES: SprintStatus[] = ['draft', 'planned', 'active', 'review', 'completed'];++export default class SprintsController {+ private sendResult<T>(res: Response, result: SprintResult<T>) {+ if (result.ok) return res.tvJson(result.data);+ return res.status(codeToStatus[result.code]).send(result.message ?? result.code);+ }++ listForGoal = async (req: Request, res: Response) => {+ const data = SprintArkTypeListQuery({ ...req.params, ...req.query });+ if (data instanceof type.errors) return res.status(400).send(data.summary);++ const statuses = data.status+ ? (data.status.split(',').map((s) => s.trim()).filter((s) => VALID_STATUSES.includes(s as SprintStatus)) as SprintStatus[])+ : undefined;++ return res.tvJson(await req.appUser.sprintsManager.listSprints({ goalId: data.goalId, statuses }).catch(logError));+ };++ getOne = async (req: Request, res: Response) => {+ const data = SprintArkTypeSprintIdParam(req.params);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return res.tvJson(await req.appUser.sprintsManager.getSprint(data.sprintId).catch(logError));+ };++ create = async (req: Request, res: Response) => {+ const data = SprintArkTypeCreate(req.body);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.sprintsManager.createSprint(data));+ };++ update = async (req: Request, res: Response) => {+ const data = SprintArkTypeUpdate({ sprintId: Number(req.params.sprintId), ...req.body });+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.sprintsManager.updateSprint(data));+ };++ activate = async (req: Request, res: Response) => {+ const data = SprintArkTypeSprintIdParam(req.params);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.sprintsManager.activateSprint(data.sprintId));+ };++ review = async (req: Request, res: Response) => {+ const data = SprintArkTypeSprintIdParam(req.params);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.sprintsManager.startReview(data.sprintId));+ };++ close = async (req: Request, res: Response) => {+ const data = SprintArkTypeClose({ sprintId: Number(req.params.sprintId), ...req.body });+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.sprintsManager.closeSprint(data));+ };++ pause = async (req: Request, res: Response) => {+ const data = SprintArkTypeSprintIdParam(req.params);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.sprintsManager.pauseSprint(data.sprintId));+ };++ resume = async (req: Request, res: Response) => {+ const data = SprintArkTypeSprintIdParam(req.params);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.sprintsManager.resumeSprint(data.sprintId));+ };++ remove = async (req: Request, res: Response) => {+ const data = SprintArkTypeSprintIdParam(req.params);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.sprintsManager.deleteSprint(data.sprintId));+ };++ saveRetro = async (req: Request, res: Response) => {+ const data = SprintArkTypeSaveRetro({ sprintId: Number(req.params.sprintId), ...req.body });+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.sprintsManager.saveRetro(data));+ };++ setTaskSprint = async (req: Request, res: Response) => {+ const data = SprintArkTypeSetTask({ taskId: Number(req.params.taskId), sprintId: req.body.sprintId });+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.sprintsManager.setTaskSprint(data));+ };++ burndown = async (req: Request, res: Response) => {+ const data = SprintArkTypeSprintIdParam(req.params);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return res.tvJson(await req.appUser.sprintsManager.getBurndown(data.sprintId).catch(logError));+ };++ planning = async (req: Request, res: Response) => {+ const data = SprintArkTypePlanningQuery({ ...req.params, ...req.query });+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return res.tvJson(+ await req.appUser.sprintsManager+ .getPlanningTasks({+ sprintId: data.sprintId,+ scope: data.scope,+ cursor: data.cursor ?? null,+ limit: data.limit ?? 30,+ })+ .catch(logError)+ );+ };++ velocity = async (req: Request, res: Response) => {+ const data = SprintArkTypeVelocityQuery({ ...req.params, ...req.query });+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return res.tvJson(+ await req.appUser.sprintsManager.getVelocity({ goalId: data.goalId, lastN: data.lastN ?? 6 }).catch(logError)+ );+ };++ getCadence = async (req: Request, res: Response) => {+ const data = SprintArkTypeGoalIdParam(req.params);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return res.tvJson(await req.appUser.sprintsManager.getCadence(data.goalId).catch(logError));+ };++ setCadence = async (req: Request, res: Response) => {+ const data = SprintArkTypeSetCadence({ goalId: Number(req.params.goalId), ...req.body });+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.sprintsManager.setCadence(data));+ };+}diff --git a/api/src/tv-modules/sprints/SprintsDispatcher.ts b/api/src/tv-modules/sprints/SprintsDispatcher.tsnew file mode 100644index 0000000..0c8cf3b--- /dev/null+++ b/api/src/tv-modules/sprints/SprintsDispatcher.ts@@ -0,0 +1,71 @@+import { eq } from 'drizzle-orm';+import {+ CollaborationUsersSchema,+ CollaborationUsersToGoalsSchema,+ GoalsSchema,+ UsersSchema,+} from 'taskview-db-schemas';+import { getCentrifugoClient } from '../../core/CentrifugoClient';+import type { Dispatcher } from '../../core/Dispatcher';+import { eventBus } from '../../core/EventBus';+import { Database } from '../../modules/db';+import { $logger } from '../../modules/logget';+import { SprintScheduler } from './SprintScheduler';++const SPRINT_RT_EVENT = 'sprints.changed';++export class SprintsDispatcher implements Dispatcher {+ private readonly scheduler = new SprintScheduler();++ register(): void {+ eventBus.on('sprint.created', (d) => this.notifyGoalMembers(d.sprint.goalId, { sprintId: d.sprint.id }));+ eventBus.on('sprint.updated', (d) => this.notifyGoalMembers(d.sprint.goalId, { sprintId: d.sprint.id }));+ eventBus.on('sprint.activated', (d) => this.notifyGoalMembers(d.goalId, { sprintId: d.sprintId }));+ eventBus.on('sprint.reviewStarted', (d) => this.notifyGoalMembers(d.goalId, { sprintId: d.sprintId }));+ eventBus.on('sprint.completed', (d) => this.notifyGoalMembers(d.goalId, { sprintId: d.sprintId }));+ eventBus.on('sprint.paused', (d) => this.notifyGoalMembers(d.goalId, { sprintId: d.sprintId }));+ eventBus.on('sprint.resumed', (d) => this.notifyGoalMembers(d.goalId, { sprintId: d.sprintId }));+ eventBus.on('sprint.deleted', (d) => this.notifyGoalMembers(d.goalId, { sprintId: d.sprintId }));+ eventBus.on('task.assignedToSprint', (d) =>+ this.notifyGoalMembers(d.goalId, { sprintId: d.sprintId, prevSprintId: d.prevSprintId, taskId: d.taskId })+ );+ }++ async registerWorkers(): Promise<void> {+ await this.scheduler.registerCadenceWorker();+ }++ private async notifyGoalMembers(goalId: number, payload: Record<string, unknown>): Promise<void> {+ try {+ const memberIds = await this.resolveGoalMemberIds(goalId);+ if (memberIds.length === 0) return;+ const centrifugo = getCentrifugoClient();+ await Promise.all(+ memberIds.map((userId) => centrifugo.publishToUser(userId, SPRINT_RT_EVENT, { goalId, ...payload }))+ );+ } catch (err) {+ $logger.error(err, '[SprintsDispatcher] real-time publish failed');+ }+ }++ private async resolveGoalMemberIds(goalId: number): Promise<number[]> {+ const db = Database.getInstance();+ const [ownerRows, collabRows] = await Promise.all([+ db.dbDrizzle.select({ id: GoalsSchema.owner }).from(GoalsSchema).where(eq(GoalsSchema.id, goalId)).limit(1),+ db.dbDrizzle+ .select({ id: UsersSchema.id })+ .from(CollaborationUsersToGoalsSchema)+ .innerJoin(+ CollaborationUsersSchema,+ eq(CollaborationUsersToGoalsSchema.userId, CollaborationUsersSchema.id)+ )+ .innerJoin(UsersSchema, eq(CollaborationUsersSchema.email, UsersSchema.email))+ .where(eq(CollaborationUsersToGoalsSchema.goalId, goalId)),+ ]);++ const ids = new Set<number>();+ if (ownerRows[0]?.id) ids.add(ownerRows[0].id);+ collabRows.forEach((r) => ids.add(r.id));+ return [...ids];+ }+}diff --git a/api/src/tv-modules/sprints/SprintsManager.ts b/api/src/tv-modules/sprints/SprintsManager.tsnew file mode 100644index 0000000..58e14c8--- /dev/null+++ b/api/src/tv-modules/sprints/SprintsManager.ts@@ -0,0 +1,332 @@+import type {+ SprintCadenceSchemaTypeForSelect,+ SprintsSchemaTypeForInsert,+ SprintsSchemaTypeForSelect,+ SprintStatus,+ TasksSchemaTypeForSelect,+} from 'taskview-db-schemas';+import type { AppUser } from '../../core/AppUser';+import { eventBus } from '../../core/EventBus';+import { $logger } from '../../modules/logget';+import { SprintScheduler } from './SprintScheduler';+import { SprintsRepository } from './SprintsRepository';+import type {+ BurndownPoint,+ SprintCloseArgs,+ SprintCreateArgs,+ SprintErrorCode,+ SprintListFilter,+ SprintPlanningManagerArgs,+ SprintPlanningPage,+ SprintResult,+ SprintSaveRetroArgs,+ SprintSetCadenceArgs,+ SprintSetTaskArgs,+ SprintUpdateArgs,+ SprintVelocityArgs,+} from './types';++const ok = <T>(data: T): SprintResult<T> => ({ ok: true, data });+const fail = (code: SprintErrorCode, message?: string): SprintResult<never> => ({ ok: false, code, message });++export class SprintsManager {+ private readonly user: AppUser;+ public readonly repository: SprintsRepository;+ private readonly scheduler: SprintScheduler;++ constructor(user: AppUser) {+ this.user = user;+ this.repository = new SprintsRepository();+ this.scheduler = new SprintScheduler();+ }++ private get initiatorId(): number {+ return this.user.getUserData()?.id as number;+ }++ private today(): string {+ return new Date().toISOString().slice(0, 10);+ }++ async listSprints(filter: SprintListFilter): Promise<SprintsSchemaTypeForSelect[]> {+ return this.repository.listForGoal(filter);+ }++ async getSprint(sprintId: number) {+ const sprint = await this.repository.getById(sprintId);+ if (!sprint) return null;+ const retro = await this.repository.getRetro(sprintId);+ return {+ ...sprint,+ retro: retro+ ? { wentWell: retro.wentWell, wentBad: retro.wentBad, actionItems: retro.actionItems }+ : null,+ };+ }++ async createSprint(args: SprintCreateArgs): Promise<SprintResult<SprintsSchemaTypeForSelect>> {+ if (args.endDate < args.startDate) return fail('invalid_state', 'endDate must be >= startDate');+ const status: SprintStatus = args.startDate > this.today() ? 'planned' : 'draft';+ const sprint = await this.repository.create({ ...args, creatorId: this.initiatorId }, status);+ if (!sprint) return fail('invalid_state', 'could not create sprint');+ eventBus.emit('sprint.created', { sprint, initiatorId: this.initiatorId });+ return ok(sprint);+ }++ async updateSprint(args: SprintUpdateArgs): Promise<SprintResult<SprintsSchemaTypeForSelect>> {+ const sprint = await this.repository.getById(args.sprintId);+ if (!sprint) return fail('not_found');+ if (sprint.status === 'completed') return fail('invalid_state', 'completed sprints are read-only');++ const patch: Partial<SprintsSchemaTypeForInsert> = {};+ if (args.name !== undefined) patch.name = args.name;+ if (args.startDate !== undefined) patch.startDate = args.startDate;+ if (args.endDate !== undefined) patch.endDate = args.endDate;+ if (args.goalText !== undefined) patch.goalText = args.goalText;+ if (args.capacity !== undefined) {+ patch.capacity = args.capacity != null ? String(args.capacity) : null;+ }++ const newStart = args.startDate ?? sprint.startDate;+ const newEnd = args.endDate ?? sprint.endDate;+ if (newEnd < newStart) return fail('invalid_state', 'endDate must be >= startDate');++ const updated = await this.repository.patch({ sprintId: args.sprintId, patch });+ if (!updated) return fail('invalid_state');++ eventBus.emit('sprint.updated', { sprint: updated, changes: patch, initiatorId: this.initiatorId });+ return ok(updated);+ }++ async activateSprint(sprintId: number): Promise<SprintResult<SprintsSchemaTypeForSelect>> {+ const sprint = await this.repository.getById(sprintId);+ if (!sprint) return fail('not_found');+ if (sprint.status !== 'draft' && sprint.status !== 'planned') {+ return fail('invalid_state', 'only draft or planned sprints can be activated');+ }+ const conflict = await this.repository.findActiveOrReview(sprint.goalId, sprint.id);+ if (conflict) return fail('conflict', 'another sprint is already active or in review');++ const updated = await this.repository.patch({ sprintId, patch: { status: 'active' } });+ if (!updated) return fail('invalid_state');+ eventBus.emit('sprint.activated', { sprintId, goalId: sprint.goalId, initiatorId: this.initiatorId });+ return ok(updated);+ }++ async startReview(sprintId: number): Promise<SprintResult<SprintsSchemaTypeForSelect>> {+ const sprint = await this.repository.getById(sprintId);+ if (!sprint) return fail('not_found');+ if (sprint.status !== 'active') return fail('invalid_state', 'only an active sprint can enter review');++ const updated = await this.repository.patch({+ sprintId,+ patch: { status: 'review', reviewStartedAt: new Date() },+ });+ if (!updated) return fail('invalid_state');+ eventBus.emit('sprint.reviewStarted', { sprintId, goalId: sprint.goalId, initiatorId: this.initiatorId });+ return ok(updated);+ }++ async closeSprint(args: SprintCloseArgs): Promise<SprintResult<SprintsSchemaTypeForSelect>> {+ const sprint = await this.repository.getById(args.sprintId);+ if (!sprint) return fail('not_found');+ if (sprint.status !== 'review') return fail('invalid_state', 'sprint must be in review before closing');++ for (const o of args.outcomes) {+ if (o.outcome === 'carried-over' && o.carriedOverTo != null) {+ if (o.carriedOverTo === sprint.id) return fail('invalid_state', 'cannot carry over to the same sprint');+ const target = await this.repository.getById(o.carriedOverTo);+ if (!target || target.goalId !== sprint.goalId) {+ return fail('invalid_state', 'carry-over target sprint not found in this project');+ }+ }+ }++ const closed = await this.repository.applyClose({ ...args, initiatorId: this.initiatorId });+ if (!closed) return fail('invalid_state');+ eventBus.emit('sprint.completed', { sprintId: args.sprintId, goalId: sprint.goalId, initiatorId: this.initiatorId });+ return ok(closed);+ }++ async pauseSprint(sprintId: number): Promise<SprintResult<SprintsSchemaTypeForSelect>> {+ const sprint = await this.repository.getById(sprintId);+ if (!sprint) return fail('not_found');+ if (sprint.status !== 'active') return fail('invalid_state', 'only an active sprint can be paused');+ if (sprint.pausedAt) return fail('invalid_state', 'sprint is already paused');+ const updated = await this.repository.patch({ sprintId, patch: { pausedAt: new Date() } });+ if (!updated) return fail('invalid_state');+ eventBus.emit('sprint.paused', { sprintId, goalId: sprint.goalId, initiatorId: this.initiatorId });+ return ok(updated);+ }++ async resumeSprint(sprintId: number): Promise<SprintResult<SprintsSchemaTypeForSelect>> {+ const sprint = await this.repository.getById(sprintId);+ if (!sprint) return fail('not_found');+ if (sprint.status !== 'active' || !sprint.pausedAt) return fail('invalid_state', 'sprint is not paused');+ const updated = await this.repository.patch({ sprintId, patch: { pausedAt: null } });+ if (!updated) return fail('invalid_state');+ eventBus.emit('sprint.resumed', { sprintId, goalId: sprint.goalId, initiatorId: this.initiatorId });+ return ok(updated);+ }++ async deleteSprint(sprintId: number): Promise<SprintResult<true>> {+ const sprint = await this.repository.getById(sprintId);+ if (!sprint) return fail('not_found');+ if (sprint.status !== 'draft' && sprint.status !== 'planned') {+ return fail('conflict', 'only draft or planned sprints can be deleted; close active sprints first');+ }+ const deleted = await this.repository.delete(sprintId);+ if (!deleted) return fail('invalid_state');+ eventBus.emit('sprint.deleted', { sprintId, goalId: sprint.goalId, initiatorId: this.initiatorId });+ return ok(true);+ }++ async saveRetro(args: SprintSaveRetroArgs): Promise<SprintResult<SprintSaveRetroArgs>> {+ const sprint = await this.repository.getById(args.sprintId);+ if (!sprint) return fail('not_found');+ const saved = await this.repository.saveRetro({ ...args, editedBy: this.initiatorId });+ if (!saved) return fail('invalid_state');+ return ok(args);+ }++ async setTaskSprint(args: SprintSetTaskArgs): Promise<SprintResult<{ taskId: number; sprintId: number | null }>> {+ const taskMeta = await this.repository.getTaskMeta(args.taskId);+ if (!taskMeta) return fail('not_found', 'task not found');++ if (args.sprintId !== null) {+ const sprint = await this.repository.getById(args.sprintId);+ if (!sprint) return fail('not_found', 'sprint not found');+ if (sprint.goalId !== taskMeta.goalId) {+ return fail('forbidden', 'task and sprint belong to different projects');+ }+ if (sprint.status === 'completed') {+ return fail('invalid_state', 'cannot move tasks into a completed sprint');+ }+ }++ const prevSprintId = taskMeta.sprintId;+ const done = await this.repository.setTaskSprint(args);+ if (!done) return fail('invalid_state');+ eventBus.emit('task.assignedToSprint', {+ taskId: args.taskId,+ sprintId: args.sprintId,+ prevSprintId,+ goalId: taskMeta.goalId,+ initiatorId: this.initiatorId,+ });+ return ok({ taskId: args.taskId, sprintId: args.sprintId });+ }++ async getBurndown(sprintId: number): Promise<{ total: number; points: BurndownPoint[] } | null> {+ const sprint = await this.repository.getById(sprintId);+ if (!sprint) return null;+ const tasks = await this.repository.getSprintTaskEstimates(sprintId);+ const total = tasks.reduce((sum, t) => sum + (t.estimateValue ? Number(t.estimateValue) : 0), 0);++ const days = this.enumerateDays(sprint.startDate, sprint.endDate);+ const n = days.length;+ const points: BurndownPoint[] = days.map((date, i) => {+ const dayEnd = new Date(`${date}T23:59:59.999Z`);+ let remaining = 0;+ for (const t of tasks) {+ const est = t.estimateValue ? Number(t.estimateValue) : 0;+ const isRemaining = t.complete !== true || (t.dateComplete != null && t.dateComplete > dayEnd);+ if (isRemaining) remaining += est;+ }+ const ideal = n > 1 ? total * (1 - i / (n - 1)) : 0;+ return {+ date,+ remainingHours: Math.round(remaining * 100) / 100,+ idealHours: Math.max(0, Math.round(ideal * 100) / 100),+ };+ });+ return { total: Math.round(total * 100) / 100, points };+ }++ async getVelocity(args: SprintVelocityArgs) {+ return this.repository.velocity({ goalId: args.goalId, lastN: args.lastN || 6 });+ }++ async getCadence(goalId: number): Promise<SprintCadenceSchemaTypeForSelect | null> {+ return this.repository.getCadence(goalId);+ }++ async setCadence(args: SprintSetCadenceArgs): Promise<SprintResult<SprintCadenceSchemaTypeForSelect>> {+ const existing = await this.repository.getCadence(args.goalId);++ const lengthDays = args.lengthDays ?? existing?.lengthDays ?? 14;+ const lookahead = args.lookahead ?? existing?.lookahead ?? 2;+ if (lengthDays < 1 || lengthDays > 90) return fail('invalid_state', 'lengthDays must be 1..90');+ if (lookahead < 0 || lookahead > 12) return fail('invalid_state', 'lookahead must be 0..12');++ const startDate = args.startDate ?? existing?.startDate ?? this.today();+ if (!/^\d{4}-\d{2}-\d{2}$/.test(startDate)) return fail('invalid_state', 'startDate must be YYYY-MM-DD');++ const nameTemplate = args.nameTemplate?.trim() || existing?.nameTemplate || 'Sprint {n}';++ const saved = await this.repository.upsertCadence({+ goalId: args.goalId,+ enabled: args.enabled,+ lengthDays,+ startDate,+ lookahead,+ nameTemplate,+ });+ if (!saved) return fail('invalid_state', 'could not save cadence');++ if (saved.enabled) {+ await this.scheduler+ .generateCadenceForGoal(args.goalId)+ .catch((e) => $logger.error(e, '[Sprints] cadence generate'));+ }+ return ok(saved);+ }++ async getPlanningTasks(args: SprintPlanningManagerArgs): Promise<SprintPlanningPage | null> {+ const sprint = await this.repository.getById(args.sprintId);+ if (!sprint) return null;++ if (args.scope === 'sprint') {+ const rows = await this.repository.getSprintTasksForPlanning({+ sprintId: args.sprintId,+ cursor: args.cursor,+ limit: args.limit,+ });+ const { tasks, nextCursor } = this.paginate(rows, args.limit);+ const totalPoints = await this.repository.sumEstimateForSprint(args.sprintId);+ return { tasks, nextCursor, totalPoints };+ }++ const rows = await this.repository.getBacklogTasksForPlanning({+ goalId: sprint.goalId,+ sprintId: args.sprintId,+ cursor: args.cursor,+ limit: args.limit,+ });+ return this.paginate(rows, args.limit);+ }++ private paginate(+ rows: TasksSchemaTypeForSelect[],+ limit: number+ ): { tasks: TasksSchemaTypeForSelect[]; nextCursor: number | null } {+ const hasMore = rows.length > limit;+ const tasks = hasMore ? rows.slice(0, limit) : rows;+ const nextCursor = hasMore ? tasks[tasks.length - 1].id : null;+ return { tasks, nextCursor };+ }++ private enumerateDays(start: string, end: string): string[] {+ const days: string[] = [];+ const cur = new Date(`${start}T00:00:00Z`);+ const last = new Date(`${end}T00:00:00Z`);+ // hard cap to avoid pathological ranges+ let guard = 0;+ while (cur <= last && guard < 400) {+ days.push(cur.toISOString().slice(0, 10));+ cur.setUTCDate(cur.getUTCDate() + 1);+ guard++;+ }+ return days;+ }+}diff --git a/api/src/tv-modules/sprints/SprintsRepository.ts b/api/src/tv-modules/sprints/SprintsRepository.tsnew file mode 100644index 0000000..89a12a7--- /dev/null+++ b/api/src/tv-modules/sprints/SprintsRepository.ts@@ -0,0 +1,473 @@+import { and, asc, desc, eq, gt, inArray, isNull, ne, or, sql } from 'drizzle-orm';+import {+ SprintCadenceSchema,+ SprintsSchema,+ SprintTaskOutcomesSchema,+ SprintUserCapacitySchema,+ SprintRetrosSchema,+ TasksSchema,+ type SprintCadenceSchemaTypeForSelect,+ type SprintStatus,+ type SprintsSchemaTypeForInsert,+ type SprintsSchemaTypeForSelect,+ type TasksSchemaTypeForSelect,+} from 'taskview-db-schemas';+import { Database } from '../../modules/db';+import { callWithCatch } from '../../utils/helpers';+import type {+ SprintCadenceFindByStartArgs,+ SprintCadenceSprintCreateArgs,+ SprintCadenceTouchArgs,+ SprintCadenceUpsertRepoArgs,+ SprintCloseManagerArgs,+ SprintCreateRepoArgs,+ SprintListFilter,+ SprintPlanningPageArgs,+ SprintSaveRetroManagerArgs,+ VelocityPoint,+} from './types';++export class SprintsRepository {+ private readonly db: Database;++ constructor() {+ this.db = Database.getInstance();+ }++ async create(args: SprintCreateRepoArgs, status: SprintStatus): Promise<SprintsSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .insert(SprintsSchema)+ .values({+ goalId: args.goalId,+ name: args.name,+ startDate: args.startDate,+ endDate: args.endDate,+ goalText: args.goalText ?? null,+ capacity: args.capacity != null ? String(args.capacity) : null,+ status,+ creatorId: args.creatorId,+ })+ .returning()+ );+ return result?.[0] ?? null;+ }++ async getById(sprintId: number): Promise<SprintsSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.select().from(SprintsSchema).where(eq(SprintsSchema.id, sprintId)).limit(1)+ );+ return result?.[0] ?? null;+ }++ /** Cadence: per-project auto-generation config (Linear-style). */+ async getCadence(goalId: number): Promise<SprintCadenceSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.select().from(SprintCadenceSchema).where(eq(SprintCadenceSchema.goalId, goalId)).limit(1)+ );+ return result?.[0] ?? null;+ }++ async upsertCadence(args: SprintCadenceUpsertRepoArgs): Promise<SprintCadenceSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .insert(SprintCadenceSchema)+ .values({+ goalId: args.goalId,+ enabled: args.enabled,+ lengthDays: args.lengthDays,+ startDate: args.startDate,+ lookahead: args.lookahead,+ nameTemplate: args.nameTemplate,+ })+ .onConflictDoUpdate({+ target: SprintCadenceSchema.goalId,+ set: {+ enabled: args.enabled,+ lengthDays: args.lengthDays,+ startDate: args.startDate,+ lookahead: args.lookahead,+ nameTemplate: args.nameTemplate,+ editedAt: new Date(),+ },+ })+ .returning()+ );+ return result?.[0] ?? null;+ }++ async getEnabledCadences(): Promise<SprintCadenceSchemaTypeForSelect[]> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.select().from(SprintCadenceSchema).where(eq(SprintCadenceSchema.enabled, true))+ );+ return result ?? [];+ }++ async findByGoalAndStartDate(args: SprintCadenceFindByStartArgs): Promise<SprintsSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(SprintsSchema)+ .where(+ and(+ eq(SprintsSchema.goalId, args.goalId),+ eq(SprintsSchema.startDate, args.startDate),+ ne(SprintsSchema.status, 'completed')+ )+ )+ .limit(1)+ );+ return result?.[0] ?? null;+ }++ async setCadenceLastGenerated(args: SprintCadenceTouchArgs): Promise<void> {+ await callWithCatch(() =>+ this.db.dbDrizzle+ .update(SprintCadenceSchema)+ .set({ lastGeneratedDate: args.lastGeneratedDate, editedAt: new Date() })+ .where(eq(SprintCadenceSchema.goalId, args.goalId))+ );+ }++ /** Create an auto-generated (cadence) sprint — no creator, always starts planned. */+ async createCadenceSprint(args: SprintCadenceSprintCreateArgs): Promise<SprintsSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .insert(SprintsSchema)+ .values({+ goalId: args.goalId,+ name: args.name,+ startDate: args.startDate,+ endDate: args.endDate,+ status: 'planned',+ creatorId: null,+ })+ .returning()+ );+ return result?.[0] ?? null;+ }++ async listForGoal(filter: SprintListFilter): Promise<SprintsSchemaTypeForSelect[]> {+ const conditions = [eq(SprintsSchema.goalId, filter.goalId)];+ if (filter.statuses && filter.statuses.length > 0) {+ conditions.push(inArray(SprintsSchema.status, filter.statuses));+ }+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(SprintsSchema)+ .where(and(...conditions))+ .orderBy(desc(SprintsSchema.startDate))+ );+ return result ?? [];+ }++ /** The single active OR in-review sprint of a goal, if any. */+ async findActiveOrReview(goalId: number, excludeSprintId?: number): Promise<SprintsSchemaTypeForSelect | null> {+ const conditions = [+ eq(SprintsSchema.goalId, goalId),+ inArray(SprintsSchema.status, ['active', 'review'] as SprintStatus[]),+ ];+ if (excludeSprintId) {+ conditions.push(ne(SprintsSchema.id, excludeSprintId));+ }+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(SprintsSchema)+ .where(and(...conditions))+ .limit(1)+ );+ return result?.[0] ?? null;+ }++ async patch(args: {+ sprintId: number;+ patch: Partial<SprintsSchemaTypeForInsert>;+ }): Promise<SprintsSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .update(SprintsSchema)+ .set({ ...args.patch, editedAt: new Date() })+ .where(eq(SprintsSchema.id, args.sprintId))+ .returning()+ );+ return result?.[0] ?? null;+ }++ async delete(sprintId: number): Promise<boolean> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.delete(SprintsSchema).where(eq(SprintsSchema.id, sprintId)).returning()+ );+ return !!result?.length;+ }++ async getTaskMeta(taskId: number): Promise<{ goalId: number; sprintId: number | null } | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({ goalId: TasksSchema.goalId, sprintId: TasksSchema.sprintId })+ .from(TasksSchema)+ .where(eq(TasksSchema.id, taskId))+ .limit(1)+ );+ return result?.[0] ?? null;+ }++ async setTaskSprint(args: { taskId: number; sprintId: number | null }): Promise<boolean> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .update(TasksSchema)+ .set({ sprintId: args.sprintId })+ .where(eq(TasksSchema.id, args.taskId))+ .returning()+ );+ return !!result?.length;+ }++ /** Estimate rows of all tasks currently in the sprint — input for burndown. */+ async getSprintTaskEstimates(+ sprintId: number+ ): Promise<{ estimateValue: string | null; complete: boolean | null; dateComplete: Date | null }[]> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({+ estimateValue: TasksSchema.estimateValue,+ complete: TasksSchema.complete,+ // trigger-maintained completion moment (tasks.update_date_complete)+ dateComplete: TasksSchema.dateComplete,+ })+ .from(TasksSchema)+ .where(eq(TasksSchema.sprintId, sprintId))+ );+ return result ?? [];+ }++ async getOutcomes(sprintId: number) {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(SprintTaskOutcomesSchema)+ .where(eq(SprintTaskOutcomesSchema.sprintId, sprintId))+ );+ return result ?? [];+ }++ async getUserCapacities(sprintId: number) {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(SprintUserCapacitySchema)+ .where(eq(SprintUserCapacitySchema.sprintId, sprintId))+ );+ return result ?? [];+ }++ async getRetro(sprintId: number) {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(SprintRetrosSchema)+ .where(eq(SprintRetrosSchema.sprintId, sprintId))+ .limit(1)+ );+ return result?.[0] ?? null;+ }++ async saveRetro(args: SprintSaveRetroManagerArgs) {+ const set = {+ wentWell: args.wentWell ?? null,+ wentBad: args.wentBad ?? null,+ actionItems: args.actionItems ?? null,+ editedBy: args.editedBy,+ editedAt: new Date(),+ };+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .insert(SprintRetrosSchema)+ .values({ sprintId: args.sprintId, ...set })+ .onConflictDoUpdate({ target: SprintRetrosSchema.sprintId, set })+ .returning()+ );+ return result?.[0] ?? null;+ }++ /**+ * Close transaction: set sprint completed, record per-task outcomes+ * (untouched tasks -> 'incomplete'), apply task sprint moves.+ */+ async applyClose(args: SprintCloseManagerArgs): Promise<SprintsSchemaTypeForSelect | null> {+ return this.db.dbDrizzle.transaction(async (tx) => {+ const updated = await tx+ .update(SprintsSchema)+ .set({+ status: 'completed',+ completedAt: new Date(),+ goalAchieved: args.goalAchieved,+ editedAt: new Date(),+ })+ .where(eq(SprintsSchema.id, args.sprintId))+ .returning();++ const tasks = await tx+ .select({ id: TasksSchema.id, complete: TasksSchema.complete, estimateValue: TasksSchema.estimateValue })+ .from(TasksSchema)+ .where(eq(TasksSchema.sprintId, args.sprintId));++ const explicit = new Map(args.outcomes.map((o) => [o.taskId, o]));++ // Resolve a final outcome per task, ENFORCING the invariant:+ // a completed task is always 'accepted' (and stays in the sprint);+ // an unfinished task can only be 'carried-over' or 'dropped' (anything+ // else falls back to 'incomplete'). This keeps velocity consistent+ // regardless of what the client sent — you can't carry over / drop+ // already-done work, nor accept unfinished work.+ const resolved = tasks.map((t) => {+ // Snapshot the task's estimate at close — frozen, independent of later edits.+ const estimateValue = t.estimateValue;+ if (t.complete) {+ return { taskId: t.id, outcome: 'accepted' as const, carriedOverTo: null as number | null, estimateValue };+ }+ const decided = explicit.get(t.id);+ if (decided?.outcome === 'carried-over') {+ return { taskId: t.id, outcome: 'carried-over' as const, carriedOverTo: decided.carriedOverTo ?? null, estimateValue };+ }+ if (decided?.outcome === 'dropped') {+ return { taskId: t.id, outcome: 'dropped' as const, carriedOverTo: null as number | null, estimateValue };+ }+ return { taskId: t.id, outcome: 'incomplete' as const, carriedOverTo: null as number | null, estimateValue };+ });++ if (resolved.length > 0) {+ await tx+ .insert(SprintTaskOutcomesSchema)+ .values(+ resolved.map((r) => ({+ sprintId: args.sprintId,+ taskId: r.taskId,+ outcome: r.outcome,+ carriedOverTo: r.carriedOverTo,+ decidedBy: args.initiatorId,+ estimateValue: r.estimateValue,+ }))+ )+ .onConflictDoNothing();+ }++ // Move only unfinished tasks out of the sprint; completed ('accepted')+ // and untouched ('incomplete') tasks stay in the closed sprint.+ for (const r of resolved) {+ if (r.outcome === 'carried-over') {+ await tx+ .update(TasksSchema)+ .set({ sprintId: r.carriedOverTo })+ .where(eq(TasksSchema.id, r.taskId));+ } else if (r.outcome === 'dropped') {+ await tx.update(TasksSchema).set({ sprintId: null }).where(eq(TasksSchema.id, r.taskId));+ }+ }++ return updated[0] ?? null;+ });+ }++ async velocity(args: { goalId: number; lastN: number }): Promise<VelocityPoint[]> {+ const sprints = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({ id: SprintsSchema.id, name: SprintsSchema.name })+ .from(SprintsSchema)+ .where(and(eq(SprintsSchema.goalId, args.goalId), eq(SprintsSchema.status, 'completed' as SprintStatus)))+ .orderBy(desc(SprintsSchema.completedAt))+ .limit(args.lastN)+ );+ if (!sprints || sprints.length === 0) return [];++ const points: VelocityPoint[] = [];+ for (const s of sprints) {+ const rows = await callWithCatch(() =>+ this.db.dbDrizzle+ // Read the FROZEN snapshot, not the live task estimate.+ .select({ outcome: SprintTaskOutcomesSchema.outcome, estimate: SprintTaskOutcomesSchema.estimateValue })+ .from(SprintTaskOutcomesSchema)+ .where(eq(SprintTaskOutcomesSchema.sprintId, s.id))+ );+ let accepted = 0;+ let planned = 0;+ (rows ?? []).forEach((r) => {+ const est = r.estimate ? Number(r.estimate) : 0;+ planned += est;+ if (r.outcome === 'accepted') accepted += est;+ });+ points.push({ sprintId: s.id, name: s.name, acceptedHours: accepted, plannedHours: planned });+ }+ return points.reverse();+ }++ /**+ * Backlog tasks for sprint planning: top-level, incomplete, not yet in any sprint.+ * Cursor-paginated by ascending task id; returns up to `limit + 1` rows so the caller+ * can detect a next page.+ */+ async getBacklogTasksForPlanning(args: SprintPlanningPageArgs & { goalId: number }): Promise<TasksSchemaTypeForSelect[]> {+ const conditions = [+ eq(TasksSchema.goalId, args.goalId),+ isNull(TasksSchema.sprintId),+ or(eq(TasksSchema.complete, false), isNull(TasksSchema.complete)),+ isNull(TasksSchema.parentId),+ ];+ if (args.cursor != null) {+ conditions.push(gt(TasksSchema.id, args.cursor));+ }+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(TasksSchema)+ .where(and(...conditions))+ .orderBy(asc(TasksSchema.id))+ .limit(args.limit + 1)+ );+ return result ?? [];+ }++ /**+ * Tasks currently in the sprint for planning: top-level tasks of the sprint+ * (completed included — they belong to the sprint). Cursor-paginated by ascending id.+ */+ async getSprintTasksForPlanning(args: SprintPlanningPageArgs): Promise<TasksSchemaTypeForSelect[]> {+ const conditions = [eq(TasksSchema.sprintId, args.sprintId), isNull(TasksSchema.parentId)];+ if (args.cursor != null) {+ conditions.push(gt(TasksSchema.id, args.cursor));+ }+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(TasksSchema)+ .where(and(...conditions))+ .orderBy(asc(TasksSchema.id))+ .limit(args.limit + 1)+ );+ return result ?? [];+ }++ /** SUM(estimate_value) over ALL top-level tasks in the sprint — for the capacity counter. */+ async sumEstimateForSprint(sprintId: number): Promise<number> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({ total: sql<string | null>`COALESCE(SUM(${TasksSchema.estimateValue}), 0)` })+ .from(TasksSchema)+ .where(and(eq(TasksSchema.sprintId, sprintId), isNull(TasksSchema.parentId)))+ );+ return result?.[0]?.total ? Number(result[0].total) : 0;+ }++ /** Active sprint id of a goal — for the kanban `sprint=current` filter. */+ async getActiveSprintId(goalId: number): Promise<number | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({ id: SprintsSchema.id })+ .from(SprintsSchema)+ .where(and(eq(SprintsSchema.goalId, goalId), eq(SprintsSchema.status, 'active' as SprintStatus)))+ .limit(1)+ );+ return result?.[0]?.id ?? null;+ }+}diff --git a/api/src/tv-modules/sprints/SprintsRoutes.ts b/api/src/tv-modules/sprints/SprintsRoutes.tsnew file mode 100644index 0000000..dd0e92d--- /dev/null+++ b/api/src/tv-modules/sprints/SprintsRoutes.ts@@ -0,0 +1,56 @@+import { Router } from 'express';+import type { Routable } from '../../types/routable.type';+import { IsLoggedIn } from '../auth/middlewares/is-logged-in';+import SprintsController from './SprintsController';+import { canAssignSprintTasks } from './middlewares/can-assign-sprint-tasks';+import { canManageSprints } from './middlewares/can-manage-sprints';+import { canViewSprintAnalytics } from './middlewares/can-view-sprint-analytics';+import { canViewSprints } from './middlewares/can-view-sprints';++export default class SprintsRoutes implements Routable {+ private readonly router: ReturnType<typeof Router>;+ private readonly controller: SprintsController;++ constructor() {+ this.router = Router();+ this.controller = new SprintsController();+ this.initRoutes();+ }++ getRouter() {+ return this.router;+ }++ initRoutes() {+ // Create+ this.router.post('', [IsLoggedIn, canManageSprints], this.controller.create);++ // Analytics+ this.router.get('/sprint/:sprintId/burndown', [IsLoggedIn, canViewSprintAnalytics], this.controller.burndown);+ this.router.get('/goal/:goalId/velocity', [IsLoggedIn, canViewSprintAnalytics], this.controller.velocity);++ // Cadence: per-project auto-generation config (Linear-style)+ this.router.get('/goal/:goalId/cadence', [IsLoggedIn, canViewSprints], this.controller.getCadence);+ this.router.put('/goal/:goalId/cadence', [IsLoggedIn, canManageSprints], this.controller.setCadence);++ // Cursor-paginated planning task lists (?scope=backlog|sprint&cursor=&limit=)+ this.router.get('/sprint/:sprintId/planning', [IsLoggedIn, canViewSprints], this.controller.planning);++ // Single sprint detail + lifecycle+ this.router.get('/sprint/:sprintId', [IsLoggedIn, canViewSprints], this.controller.getOne);+ this.router.patch('/sprint/:sprintId', [IsLoggedIn, canManageSprints], this.controller.update);+ this.router.post('/sprint/:sprintId/activate', [IsLoggedIn, canManageSprints], this.controller.activate);+ this.router.post('/sprint/:sprintId/review', [IsLoggedIn, canManageSprints], this.controller.review);+ this.router.post('/sprint/:sprintId/close', [IsLoggedIn, canManageSprints], this.controller.close);+ this.router.post('/sprint/:sprintId/pause', [IsLoggedIn, canManageSprints], this.controller.pause);+ this.router.post('/sprint/:sprintId/resume', [IsLoggedIn, canManageSprints], this.controller.resume);+ this.router.delete('/sprint/:sprintId', [IsLoggedIn, canManageSprints], this.controller.remove);+ this.router.put('/sprint/:sprintId/retro', [IsLoggedIn, canManageSprints], this.controller.saveRetro);++ // Assign a task to / out of a sprint (business boundary lives here, not in tasks)+ this.router.patch('/task/:taskId/sprint', [IsLoggedIn, canAssignSprintTasks], this.controller.setTaskSprint);++ // List sprints of a project (supports ?status=active,planned)+ this.router.get('/:goalId', [IsLoggedIn, canViewSprints], this.controller.listForGoal);+ }+}diff --git a/api/src/tv-modules/sprints/middlewares/can-assign-sprint-tasks.ts b/api/src/tv-modules/sprints/middlewares/can-assign-sprint-tasks.tsnew file mode 100644index 0000000..ba8bb47--- /dev/null+++ b/api/src/tv-modules/sprints/middlewares/can-assign-sprint-tasks.ts@@ -0,0 +1,22 @@+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 canAssignSprintTasks = async (req: Request, res: Response, next: NextFunction) => {+ const taskId = req.params.taskId ?? req.body?.taskId;+ if (!taskId) return res.status(400).end();++ const permissions = await req.appUser.permissionsFetcher+ .getPermissionsForType(Number(taskId), GoalPermissionsFetcher.PERMISSION_TYPE_FOR_TASK)+ .catch(logError);++ if (!permissions) {+ $logger.error('Can not get permissions for canAssignSprintTasks middleware');+ return res.status(500).end();+ }++ if (permissions.hasPermissions(GoalPermissions.SPRINT_CAN_ASSIGN_TASKS)) return next();+ return res.status(403).end();+};diff --git a/api/src/tv-modules/sprints/middlewares/can-manage-sprints.ts b/api/src/tv-modules/sprints/middlewares/can-manage-sprints.tsnew file mode 100644index 0000000..b9915e9--- /dev/null+++ b/api/src/tv-modules/sprints/middlewares/can-manage-sprints.ts@@ -0,0 +1,23 @@+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';+import { resolveGoalId } from './resolve-goal-id';++export const canManageSprints = async (req: Request, res: Response, next: NextFunction) => {+ const goalId = await resolveGoalId(req);+ if (!goalId) return res.status(400).end();++ const permissions = await req.appUser.permissionsFetcher+ .getPermissionsForType(goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)+ .catch(logError);++ if (!permissions) {+ $logger.error('Can not get permissions for canManageSprints middleware');+ return res.status(500).end();+ }++ if (permissions.hasPermissions(GoalPermissions.SPRINT_CAN_MANAGE)) return next();+ return res.status(403).end();+};diff --git a/api/src/tv-modules/sprints/middlewares/can-view-sprint-analytics.ts b/api/src/tv-modules/sprints/middlewares/can-view-sprint-analytics.tsnew file mode 100644index 0000000..55eeae5--- /dev/null+++ b/api/src/tv-modules/sprints/middlewares/can-view-sprint-analytics.ts@@ -0,0 +1,23 @@+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';+import { resolveGoalId } from './resolve-goal-id';++export const canViewSprintAnalytics = async (req: Request, res: Response, next: NextFunction) => {+ const goalId = await resolveGoalId(req);+ if (!goalId) return res.status(400).end();++ const permissions = await req.appUser.permissionsFetcher+ .getPermissionsForType(goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)+ .catch(logError);++ if (!permissions) {+ $logger.error('Can not get permissions for canViewSprintAnalytics middleware');+ return res.status(500).end();+ }++ if (permissions.hasPermissions(GoalPermissions.SPRINT_CAN_VIEW_ANALYTICS)) return next();+ return res.status(403).end();+};diff --git a/api/src/tv-modules/sprints/middlewares/can-view-sprints.ts b/api/src/tv-modules/sprints/middlewares/can-view-sprints.tsnew file mode 100644index 0000000..6e3b884--- /dev/null+++ b/api/src/tv-modules/sprints/middlewares/can-view-sprints.ts@@ -0,0 +1,23 @@+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';+import { resolveGoalId } from './resolve-goal-id';++export const canViewSprints = async (req: Request, res: Response, next: NextFunction) => {+ const goalId = await resolveGoalId(req);+ if (!goalId) return res.status(400).end();++ const permissions = await req.appUser.permissionsFetcher+ .getPermissionsForType(goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)+ .catch(logError);++ if (!permissions) {+ $logger.error('Can not get permissions for canViewSprints middleware');+ return res.status(500).end();+ }++ if (permissions.hasPermissions(GoalPermissions.SPRINT_CAN_VIEW)) return next();+ return res.status(403).end();+};diff --git a/api/src/tv-modules/sprints/middlewares/resolve-goal-id.ts b/api/src/tv-modules/sprints/middlewares/resolve-goal-id.tsnew file mode 100644index 0000000..40e446f--- /dev/null+++ b/api/src/tv-modules/sprints/middlewares/resolve-goal-id.ts@@ -0,0 +1,18 @@+import type { Request } from 'express';+import { SprintsRepository } from '../SprintsRepository';++/**+ * Resolves the goalId a sprint request operates on, from (in order):+ * a goalId param/body, or a sprintId param/body (looked up to its goal).+ */+export async function resolveGoalId(req: Request): Promise<number | null> {+ const fromGoal = req.params.goalId ?? req.body?.goalId;+ if (fromGoal) return Number(fromGoal);++ const sprintId = req.params.sprintId ?? req.body?.sprintId;+ if (sprintId) {+ const sprint = await new SprintsRepository().getById(Number(sprintId));+ return sprint?.goalId ?? null;+ }+ return null;+}diff --git a/api/src/tv-modules/sprints/types.ts b/api/src/tv-modules/sprints/types.tsnew file mode 100644index 0000000..e42e94c--- /dev/null+++ b/api/src/tv-modules/sprints/types.ts@@ -0,0 +1,174 @@+import { type } from 'arktype';+import type { SprintStatus, TasksSchemaTypeForSelect } from 'taskview-db-schemas';++/** Request validators (ArkType) */++export const SprintArkTypeCreate = type({+ goalId: 'number',+ name: 'string > 0',+ startDate: 'string', // 'YYYY-MM-DD'+ endDate: 'string',+ 'goalText?': 'string | null',+ 'capacity?': 'number | null',+});++export const SprintArkTypeUpdate = type({+ sprintId: 'number',+ 'name?': 'string > 0',+ 'startDate?': 'string',+ 'endDate?': 'string',+ 'goalText?': 'string | null',+ 'capacity?': 'number | null',+});++export const SprintArkTypeSprintIdParam = type({+ sprintId: type('string | number').pipe((v) => Number(v)),+});++export const SprintArkTypeGoalIdParam = type({+ goalId: type('string | number').pipe((v) => Number(v)),+});++export const SprintArkTypeListQuery = type({+ goalId: type('string | number').pipe((v) => Number(v)),+ 'status?': 'string', // comma-separated subset of statuses+});++export const SprintArkTypeClose = type({+ sprintId: 'number',+ outcomes: type({+ taskId: 'number',+ outcome: "'accepted' | 'carried-over' | 'dropped'",+ 'carriedOverTo?': 'number | null',+ }).array(),+ goalAchieved: 'boolean',+});++export const SprintArkTypeSaveRetro = type({+ sprintId: 'number',+ 'wentWell?': 'string | null',+ 'wentBad?': 'string | null',+ 'actionItems?': 'string | null',+});++export const SprintArkTypeSetTask = type({+ taskId: 'number',+ sprintId: 'number | null',+});++export const SprintArkTypeVelocityQuery = type({+ goalId: type('string | number').pipe((v) => Number(v)),+ 'lastN?': type('string | number').pipe((v) => Number(v)),+});++export const SprintArkTypeSetCadence = type({+ goalId: 'number',+ enabled: 'boolean',+ 'lengthDays?': 'number',+ 'startDate?': 'string', // 'YYYY-MM-DD', anchor of the first window+ 'lookahead?': 'number', // how many future sprints to keep created beyond the current one+ 'nameTemplate?': 'string', // '{n}' is replaced with the 1-based window number+});++const PLANNING_DEFAULT_LIMIT = 30;+const PLANNING_MAX_LIMIT = 100;++export const SprintArkTypePlanningQuery = type({+ sprintId: type('string | number').pipe((v) => Number(v)),+ scope: "'backlog' | 'sprint'",+ 'cursor?': type('string | number').pipe((v) => Number(v)),+ 'limit?': type('string | number').pipe((v) => {+ const n = Number(v);+ if (isNaN(n) || n <= 0) return PLANNING_DEFAULT_LIMIT;+ return Math.min(n, PLANNING_MAX_LIMIT);+ }),+});++/** Inferred argument types (args-as-object) */++export type SprintCreateArgs = typeof SprintArkTypeCreate.infer;+export type SprintUpdateArgs = typeof SprintArkTypeUpdate.infer;+export type SprintCloseArgs = typeof SprintArkTypeClose.infer;+export type SprintSaveRetroArgs = typeof SprintArkTypeSaveRetro.infer;+export type SprintSetTaskArgs = typeof SprintArkTypeSetTask.infer;+export type SprintPlanningQueryArgs = typeof SprintArkTypePlanningQuery.infer;+export type SprintSetCadenceArgs = typeof SprintArkTypeSetCadence.infer;++/** Planning scope: backlog (unassigned, incomplete) vs tasks already in the sprint. */+export type SprintPlanningScope = 'backlog' | 'sprint';++/** Manager-level args for the planning page fetch. */+export type SprintPlanningManagerArgs = {+ sprintId: number;+ scope: SprintPlanningScope;+ cursor: number | null;+ limit: number;+};++/** Repository-level args for a cursor-paginated planning page. */+export type SprintPlanningPageArgs = {+ sprintId: number;+ cursor: number | null;+ limit: number;+};++export type SprintTaskOutcomeInput = SprintCloseArgs['outcomes'][number];++/** Internal manager/repository arg types */++export type SprintCreateRepoArgs = SprintCreateArgs & { creatorId: number };+export type SprintActivateArgs = { sprintId: number; initiatorId: number | null };+export type SprintReviewArgs = { sprintId: number; initiatorId: number };+export type SprintPauseArgs = { sprintId: number; initiatorId: number };+export type SprintResumeArgs = { sprintId: number; initiatorId: number };+export type SprintVelocityArgs = { goalId: number; lastN: number };+export type SprintCloseManagerArgs = SprintCloseArgs & { initiatorId: number };+export type SprintSaveRetroManagerArgs = SprintSaveRetroArgs & { editedBy: number };+export type SprintSetTaskManagerArgs = SprintSetTaskArgs & { initiatorId: number };++/** Cadence repository arg types (args-as-object) */+export type SprintCadenceUpsertRepoArgs = {+ goalId: number;+ enabled: boolean;+ lengthDays: number;+ startDate: string;+ lookahead: number;+ nameTemplate: string;+};+export type SprintCadenceFindByStartArgs = { goalId: number; startDate: string };+export type SprintCadenceTouchArgs = { goalId: number; lastGeneratedDate: string };+export type SprintCadenceSprintCreateArgs = {+ goalId: number;+ name: string;+ startDate: string;+ endDate: string;+};++export type SprintListFilter = { goalId: number; statuses?: SprintStatus[] };++export type BurndownPoint = { date: string; remainingHours: number; idealHours: number };+export type VelocityPoint = { sprintId: number; name: string; acceptedHours: number; plannedHours: number };++/** Sprint with related data for the detail endpoint */+export type SprintRetro = {+ wentWell: string | null;+ wentBad: string | null;+ actionItems: string | null;+};++/** Planning page response shapes. Backlog has no capacity counter; sprint scope carries totalPoints. */+export type SprintPlanningBacklogPage = {+ tasks: TasksSchemaTypeForSelect[];+ nextCursor: number | null;+};++export type SprintPlanningSprintPage = {+ tasks: TasksSchemaTypeForSelect[];+ nextCursor: number | null;+ totalPoints: number;+};++export type SprintPlanningPage = SprintPlanningBacklogPage | SprintPlanningSprintPage;++export type SprintErrorCode = 'not_found' | 'conflict' | 'invalid_state' | 'forbidden';+export type SprintResult<T> = { ok: true; data: T } | { ok: false; code: SprintErrorCode; message?: string };diff --git a/api/src/tv-modules/tasks/TasksManager.ts b/api/src/tv-modules/tasks/TasksManager.tsindex 0f91894..4ef7beb 100644--- a/api/src/tv-modules/tasks/TasksManager.ts+++ b/api/src/tv-modules/tasks/TasksManager.ts@@ -34,14 +34,13 @@ import {type TaskArgFetchTasksNew,type TaskArgRestoreTaskHistory,type TaskArgUpdate,- type TaskFieldPermissionsForEditOrCreation,TaskFieldPermissionsForWatching,type TaskForClientNew,type TasksArgToggleTaskUsers,} from './tasks.server.types';import type { KanbanArgFetchTasksForColumn, KanbanArgFilters } from '../kanban/types';-type TaskFieldPermissionKey = keyof typeof TaskFieldPermissionsForEditOrCreation & keyof TasksSchemaTypeForSelect;+type TaskFieldPermissionKey = keyof typeof TaskFieldPermissionsForWatching & keyof TasksSchemaTypeForSelect;export class TasksManager {public readonly repository: TasksRepository;diff --git a/api/src/tv-modules/tasks/TasksRepository.ts b/api/src/tv-modules/tasks/TasksRepository.tsindex 37e1df3..1795a7c 100644--- a/api/src/tv-modules/tasks/TasksRepository.ts+++ b/api/src/tv-modules/tasks/TasksRepository.ts@@ -209,6 +209,7 @@ export class TasksRepository {async updateTaskComplete(taskId: number, complete: boolean): Promise<TaskItemInDb | false> {const queryData = updateQuery({table: 'tasks.tasks',+ // date_complete is maintained by the tasks.update_date_complete DB trigger.data: { complete: Number(complete) },where: { id: taskId },});@@ -555,6 +556,11 @@ export class TasksRepository {conditions.push(eq(TasksSchema.priorityId, data.filters.priority as 1 | 2 | 3));}+ // sprint+ if (data.filters?.sprintId !== undefined) {+ conditions.push(eq(TasksSchema.sprintId, data.filters.sprintId));+ }+// searchif (data.searchText) {conditions.push(ilike(TasksSchema.description, `%${data.searchText}%`));@@ -663,6 +669,9 @@ export class TasksRepository {if (cursor !== null) {conditions.push(gt(TasksSchema.kanbanOrder, cursor));}+ if (filters?.sprintId !== undefined) {+ conditions.push(eq(TasksSchema.sprintId, filters.sprintId));+ }if (filters?.listIds && filters.listIds.length > 0) {conditions.push(inArray(TasksSchema.goalListId, filters.listIds));}diff --git a/api/src/tv-modules/tasks/tasks.server.types.ts b/api/src/tv-modules/tasks/tasks.server.types.tsindex 863e826..dbcdff8 100644--- a/api/src/tv-modules/tasks/tasks.server.types.ts+++ b/api/src/tv-modules/tasks/tasks.server.types.ts@@ -26,6 +26,7 @@ export const TaskArkTypeUpdate = type({'amount?': 'string|null','transactionType?': '1|0|null','nodeGraphPosition?': 'object|null',+ 'estimateValue?': 'number|null',});export const TaskArkTypeNumberFromString = type('string | number').pipe((v) => Number(v));@@ -42,6 +43,7 @@ export const TaskArkTypeFetchTasksNewFilters = type({'selectedUser?': TaskArkTypeNumberFromString,'priority?': TaskArkTypePriorityToNumber,'selectedTags?': TaskArkTypeSelectedTagsToNumber,+ 'sprintId?': TaskArkTypeNumberFromString,});export const TaskArkTypeFetchTasksNew = type({@@ -97,6 +99,7 @@ export const TaskArkTypeAdd = type({amount: type('number | null').optional(),transactionType: type('0 | 1 | null').optional(),nodeGraphPosition: type('object | null').optional(),+ estimateValue: type('number | null').optional(),});export type TaskArgAdd = typeof TaskArkTypeAdd.infer;@@ -118,8 +121,9 @@ export const TaskFieldPermissionsForEditOrCreation = {taskOrder: GoalPermissions.TASKS_CAN_DELETE,kanbanOrder: GoalPermissions.TASKS_CAN_DELETE,amount: GoalPermissions.TASKS_CAN_DELETE,- transactionType: GoalPermissions.TASKS_CAN_DELETE,+ transactionType: GoalPermissions.TASKS_CAN_DELETE,nodeGraphPosition: GoalPermissions.TASKS_CAN_DELETE,+ estimateValue: GoalPermissions.TASKS_CAN_EDIT_PRIORITY,};export const TaskFieldPermissionsForWatching = {diff --git a/api/src/tv-modules/webhooks/WebhooksDispatcher.ts b/api/src/tv-modules/webhooks/WebhooksDispatcher.tsindex d816ff7..3fa729c 100644--- a/api/src/tv-modules/webhooks/WebhooksDispatcher.ts+++ b/api/src/tv-modules/webhooks/WebhooksDispatcher.ts@@ -1,5 +1,5 @@import { eq } from 'drizzle-orm';-import { TasksSchema } from 'taskview-db-schemas';+import { SprintsSchema, TasksSchema } from 'taskview-db-schemas';import { eventBus, type AppEvents } from '../../core/EventBus';import { getJobQueue } from '../../core/JobQueue';import { decrypt } from '../../utils/crypto';@@ -28,6 +28,15 @@ export class WebhooksDispatcher implements Dispatcher {eventBus.on('time-entry.created', (data) => this.dispatch('time-entry.created', data.entry.goalId, data));eventBus.on('time-entry.updated', (data) => this.dispatch('time-entry.updated', data.entry.goalId, data));eventBus.on('time-entry.deleted', (data) => this.dispatch('time-entry.deleted', data.goalId, data));+ eventBus.on('sprint.created', (data) => this.dispatch('sprint.created', data.sprint.goalId, data));+ eventBus.on('sprint.updated', (data) => this.dispatch('sprint.updated', data.sprint.goalId, data));+ eventBus.on('sprint.activated', (data) => this.dispatchSprintLifecycle('sprint.activated', data));+ eventBus.on('sprint.reviewStarted', (data) => this.dispatchSprintLifecycle('sprint.reviewStarted', data));+ eventBus.on('sprint.completed', (data) => this.dispatchSprintLifecycle('sprint.completed', data));+ eventBus.on('sprint.paused', (data) => this.dispatchSprintLifecycle('sprint.paused', data));+ eventBus.on('sprint.resumed', (data) => this.dispatchSprintLifecycle('sprint.resumed', data));+ eventBus.on('sprint.deleted', (data) => this.dispatch('sprint.deleted', data.goalId, data));+ eventBus.on('task.assignedToSprint', (data) => this.dispatch('task.assignedToSprint', data.goalId, data));}async registerWorkers(): Promise<void> {@@ -56,6 +65,15 @@ export class WebhooksDispatcher implements Dispatcher {await this.dispatch('task.assigneesChanged', task[0].goalId, data);}+ private async dispatchSprintLifecycle(+ event: string,+ data: { sprintId: number; goalId: number; initiatorId: number | null },+ ): Promise<void> {+ const db = Database.getInstance();+ const sprint = await db.dbDrizzle.select().from(SprintsSchema).where(eq(SprintsSchema.id, data.sprintId)).limit(1);+ await this.dispatch(event, data.goalId, { ...data, sprint: sprint[0] ?? null });+ }+private async enqueueDelivery(webhookId: number, url: string, secretEncrypted: string, event: string, payload: object): Promise<void> {const delivery = await this.repository.createDelivery({ webhookId, event, payload });if (!delivery) return;diff --git a/api/src/tv-modules/webhooks/types.ts b/api/src/tv-modules/webhooks/types.tsindex 74b674d..a2ffb57 100644--- a/api/src/tv-modules/webhooks/types.ts+++ b/api/src/tv-modules/webhooks/types.ts@@ -57,6 +57,15 @@ export const WEBHOOK_EVENTS = ['time-entry.created','time-entry.updated','time-entry.deleted',+ 'sprint.created',+ 'sprint.updated',+ 'sprint.activated',+ 'sprint.reviewStarted',+ 'sprint.completed',+ 'sprint.paused',+ 'sprint.resumed',+ 'sprint.deleted',+ 'task.assignedToSprint',] as const;export type WebhookEvent = typeof WEBHOOK_EVENTS[number];diff --git a/api/src/types/auth.types.ts b/api/src/types/auth.types.tsindex 225f852..e1a65ed 100644--- a/api/src/types/auth.types.ts+++ b/api/src/types/auth.types.ts@@ -132,6 +132,11 @@ export const GoalPermissions = {TIMETRACKING_CAN_VIEW: 'timetracking_can_view',TIMETRACKING_CAN_LOG: 'timetracking_can_log',TIMETRACKING_CAN_MANAGE_ALL: 'timetracking_can_manage_all',++ SPRINT_CAN_VIEW: 'sprint_can_view',+ SPRINT_CAN_MANAGE: 'sprint_can_manage',+ SPRINT_CAN_ASSIGN_TASKS: 'sprint_can_assign_tasks',+ SPRINT_CAN_VIEW_ANALYTICS: 'sprint_can_view_analytics',} as const;export type PermissionsEntityType =diff --git a/api/src/types/tasks.types.ts b/api/src/types/tasks.types.tsindex 3d2c543..243f880 100644--- a/api/src/types/tasks.types.ts+++ b/api/src/types/tasks.types.ts@@ -45,6 +45,7 @@ export const TasksFiltersSchema = z.object({selectedUser: z.number().optional(),priority: z.union([z.literal(1), z.literal(2), z.literal(3)]).optional(),selectedTags: NumberTrueSchema.optional(),+ sprintId: z.number().optional(),});const zeroOrOneSchema = zdiff --git a/docs/2.features/7.webhooks.md b/docs/2.features/7.webhooks.mdindex 61870e6..361eccc 100644--- a/docs/2.features/7.webhooks.md+++ b/docs/2.features/7.webhooks.md@@ -15,6 +15,20 @@ Webhooks let you receive HTTP POST requests when events happen in your projects.| `task.updated` | A task is updated (description, status, priority, deadline, etc.) || `task.deleted` | A task is deleted || `task.assigneesChanged` | Task assignees are added or removed |+| `time-entry.started` | A timer is started on a task |+| `time-entry.stopped` | A running timer is stopped |+| `time-entry.created` | A time entry is created manually |+| `time-entry.updated` | A time entry is updated |+| `time-entry.deleted` | A time entry is deleted |+| `sprint.created` | A new sprint is created (draft or planned) |+| `sprint.updated` | Sprint fields are edited (name, dates, capacity, goal) |+| `sprint.activated` | A sprint transitions to the active state |+| `sprint.reviewStarted` | An active sprint enters review |+| `sprint.completed` | A sprint is closed and marked completed |+| `sprint.paused` | An active sprint is paused |+| `sprint.resumed` | A paused sprint is resumed |+| `sprint.deleted` | A draft or planned sprint is deleted |+| `task.assignedToSprint` | A task is added to, moved between, or removed from a sprint |## Setup@@ -52,7 +66,31 @@ Every webhook delivery is an HTTP POST with `Content-Type: application/json`:}```-The `changes` field is only present on `task.updated` events and contains only the fields that changed.+The `changes` field is only present on `task.updated` and `sprint.updated` events and contains only the fields that changed.++Sprint events carry the sprint payload. Lifecycle events (`sprint.activated`, `sprint.reviewStarted`, `sprint.completed`, `sprint.paused`, `sprint.resumed`) include the full sprint object reflecting its state at the time the event fired, plus `sprintId`, `goalId`, and `initiatorId`:++```json+{+ "event": "sprint.completed",+ "timestamp": "2026-03-22T12:00:00.000Z",+ "sprintId": 42,+ "goalId": 774,+ "initiatorId": 1,+ "sprint": {+ "id": 42,+ "goalId": 774,+ "name": "Sprint 7",+ "status": "completed",+ "startDate": "2026-03-08",+ "endDate": "2026-03-22",+ "goalAchieved": true,+ "completedAt": "2026-03-22T12:00:00.000Z"+ }+}+```++`task.assignedToSprint` carries `taskId`, `sprintId` (the new sprint, or `null` when removed), `prevSprintId`, `goalId`, and `initiatorId`. `sprint.deleted` carries `sprintId`, `goalId`, and `initiatorId` only, since the sprint no longer exists. `initiatorId` may be `null` for sprints generated automatically by a cadence.## Signature verificationdiff --git a/taskview-packages/taskview-api/src/api/__tests__/sprints.test.ts b/taskview-packages/taskview-api/src/api/__tests__/sprints.test.tsnew file mode 100644index 0000000..0be8f05--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/sprints.test.ts@@ -0,0 +1,571 @@+import { TvApi } from '@/tv'+import {+ describe,+ it,+ expect,+ beforeAll,+ afterAll,+ afterEach,+} from 'vitest'+import { initApi } from './init-api'+import { ymd } from './test-helpers'+import type { SprintPlanningSprintPage } from '@/api/sprints.types'++describe('Sprints', () => {+ let $api: TvApi+ let goalId: number+ const created: number[] = []++ /** Track a sprint so afterEach can drive it to a terminal/deletable state. */+ const track = (id: number) => { created.push(id); return id }++ /** Force a sprint out of any active/review state so it never blocks later activations. */+ async function releaseSprint(id: number) {+ const s = await $api.sprints.getById(id).catch(() => null)+ if (!s) return+ if (s.status === 'draft' || s.status === 'planned') {+ await $api.sprints.remove(id).catch(() => {})+ return+ }+ if (s.status === 'active') {+ await $api.sprints.startReview(id).catch(() => {})+ }+ const cur = await $api.sprints.getById(id).catch(() => null)+ if (cur?.status === 'review') {+ await $api.sprints.close({ sprintId: id, outcomes: [], goalAchieved: false }).catch(() => {})+ }+ }++ beforeAll(async () => {+ const { $tvApi } = await initApi()+ $api = $tvApi++ const goal = await $api.goals.createGoal({ name: `Sprint test project-${Date.now()}` }).catch(console.error)+ if (!goal) throw new Error('Failed to create goal')+ goalId = goal.id!+ })++ afterEach(async () => {+ for (const id of created) {+ await releaseSprint(id)+ }+ created.length = 0+ })++ afterAll(async () => {+ await $api.goals.deleteGoal(goalId).catch(() => {})+ })++ async function createPlanned(name = `Planned-${Date.now()}`) {+ const sprint = await $api.sprints.create({+ goalId,+ name,+ startDate: ymd(7),+ endDate: ymd(21),+ }).catch(console.error)+ if (!sprint) throw new Error('Failed to create sprint')+ return track(sprint.id)+ }++ describe('CRUD', () => {+ it('creates a planned sprint when startDate is in the future', async () => {+ const sprint = await $api.sprints.create({+ goalId,+ name: 'Future sprint',+ startDate: ymd(7),+ endDate: ymd(21),+ goalText: 'Ship the thing',+ capacity: 40,+ }).catch(console.error)++ if (!sprint) throw new Error('Failed to create sprint')+ track(sprint.id)++ expect(sprint.id).toBeGreaterThan(0)+ expect(sprint.goalId).toBe(goalId)+ expect(sprint.name).toBe('Future sprint')+ expect(sprint.status).toBe('planned')+ expect(sprint.startDate).toBe(ymd(7))+ expect(sprint.endDate).toBe(ymd(21))+ expect(sprint.goalText).toBe('Ship the thing')+ expect(Number(sprint.capacity)).toBe(40)+ })++ it('creates a draft sprint when startDate is today or earlier', async () => {+ const sprint = await $api.sprints.create({+ goalId,+ name: 'Draft sprint',+ startDate: ymd(0),+ endDate: ymd(14),+ }).catch(console.error)++ if (!sprint) throw new Error('Failed to create sprint')+ track(sprint.id)++ expect(sprint.status).toBe('draft')+ })++ it('rejects creation when endDate is before startDate', async () => {+ const sprint = await $api.sprints.create({+ goalId,+ name: 'Bad dates',+ startDate: ymd(10),+ endDate: ymd(5),+ }).catch(() => null)++ expect(sprint).toBeFalsy()+ })++ it('lists sprints for a goal', async () => {+ const id = await createPlanned('Listed sprint')++ const list = await $api.sprints.listForGoal({ goalId }).catch(console.error)+ if (!list) throw new Error('Failed to list sprints')++ expect(Array.isArray(list)).toBe(true)+ expect(list.find((s) => s.id === id)).toBeDefined()+ })++ it('filters sprints by status', async () => {+ const plannedId = await createPlanned('Planned for filter')+ const draft = await $api.sprints.create({+ goalId, name: 'Draft for filter', startDate: ymd(0), endDate: ymd(14),+ }).catch(console.error)+ if (!draft) throw new Error('Failed to create draft')+ track(draft.id)++ const onlyPlanned = await $api.sprints.listForGoal({ goalId, status: 'planned' }).catch(console.error)+ if (!onlyPlanned) throw new Error('Failed to filter sprints')++ expect(onlyPlanned.every((s) => s.status === 'planned')).toBe(true)+ expect(onlyPlanned.find((s) => s.id === plannedId)).toBeDefined()+ expect(onlyPlanned.find((s) => s.id === draft.id)).toBeUndefined()+ })++ it('gets a sprint by id with a null retro', async () => {+ const id = await createPlanned('Fetched sprint')++ const sprint = await $api.sprints.getById(id).catch(console.error)+ if (!sprint) throw new Error('Failed to get sprint')++ expect(sprint.id).toBe(id)+ expect(sprint.retro).toBeNull()+ })++ it('updates name, dates, goalText and capacity', async () => {+ const id = await createPlanned('Before update')++ const updated = await $api.sprints.update({+ sprintId: id,+ name: 'After update',+ startDate: ymd(8),+ endDate: ymd(22),+ goalText: 'Revised goal',+ capacity: 55,+ }).catch(console.error)+ if (!updated) throw new Error('Failed to update sprint')++ expect(updated.name).toBe('After update')+ expect(updated.startDate).toBe(ymd(8))+ expect(updated.endDate).toBe(ymd(22))+ expect(updated.goalText).toBe('Revised goal')+ expect(Number(updated.capacity)).toBe(55)+ })++ it('deletes a draft/planned sprint', async () => {+ const sprint = await $api.sprints.create({+ goalId, name: 'To delete', startDate: ymd(5), endDate: ymd(19),+ }).catch(console.error)+ if (!sprint) throw new Error('Failed to create sprint')++ const result = await $api.sprints.remove(sprint.id).catch(console.error)+ expect(result).toBe(true)++ const gone = await $api.sprints.getById(sprint.id).catch(() => null)+ expect(gone).toBeNull()+ })+ })++ describe('Lifecycle', () => {+ it('activates a planned sprint', async () => {+ const id = await createPlanned()++ const activated = await $api.sprints.activate(id).catch(console.error)+ if (!activated) throw new Error('Failed to activate')++ expect(activated.status).toBe('active')+ })++ it('rejects activating a second sprint while one is active', async () => {+ const first = await createPlanned('First active')+ await $api.sprints.activate(first)++ const second = await createPlanned('Second sprint')+ const conflict = await $api.sprints.activate(second).catch(() => null)++ expect(conflict).toBeFalsy()+ })++ it('rejects deleting an active sprint', async () => {+ const id = await createPlanned()+ await $api.sprints.activate(id)++ const result = await $api.sprints.remove(id).catch(() => null)+ expect(result).toBeFalsy()+ })++ it('pauses and resumes an active sprint', async () => {+ const id = await createPlanned()+ await $api.sprints.activate(id)++ const paused = await $api.sprints.pause(id).catch(console.error)+ if (!paused) throw new Error('Failed to pause')+ expect(paused.status).toBe('active')+ expect(paused.pausedAt).toBeTruthy()++ const resumed = await $api.sprints.resume(id).catch(console.error)+ if (!resumed) throw new Error('Failed to resume')+ expect(resumed.status).toBe('active')+ expect(resumed.pausedAt).toBeNull()+ })++ it('rejects pausing a sprint that is not active', async () => {+ const id = await createPlanned()+ const result = await $api.sprints.pause(id).catch(() => null)+ expect(result).toBeFalsy()+ })++ it('moves an active sprint into review', async () => {+ const id = await createPlanned()+ await $api.sprints.activate(id)++ const review = await $api.sprints.startReview(id).catch(console.error)+ if (!review) throw new Error('Failed to start review')++ expect(review.status).toBe('review')+ expect(review.reviewStartedAt).toBeTruthy()+ })++ it('rejects starting review on a non-active sprint', async () => {+ const id = await createPlanned()+ const result = await $api.sprints.startReview(id).catch(() => null)+ expect(result).toBeFalsy()+ })++ it('closes a sprint in review and marks it completed', async () => {+ const id = await createPlanned()+ await $api.sprints.activate(id)+ await $api.sprints.startReview(id)++ const closed = await $api.sprints.close({+ sprintId: id,+ outcomes: [],+ goalAchieved: true,+ }).catch(console.error)+ if (!closed) throw new Error('Failed to close')++ expect(closed.status).toBe('completed')+ expect(closed.goalAchieved).toBe(true)+ expect(closed.completedAt).toBeTruthy()+ })++ it('rejects closing a sprint that is not in review', async () => {+ const id = await createPlanned()+ await $api.sprints.activate(id)++ const result = await $api.sprints.close({ sprintId: id, outcomes: [], goalAchieved: true }).catch(() => null)+ expect(result).toBeFalsy()+ })++ it('treats a completed sprint as read-only and undeletable', async () => {+ const id = await createPlanned()+ await $api.sprints.activate(id)+ await $api.sprints.startReview(id)+ await $api.sprints.close({ sprintId: id, outcomes: [], goalAchieved: false })++ const update = await $api.sprints.update({ sprintId: id, name: 'nope' }).catch(() => null)+ expect(update).toBeFalsy()++ const remove = await $api.sprints.remove(id).catch(() => null)+ expect(remove).toBeFalsy()+ })+ })++ describe('Close outcomes', () => {+ async function reviewSprintWithTask(opts: { complete?: boolean } = {}) {+ const id = await createPlanned()+ const task = await $api.tasks.createTask({ goalId, description: `Outcome task-${Date.now()}` }).catch(console.error)+ if (!task) throw new Error('Failed to create task')+ if (opts.complete) await $api.tasks.updateTask({ id: task.id, complete: true })+ await $api.sprints.setTaskSprint({ taskId: task.id, sprintId: id })+ await $api.sprints.activate(id)+ await $api.sprints.startReview(id)+ return { id, taskId: task.id }+ }++ it('carries an unfinished task over to the target sprint', async () => {+ const target = await createPlanned('Carry-over target')+ const { id, taskId } = await reviewSprintWithTask()++ const closed = await $api.sprints.close({+ sprintId: id,+ outcomes: [{ taskId, outcome: 'carried-over', carriedOverTo: target }],+ goalAchieved: false,+ }).catch(console.error)+ expect(closed).toBeTruthy()++ const moved = await $api.tasks.fetchTaskById(taskId).catch(console.error)+ expect(moved?.sprintId).toBe(target)++ await $api.tasks.deleteTask(taskId).catch(() => {})+ })++ it('drops an unfinished task out of the sprint', async () => {+ const { id, taskId } = await reviewSprintWithTask()++ const closed = await $api.sprints.close({+ sprintId: id,+ outcomes: [{ taskId, outcome: 'dropped' }],+ goalAchieved: false,+ }).catch(console.error)+ expect(closed).toBeTruthy()++ const dropped = await $api.tasks.fetchTaskById(taskId).catch(console.error)+ expect(dropped?.sprintId).toBeNull()++ await $api.tasks.deleteTask(taskId).catch(() => {})+ })++ it('forces a completed task to "accepted" even when the client requests "dropped"', async () => {+ const { id, taskId } = await reviewSprintWithTask({ complete: true })++ await $api.sprints.close({+ sprintId: id,+ outcomes: [{ taskId, outcome: 'dropped' }],+ goalAchieved: true,+ })++ // A done task can't be dropped — it is accepted and stays in the closed sprint.+ const kept = await $api.tasks.fetchTaskById(taskId).catch(console.error)+ expect(kept?.sprintId).toBe(id)++ await $api.tasks.deleteTask(taskId).catch(() => {})+ })++ it('rejects carrying a task over to the same sprint', async () => {+ const { id, taskId } = await reviewSprintWithTask()++ const result = await $api.sprints.close({+ sprintId: id,+ outcomes: [{ taskId, outcome: 'carried-over', carriedOverTo: id }],+ goalAchieved: false,+ }).catch(() => null)+ expect(result).toBeFalsy()++ const stillReview = await $api.sprints.getById(id).catch(console.error)+ expect(stillReview?.status).toBe('review')++ await $api.tasks.deleteTask(taskId).catch(() => {})+ })++ it('rejects carrying a task over to a sprint in a different project', async () => {+ const otherGoal = await $api.goals.createGoal({ name: `Other project-${Date.now()}` }).catch(console.error)+ if (!otherGoal) throw new Error('Failed to create other goal')+ const otherSprint = await $api.sprints.create({+ goalId: otherGoal.id!, name: 'Other sprint', startDate: ymd(7), endDate: ymd(21),+ }).catch(console.error)+ if (!otherSprint) throw new Error('Failed to create other sprint')++ const { id, taskId } = await reviewSprintWithTask()++ const result = await $api.sprints.close({+ sprintId: id,+ outcomes: [{ taskId, outcome: 'carried-over', carriedOverTo: otherSprint.id }],+ goalAchieved: false,+ }).catch(() => null)+ expect(result).toBeFalsy()++ await $api.tasks.deleteTask(taskId).catch(() => {})+ await $api.goals.deleteGoal(otherGoal.id!).catch(() => {})+ })+ })++ describe('Tasks in sprint', () => {+ it('assigns a task to a sprint and removes it', async () => {+ const id = await createPlanned()+ const task = await $api.tasks.createTask({ goalId, description: `Sprint task-${Date.now()}` }).catch(console.error)+ if (!task) throw new Error('Failed to create task')++ const assigned = await $api.sprints.setTaskSprint({ taskId: task.id, sprintId: id }).catch(console.error)+ expect(assigned).toBeDefined()+ expect(assigned!.sprintId).toBe(id)++ const inSprint = await $api.sprints.getPlanningTasks({ sprintId: id, scope: 'sprint' }).catch(console.error)+ expect(inSprint?.tasks.find((t) => t.id === task.id)).toBeDefined()++ const removed = await $api.sprints.setTaskSprint({ taskId: task.id, sprintId: null }).catch(console.error)+ expect(removed).toBeDefined()+ expect(removed!.sprintId).toBeNull()++ await $api.tasks.deleteTask(task.id).catch(() => {})+ })++ it('rejects assigning a task into a completed sprint', async () => {+ const id = await createPlanned()+ await $api.sprints.activate(id)+ await $api.sprints.startReview(id)+ await $api.sprints.close({ sprintId: id, outcomes: [], goalAchieved: false })++ const task = await $api.tasks.createTask({ goalId, description: `Late task-${Date.now()}` }).catch(console.error)+ if (!task) throw new Error('Failed to create task')++ const result = await $api.sprints.setTaskSprint({ taskId: task.id, sprintId: id }).catch(() => null)+ expect(result).toBeFalsy()++ await $api.tasks.deleteTask(task.id).catch(() => {})+ })++ it('rejects assigning a task to a sprint in a different project', async () => {+ const otherGoal = await $api.goals.createGoal({ name: `Foreign project-${Date.now()}` }).catch(console.error)+ if (!otherGoal) throw new Error('Failed to create other goal')+ const otherSprint = await $api.sprints.create({+ goalId: otherGoal.id!, name: 'Foreign sprint', startDate: ymd(7), endDate: ymd(21),+ }).catch(console.error)+ if (!otherSprint) throw new Error('Failed to create other sprint')++ const task = await $api.tasks.createTask({ goalId, description: `Foreign assign-${Date.now()}` }).catch(console.error)+ if (!task) throw new Error('Failed to create task')++ const result = await $api.sprints.setTaskSprint({ taskId: task.id, sprintId: otherSprint.id }).catch(() => null)+ expect(result).toBeFalsy()++ await $api.tasks.deleteTask(task.id).catch(() => {})+ await $api.goals.deleteGoal(otherGoal.id!).catch(() => {})+ })++ it('separates backlog and sprint planning scopes with capacity totals', async () => {+ const id = await createPlanned()+ const task = await $api.tasks.createTask({ goalId, description: `Backlog task-${Date.now()}` }).catch(console.error)+ if (!task) throw new Error('Failed to create task')+ await $api.tasks.updateTask({ id: task.id, estimateValue: 8 })++ const backlog = await $api.sprints.getPlanningTasks({ sprintId: id, scope: 'backlog' }).catch(console.error)+ expect(backlog?.tasks.find((t) => t.id === task.id)).toBeDefined()++ await $api.sprints.setTaskSprint({ taskId: task.id, sprintId: id })++ const sprintScope = await $api.sprints.getPlanningTasks({ sprintId: id, scope: 'sprint' }).catch(console.error) as SprintPlanningSprintPage | undefined+ expect(sprintScope?.tasks.find((t) => t.id === task.id)).toBeDefined()+ expect(sprintScope?.totalPoints).toBe(8)++ const backlogAfter = await $api.sprints.getPlanningTasks({ sprintId: id, scope: 'backlog' }).catch(console.error)+ expect(backlogAfter?.tasks.find((t) => t.id === task.id)).toBeUndefined()++ await $api.tasks.deleteTask(task.id).catch(() => {})+ })+ })++ describe('Retro', () => {+ it('saves and reads back a retrospective', async () => {+ const id = await createPlanned()++ const saved = await $api.sprints.saveRetro({+ sprintId: id,+ wentWell: 'Shipped on time',+ wentBad: 'Too many meetings',+ actionItems: 'Fewer meetings',+ }).catch(console.error)+ expect(saved).toBeDefined()++ const sprint = await $api.sprints.getById(id).catch(console.error)+ expect(sprint?.retro).toBeDefined()+ expect(sprint?.retro?.wentWell).toBe('Shipped on time')+ expect(sprint?.retro?.wentBad).toBe('Too many meetings')+ expect(sprint?.retro?.actionItems).toBe('Fewer meetings')+ })+ })++ describe('Burndown & Velocity', () => {+ it('returns a burndown curve with the total estimate', async () => {+ const id = await createPlanned()+ const task = await $api.tasks.createTask({ goalId, description: `Burndown task-${Date.now()}` }).catch(console.error)+ if (!task) throw new Error('Failed to create task')+ await $api.tasks.updateTask({ id: task.id, estimateValue: 6 })+ await $api.sprints.setTaskSprint({ taskId: task.id, sprintId: id })++ const burndown = await $api.sprints.getBurndown(id).catch(console.error)+ if (!burndown) throw new Error('Failed to get burndown')++ expect(burndown.total).toBeGreaterThanOrEqual(6)+ expect(Array.isArray(burndown.points)).toBe(true)+ expect(burndown.points.length).toBeGreaterThan(0)++ await $api.tasks.deleteTask(task.id).catch(() => {})+ })++ it('reports velocity for completed sprints', async () => {+ const id = await createPlanned()+ const task = await $api.tasks.createTask({ goalId, description: `Velocity task-${Date.now()}` }).catch(console.error)+ if (!task) throw new Error('Failed to create task')+ await $api.tasks.updateTask({ id: task.id, estimateValue: 5, complete: true })+ await $api.sprints.setTaskSprint({ taskId: task.id, sprintId: id })++ await $api.sprints.activate(id)+ await $api.sprints.startReview(id)+ await $api.sprints.close({ sprintId: id, outcomes: [], goalAchieved: true })++ const velocity = await $api.sprints.getVelocity({ goalId }).catch(console.error)+ if (!velocity) throw new Error('Failed to get velocity')++ const point = velocity.find((p) => p.sprintId === id)+ expect(point).toBeDefined()+ expect(point!.acceptedHours).toBe(5)+ expect(point!.plannedHours).toBe(5)++ await $api.tasks.deleteTask(task.id).catch(() => {})+ })+ })++ describe('Cadence', () => {+ it('returns null cadence before configuration', async () => {+ const fresh = await $api.goals.createGoal({ name: `Cadence empty-${Date.now()}` }).catch(console.error)+ if (!fresh) throw new Error('Failed to create goal')++ const cadence = await $api.sprints.getCadence(fresh.id!).catch(console.error)+ expect(cadence).toBeNull()++ await $api.goals.deleteGoal(fresh.id!).catch(() => {})+ })++ it('configures cadence and auto-generates planned sprints', async () => {+ const fresh = await $api.goals.createGoal({ name: `Cadence project-${Date.now()}` }).catch(console.error)+ if (!fresh) throw new Error('Failed to create goal')+ const cadenceGoalId = fresh.id!++ const saved = await $api.sprints.setCadence({+ goalId: cadenceGoalId,+ enabled: true,+ lengthDays: 7,+ startDate: ymd(0),+ lookahead: 2,+ nameTemplate: 'Iteration {n}',+ }).catch(console.error)+ if (!saved) throw new Error('Failed to set cadence')++ expect(saved.enabled).toBe(true)+ expect(saved.lengthDays).toBe(7)+ expect(saved.lookahead).toBe(2)+ expect(saved.nameTemplate).toBe('Iteration {n}')++ const cadence = await $api.sprints.getCadence(cadenceGoalId).catch(console.error)+ expect(cadence?.enabled).toBe(true)+ expect(cadence?.lengthDays).toBe(7)++ const generated = await $api.sprints.listForGoal({ goalId: cadenceGoalId }).catch(console.error)+ expect(generated && generated.length).toBeGreaterThanOrEqual(1)+ expect(generated!.every((s) => s.status === 'planned')).toBe(true)++ await $api.goals.deleteGoal(cadenceGoalId).catch(() => {})+ })+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/test-helpers.ts b/taskview-packages/taskview-api/src/api/__tests__/test-helpers.tsnew file mode 100644index 0000000..2ebedc2--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/test-helpers.ts@@ -0,0 +1,6 @@+/** Returns a YYYY-MM-DD date string offset by `offsetDays` from today (UTC). */+export function ymd(offsetDays = 0): string {+ const d = new Date()+ d.setUTCDate(d.getUTCDate() + offsetDays)+ return d.toISOString().slice(0, 10)+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/webhook-receiver.ts b/taskview-packages/taskview-api/src/api/__tests__/webhook-receiver.tsnew file mode 100644index 0000000..061f69c--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/webhook-receiver.ts@@ -0,0 +1,90 @@+import { createServer, type IncomingMessage, type ServerResponse } from 'http'+import { networkInterfaces } from 'os'++function getLocalIp(): string {+ const nets = networkInterfaces()+ for (const name of Object.keys(nets)) {+ for (const net of nets[name]!) {+ if (net.family === 'IPv4' && !net.internal) {+ return net.address+ }+ }+ }+ return '127.0.0.1'+}++export type ReceivedWebhook = {+ body: any+ headers: Record<string, string | string[] | undefined>+}++/**+ * A tiny HTTP server the API container can POST webhook deliveries to.+ * Binds on 0.0.0.0 and advertises the host LAN IP so the Dockerized API+ * (which cannot reach `localhost`) can deliver to it.+ */+export function createWebhookReceiver() {+ const received: ReceivedWebhook[] = []+ const waiters: Array<(value: any) => void> = []++ const server = createServer((req: IncomingMessage, res: ServerResponse) => {+ let body = ''+ req.on('data', (chunk) => { body += chunk })+ req.on('end', () => {+ let parsed: any = null+ try { parsed = JSON.parse(body) } catch { parsed = body }+ received.push({ body: parsed, headers: req.headers })+ if (waiters.length > 0) {+ waiters.shift()!(parsed)+ }+ res.writeHead(200)+ res.end('ok')+ })+ })++ const ip = getLocalIp()++ return {+ server,+ received,+ getUrl: () => `http://${ip}:${(server.address() as any).port}/webhook`,+ start: () => new Promise<void>((resolve) => {+ server.listen(0, '0.0.0.0', () => resolve())+ }),+ stop: () => new Promise<void>((resolve) => {+ server.close(() => resolve())+ }),+ // Reset BOTH buffers: a lingering waiter (e.g. one whose promise already+ // timed out) would otherwise consume a future delivery slot and starve the+ // next test's waitForDelivery, so the queue must be emptied alongside `received`.+ clear: () => { received.length = 0; waiters.length = 0 },+ /** Resolve with the payload of the first delivery whose `event` matches (already-received or future). */+ waitForDelivery: (event?: string, timeoutMs = 8000) => new Promise<any>((resolve, reject) => {+ const idx = event+ ? received.findIndex(r => r.body?.event === event)+ : received.length > 0 ? 0 : -1+ if (idx >= 0) {+ resolve(received[idx].body)+ return+ }++ const check = (payload: any) => {+ if (!event || payload?.event === event) {+ clearTimeout(timer)+ resolve(payload)+ } else {+ waiters.push(check)+ }+ }++ const timer = setTimeout(() => {+ // Drop our own waiter so a late delivery doesn't fire a dead resolver.+ const i = waiters.indexOf(check)+ if (i >= 0) waiters.splice(i, 1)+ reject(new Error(`No webhook delivery${event ? ` for ${event}` : ''} received within ${timeoutMs}ms`))+ }, timeoutMs)++ waiters.push(check)+ }),+ }+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/webhooks-sprints.test.ts b/taskview-packages/taskview-api/src/api/__tests__/webhooks-sprints.test.tsnew file mode 100644index 0000000..85909d2--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/webhooks-sprints.test.ts@@ -0,0 +1,251 @@+import { TvApi } from '@/tv'+import {+ describe,+ it,+ expect,+ beforeAll,+ afterAll,+} from 'vitest'+import { initApi } from './init-api'+import { createWebhookReceiver } from './webhook-receiver'+import { ymd } from './test-helpers'++const SPRINT_EVENTS = [+ 'sprint.created',+ 'sprint.updated',+ 'sprint.activated',+ 'sprint.reviewStarted',+ 'sprint.completed',+ 'sprint.paused',+ 'sprint.resumed',+ 'sprint.deleted',+ 'task.assignedToSprint',+]++describe('Webhooks: sprint events', () => {+ let $api: TvApi+ let goalId: number+ let webhookId: number+ let webhookUrl: string+ const receiver = createWebhookReceiver()++ beforeAll(async () => {+ const { $tvApi } = await initApi()+ $api = $tvApi++ await receiver.start()+ webhookUrl = receiver.getUrl()++ const goal = await $api.goals.createGoal({ name: `Sprint webhook project-${Date.now()}` }).catch(console.error)+ if (!goal) throw new Error('Failed to create goal')+ goalId = goal.id!++ const created = await $api.webhooks.create({+ goalId,+ url: webhookUrl,+ events: SPRINT_EVENTS,+ }).catch(console.error)+ if (!created) throw new Error('Failed to create webhook')+ webhookId = created.webhook.id++ expect(created.webhook.events).toEqual(SPRINT_EVENTS)+ })++ afterAll(async () => {+ await $api.webhooks.delete({ id: webhookId }).catch(() => {})+ await $api.goals.deleteGoal(goalId).catch(() => {})+ await receiver.stop()+ })++ async function createPlanned(name = `Webhook sprint-${Date.now()}`) {+ const sprint = await $api.sprints.create({+ goalId, name, startDate: ymd(7), endDate: ymd(21),+ }).catch(console.error)+ if (!sprint) throw new Error('Failed to create sprint')+ return sprint+ }++ it('delivers an enriched payload through the whole lifecycle', async () => {+ receiver.clear()++ const sprint = await createPlanned('Lifecycle sprint')++ const createdPayload = await receiver.waitForDelivery('sprint.created')+ expect(createdPayload.event).toBe('sprint.created')+ expect(createdPayload.timestamp).toBeTruthy()+ expect(createdPayload.sprint).toBeDefined()+ expect(createdPayload.sprint.id).toBe(sprint.id)+ expect(createdPayload.sprint.goalId).toBe(goalId)+ // The event is attributed to the acting user — the same id the sprint records as its creator.+ expect(createdPayload.initiatorId).toBe(createdPayload.sprint.creatorId)++ await $api.sprints.update({+ sprintId: sprint.id,+ name: 'Lifecycle renamed',+ goalText: 'Revised',+ capacity: 30,+ })+ const updatedPayload = await receiver.waitForDelivery('sprint.updated')+ expect(updatedPayload.sprint.id).toBe(sprint.id)+ expect(updatedPayload.changes).toBeDefined()+ expect(updatedPayload.changes.name).toBe('Lifecycle renamed')+ expect(updatedPayload.changes.goalText).toBe('Revised')+ // capacity is serialized to a numeric string in the change set.+ expect(Number(updatedPayload.changes.capacity)).toBe(30)++ await $api.sprints.activate(sprint.id)+ const activatedPayload = await receiver.waitForDelivery('sprint.activated')+ expect(activatedPayload.sprintId).toBe(sprint.id)+ expect(activatedPayload.goalId).toBe(goalId)+ expect(activatedPayload.sprint?.status).toBe('active')++ await $api.sprints.pause(sprint.id)+ const pausedPayload = await receiver.waitForDelivery('sprint.paused')+ expect(pausedPayload.sprintId).toBe(sprint.id)+ expect(pausedPayload.sprint?.pausedAt).toBeTruthy()++ await $api.sprints.resume(sprint.id)+ const resumedPayload = await receiver.waitForDelivery('sprint.resumed')+ expect(resumedPayload.sprintId).toBe(sprint.id)+ expect(resumedPayload.sprint?.pausedAt).toBeNull()++ await $api.sprints.startReview(sprint.id)+ const reviewPayload = await receiver.waitForDelivery('sprint.reviewStarted')+ expect(reviewPayload.sprintId).toBe(sprint.id)+ expect(reviewPayload.sprint?.status).toBe('review')++ await $api.sprints.close({ sprintId: sprint.id, outcomes: [], goalAchieved: true })+ const completedPayload = await receiver.waitForDelivery('sprint.completed')+ expect(completedPayload.sprintId).toBe(sprint.id)+ expect(completedPayload.goalId).toBe(goalId)+ expect(completedPayload.sprint?.status).toBe('completed')+ expect(completedPayload.sprint?.goalAchieved).toBe(true)+ }, 40000)++ it('signs sprint deliveries with an HMAC header', async () => {+ receiver.clear()+ const sprint = await createPlanned('Signed sprint')++ await receiver.waitForDelivery('sprint.created')+ const delivery = receiver.received.find((r) => r.body?.event === 'sprint.created')+ expect(delivery).toBeDefined()+ const signature = delivery!.headers['x-webhook-signature']+ expect(typeof signature).toBe('string')+ expect(String(signature)).toMatch(/^sha256=/)++ await $api.sprints.remove(sprint.id).catch(() => {})+ }, 15000)++ it('delivers sprint.deleted with ids only (no sprint body)', async () => {+ receiver.clear()+ const sprint = await createPlanned('Deletable sprint')+ await receiver.waitForDelivery('sprint.created')++ receiver.clear()+ await $api.sprints.remove(sprint.id)++ const deletedPayload = await receiver.waitForDelivery('sprint.deleted')+ expect(deletedPayload.sprintId).toBe(sprint.id)+ expect(deletedPayload.goalId).toBe(goalId)+ expect(typeof deletedPayload.initiatorId).toBe('number')+ expect(deletedPayload.sprint).toBeUndefined()+ }, 15000)++ it('delivers task.assignedToSprint on assignment and removal', async () => {+ receiver.clear()+ const sprint = await createPlanned('Assignment sprint')+ await receiver.waitForDelivery('sprint.created')++ const task = await $api.tasks.createTask({ goalId, description: `Assigned task-${Date.now()}` }).catch(console.error)+ if (!task) throw new Error('Failed to create task')++ receiver.clear()+ await $api.sprints.setTaskSprint({ taskId: task.id, sprintId: sprint.id })++ const assignedPayload = await receiver.waitForDelivery('task.assignedToSprint')+ expect(assignedPayload.taskId).toBe(task.id)+ expect(assignedPayload.sprintId).toBe(sprint.id)+ expect(assignedPayload.prevSprintId).toBeNull()+ expect(assignedPayload.goalId).toBe(goalId)++ receiver.clear()+ await $api.sprints.setTaskSprint({ taskId: task.id, sprintId: null })++ const removedPayload = await receiver.waitForDelivery('task.assignedToSprint')+ expect(removedPayload.taskId).toBe(task.id)+ expect(removedPayload.sprintId).toBeNull()+ expect(removedPayload.prevSprintId).toBe(sprint.id)++ await $api.tasks.deleteTask(task.id).catch(() => {})+ await $api.sprints.remove(sprint.id).catch(() => {})+ }, 20000)++ it('does not emit task.assignedToSprint when a close carries a task over', async () => {+ // Closing a sprint moves carried-over tasks directly; unlike setTaskSprint it+ // does NOT emit task.assignedToSprint. Only sprint.completed should fire.+ receiver.clear()+ const target = await createPlanned('Carry target (wh)')+ const source = await createPlanned('Carry source (wh)')+ const task = await $api.tasks.createTask({ goalId, description: `Carry task-${Date.now()}` }).catch(console.error)+ if (!task) throw new Error('Failed to create task')++ await $api.sprints.setTaskSprint({ taskId: task.id, sprintId: source.id })+ // Drain the legit assignment event before clearing, so its async delivery+ // can't bleed into the post-close window and be mistaken for a close emit.+ await receiver.waitForDelivery('task.assignedToSprint')+ await $api.sprints.activate(source.id)+ await $api.sprints.startReview(source.id)++ receiver.clear()+ await $api.sprints.close({+ sprintId: source.id,+ outcomes: [{ taskId: task.id, outcome: 'carried-over', carriedOverTo: target.id }],+ goalAchieved: false,+ })++ await receiver.waitForDelivery('sprint.completed')+ // Give any (erroneous) task.assignedToSprint delivery time to land, then assert none did.+ await new Promise((r) => setTimeout(r, 1500))+ const assignmentEvents = receiver.received.filter((r) => r.body?.event === 'task.assignedToSprint')+ expect(assignmentEvents.length).toBe(0)++ // The move still happened in the data, just without an assignment event.+ const moved = await $api.tasks.fetchTaskById(task.id).catch(console.error)+ expect(moved?.sprintId).toBe(target.id)++ await $api.tasks.deleteTask(task.id).catch(() => {})+ await $api.sprints.remove(target.id).catch(() => {})+ }, 25000)++ it('delivers only subscribed events to a narrowly-scoped webhook', async () => {+ // A dedicated receiver + a webhook subscribed ONLY to sprint.completed: it must+ // receive nothing for sprint.created, but must receive sprint.completed.+ const narrowReceiver = createWebhookReceiver()+ await narrowReceiver.start()+ const narrow = await $api.webhooks.create({+ goalId,+ url: narrowReceiver.getUrl(),+ events: ['sprint.completed'],+ }).catch(console.error)+ if (!narrow) throw new Error('Failed to create narrow webhook')++ try {+ const sprint = await createPlanned('Narrow-scope sprint')+ // sprint.created fired; let any delivery settle, then confirm the narrow webhook got nothing.+ await new Promise((r) => setTimeout(r, 1500))+ expect(narrowReceiver.received.length).toBe(0)++ await $api.sprints.activate(sprint.id)+ await $api.sprints.startReview(sprint.id)+ await $api.sprints.close({ sprintId: sprint.id, outcomes: [], goalAchieved: true })++ const completed = await narrowReceiver.waitForDelivery('sprint.completed')+ expect(completed.sprintId).toBe(sprint.id)+ // It only ever saw the one subscribed event.+ expect(narrowReceiver.received.every((r) => r.body?.event === 'sprint.completed')).toBe(true)+ } finally {+ await $api.webhooks.delete({ id: narrow.webhook.id }).catch(() => {})+ await narrowReceiver.stop()+ }+ }, 20000)+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/webhooks.test.ts b/taskview-packages/taskview-api/src/api/__tests__/webhooks.test.tsindex 2168ab0..3700b4c 100644--- a/taskview-packages/taskview-api/src/api/__tests__/webhooks.test.ts+++ b/taskview-packages/taskview-api/src/api/__tests__/webhooks.test.ts@@ -7,79 +7,7 @@ import {afterAll,} from 'vitest'import { initApi } from './init-api'-import { createServer, type IncomingMessage, type ServerResponse } from 'http'-import { networkInterfaces } from 'os'--function getLocalIp(): string {- const nets = networkInterfaces()- for (const name of Object.keys(nets)) {- for (const net of nets[name]!) {- if (net.family === 'IPv4' && !net.internal) {- return net.address- }- }- }- return '127.0.0.1'-}--function createWebhookReceiver() {- const received: Array<{ body: any; headers: Record<string, string | string[] | undefined> }> = []- const waiters: Array<(value: any) => void> = []-- const server = createServer((req: IncomingMessage, res: ServerResponse) => {- let body = ''- req.on('data', (chunk) => { body += chunk })- req.on('end', () => {- let parsed: any = null- try { parsed = JSON.parse(body) } catch { parsed = body }- received.push({ body: parsed, headers: req.headers })- if (waiters.length > 0) {- waiters.shift()!(parsed)- }- res.writeHead(200)- res.end('ok')- })- })-- const ip = getLocalIp()-- return {- server,- received,- getUrl: () => `http://${ip}:${(server.address() as any).port}/webhook`,- start: () => new Promise<void>((resolve) => {- server.listen(0, '0.0.0.0', () => resolve())- }),- stop: () => new Promise<void>((resolve) => {- server.close(() => resolve())- }),- clear: () => { received.length = 0 },- waitForDelivery: (event?: string, timeoutMs = 5000) => new Promise<any>((resolve, reject) => {- // check already received- const idx = event- ? received.findIndex(r => r.body?.event === event)- : received.length > 0 ? 0 : -1- if (idx >= 0) {- resolve(received[idx].body)- return- }-- const timer = setTimeout(() => {- reject(new Error(`No webhook delivery${event ? ` for ${event}` : ''} received within ${timeoutMs}ms`))- }, timeoutMs)-- const check = (payload: any) => {- if (!event || payload?.event === event) {- clearTimeout(timer)- resolve(payload)- } else {- waiters.push(check)- }- }- waiters.push(check)- }),- }-}+import { createWebhookReceiver } from './webhook-receiver'describe('Webhooks', () => {let $api: TvApidiff --git a/taskview-packages/taskview-api/src/api/collaboration.types.ts b/taskview-packages/taskview-api/src/api/collaboration.types.tsindex 109d6aa..74e2fc0 100644--- a/taskview-packages/taskview-api/src/api/collaboration.types.ts+++ b/taskview-packages/taskview-api/src/api/collaboration.types.ts@@ -49,7 +49,7 @@ export type CollaborationArgDeleteRoleFromGoal = {export type CollaborationResponseDeleteRoleFromGoal = boolean;//FIXME describe each group differently-export type PermissionGroupsIds = 1 | 2 | 3 | 4;+export type PermissionGroupsIds = 1 | 2 | 3 | 4 | 5;export type CollaborationPermission = {id: number;diff --git a/taskview-packages/taskview-api/src/api/goals.types.ts b/taskview-packages/taskview-api/src/api/goals.types.tsindex 85181b4..016af5f 100644--- a/taskview-packages/taskview-api/src/api/goals.types.ts+++ b/taskview-packages/taskview-api/src/api/goals.types.ts@@ -43,13 +43,14 @@ export type GoalItem = {archive: 1 | 0;dateCreation: string | null;organizationId: number | null;+ estimateUnit: 'hours' | 'points';};export type GoalArgItemAdd = Pick<GoalItem, 'name'> & Partial<Pick<GoalItem, 'description' | 'color' | 'organizationId'>>;export type GoalResponseAdd = GoalItem | null;-export type GoalArgItemUpdate = Pick<GoalItem, 'id'> & Partial<Pick<GoalItem, 'name' | 'description' | 'color' | 'archive'>>;+export type GoalArgItemUpdate = Pick<GoalItem, 'id'> & Partial<Pick<GoalItem, 'name' | 'description' | 'color' | 'archive' | 'estimateUnit'>>;export type GoalResponseUpdate = GoalItem | null;diff --git a/taskview-packages/taskview-api/src/api/kanban.ts b/taskview-packages/taskview-api/src/api/kanban.tsindex 22d9153..8056768 100644--- a/taskview-packages/taskview-api/src/api/kanban.ts+++ b/taskview-packages/taskview-api/src/api/kanban.ts@@ -15,6 +15,9 @@ export default class TvKanban extends TvApiBase {if (filters.assigneeIds && filters.assigneeIds.length > 0) {params.set('assigneeIds', filters.assigneeIds.join(','));}+ if (filters.sprintId !== undefined && filters.sprintId !== null) {+ params.set('sprintId', String(filters.sprintId));+ }}const query = params.toString();const url = `${this.moduleUrl}/tasks/${goalId}/${columnId}/${cursor}${query ? `?${query}` : ''}`;diff --git a/taskview-packages/taskview-api/src/api/kanban.types.ts b/taskview-packages/taskview-api/src/api/kanban.types.tsindex ed49b5c..fa9334a 100644--- a/taskview-packages/taskview-api/src/api/kanban.types.ts+++ b/taskview-packages/taskview-api/src/api/kanban.types.ts@@ -3,6 +3,8 @@ import type { Task } from "./tasks.api.types";export type KanbanFilters = {listIds?: number[];assigneeIds?: number[];+ /** Filter to a sprint by id. */+ sprintId?: number;};export type KanbanColumnItem = {diff --git a/taskview-packages/taskview-api/src/api/permissions.ts b/taskview-packages/taskview-api/src/api/permissions.tsindex 2481e34..14009a1 100644--- a/taskview-packages/taskview-api/src/api/permissions.ts+++ b/taskview-packages/taskview-api/src/api/permissions.ts@@ -147,6 +147,23 @@ export const TvPermissions: Record<Uppercase<keyof GoalPermissions>, keyof GoalP* Implies both view and log permissions.*/TIMETRACKING_CAN_MANAGE_ALL: 'timetracking_can_manage_all',++ /**+ * Can view the project's sprints+ */+ SPRINT_CAN_VIEW: 'sprint_can_view',+ /**+ * Can create/edit/activate/close sprints and manage sprint cadence+ */+ SPRINT_CAN_MANAGE: 'sprint_can_manage',+ /**+ * Can move tasks in and out of sprints+ */+ SPRINT_CAN_ASSIGN_TASKS: 'sprint_can_assign_tasks',+ /**+ * Can view sprint analytics (burndown, velocity)+ */+ SPRINT_CAN_VIEW_ANALYTICS: 'sprint_can_view_analytics',} as const;export type GoalPermissions = {@@ -195,4 +212,9 @@ export type GoalPermissions = {timetracking_can_view?: true;timetracking_can_log?: true;timetracking_can_manage_all?: true;++ sprint_can_view?: true;+ sprint_can_manage?: true;+ sprint_can_assign_tasks?: true;+ sprint_can_view_analytics?: true;};\ No newline at end of filediff --git a/taskview-packages/taskview-api/src/api/sprints.ts b/taskview-packages/taskview-api/src/api/sprints.tsnew file mode 100644index 0000000..b95a700--- /dev/null+++ b/taskview-packages/taskview-api/src/api/sprints.ts@@ -0,0 +1,122 @@+import TvApiBase from './base';+import type { AppResponse } from './base.types';+import type {+ Sprint,+ SprintBurndown,+ SprintCadence,+ SprintCloseArgs,+ SprintCreateArgs,+ SprintListFilterArgs,+ SprintPlanningArgs,+ SprintPlanningPage,+ SprintSaveRetroArgs,+ SprintSetCadenceArgs,+ SprintSetTaskArgs,+ SprintUpdateArgs,+ SprintVelocityArgs,+ SprintVelocityPoint,+ SprintWithRetro,+} from './sprints.types';++export default class TvSprintApi extends TvApiBase {+ protected moduleUrl = '/module/sprints';++ public async listForGoal(args: SprintListFilterArgs) {+ const query = args.status ? `?status=${encodeURIComponent(args.status)}` : '';+ return this.request(this.$axios.get<AppResponse<Sprint[]>>(`${this.moduleUrl}/${args.goalId}${query}`));+ }++ public async getById(sprintId: number) {+ return this.request(+ this.$axios.get<AppResponse<SprintWithRetro | null>>(`${this.moduleUrl}/sprint/${sprintId}`)+ );+ }++ public async getBurndown(sprintId: number) {+ return this.request(+ this.$axios.get<AppResponse<SprintBurndown | null>>(`${this.moduleUrl}/sprint/${sprintId}/burndown`)+ );+ }++ public async getPlanningTasks(args: SprintPlanningArgs) {+ const params = new URLSearchParams();+ params.set('scope', args.scope);+ if (args.cursor != null) params.set('cursor', String(args.cursor));+ if (args.limit != null) params.set('limit', String(args.limit));+ return this.request(+ this.$axios.get<AppResponse<SprintPlanningPage>>(+ `${this.moduleUrl}/sprint/${args.sprintId}/planning?${params.toString()}`+ )+ );+ }++ public async getVelocity(args: SprintVelocityArgs) {+ const query = args.lastN ? `?lastN=${args.lastN}` : '';+ return this.request(+ this.$axios.get<AppResponse<SprintVelocityPoint[]>>(`${this.moduleUrl}/goal/${args.goalId}/velocity${query}`)+ );+ }++ public async create(args: SprintCreateArgs) {+ return this.request(this.$axios.post<AppResponse<Sprint>>(`${this.moduleUrl}`, args));+ }++ public async update(args: SprintUpdateArgs) {+ const { sprintId, ...body } = args;+ return this.request(this.$axios.patch<AppResponse<Sprint>>(`${this.moduleUrl}/sprint/${sprintId}`, body));+ }++ public async activate(sprintId: number) {+ return this.request(this.$axios.post<AppResponse<Sprint>>(`${this.moduleUrl}/sprint/${sprintId}/activate`, {}));+ }++ public async startReview(sprintId: number) {+ return this.request(this.$axios.post<AppResponse<Sprint>>(`${this.moduleUrl}/sprint/${sprintId}/review`, {}));+ }++ public async close(args: SprintCloseArgs) {+ const { sprintId, ...body } = args;+ return this.request(this.$axios.post<AppResponse<Sprint>>(`${this.moduleUrl}/sprint/${sprintId}/close`, body));+ }++ public async pause(sprintId: number) {+ return this.request(this.$axios.post<AppResponse<Sprint>>(`${this.moduleUrl}/sprint/${sprintId}/pause`, {}));+ }++ public async resume(sprintId: number) {+ return this.request(this.$axios.post<AppResponse<Sprint>>(`${this.moduleUrl}/sprint/${sprintId}/resume`, {}));+ }++ public async remove(sprintId: number) {+ return this.request(this.$axios.delete<AppResponse<boolean>>(`${this.moduleUrl}/sprint/${sprintId}`));+ }++ public async saveRetro(args: SprintSaveRetroArgs) {+ const { sprintId, ...body } = args;+ return this.request(+ this.$axios.put<AppResponse<SprintSaveRetroArgs>>(`${this.moduleUrl}/sprint/${sprintId}/retro`, body)+ );+ }++ public async setTaskSprint(args: SprintSetTaskArgs) {+ return this.request(+ this.$axios.patch<AppResponse<{ taskId: number; sprintId: number | null }>>(+ `${this.moduleUrl}/task/${args.taskId}/sprint`,+ { sprintId: args.sprintId }+ )+ );+ }++ public async getCadence(goalId: number) {+ return this.request(+ this.$axios.get<AppResponse<SprintCadence | null>>(`${this.moduleUrl}/goal/${goalId}/cadence`)+ );+ }++ public async setCadence(args: SprintSetCadenceArgs) {+ const { goalId, ...body } = args;+ return this.request(+ this.$axios.put<AppResponse<SprintCadence>>(`${this.moduleUrl}/goal/${goalId}/cadence`, body)+ );+ }+}diff --git a/taskview-packages/taskview-api/src/api/sprints.types.ts b/taskview-packages/taskview-api/src/api/sprints.types.tsnew file mode 100644index 0000000..6ed8f46--- /dev/null+++ b/taskview-packages/taskview-api/src/api/sprints.types.ts@@ -0,0 +1,133 @@+import type { Task } from './tasks.api.types';++export type SprintStatus = 'draft' | 'planned' | 'active' | 'review' | 'completed';++export type Sprint = {+ id: number;+ goalId: number;+ name: string;+ goalText: string | null;+ goalAchieved: boolean | null;+ status: SprintStatus;+ startDate: string;+ endDate: string;+ capacity: string | null;+ pausedAt: string | null;+ creatorId: number | null;+ createdAt: string;+ editedAt: string;+ reviewStartedAt: string | null;+ completedAt: string | null;+};++export type SprintRetro = {+ wentWell: string | null;+ wentBad: string | null;+ actionItems: string | null;+};++export type SprintWithRetro = Sprint & { retro: SprintRetro | null };++export type SprintCreateArgs = {+ goalId: number;+ name: string;+ startDate: string;+ endDate: string;+ goalText?: string | null;+ capacity?: number | null;+};++export type SprintUpdateArgs = {+ sprintId: number;+ name?: string;+ startDate?: string;+ endDate?: string;+ goalText?: string | null;+ capacity?: number | null;+};++export type SprintOutcome = 'accepted' | 'carried-over' | 'dropped';++export type SprintTaskOutcomeInput = {+ taskId: number;+ outcome: SprintOutcome;+ carriedOverTo?: number | null;+};++export type SprintCloseArgs = {+ sprintId: number;+ outcomes: SprintTaskOutcomeInput[];+ goalAchieved: boolean;+};++export type SprintSaveRetroArgs = {+ sprintId: number;+ wentWell?: string | null;+ wentBad?: string | null;+ actionItems?: string | null;+};++export type SprintSetTaskArgs = {+ taskId: number;+ sprintId: number | null;+};++export type SprintListFilterArgs = {+ goalId: number;+ /** comma-separated subset, e.g. 'active,planned' */+ status?: string;+};++export type SprintVelocityArgs = {+ goalId: number;+ lastN?: number;+};++export type SprintPlanningScope = 'backlog' | 'sprint';++export type SprintPlanningArgs = {+ sprintId: number;+ scope: SprintPlanningScope;+ cursor?: number;+ limit?: number;+};++/** Backlog scope: tasks + cursor only. */+export type SprintPlanningBacklogPage = {+ tasks: Task[];+ nextCursor: number | null;+};++/** Sprint scope: tasks + cursor + capacity counter (sum of all in-sprint estimates). */+export type SprintPlanningSprintPage = {+ tasks: Task[];+ nextCursor: number | null;+ totalPoints: number;+};++export type SprintPlanningPage = SprintPlanningBacklogPage | SprintPlanningSprintPage;++export type SprintBurndownPoint = { date: string; remainingHours: number; idealHours: number };+export type SprintBurndown = { total: number; points: SprintBurndownPoint[] };+export type SprintVelocityPoint = { sprintId: number; name: string; acceptedHours: number; plannedHours: number };++export type SprintCadence = {+ goalId: number;+ enabled: boolean;+ lengthDays: number;+ startDate: string;+ lookahead: number;+ nameTemplate: string;+ lastGeneratedDate: string | null;+ createdAt: string;+ editedAt: string;+};++export type SprintSetCadenceArgs = {+ goalId: number;+ enabled: boolean;+ lengthDays?: number;+ startDate?: string;+ lookahead?: number;+ nameTemplate?: string;+};diff --git a/taskview-packages/taskview-api/src/api/tasks.api.types.ts b/taskview-packages/taskview-api/src/api/tasks.api.types.tsindex fb56839..265b733 100644--- a/taskview-packages/taskview-api/src/api/tasks.api.types.ts+++ b/taskview-packages/taskview-api/src/api/tasks.api.types.ts@@ -31,6 +31,9 @@ export interface TaskBase {nodeGraphPosition: Record<'x' | 'y', number> | null;creatorId: number | null;sourceUrl: string | null;++ sprintId: number | null;+ estimateValue: number | string | null;}export interface Task extends TaskBase {@@ -40,7 +43,8 @@ export interface Task extends TaskBase {};// we can not update defined fields-type NotAllowedToUpdate = 'id' | 'goalId' | 'owner' | 'dateCreation' | 'dateComplete' | 'historyId';+// sprintId is managed via the sprints module; dateComplete is trigger-maintained.+type NotAllowedToUpdate = 'id' | 'goalId' | 'owner' | 'dateCreation' | 'dateComplete' | 'historyId' | 'sprintId';export type TaskArgUpdate = Pick<Task, 'id'> & Partial<Omit<Task, NotAllowedToUpdate>>;export type TaskResponseUpdate = (Task & { syncFailed?: boolean }) | null;diff --git a/taskview-packages/taskview-api/src/api/webhooks.types.ts b/taskview-packages/taskview-api/src/api/webhooks.types.tsindex 070bb89..fe97205 100644--- a/taskview-packages/taskview-api/src/api/webhooks.types.ts+++ b/taskview-packages/taskview-api/src/api/webhooks.types.ts@@ -52,6 +52,15 @@ export const WEBHOOK_EVENTS = ['time-entry.created','time-entry.updated','time-entry.deleted',+ 'sprint.created',+ 'sprint.updated',+ 'sprint.activated',+ 'sprint.reviewStarted',+ 'sprint.completed',+ 'sprint.paused',+ 'sprint.resumed',+ 'sprint.deleted',+ 'task.assignedToSprint',] as const;export type WebhookEvent = typeof WEBHOOK_EVENTS[number];diff --git a/taskview-packages/taskview-api/src/index.ts b/taskview-packages/taskview-api/src/index.tsindex 01687a3..37f9d6c 100644--- a/taskview-packages/taskview-api/src/index.ts+++ b/taskview-packages/taskview-api/src/index.ts@@ -18,4 +18,5 @@ export * from '@/api/organizations.types';export * from '@/api/sso.types';export * from '@/api/analytics.types';export * from '@/api/time-tracking.types';-export * from '@/api/ui-preferences.types';\ No newline at end of file+export * from '@/api/ui-preferences.types';+export * from '@/api/sprints.types';\ No newline at end of filediff --git a/taskview-packages/taskview-api/src/tv.ts b/taskview-packages/taskview-api/src/tv.tsindex 4ac5801..cbd8eca 100644--- a/taskview-packages/taskview-api/src/tv.ts+++ b/taskview-packages/taskview-api/src/tv.ts@@ -16,6 +16,7 @@ import TvSsoApi from "./api/sso";import TvAnalyticsApi from "./api/analytics";import TvTimeTrackingApi from "./api/time-tracking";import TvUiPreferencesApi from "./api/ui-preferences";+import TvSprintApi from "./api/sprints";export class TvApi {@@ -55,6 +56,8 @@ export class TvApi {public uiPreferences: TvUiPreferencesApi;+ public sprints: TvSprintApi;+constructor($axios: AxiosInstance) {this.$axios = $axios;@@ -91,6 +94,8 @@ export class TvApi {this.timeTracking = new TvTimeTrackingApi(this.$axios);this.uiPreferences = new TvUiPreferencesApi(this.$axios);++ this.sprints = new TvSprintApi(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 6fcc40e..614e105 100644--- a/taskview-packages/taskview-db-schemas/src/index.ts+++ b/taskview-packages/taskview-db-schemas/src/index.ts@@ -20,3 +20,8 @@ export * from './schemas/sso.schema';export * from './schemas/time-entries.schema';export * from './schemas/time-entries-history.schema';export * from './schemas/ui-preferences.schema';+export * from './schemas/sprints.schema';+export * from './schemas/sprint-task-outcomes.schema';+export * from './schemas/sprint-user-capacity.schema';+export * from './schemas/sprint-retros.schema';+export * from './schemas/sprint-cadence.schema';diff --git a/taskview-packages/taskview-db-schemas/src/schemas/goals.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/goals.schema.tsindex 264a9f4..4922395 100644--- a/taskview-packages/taskview-db-schemas/src/schemas/goals.schema.ts+++ b/taskview-packages/taskview-db-schemas/src/schemas/goals.schema.ts@@ -15,6 +15,7 @@ export const GoalsSchema = pgSchema('tasks').table('goals', {archive: integer().notNull().default(0),backlogVersion: integer('backlog_version').default(1),organizationId: integer('organization_id').references(() => OrganizationsSchema.id, { onDelete: 'cascade' }),+ estimateUnit: varchar('estimate_unit', { length: 10 }).$type<'hours' | 'points'>().notNull().default('points'),});export type GoalsSchemaTypeForSelect = typeof GoalsSchema.$inferSelect;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/notifications.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/notifications.schema.tsindex 5fb8b7a..c0944e0 100644--- a/taskview-packages/taskview-db-schemas/src/schemas/notifications.schema.ts+++ b/taskview-packages/taskview-db-schemas/src/schemas/notifications.schema.ts@@ -1,6 +1,7 @@import { integer, pgSchema, varchar, boolean, timestamp } from "drizzle-orm/pg-core";import { TasksSchema } from "./tasks.schema";import { UsersSchema } from "./users.schema";+import { SprintsSchema } from "./sprints.schema";export const NotificationsSchema = pgSchema('tasks').table('notifications', {id: integer().primaryKey().generatedAlwaysAsIdentity(),@@ -11,6 +12,7 @@ export const NotificationsSchema = pgSchema('tasks').table('notifications', {body: varchar({ length: 1000 }),read: boolean().notNull().default(false),createdAt: timestamp('created_at').notNull().defaultNow(),+ sprintId: integer('sprint_id').references(() => SprintsSchema.id, { onDelete: 'cascade' }),});export type NotificationsSchemaTypeForSelect = typeof NotificationsSchema.$inferSelect;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/sprint-cadence.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/sprint-cadence.schema.tsnew file mode 100644index 0000000..b0d1df0--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/sprint-cadence.schema.ts@@ -0,0 +1,17 @@+import { boolean, date, integer, pgSchema, timestamp, varchar } from "drizzle-orm/pg-core";+import { GoalsSchema } from "./goals.schema";++export const SprintCadenceSchema = pgSchema('tasks').table('sprint_cadence', {+ goalId: integer('goal_id').primaryKey().references(() => GoalsSchema.id, { onDelete: 'cascade' }),+ enabled: boolean().notNull().default(false),+ lengthDays: integer('length_days').notNull().default(14),+ startDate: date('start_date').notNull(),+ lookahead: integer().notNull().default(2),+ nameTemplate: varchar('name_template', { length: 100 }).notNull().default('Sprint {n}'),+ lastGeneratedDate: date('last_generated_date'),+ createdAt: timestamp('created_at').notNull().defaultNow(),+ editedAt: timestamp('edited_at').notNull().defaultNow(),+});++export type SprintCadenceSchemaTypeForSelect = typeof SprintCadenceSchema.$inferSelect;+export type SprintCadenceSchemaTypeForInsert = typeof SprintCadenceSchema.$inferInsert;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/sprint-retros.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/sprint-retros.schema.tsnew file mode 100644index 0000000..5551b52--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/sprint-retros.schema.ts@@ -0,0 +1,15 @@+import { integer, pgSchema, text, timestamp } from "drizzle-orm/pg-core";+import { SprintsSchema } from "./sprints.schema";+import { UsersSchema } from "./users.schema";++export const SprintRetrosSchema = pgSchema('tasks').table('sprint_retros', {+ sprintId: integer('sprint_id').primaryKey().references(() => SprintsSchema.id, { onDelete: 'cascade' }),+ wentWell: text('went_well'),+ wentBad: text('went_bad'),+ actionItems: text('action_items'),+ editedAt: timestamp('edited_at').notNull().defaultNow(),+ editedBy: integer('edited_by').references(() => UsersSchema.id),+});++export type SprintRetrosSchemaTypeForSelect = typeof SprintRetrosSchema.$inferSelect;+export type SprintRetrosSchemaTypeForInsert = typeof SprintRetrosSchema.$inferInsert;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/sprint-task-outcomes.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/sprint-task-outcomes.schema.tsnew file mode 100644index 0000000..2783b53--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/sprint-task-outcomes.schema.ts@@ -0,0 +1,22 @@+import { integer, numeric, pgSchema, primaryKey, timestamp, varchar } from "drizzle-orm/pg-core";+import { SprintsSchema } from "./sprints.schema";+import { TasksSchema } from "./tasks.schema";+import { UsersSchema } from "./users.schema";++export type SprintOutcome = 'accepted' | 'carried-over' | 'dropped' | 'incomplete';++export const SprintTaskOutcomesSchema = pgSchema('tasks').table('sprint_task_outcomes', {+ sprintId: integer('sprint_id').notNull().references(() => SprintsSchema.id, { onDelete: 'cascade' }),+ taskId: integer('task_id').notNull().references(() => TasksSchema.id, { onDelete: 'cascade' }),+ outcome: varchar({ length: 20 }).$type<SprintOutcome>().notNull(),+ carriedOverTo: integer('carried_over_to').references(() => SprintsSchema.id, { onDelete: 'set null' }),+ decidedBy: integer('decided_by').references(() => UsersSchema.id),+ decidedAt: timestamp('decided_at').notNull().defaultNow(),+ // Snapshot of the task's estimate captured at sprint close — frozen history.+ estimateValue: numeric('estimate_value', { precision: 10, scale: 2 }),+}, (table) => [+ primaryKey({ columns: [table.sprintId, table.taskId] }),+]);++export type SprintTaskOutcomesSchemaTypeForSelect = typeof SprintTaskOutcomesSchema.$inferSelect;+export type SprintTaskOutcomesSchemaTypeForInsert = typeof SprintTaskOutcomesSchema.$inferInsert;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/sprint-user-capacity.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/sprint-user-capacity.schema.tsnew file mode 100644index 0000000..42ea0b4--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/sprint-user-capacity.schema.ts@@ -0,0 +1,14 @@+import { integer, numeric, pgSchema, primaryKey } from "drizzle-orm/pg-core";+import { SprintsSchema } from "./sprints.schema";+import { UsersSchema } from "./users.schema";++export const SprintUserCapacitySchema = pgSchema('tasks').table('sprint_user_capacity', {+ sprintId: integer('sprint_id').notNull().references(() => SprintsSchema.id, { onDelete: 'cascade' }),+ userId: integer('user_id').notNull().references(() => UsersSchema.id, { onDelete: 'cascade' }),+ hours: numeric({ precision: 10, scale: 2 }).notNull(),+}, (table) => [+ primaryKey({ columns: [table.sprintId, table.userId] }),+]);++export type SprintUserCapacitySchemaTypeForSelect = typeof SprintUserCapacitySchema.$inferSelect;+export type SprintUserCapacitySchemaTypeForInsert = typeof SprintUserCapacitySchema.$inferInsert;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/sprints.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/sprints.schema.tsnew file mode 100644index 0000000..f49130a--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/sprints.schema.ts@@ -0,0 +1,26 @@+import { boolean, date, integer, numeric, pgSchema, timestamp, varchar } from "drizzle-orm/pg-core";+import { GoalsSchema } from "./goals.schema";+import { UsersSchema } from "./users.schema";++export type SprintStatus = 'draft' | 'planned' | 'active' | 'review' | 'completed';++export const SprintsSchema = pgSchema('tasks').table('sprints', {+ id: integer().primaryKey().generatedAlwaysAsIdentity(),+ goalId: integer('goal_id').notNull().references(() => GoalsSchema.id, { onDelete: 'cascade' }),+ name: varchar({ length: 255 }).notNull(),+ goalText: varchar('goal_text', { length: 2000 }),+ goalAchieved: boolean('goal_achieved'),+ status: varchar({ length: 20 }).$type<SprintStatus>().notNull().default('draft'),+ startDate: date('start_date').notNull(),+ endDate: date('end_date').notNull(),+ capacity: numeric('capacity', { precision: 10, scale: 2 }),+ pausedAt: timestamp('paused_at'),+ creatorId: integer('creator_id').references(() => UsersSchema.id),+ createdAt: timestamp('created_at').notNull().defaultNow(),+ editedAt: timestamp('edited_at').notNull().defaultNow(),+ reviewStartedAt: timestamp('review_started_at'),+ completedAt: timestamp('completed_at'),+});++export type SprintsSchemaTypeForSelect = typeof SprintsSchema.$inferSelect;+export type SprintsSchemaTypeForInsert = typeof SprintsSchema.$inferInsert;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/tasks.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/tasks.schema.tsindex 44e8452..d1ae6e8 100644--- a/taskview-packages/taskview-db-schemas/src/schemas/tasks.schema.ts+++ b/taskview-packages/taskview-db-schemas/src/schemas/tasks.schema.ts@@ -1,4 +1,4 @@-import { integer, numeric, pgSchema, varchar, boolean, date, time, jsonb } from "drizzle-orm/pg-core";+import { integer, numeric, pgSchema, varchar, boolean, date, time, jsonb, timestamp } from "drizzle-orm/pg-core";import { createInsertSchema } from 'drizzle-arktype';import { UsersSchema } from "./users.schema";@@ -24,6 +24,9 @@ export const TasksSchema = pgSchema('tasks').table('tasks', {transactionType: integer('transaction_type').$type<1 | 0 | null>(),nodeGraphPosition: jsonb('node_graph_position'),sourceUrl: varchar('source_url', { length: 500 }),+ sprintId: integer('sprint_id'),+ estimateValue: numeric('estimate_value', { precision: 10, scale: 2 }),+ dateComplete: timestamp('date_complete'),});export type TasksSchemaTypeForSelect = typeof TasksSchema.$inferSelect;diff --git a/web/src/components/features/base/TvKanbanFilters.vue b/web/src/components/features/base/TvKanbanFilters.vueindex 0e66427..532481d 100644--- a/web/src/components/features/base/TvKanbanFilters.vue+++ b/web/src/components/features/base/TvKanbanFilters.vue@@ -1,4 +1,8 @@<template>+ <TvKanbanSprintFilter+ v-model="sprintId"+ :goal-id="goalId"+ /><TvListFilter v-model="listIds" /><TvUserFilter v-model="assigneeIds" /><UButton@@ -19,8 +23,10 @@ import { computed } from 'vue'import { useI18n } from 'vue-i18n'import TvListFilter from './TvListFilter.vue'import TvUserFilter from './TvUserFilter.vue'+import TvKanbanSprintFilter from './TvKanbanSprintFilter.vue'withDefaults(defineProps<{+ goalId: numbershowResetLabel?: boolean}>(), {showResetLabel: false,@@ -28,14 +34,18 @@ withDefaults(defineProps<{const listIds = defineModel<number[]>('listIds', { default: () => [] })const assigneeIds = defineModel<number[]>('assigneeIds', { default: () => [] })+const sprintId = defineModel<number | null>('sprintId', { default: null })const { t } = useI18n()-const hasActiveFilters = computed(() => listIds.value.length > 0 || assigneeIds.value.length > 0)+const hasActiveFilters = computed(+ () => listIds.value.length > 0 || assigneeIds.value.length > 0 || sprintId.value !== null,+)const resetFilters = () => {listIds.value = []assigneeIds.value = []+ sprintId.value = null}defineExpose({ hasActiveFilters })diff --git a/web/src/components/features/base/TvKanbanSprintFilter.vue b/web/src/components/features/base/TvKanbanSprintFilter.vuenew file mode 100644index 0000000..452b7f3--- /dev/null+++ b/web/src/components/features/base/TvKanbanSprintFilter.vue@@ -0,0 +1,96 @@+<template>+ <USelectMenu+ v-if="canView"+ :model-value="selectedValue"+ :items="options"+ value-key="value"+ :search-input="false"+ size="sm"+ variant="subtle"+ class="min-w-40 max-w-56 shrink-0 [&>button]:truncate"+ @update:model-value="onSelect"+ @update:open="onOpen"+ >+ <template #leading>+ <UIcon+ name="i-lucide-rocket"+ class="size-4"+ />+ </template>+ </USelectMenu>+</template>++<script setup lang="ts">+import { computed, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import type { Sprint } from 'taskview-api'+import { $tvApi } from '@/plugins/axios'+import { logError } from '@/helpers/Helper'+import { useGoalsStore } from '@/stores/goals.store'+import { useGoalPermissionsFor } from '@/composables/useGoalPermissions'++const props = defineProps<{+ goalId: number+}>()++const model = defineModel<number | null>({ default: null })++const ALL_VALUE = 'all'+const CURRENT_VALUE = 'current'++const { t } = useI18n()+const goalsStore = useGoalsStore()++const sprints = ref<Sprint[]>([])+const loadedGoalId = ref<number | null>(null)++const goal = computed(() => goalsStore.goalMap.get(props.goalId) ?? null)+const { canViewSprints: canView } = useGoalPermissionsFor(goal)++const activeSprintId = computed(() => sprints.value.find((s) => s.status === 'active')?.id ?? null)++const options = computed(() => [+ { label: t('kanban.sprintFilter.all'), value: ALL_VALUE },+ ...(activeSprintId.value != null+ ? [{ label: t('kanban.sprintFilter.current'), value: CURRENT_VALUE }]+ : []),+ ...sprints.value.map((s) => ({ label: s.name, value: String(s.id) })),+])++const selectedValue = computed(() => {+ if (model.value == null) return ALL_VALUE+ if (model.value === activeSprintId.value) return CURRENT_VALUE+ return String(model.value)+})++const onSelect = (value: string) => {+ if (value === ALL_VALUE) {+ model.value = null+ } else if (value === CURRENT_VALUE) {+ model.value = activeSprintId.value+ } else {+ model.value = Number(value)+ }+}++const loadSprints = async (force = false) => {+ if (!canView.value) return+ if (!force && loadedGoalId.value === props.goalId) return+ const result = await $tvApi.sprints.listForGoal({ goalId: props.goalId }).catch(logError)+ if (!result) return+ sprints.value = result+ loadedGoalId.value = props.goalId+}++// Refetch on open so the list (and which sprint is "current") stays fresh+// when a sprint is activated/closed elsewhere.+const onOpen = (open: boolean) => {+ if (open) loadSprints(true)+}++watch(+ () => [props.goalId, canView.value] as const,+ () => loadSprints(),+ { immediate: true },+)+</script>diff --git a/web/src/components/features/graph/ProjectGraph.vue b/web/src/components/features/graph/ProjectGraph.vueindex 518f075..2d2910e 100644--- a/web/src/components/features/graph/ProjectGraph.vue+++ b/web/src/components/features/graph/ProjectGraph.vue@@ -100,6 +100,7 @@ import TaskNode from './TaskNode.vue'const listIds = defineModel<number[]>('listIds', { default: () => [] })const assigneeIds = defineModel<number[]>('assigneeIds', { default: () => [] })+const sprintId = defineModel<number | null>('sprintId', { default: null })const applyFilters = () => {let filtered = [...store.allNodes]@@ -111,6 +112,9 @@ const applyFilters = () => {n.data.task.assignedUsers?.some((id: number) => assigneeIds.value.includes(id)),)}+ if (sprintId.value != null) {+ filtered = filtered.filter((n) => n.data.task.sprintId === sprintId.value)+ }const nodeIds = new Set(filtered.map((n) => n.id))store.nodes = filteredstore.edges = store.allEdges.filter((e) => nodeIds.has(e.source) && nodeIds.has(e.target))@@ -119,6 +123,7 @@ const applyFilters = () => {watch(listIds, applyFilters, { deep: true })watch(assigneeIds, applyFilters, { deep: true })+watch(sprintId, applyFilters)const {fitView,diff --git a/web/src/components/features/projects/ArchiveList.vue b/web/src/components/features/projects/ArchiveList.vueindex defc1fe..428b61e 100644--- a/web/src/components/features/projects/ArchiveList.vue+++ b/web/src/components/features/projects/ArchiveList.vue@@ -14,14 +14,14 @@<script setup lang="ts">import { useI18n } from 'vue-i18n'import ProjectListBase from '@/components/features/projects/parts/ProjectListBase.vue'-import type { Project } from '@/components/features/projects/types'+import type { Project, ProjectSaveData } from '@/components/features/projects/types'defineProps<{projects: Project[]}>()const emit = defineEmits<{- save: [project: Project, data: { name: string; description: string }]+ save: [project: Project, data: ProjectSaveData]delete: [project: Project]restore: [project: Project]}>()@@ -30,7 +30,7 @@ const { t } = useI18n()const open = defineModel<boolean>('open', { required: false, default: false })-function handleSave(project: Project, data: { name: string; description: string }) {+function handleSave(project: Project, data: ProjectSaveData) {emit('save', project, data)}diff --git a/web/src/components/features/projects/ProjectsList.vue b/web/src/components/features/projects/ProjectsList.vueindex e60a467..b0283f7 100644--- a/web/src/components/features/projects/ProjectsList.vue+++ b/web/src/components/features/projects/ProjectsList.vue@@ -13,14 +13,14 @@<script setup lang="ts">import { useI18n } from 'vue-i18n'import ProjectListBase from '@/components/features/projects/parts/ProjectListBase.vue'-import type { Project } from '@/components/features/projects/types'+import type { Project, ProjectSaveData } from '@/components/features/projects/types'defineProps<{projects: Project[]}>()const emit = defineEmits<{- save: [project: Project, data: { name: string; description: string }]+ save: [project: Project, data: ProjectSaveData]delete: [project: Project]archive: [project: Project]add: [name: string]@@ -30,7 +30,7 @@ const { t } = useI18n()const open = defineModel<boolean>('open', { required: false, default: true })-function handleSave(project: Project, data: { name: string; description: string }) {+function handleSave(project: Project, data: ProjectSaveData) {emit('save', project, data)}diff --git a/web/src/components/features/projects/ProjectsSidebar.vue b/web/src/components/features/projects/ProjectsSidebar.vueindex a100129..0928b13 100644--- a/web/src/components/features/projects/ProjectsSidebar.vue+++ b/web/src/components/features/projects/ProjectsSidebar.vue@@ -24,7 +24,7 @@ import { useGoalsStore } from '@/stores/goals.store'import { useOrganizationStore } from '@/stores/organization.store'import ProjectsList from '@/components/features/projects/ProjectsList.vue'import ArchiveList from '@/components/features/projects/ArchiveList.vue'-import type { Project } from '@/components/features/projects/types'+import type { Project, ProjectSaveData } from '@/components/features/projects/types'import { ALL_TASKS_LIST_ID } from 'taskview-api'const router = useRouter()@@ -42,11 +42,12 @@ watch(() => orgStore.currentOrg, async () => {await goalsStore.fetchGoals()})-async function handleSave(project: Project, data: { name: string; description: string }) {+async function handleSave(project: Project, data: ProjectSaveData) {await goalsStore.updateGoal({id: project.id,name: data.name,description: data.description,+ estimateUnit: data.estimateUnit,})}diff --git a/web/src/components/features/projects/parts/ProjectEditModal.vue b/web/src/components/features/projects/parts/ProjectEditModal.vueindex d406935..921fb6d 100644--- a/web/src/components/features/projects/parts/ProjectEditModal.vue+++ b/web/src/components/features/projects/parts/ProjectEditModal.vue@@ -24,6 +24,14 @@class="w-full"/></UFormField>+ <UFormField :label="t('projects.estimateUnit')">+ <USelect+ v-model="form.estimateUnit"+ :items="estimateUnitItems"+ class="w-full"+ data-testid="project-edit-estimate-unit"+ />+ </UFormField></div></template>@@ -48,9 +56,9 @@</template><script setup lang="ts">-import { reactive, watch } from 'vue'+import { computed, reactive, watch } from 'vue'import { useI18n } from 'vue-i18n'-import type { Project } from '@/components/features/projects/types'+import type { Project, ProjectSaveData } from '@/components/features/projects/types'const props = defineProps<{project: Project | null@@ -59,22 +67,29 @@ const props = defineProps<{const isOpen = defineModel<boolean>('open', { required: true })const emit = defineEmits<{- save: [data: { name: string; description: string }]+ save: [data: ProjectSaveData]}>()const { t } = useI18n()-const form = reactive({+const form = reactive<ProjectSaveData>({name: '',description: '',+ estimateUnit: 'points',})+const estimateUnitItems = computed(() => [+ { label: t('projects.estimateUnitPoints'), value: 'points' as const },+ { label: t('projects.estimateUnitHours'), value: 'hours' as const },+])+watch(() => props.project,(project) => {if (project) {form.name = project.nameform.description = project.description || ''+ form.estimateUnit = project.estimateUnit ?? 'points'}},{ immediate: true },@@ -85,7 +100,7 @@ function close() {}function save() {- emit('save', { name: form.name, description: form.description })+ emit('save', { name: form.name, description: form.description, estimateUnit: form.estimateUnit })close()}</script>diff --git a/web/src/components/features/projects/parts/ProjectListBase.vue b/web/src/components/features/projects/parts/ProjectListBase.vueindex 1e1cf03..74662f9 100644--- a/web/src/components/features/projects/parts/ProjectListBase.vue+++ b/web/src/components/features/projects/parts/ProjectListBase.vue@@ -74,6 +74,17 @@:to="{ name: 'graph', params: { projectId: selectedProject?.id } }"@click="contextMenu?.close()"/>+ <!-- Sprints -->+ <UButton+ v-if="canViewSprints"+ :label="t('contextMenu.sprints')"+ icon="i-lucide-rocket"+ variant="ghost"+ color="neutral"+ class="w-full justify-start"+ :to="{ name: 'sprints', params: { projectId: selectedProject?.id } }"+ @click="contextMenu?.close()"+ /><!-- Collaboration --><UButtonv-if="canManageUsers"@@ -195,7 +206,7 @@ import TvContextMenu from '@/components/features/base/TvContextMenu.vue'import ProjectEditModal from '@/components/features/projects/parts/ProjectEditModal.vue'import ProjectDeleteDialog from '@/components/features/projects/parts/ProjectDeleteDialog.vue'import ProjectAddInput from '@/components/features/projects/parts/ProjectAddInput.vue'-import type { Project } from '@/components/features/projects/types'+import type { Project, ProjectSaveData } from '@/components/features/projects/types'import { useGoalPermissionsFor } from '@/composables/useGoalPermissions'import { useI18n } from 'vue-i18n'@@ -214,7 +225,7 @@ withDefaults()const emit = defineEmits<{- save: [project: Project, data: { name: string; description: string }]+ save: [project: Project, data: ProjectSaveData]delete: [project: Project]archive: [project: Project]restore: [project: Project]@@ -237,6 +248,7 @@ const {canManageUsers,canEditGoal,canDeleteGoal,+ canViewSprints,} = useGoalPermissionsFor(selectedProject)const isEditModalOpen = ref(false)@@ -253,7 +265,7 @@ function openEditModal() {isEditModalOpen.value = true}-function handleSave(data: { name: string; description: string }) {+function handleSave(data: ProjectSaveData) {if (selectedProject.value) {emit('save', selectedProject.value, data)}diff --git a/web/src/components/features/projects/types.ts b/web/src/components/features/projects/types.tsindex 7f7dc8c..7777193 100644--- a/web/src/components/features/projects/types.ts+++ b/web/src/components/features/projects/types.ts@@ -1,3 +1,9 @@import type { GoalItem } from 'taskview-api'export type Project = GoalItem++export type ProjectSaveData = {+ name: string+ description: string+ estimateUnit: 'hours' | 'points'+}diff --git a/web/src/components/features/sprints/composables/useSprintFormat.ts b/web/src/components/features/sprints/composables/useSprintFormat.tsnew file mode 100644index 0000000..1aeaf1f--- /dev/null+++ b/web/src/components/features/sprints/composables/useSprintFormat.ts@@ -0,0 +1,56 @@+import { useI18n } from 'vue-i18n'+import type { SprintStatus } from 'taskview-api'+import type { SprintTask } from '@/types/sprints.types'++export type EstimateUnit = 'hours' | 'points'++type BadgeColor = 'neutral' | 'primary' | 'info' | 'warning' | 'success' | 'error'++export function useSprintFormat() {+ const { t } = useI18n()++ const STATUS_COLORS: Record<SprintStatus, BadgeColor> = {+ draft: 'neutral',+ planned: 'info',+ active: 'primary',+ review: 'warning',+ completed: 'success',+ }++ function statusColor(status: SprintStatus): BadgeColor {+ return STATUS_COLORS[status] ?? 'neutral'+ }++ /** Display label for the project's estimate unit. */+ function unitLabel(unit: EstimateUnit, short = false): string {+ if (unit === 'hours') {+ return short ? t('sprints.units.hoursShort') : t('sprints.units.hours')+ }+ return short ? t('sprints.units.pointsShort') : t('sprints.units.points')+ }++ /** Coerce a numeric string (e.g. "80.00") or null into a number. */+ function toNumber(value: string | number | null | undefined): number {+ if (value === null || value === undefined || value === '') return 0+ const parsed = Number(value)+ return Number.isFinite(parsed) ? parsed : 0+ }++ /** Sum estimate_value (story points) of tasks. */+ function sumEstimatePoints(tasks: SprintTask[]): number {+ return tasks.reduce((total, task) => total + toNumber(task.estimateValue), 0)+ }++ /** Capacity utilization ratio in [0, ∞); null when capacity is unknown. */+ function capacityUtilization(used: number, capacity: string | number | null | undefined): number | null {+ const cap = toNumber(capacity)+ if (cap <= 0) return null+ return used / cap+ }++ function formatPoints(points: number): string {+ return Number.isInteger(points) ? String(points) : points.toFixed(1)+ }++ return { statusColor, unitLabel, toNumber, sumEstimatePoints, capacityUtilization, formatPoints }+}diff --git a/web/src/components/features/sprints/parts/SprintBurndownChart.vue b/web/src/components/features/sprints/parts/SprintBurndownChart.vuenew file mode 100644index 0000000..8d33986--- /dev/null+++ b/web/src/components/features/sprints/parts/SprintBurndownChart.vue@@ -0,0 +1,115 @@+<template>+ <UCard>+ <template #header>+ <h3 class="font-semibold">+ {{ t('sprints.burndown.title') }}+ </h3>+ </template>++ <p+ v-if="!hasData"+ class="py-6 text-center text-sm text-dimmed"+ >+ {{ t('sprints.burndown.empty') }}+ </p>+ <div+ v-else+ class="relative"+ :style="{ height: `${isMobile ? 200 : 320}px` }"+ >+ <canvas ref="canvas" />+ </div>+ </UCard>+</template>++<script setup lang="ts">+import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import { Chart, type ChartConfiguration } from 'chart.js'+import type { SprintBurndown } from 'taskview-api'+import { registerChartJs } from '@/components/features/analytics/chart-setup'+import { useTaskView } from '@/composables/useTaskView'+import { useSprintFormat, type EstimateUnit } from '../composables/useSprintFormat'++const props = withDefaults(+ defineProps<{+ burndown: SprintBurndown | null+ unit?: EstimateUnit+ }>(),+ {+ unit: 'points',+ },+)++const { t } = useI18n()+const { isMobile } = useTaskView()+const { unitLabel } = useSprintFormat()++registerChartJs()++const canvas = ref<HTMLCanvasElement | null>(null)+let instance: Chart | null = null++const hasData = computed(() => !!props.burndown && props.burndown.points.length > 0)++function render() {+ if (!canvas.value || !props.burndown) return++ const labels = props.burndown.points.map((p) => p.date.slice(5))+ const config: ChartConfiguration = {+ type: 'line',+ data: {+ labels,+ datasets: [+ {+ label: t('sprints.burndown.ideal'),+ data: props.burndown.points.map((p) => p.idealHours),+ borderColor: '#a1a1aa',+ borderDash: [6, 4],+ pointRadius: 0,+ tension: 0,+ },+ {+ label: t('sprints.burndown.actual'),+ data: props.burndown.points.map((p) => p.remainingHours),+ borderColor: '#22c55e',+ backgroundColor: 'rgba(34,197,94,0.1)',+ fill: true,+ tension: 0.2,+ },+ ],+ },+ options: {+ responsive: true,+ maintainAspectRatio: false,+ interaction: { mode: 'index', intersect: false },+ plugins: {+ legend: { display: true, position: 'bottom' },+ tooltip: { enabled: !isMobile.value },+ },+ scales: {+ y: { beginAtZero: true, title: { display: !isMobile.value, text: unitLabel(props.unit) } },+ },+ },+ }++ if (instance) {+ instance.destroy()+ instance = null+ }+ instance = new Chart(canvas.value, config)+}++onMounted(() => {+ if (hasData.value) render()+})++onBeforeUnmount(() => {+ instance?.destroy()+ instance = null+})++watch(() => props.burndown, () => {+ if (hasData.value) render()+}, { deep: true })+</script>diff --git a/web/src/components/features/sprints/parts/SprintCadenceDialog.vue b/web/src/components/features/sprints/parts/SprintCadenceDialog.vuenew file mode 100644index 0000000..c8650c9--- /dev/null+++ b/web/src/components/features/sprints/parts/SprintCadenceDialog.vue@@ -0,0 +1,211 @@+<template>+ <UModal+ v-model:open="open"+ :fullscreen="isMobile"+ >+ <template #content>+ <UCard>+ <template #header>+ <div class="flex items-center justify-between">+ <h3 class="font-semibold">+ {{ t('sprints.cadence.title') }}+ </h3>+ <UButton+ icon="i-lucide-x"+ variant="ghost"+ color="neutral"+ @click="open = false"+ />+ </div>+ </template>++ <div class="flex flex-col gap-4">+ <p class="text-sm text-muted">+ {{ t('sprints.cadence.description') }}+ </p>++ <div class="flex items-center justify-between gap-3 rounded-lg border border-default p-3">+ <div class="flex flex-col">+ <span class="font-medium">{{ t('sprints.cadence.enable') }}</span>+ <span class="text-xs text-dimmed">{{ t('sprints.cadence.enableHint') }}</span>+ </div>+ <USwitch v-model="form.enabled" />+ </div>++ <template v-if="form.enabled">+ <UFormField :label="t('sprints.cadence.length')">+ <USelect+ v-model="form.lengthWeeks"+ :items="lengthOptions"+ class="w-full"+ />+ </UFormField>++ <UFormField :label="t('sprints.cadence.startDate')">+ <UPopover v-model:open="startOpen">+ <UButton+ icon="i-lucide-calendar"+ :label="formattedStart"+ color="neutral"+ variant="outline"+ class="w-full justify-start"+ />+ <template #content>+ <UCalendar+ v-model="startDateModel"+ class="p-2"+ />+ </template>+ </UPopover>+ <p class="mt-1 text-xs text-dimmed">+ {{ t('sprints.cadence.startDateHint') }}+ </p>+ </UFormField>++ <UFormField :label="t('sprints.cadence.lookahead')">+ <USelect+ v-model="form.lookahead"+ :items="lookaheadOptions"+ class="w-full"+ />+ <p class="mt-1 text-xs text-dimmed">+ {{ t('sprints.cadence.lookaheadHint') }}+ </p>+ </UFormField>++ <UFormField :label="t('sprints.cadence.nameTemplate')">+ <UInput+ v-model="form.nameTemplate"+ :placeholder="'Sprint {n}'"+ class="w-full"+ />+ <p class="mt-1 text-xs text-dimmed">+ {{ t('sprints.cadence.nameTemplateHint') }}+ </p>+ </UFormField>+ </template>++ <div class="flex justify-end gap-2">+ <UButton+ :label="t('common.cancel')"+ color="neutral"+ variant="ghost"+ @click="open = false"+ />+ <UButton+ :label="t('common.save')"+ :loading="loading"+ :disabled="!canSubmit"+ @click="submit"+ />+ </div>+ </div>+ </UCard>+ </template>+ </UModal>+</template>++<script setup lang="ts">+import { computed, ref, shallowRef, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import { useDateFormat } from '@vueuse/core'+import { CalendarDate } from '@internationalized/date'+import { useTaskView } from '@/composables/useTaskView'+import { useSprintsStore } from '@/stores/sprints.store'+import type { SprintCadenceFormValue } from '@/types/sprints.types'++const open = defineModel<boolean>('open', { default: false })++const props = defineProps<{+ goalId: number+}>()++const emit = defineEmits<{+ saved: []+}>()++const { t } = useI18n()+const toast = useToast()+const { isMobile } = useTaskView()+const sprintsStore = useSprintsStore()++const loading = ref(false)+const startOpen = ref(false)++const lengthOptions = computed(() =>+ [1, 2, 3, 4].map((weeks) => ({ label: t('sprints.cadence.weeks', weeks), value: weeks })),+)+const lookaheadOptions = computed(() =>+ [1, 2, 3, 4, 5, 6].map((n) => ({ label: String(n), value: n })),+)++function today(): string {+ return new Date().toISOString().slice(0, 10)+}++function defaultForm(): SprintCadenceFormValue {+ return { enabled: false, lengthWeeks: 2, startDate: today(), lookahead: 2, nameTemplate: 'Sprint {n}' }+}++const form = ref<SprintCadenceFormValue>(defaultForm())++function toCalendarDate(value: string | null): CalendarDate | undefined {+ if (!value) return undefined+ const [year, month, day] = value.split('-').map(Number)+ if (!year || !month || !day) return undefined+ return new CalendarDate(year, month, day)+}++const startDateModel = shallowRef<CalendarDate | undefined>(toCalendarDate(form.value.startDate))++watch(startDateModel, (value) => {+ form.value.startDate = value ? value.toString() : null+ if (value) startOpen.value = false+})++const formattedStart = computed(() =>+ startDateModel.value+ ? useDateFormat(new Date(startDateModel.value.toString()), 'DD MMM YYYY').value+ : t('sprints.cadence.startDate'),+)++const canSubmit = computed(() => !form.value.enabled || (!!form.value.startDate && form.value.lengthWeeks > 0))++watch(open, async (value) => {+ if (!value) return+ await sprintsStore.fetchCadence(props.goalId)+ const c = sprintsStore.cadence+ form.value = c+ ? {+ enabled: c.enabled,+ lengthWeeks: Math.max(1, Math.round(c.lengthDays / 7)),+ startDate: c.startDate,+ lookahead: c.lookahead,+ nameTemplate: c.nameTemplate,+ }+ : defaultForm()+ startDateModel.value = toCalendarDate(form.value.startDate)+})++async function submit() {+ if (!canSubmit.value) return+ loading.value = true+ try {+ const saved = await sprintsStore.saveCadence({+ goalId: props.goalId,+ enabled: form.value.enabled,+ lengthDays: form.value.lengthWeeks * 7,+ startDate: form.value.startDate ?? today(),+ lookahead: form.value.lookahead,+ nameTemplate: form.value.nameTemplate.trim() || 'Sprint {n}',+ })+ if (saved) {+ toast.add({ title: t('sprints.cadence.saved'), color: 'success' })+ emit('saved')+ open.value = false+ }+ } finally {+ loading.value = false+ }+}+</script>diff --git a/web/src/components/features/sprints/parts/SprintCreateForm.vue b/web/src/components/features/sprints/parts/SprintCreateForm.vuenew file mode 100644index 0000000..86f9e6d--- /dev/null+++ b/web/src/components/features/sprints/parts/SprintCreateForm.vue@@ -0,0 +1,26 @@+<template>+ <SprintForm+ v-model="model"+ :submit-label="t('sprints.create')"+ :loading="loading"+ @submit="emit('submit')"+ @cancel="emit('cancel')"+ />+</template>++<script setup lang="ts">+import { useI18n } from 'vue-i18n'+import SprintForm from './SprintForm.vue'+import type { SprintFormValue } from '@/types/sprints.types'++const model = defineModel<SprintFormValue>({ required: true })++defineProps<{ loading?: boolean }>()++const emit = defineEmits<{+ submit: []+ cancel: []+}>()++const { t } = useI18n()+</script>diff --git a/web/src/components/features/sprints/parts/SprintEditForm.vue b/web/src/components/features/sprints/parts/SprintEditForm.vuenew file mode 100644index 0000000..a712f94--- /dev/null+++ b/web/src/components/features/sprints/parts/SprintEditForm.vue@@ -0,0 +1,26 @@+<template>+ <SprintForm+ v-model="model"+ :submit-label="t('common.save')"+ :loading="loading"+ @submit="emit('submit')"+ @cancel="emit('cancel')"+ />+</template>++<script setup lang="ts">+import { useI18n } from 'vue-i18n'+import SprintForm from './SprintForm.vue'+import type { SprintFormValue } from '@/types/sprints.types'++const model = defineModel<SprintFormValue>({ required: true })++defineProps<{ loading?: boolean }>()++const emit = defineEmits<{+ submit: []+ cancel: []+}>()++const { t } = useI18n()+</script>diff --git a/web/src/components/features/sprints/parts/SprintForm.vue b/web/src/components/features/sprints/parts/SprintForm.vuenew file mode 100644index 0000000..7ad3077--- /dev/null+++ b/web/src/components/features/sprints/parts/SprintForm.vue@@ -0,0 +1,189 @@+<template>+ <div class="flex flex-col gap-4">+ <UFormField :label="t('sprints.fields.name')">+ <UInput+ v-model="model.name"+ :placeholder="t('sprints.fields.namePlaceholder')"+ autofocus+ class="w-full"+ />+ </UFormField>++ <UFormField :label="t('sprints.fields.goal')">+ <UTextarea+ v-model="model.goalText"+ :placeholder="t('sprints.fields.goalPlaceholder')"+ :rows="2"+ class="w-full"+ />+ </UFormField>++ <div class="flex flex-col gap-3 lg:flex-row">+ <UFormField+ :label="t('sprints.fields.startDate')"+ class="flex-1"+ >+ <UPopover v-model:open="startOpen">+ <UButton+ icon="i-lucide-calendar"+ :label="formattedStart"+ color="neutral"+ variant="outline"+ class="w-full justify-start"+ />+ <template #content>+ <UCalendar+ v-model="startDateModel"+ :max-value="endDateModel"+ class="p-2"+ />+ </template>+ </UPopover>+ </UFormField>++ <UFormField+ :label="t('sprints.fields.endDate')"+ class="flex-1"+ >+ <UPopover v-model:open="endOpen">+ <UButton+ icon="i-lucide-calendar-check"+ :label="formattedEnd"+ color="neutral"+ variant="outline"+ class="w-full justify-start"+ />+ <template #content>+ <UCalendar+ v-model="endDateModel"+ :min-value="startDateModel"+ class="p-2"+ />+ </template>+ </UPopover>+ </UFormField>+ </div>++ <UFormField :label="t('sprints.fields.capacity')">+ <UInput+ v-model="capacityModel"+ type="number"+ min="0"+ step="1"+ :placeholder="t('sprints.fields.capacityPlaceholder')"+ class="w-full"+ >+ <template #trailing>+ <span class="text-xs text-dimmed">{{ unitLabel(unit, true) }}</span>+ </template>+ </UInput>+ </UFormField>++ <div class="flex justify-end gap-2">+ <UButton+ :label="t('common.cancel')"+ color="neutral"+ variant="ghost"+ @click="emit('cancel')"+ />+ <UButton+ :label="submitLabel"+ :loading="loading"+ :disabled="!canSubmit"+ @click="submit"+ />+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed, ref, shallowRef, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import { useDateFormat } from '@vueuse/core'+import { CalendarDate } from '@internationalized/date'+import { useSprintFormat, type EstimateUnit } from '../composables/useSprintFormat'+import type { SprintFormValue } from '@/types/sprints.types'++const model = defineModel<SprintFormValue>({ required: true })++const props = withDefaults(+ defineProps<{+ submitLabel: string+ loading?: boolean+ unit?: EstimateUnit+ }>(),+ {+ unit: 'points',+ },+)++const emit = defineEmits<{+ submit: []+ cancel: []+}>()++const { t } = useI18n()+const { unitLabel } = useSprintFormat()++const unit = computed(() => props.unit)++const startOpen = ref(false)+const endOpen = ref(false)++function toCalendarDate(value: string | null): CalendarDate | undefined {+ if (!value) return undefined+ const [year, month, day] = value.split('-').map(Number)+ if (!year || !month || !day) return undefined+ return new CalendarDate(year, month, day)+}++const startDateModel = shallowRef<CalendarDate | undefined>(toCalendarDate(model.value.startDate))+const endDateModel = shallowRef<CalendarDate | undefined>(toCalendarDate(model.value.endDate))++watch(startDateModel, (value) => {+ model.value.startDate = value ? value.toString() : null+ if (value) startOpen.value = false+})+watch(endDateModel, (value) => {+ model.value.endDate = value ? value.toString() : null+ if (value) endOpen.value = false+})++watch(+ () => [model.value.startDate, model.value.endDate],+ ([start, end]) => {+ const nextStart = toCalendarDate(start)+ const nextEnd = toCalendarDate(end)+ if (nextStart?.toString() !== startDateModel.value?.toString()) startDateModel.value = nextStart+ if (nextEnd?.toString() !== endDateModel.value?.toString()) endDateModel.value = nextEnd+ },+)++const capacityModel = computed({+ get: () => (model.value.capacity === null ? '' : String(model.value.capacity)),+ set: (value: string) => {+ const trimmed = String(value).trim()+ model.value.capacity = trimmed === '' ? null : Number(trimmed)+ },+})++const formattedStart = computed(() =>+ startDateModel.value+ ? useDateFormat(new Date(startDateModel.value.toString()), 'DD MMM YYYY').value+ : t('sprints.fields.startDate'),+)+const formattedEnd = computed(() =>+ endDateModel.value+ ? useDateFormat(new Date(endDateModel.value.toString()), 'DD MMM YYYY').value+ : t('sprints.fields.endDate'),+)++const canSubmit = computed(+ () => model.value.name.trim().length > 0 && !!model.value.startDate && !!model.value.endDate,+)++function submit() {+ if (!canSubmit.value) return+ emit('submit')+}+</script>diff --git a/web/src/components/features/sprints/parts/SprintFormDialog.vue b/web/src/components/features/sprints/parts/SprintFormDialog.vuenew file mode 100644index 0000000..115dd88--- /dev/null+++ b/web/src/components/features/sprints/parts/SprintFormDialog.vue@@ -0,0 +1,112 @@+<template>+ <UModal+ v-model:open="open"+ :fullscreen="isMobile"+ >+ <template #content>+ <UCard>+ <template #header>+ <div class="flex items-center justify-between">+ <h3 class="font-semibold">+ {{ isEdit ? t('sprints.editTitle') : t('sprints.create') }}+ </h3>+ <UButton+ icon="i-lucide-x"+ variant="ghost"+ color="neutral"+ @click="open = false"+ />+ </div>+ </template>++ <SprintForm+ v-model="formValue"+ :submit-label="isEdit ? t('common.save') : t('sprints.create')"+ :loading="loading"+ :unit="unit"+ @submit="submit"+ @cancel="open = false"+ />+ </UCard>+ </template>+ </UModal>+</template>++<script setup lang="ts">+import { computed, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import type { Sprint } from 'taskview-api'+import SprintForm from './SprintForm.vue'+import { useTaskView } from '@/composables/useTaskView'+import { useSprintsStore } from '@/stores/sprints.store'+import { useGoalsStore } from '@/stores/goals.store'+import type { SprintFormValue } from '@/types/sprints.types'++const open = defineModel<boolean>('open', { default: false })++const props = defineProps<{+ goalId: number+ sprint?: Sprint | null+}>()++const emit = defineEmits<{+ saved: [sprint: Sprint]+}>()++const { t } = useI18n()+const toast = useToast()+const { isMobile } = useTaskView()+const sprintsStore = useSprintsStore()+const goalsStore = useGoalsStore()++const loading = ref(false)+const isEdit = computed(() => !!props.sprint)+const unit = computed(() => goalsStore.goalMap.get(props.goalId)?.estimateUnit ?? 'points')++function emptyValue(): SprintFormValue {+ return { name: '', goalText: '', startDate: null, endDate: null, capacity: null }+}++function fromSprint(sprint: Sprint): SprintFormValue {+ return {+ name: sprint.name,+ goalText: sprint.goalText ?? '',+ startDate: sprint.startDate,+ endDate: sprint.endDate,+ capacity: sprint.capacity === null ? null : Number(sprint.capacity),+ }+}++const formValue = ref<SprintFormValue>(props.sprint ? fromSprint(props.sprint) : emptyValue())++watch(open, (value) => {+ if (value) {+ formValue.value = props.sprint ? fromSprint(props.sprint) : emptyValue()+ }+})++async function submit() {+ loading.value = true+ try {+ const payload = {+ name: formValue.value.name.trim(),+ startDate: formValue.value.startDate as string,+ endDate: formValue.value.endDate as string,+ goalText: formValue.value.goalText.trim() || null,+ capacity: formValue.value.capacity,+ }++ const sprint = isEdit.value && props.sprint+ ? await sprintsStore.updateSprint({ sprintId: props.sprint.id, ...payload })+ : await sprintsStore.createSprint({ goalId: props.goalId, ...payload })++ if (sprint) {+ toast.add({ title: t(isEdit.value ? 'sprints.toasts.updated' : 'sprints.toasts.created'), color: 'success' })+ emit('saved', sprint)+ open.value = false+ }+ } finally {+ loading.value = false+ }+}+</script>diff --git a/web/src/components/features/sprints/parts/SprintHeader.vue b/web/src/components/features/sprints/parts/SprintHeader.vuenew file mode 100644index 0000000..5483923--- /dev/null+++ b/web/src/components/features/sprints/parts/SprintHeader.vue@@ -0,0 +1,128 @@+<template>+ <UCard>+ <div class="flex flex-col gap-4">+ <div class="flex flex-wrap items-start justify-between gap-3">+ <div class="flex flex-col gap-1">+ <div class="flex items-center gap-2">+ <h2 class="text-lg font-semibold">+ {{ sprint.name }}+ </h2>+ <UBadge+ :color="statusColor(sprint.status)"+ variant="subtle"+ size="sm"+ >+ {{ t(`sprints.status.${sprint.status}`) }}+ </UBadge>+ <UBadge+ v-if="sprint.pausedAt"+ color="warning"+ variant="outline"+ size="sm"+ icon="i-lucide-pause"+ >+ {{ t('sprints.paused') }}+ </UBadge>+ </div>+ <p class="text-sm text-dimmed">+ {{ dateRange }}+ </p>+ <p+ v-if="sprint.goalText"+ class="text-sm text-muted"+ >+ {{ sprint.goalText }}+ </p>+ </div>++ <div class="flex items-center gap-2">+ <slot name="actions" />+ </div>+ </div>++ <div class="flex flex-col gap-2">+ <div class="flex items-center justify-between text-sm">+ <span class="text-muted">{{ t('sprints.metrics.capacityUtilization') }}</span>+ <span :class="overCapacity ? 'text-error font-medium' : 'text-default'">+ {{ formatPoints(usedPoints) }} / {{ capacityLabel }} {{ unitLabel(unit) }}+ </span>+ </div>+ <UProgress+ v-if="utilization !== null"+ :model-value="Math.min(utilization * 100, 100)"+ :color="overCapacity ? 'error' : 'primary'"+ />+ <p+ v-else+ class="text-xs text-dimmed"+ >+ {{ t('sprints.metrics.noCapacity') }}+ </p>+ </div>++ <div class="flex flex-wrap gap-4 text-sm">+ <div class="flex flex-col">+ <span class="text-dimmed">{{ t('sprints.metrics.planned') }}</span>+ <span class="font-medium">{{ formatPoints(plannedPoints) }} {{ unitLabel(unit) }}</span>+ </div>+ <div class="flex flex-col">+ <span class="text-dimmed">{{ t('sprints.metrics.accepted') }}</span>+ <span class="font-medium">{{ formatPoints(acceptedPoints) }} {{ unitLabel(unit) }}</span>+ </div>+ <div+ v-if="sprint.goalAchieved !== null"+ class="flex flex-col"+ >+ <span class="text-dimmed">{{ t('sprints.metrics.goal') }}</span>+ <UBadge+ :color="sprint.goalAchieved ? 'success' : 'error'"+ variant="subtle"+ size="sm"+ >+ {{ sprint.goalAchieved ? t('sprints.metrics.goalAchieved') : t('sprints.metrics.goalMissed') }}+ </UBadge>+ </div>+ </div>+ </div>+ </UCard>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import { useDateFormat } from '@vueuse/core'+import type { Sprint } from 'taskview-api'+import { useSprintFormat } from '../composables/useSprintFormat'+import { useGoalsStore } from '@/stores/goals.store'+import type { SprintTask } from '@/types/sprints.types'++const props = defineProps<{+ sprint: Sprint+ tasks: SprintTask[]+ acceptedPoints?: number+}>()++const { t } = useI18n()+const { statusColor, formatPoints, sumEstimatePoints, capacityUtilization, toNumber, unitLabel } = useSprintFormat()+const goalsStore = useGoalsStore()++const unit = computed(() => goalsStore.goalMap.get(props.sprint.goalId)?.estimateUnit ?? 'points')++const dateRange = computed(() => {+ const start = useDateFormat(new Date(props.sprint.startDate), 'DD MMM').value+ const end = useDateFormat(new Date(props.sprint.endDate), 'DD MMM YYYY').value+ return `${start} – ${end}`+})++const usedPoints = computed(() => sumEstimatePoints(props.tasks))+const plannedPoints = computed(() => usedPoints.value)+const acceptedPoints = computed(() => props.acceptedPoints ?? 0)++const utilization = computed(() => capacityUtilization(usedPoints.value, props.sprint.capacity))+const overCapacity = computed(() => utilization.value !== null && utilization.value > 1)++const capacityLabel = computed(() => {+ const cap = toNumber(props.sprint.capacity)+ return cap > 0 ? formatPoints(cap) : '—'+})+</script>diff --git a/web/src/components/features/sprints/parts/SprintPlanningColumn.vue b/web/src/components/features/sprints/parts/SprintPlanningColumn.vuenew file mode 100644index 0000000..3de48b7--- /dev/null+++ b/web/src/components/features/sprints/parts/SprintPlanningColumn.vue@@ -0,0 +1,113 @@+<template>+ <div class="flex flex-col gap-2">+ <h4 class="text-sm font-semibold text-muted">+ {{ title }}+ </h4>+ <div+ ref="scrollEl"+ class="flex max-h-[60vh] flex-col gap-2 overflow-y-auto"+ >+ <p+ v-if="!loading && !error && !tasks.length"+ class="py-4 text-center text-sm text-dimmed"+ >+ {{ emptyLabel }}+ </p>++ <button+ v-for="task in tasks"+ :key="task.id"+ type="button"+ class="flex items-center justify-between gap-2 rounded-lg border border-default p-2 text-left hover:bg-elevated disabled:opacity-50"+ :disabled="busyId === task.id"+ @click="emit('assign', task)"+ >+ <template v-if="direction === 'forward'">+ <span class="truncate text-sm">{{ task.description }}</span>+ <span class="flex shrink-0 items-center gap-1 text-xs text-dimmed">+ {{ formatPoints(toNumber(task.estimateValue)) }} {{ unitLabel(unit, true) }}+ <UIcon name="i-lucide-arrow-right" />+ </span>+ </template>+ <template v-else>+ <span class="flex shrink-0 items-center gap-1 text-xs text-dimmed">+ <UIcon name="i-lucide-arrow-left" />+ {{ formatPoints(toNumber(task.estimateValue)) }} {{ unitLabel(unit, true) }}+ </span>+ <span class="truncate text-sm">{{ task.description }}</span>+ </template>+ </button>++ <div+ v-if="loading"+ class="flex justify-center py-3"+ >+ <UIcon+ name="i-lucide-loader-circle"+ class="size-5 animate-spin text-dimmed"+ />+ </div>++ <div+ v-if="error && !loading"+ class="flex flex-col items-center gap-2 py-3"+ >+ <p class="text-sm text-error">+ {{ t('sprints.planning.loadError') }}+ </p>+ <UButton+ size="xs"+ variant="soft"+ icon="i-lucide-rotate-cw"+ :label="t('sprints.planning.retry')"+ @click="emit('retry')"+ />+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { nextTick, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import { useInfiniteScroll } from '@vueuse/core'+import { useSprintFormat } from '../composables/useSprintFormat'+import type { EstimateUnit } from '../composables/useSprintFormat'+import type { SprintTask } from '@/types/sprints.types'++const props = defineProps<{+ title: string+ emptyLabel: string+ tasks: SprintTask[]+ unit: EstimateUnit+ direction: 'forward' | 'back'+ loading: boolean+ hasMore: boolean+ error: boolean+ busyId: number | null+}>()++const emit = defineEmits<{+ assign: [task: SprintTask]+ loadMore: []+ retry: []+}>()++const { t } = useI18n()+const { formatPoints, toNumber, unitLabel } = useSprintFormat()++const scrollEl = ref<HTMLElement | null>(null)++watch(scrollEl, async (el) => {+ if (!el) return+ await nextTick()+ useInfiniteScroll(+ el,+ () => emit('loadMore'),+ {+ distance: 200,+ canLoadMore: () => props.hasMore && !props.loading && !props.error,+ },+ )+})+</script>diff --git a/web/src/components/features/sprints/parts/SprintPlanningDialog.vue b/web/src/components/features/sprints/parts/SprintPlanningDialog.vuenew file mode 100644index 0000000..bc1c7e5--- /dev/null+++ b/web/src/components/features/sprints/parts/SprintPlanningDialog.vue@@ -0,0 +1,212 @@+<template>+ <UModal+ v-model:open="open"+ :fullscreen="isMobile"+ :ui="{ content: 'lg:max-w-4xl' }"+ >+ <template #content>+ <UCard>+ <template #header>+ <div class="flex items-center justify-between gap-3">+ <h3 class="font-semibold">+ {{ t('sprints.planning.title') }}+ </h3>+ <div class="flex items-center gap-3">+ <span+ class="text-sm font-medium"+ :class="overCapacity ? 'text-error' : 'text-muted'"+ >+ {{ formatPoints(totalPoints) }} / {{ capacityLabel }} {{ unitLabel(unit) }}+ </span>+ <UButton+ icon="i-lucide-x"+ variant="ghost"+ color="neutral"+ @click="open = false"+ />+ </div>+ </div>+ </template>++ <div class="grid grid-cols-1 gap-4 lg:grid-cols-2">+ <SprintPlanningColumn+ :title="t('sprints.planning.backlog')"+ :empty-label="t('sprints.planning.backlogEmpty')"+ :tasks="backlog.tasks"+ :unit="unit"+ direction="forward"+ :loading="backlog.loading"+ :has-more="backlog.cursor !== undefined ? backlog.nextCursor !== null : true"+ :error="backlog.errored"+ :busy-id="busyId"+ @assign="(task) => assign(task, sprint.id)"+ @load-more="() => loadPage('backlog')"+ @retry="() => loadPage('backlog')"+ />++ <SprintPlanningColumn+ :title="t('sprints.planning.inSprint')"+ :empty-label="t('sprints.planning.sprintEmpty')"+ :tasks="sprint_.tasks"+ :unit="unit"+ direction="back"+ :loading="sprint_.loading"+ :has-more="sprint_.cursor !== undefined ? sprint_.nextCursor !== null : true"+ :error="sprint_.errored"+ :busy-id="busyId"+ @assign="(task) => assign(task, null)"+ @load-more="() => loadPage('sprint')"+ @retry="() => loadPage('sprint')"+ />+ </div>+ </UCard>+ </template>+ </UModal>+</template>++<script setup lang="ts">+import { computed, reactive, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import type { Sprint, SprintPlanningScope, SprintPlanningSprintPage } from 'taskview-api'+import { useTaskView } from '@/composables/useTaskView'+import { useSprintsStore } from '@/stores/sprints.store'+import { useGoalsStore } from '@/stores/goals.store'+import { useSprintFormat } from '../composables/useSprintFormat'+import SprintPlanningColumn from './SprintPlanningColumn.vue'+import type { SprintTask } from '@/types/sprints.types'++const open = defineModel<boolean>('open', { default: false })++const props = defineProps<{+ sprint: Sprint+}>()++const emit = defineEmits<{+ changed: []+}>()++const { t } = useI18n()+const { isMobile } = useTaskView()+const toast = useToast()+const sprintsStore = useSprintsStore()+const goalsStore = useGoalsStore()+const { formatPoints, toNumber, capacityUtilization, unitLabel } = useSprintFormat()++const PAGE_SIZE = 30++const unit = computed(() => goalsStore.goalMap.get(props.sprint.goalId)?.estimateUnit ?? 'points')++type ColumnState = {+ tasks: SprintTask[]+ // cursor === undefined means no page has been loaded yet (hasMore is true).+ cursor: number | undefined+ nextCursor: number | null+ loading: boolean+ // a failed request stops auto-loading and surfaces a Retry button+ errored: boolean+}++function emptyColumn(): ColumnState {+ return { tasks: [], cursor: undefined, nextCursor: null, loading: false, errored: false }+}++const backlog = reactive<ColumnState>(emptyColumn())+const sprint_ = reactive<ColumnState>(emptyColumn())+const totalPoints = ref(0)+const busyId = ref<number | null>(null)++function columnFor(scope: SprintPlanningScope): ColumnState {+ return scope === 'backlog' ? backlog : sprint_+}++function reset() {+ Object.assign(backlog, emptyColumn())+ Object.assign(sprint_, emptyColumn())+ totalPoints.value = 0+ busyId.value = null+}++async function loadPage(scope: SprintPlanningScope) {+ const column = columnFor(scope)+ if (column.loading) return+ // Stop once a page has been loaded and the server reports no more.+ if (column.cursor !== undefined && column.nextCursor === null) return++ column.loading = true+ column.errored = false+ try {+ const page = await sprintsStore.fetchPlanningTasks({+ sprintId: props.sprint.id,+ scope,+ cursor: column.cursor,+ limit: PAGE_SIZE,+ })+ if (!page) {+ column.errored = true+ return+ }+ column.tasks.push(...(page.tasks as SprintTask[]))+ column.nextCursor = page.nextCursor+ column.cursor = page.nextCursor ?? column.cursor ?? -1+ if (scope === 'sprint') totalPoints.value = (page as SprintPlanningSprintPage).totalPoints+ } catch {+ column.errored = true+ } finally {+ column.loading = false+ }+}++const utilization = computed(() => capacityUtilization(totalPoints.value, props.sprint.capacity))+const overCapacity = computed(() => utilization.value !== null && utilization.value > 1)+const capacityLabel = computed(() => {+ const cap = toNumber(props.sprint.capacity)+ return cap > 0 ? formatPoints(cap) : '—'+})++async function assign(task: SprintTask, sprintId: number | null) {+ busyId.value = task.id+ try {+ const ok = await sprintsStore.setTaskSprint({ taskId: task.id, sprintId })+ if (!ok) {+ toast.add({ title: t('sprints.toasts.assignFailed'), color: 'error' })+ return+ }+ const points = toNumber(task.estimateValue)+ const moving: SprintTask = { ...task, sprintId }+ if (sprintId === null) {+ // Moving out of the sprint, back to backlog.+ removeFromColumn(sprint_, task.id)+ backlog.tasks.unshift(moving)+ totalPoints.value = Math.max(0, totalPoints.value - points)+ } else {+ // Moving into the sprint.+ removeFromColumn(backlog, task.id)+ sprint_.tasks.unshift(moving)+ totalPoints.value += points+ }+ emit('changed')+ } finally {+ busyId.value = null+ }+}++function removeFromColumn(column: ColumnState, taskId: number) {+ const index = column.tasks.findIndex((item) => item.id === taskId)+ if (index !== -1) column.tasks.splice(index, 1)+}++watch(+ () => [open.value, props.sprint.id] as const,+ ([isOpen], previous) => {+ const wasOpen = previous?.[0]+ if (isOpen) {+ reset()+ loadPage('backlog')+ loadPage('sprint')+ } else if (wasOpen) {+ reset()+ }+ },+ { immediate: true },+)+</script>diff --git a/web/src/components/features/sprints/parts/SprintRetroPanel.vue b/web/src/components/features/sprints/parts/SprintRetroPanel.vuenew file mode 100644index 0000000..ca84384--- /dev/null+++ b/web/src/components/features/sprints/parts/SprintRetroPanel.vue@@ -0,0 +1,122 @@+<template>+ <UCard>+ <template #header>+ <div class="flex items-center justify-between">+ <h3 class="font-semibold">+ {{ t('sprints.retro.title') }}+ </h3>+ <UButton+ v-if="canManage"+ :label="t('sprints.actions.saveRetro')"+ icon="i-lucide-save"+ size="sm"+ :loading="loading"+ :disabled="!dirty"+ @click="save"+ />+ </div>+ </template>++ <UTabs+ v-if="isMobile"+ :items="tabItems"+ class="w-full"+ >+ <template #content="{ item }">+ <UTextarea+ v-model="fields[item.value as RetroKey]"+ :rows="6"+ :disabled="!canManage"+ :placeholder="t(`sprints.retro.${item.value}Placeholder`)"+ class="mt-3 w-full"+ />+ </template>+ </UTabs>++ <div+ v-else+ class="grid grid-cols-3 gap-4"+ >+ <div+ v-for="key in retroKeys"+ :key="key"+ class="flex flex-col gap-2"+ >+ <label class="text-sm font-medium">{{ t(`sprints.retro.${key}`) }}</label>+ <UTextarea+ v-model="fields[key]"+ :rows="8"+ :disabled="!canManage"+ :placeholder="t(`sprints.retro.${key}Placeholder`)"+ class="w-full"+ />+ </div>+ </div>+ </UCard>+</template>++<script setup lang="ts">+import { computed, reactive, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import type { SprintRetro } from 'taskview-api'+import { useTaskView } from '@/composables/useTaskView'+import { useSprintsStore } from '@/stores/sprints.store'++type RetroKey = 'wentWell' | 'wentBad' | 'actionItems'++const props = defineProps<{+ sprintId: number+ retro: SprintRetro | null+ canManage: boolean+}>()++const { t } = useI18n()+const { isMobile } = useTaskView()+const toast = useToast()+const sprintsStore = useSprintsStore()++const retroKeys: RetroKey[] = ['wentWell', 'wentBad', 'actionItems']++const fields = reactive<Record<RetroKey, string>>({+ wentWell: props.retro?.wentWell ?? '',+ wentBad: props.retro?.wentBad ?? '',+ actionItems: props.retro?.actionItems ?? '',+})++const loading = ref(false)++watch(+ () => props.retro,+ (retro) => {+ fields.wentWell = retro?.wentWell ?? ''+ fields.wentBad = retro?.wentBad ?? ''+ fields.actionItems = retro?.actionItems ?? ''+ },+)++const dirty = computed(+ () =>+ fields.wentWell !== (props.retro?.wentWell ?? '') ||+ fields.wentBad !== (props.retro?.wentBad ?? '') ||+ fields.actionItems !== (props.retro?.actionItems ?? ''),+)++const tabItems = computed(() =>+ retroKeys.map((key) => ({ value: key, label: t(`sprints.retro.${key}`) })),+)++async function save() {+ loading.value = true+ try {+ const ok = await sprintsStore.saveRetro({+ sprintId: props.sprintId,+ wentWell: fields.wentWell.trim() || null,+ wentBad: fields.wentBad.trim() || null,+ actionItems: fields.actionItems.trim() || null,+ })+ if (ok) toast.add({ title: t('sprints.toasts.retroSaved'), color: 'success' })+ } finally {+ loading.value = false+ }+}+</script>diff --git a/web/src/components/features/sprints/parts/SprintReviewDialog.vue b/web/src/components/features/sprints/parts/SprintReviewDialog.vuenew file mode 100644index 0000000..04ef737--- /dev/null+++ b/web/src/components/features/sprints/parts/SprintReviewDialog.vue@@ -0,0 +1,235 @@+<template>+ <UModal+ v-model:open="open"+ :fullscreen="isMobile"+ :ui="{ content: 'lg:max-w-3xl' }"+ >+ <template #content>+ <UCard>+ <template #header>+ <div class="flex items-center justify-between">+ <h3 class="font-semibold">+ {{ t('sprints.review.title') }}+ </h3>+ <UButton+ icon="i-lucide-x"+ variant="ghost"+ color="neutral"+ @click="open = false"+ />+ </div>+ </template>++ <div class="flex flex-col gap-3">+ <p class="text-sm text-muted">+ {{ t('sprints.review.hint') }}+ </p>++ <p+ v-if="!tasks.length"+ class="py-4 text-center text-sm text-dimmed"+ >+ {{ t('sprints.review.noTasks') }}+ </p>++ <div+ v-else+ class="flex max-h-[50vh] flex-col gap-2 overflow-y-auto pr-1"+ >+ <div+ v-for="task in tasks"+ :key="task.id"+ class="flex flex-col gap-2 rounded-lg border border-default p-3"+ >+ <div class="flex items-start justify-between gap-2">+ <span class="font-medium">{{ task.description }}</span>+ <UBadge+ color="neutral"+ variant="subtle"+ size="sm"+ class="shrink-0"+ >+ {{ formatPoints(toNumber(task.estimateValue)) }} {{ unitLabel(unit, true) }}+ </UBadge>+ </div>+ <div+ v-if="task.complete"+ class="flex items-center gap-1.5 text-sm text-success"+ >+ <UIcon+ name="i-lucide-check"+ class="size-4"+ />+ {{ t('sprints.outcomes.accepted') }}+ </div>+ <div+ v-else+ class="flex flex-col gap-2"+ >+ <URadioGroup+ v-model="outcomes[task.id]"+ :items="incompleteOutcomeItems"+ orientation="horizontal"+ size="sm"+ />+ <div+ v-if="outcomes[task.id] === 'carried-over'"+ class="mt-1 flex flex-col gap-1"+ >+ <span class="text-xs text-muted">{{ t('sprints.review.carryTo') }}</span>+ <USelectMenu+ v-model="carryTargets[task.id]"+ :items="carryTargetItems"+ value-key="value"+ size="sm"+ class="w-full"+ />+ </div>+ </div>+ </div>+ </div>++ <USeparator />++ <UCheckbox+ v-model="goalAchieved"+ :label="t('sprints.review.goalAchieved')"+ />+ </div>++ <template #footer>+ <div class="flex justify-end gap-2">+ <UButton+ :label="t('common.cancel')"+ color="neutral"+ variant="ghost"+ @click="open = false"+ />+ <UButton+ :label="t('sprints.actions.close')"+ color="primary"+ :loading="loading"+ @click="submit"+ />+ </div>+ </template>+ </UCard>+ </template>+ </UModal>+</template>++<script setup lang="ts">+import { computed, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import type { Sprint, SprintOutcome, SprintTaskOutcomeInput } from 'taskview-api'+import { useTaskView } from '@/composables/useTaskView'+import { useSprintsStore } from '@/stores/sprints.store'+import { useGoalsStore } from '@/stores/goals.store'+import { useSprintFormat } from '../composables/useSprintFormat'+import type { SprintTask } from '@/types/sprints.types'++const open = defineModel<boolean>('open', { default: false })++const props = defineProps<{+ sprint: Sprint+ tasks: SprintTask[]+}>()++const emit = defineEmits<{+ closed: [sprint: Sprint]+}>()++const { t } = useI18n()+const { isMobile } = useTaskView()+const toast = useToast()+const sprintsStore = useSprintsStore()+const goalsStore = useGoalsStore()+const { formatPoints, toNumber, unitLabel } = useSprintFormat()++const unit = computed(() => goalsStore.goalMap.get(props.sprint.goalId)?.estimateUnit ?? 'points')++const loading = ref(false)+const goalAchieved = ref(false)+const outcomes = ref<Record<number, SprintOutcome>>({})+// Target sprint per carried-over task. The BACKLOG sentinel (0) means "no sprint"+// (sprintId becomes null); any positive value is the destination sprint id.+const BACKLOG = 0+const carryTargets = ref<Record<number, number>>({})++// Accepted ⇔ task is done. For unfinished tasks the only meaningful choices are+// carry over (continue in another sprint) or drop (won't do). Completed tasks are+// fixed as accepted — carrying over / dropping already-done work skews velocity.+const incompleteOutcomeItems = [+ { value: 'carried-over', label: t('sprints.outcomes.carriedOver') },+ { value: 'dropped', label: t('sprints.outcomes.dropped') },+]++// Sprints a task can be carried into: any sprint of this project that isn't the one+// being closed and isn't already completed, ordered by start date (soonest first).+const carryCandidates = computed(() =>+ sprintsStore.sprints+ .filter((s) => s.id !== props.sprint.id && s.status !== 'completed')+ .slice()+ .sort((a, b) => a.startDate.localeCompare(b.startDate) || a.id - b.id),+)++// Default destination: the soonest candidate, or backlog when there is none.+const nearestTarget = computed(() => carryCandidates.value[0]?.id ?? BACKLOG)++const carryTargetItems = computed(() => [+ { value: BACKLOG, label: t('sprints.review.backlogOption') },+ ...carryCandidates.value.map((s) => ({ value: s.id, label: s.name })),+])++watch(open, (value) => {+ if (value) {+ goalAchieved.value = false+ outcomes.value = Object.fromEntries(+ props.tasks.map((task) => [task.id, task.complete ? 'accepted' : 'carried-over']),+ )+ carryTargets.value = Object.fromEntries(+ props.tasks.filter((task) => !task.complete).map((task) => [task.id, nearestTarget.value]),+ )+ }+})++async function submit() {+ loading.value = true+ try {+ // Lifecycle is active -> review -> completed. If review hasn't been started+ // yet (sprint still active), move it into review first, then close.+ if (props.sprint.status === 'active') {+ const review = await sprintsStore.startReview(props.sprint.id)+ if (!review) {+ toast.add({ title: t('sprints.toasts.closeFailed'), color: 'error' })+ return+ }+ }++ const payload: SprintTaskOutcomeInput[] = props.tasks+ .filter((task) => outcomes.value[task.id])+ .map((task) => {+ const outcome = outcomes.value[task.id]+ if (outcome !== 'carried-over') {+ return { taskId: task.id, outcome }+ }+ const target = carryTargets.value[task.id] ?? BACKLOG+ return { taskId: task.id, outcome, carriedOverTo: target === BACKLOG ? null : target }+ })++ const sprint = await sprintsStore.closeSprint({+ sprintId: props.sprint.id,+ outcomes: payload,+ goalAchieved: goalAchieved.value,+ })++ if (sprint) {+ toast.add({ title: t('sprints.toasts.closed'), color: 'success' })+ emit('closed', sprint)+ open.value = false+ }+ } finally {+ loading.value = false+ }+}+</script>diff --git a/web/src/components/features/sprints/parts/SprintTaskList.vue b/web/src/components/features/sprints/parts/SprintTaskList.vuenew file mode 100644index 0000000..05f7bf7--- /dev/null+++ b/web/src/components/features/sprints/parts/SprintTaskList.vue@@ -0,0 +1,99 @@+<template>+ <UCard>+ <template #header>+ <div class="flex items-center justify-between">+ <h3 class="font-semibold">+ {{ t('sprints.taskList.title') }}+ </h3>+ <div class="flex items-center gap-2">+ <UBadge+ color="neutral"+ variant="subtle"+ >+ {{ tasks.length }}+ </UBadge>+ <slot name="actions" />+ </div>+ </div>+ </template>++ <p+ v-if="!tasks.length"+ class="py-6 text-center text-sm text-dimmed"+ >+ {{ t('sprints.taskList.empty') }}+ </p>++ <div+ v-else+ class="flex flex-col divide-y divide-default"+ >+ <div+ v-for="task in tasks"+ :key="task.id"+ class="flex flex-col gap-2 py-3 lg:flex-row lg:items-center lg:justify-between"+ >+ <div class="flex min-w-0 items-center gap-2">+ <UIcon+ :name="task.complete ? 'i-lucide-check-circle-2' : 'i-lucide-circle'"+ :class="task.complete ? 'text-success' : 'text-dimmed'"+ />+ <span+ class="truncate"+ :class="{ 'line-through text-dimmed': task.complete }"+ >+ {{ task.description }}+ </span>+ </div>++ <div class="flex flex-wrap items-center gap-3 text-sm">+ <UBadge+ v-if="assigneeLabel(task)"+ color="neutral"+ variant="soft"+ icon="i-lucide-user"+ >+ {{ assigneeLabel(task) }}+ </UBadge>++ <span class="text-muted">+ {{ t('sprints.taskList.estimate') }}:+ <span class="font-medium text-default">{{ formatPoints(toNumber(task.estimateValue)) }} {{ unitLabel(unit, true) }}</span>+ </span>+ </div>+ </div>+ </div>+ </UCard>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import { useSprintFormat, type EstimateUnit } from '../composables/useSprintFormat'+import type { SprintTask } from '@/types/sprints.types'++const props = withDefaults(+ defineProps<{+ tasks: SprintTask[]+ userMap: Map<number, { id: number; email: string }>+ unit?: EstimateUnit+ }>(),+ {+ unit: 'points',+ },+)++const { t } = useI18n()+const { formatPoints, toNumber, unitLabel } = useSprintFormat()++const unit = computed(() => props.unit)++function assigneeLabel(task: SprintTask): string {+ const first = task.assignedUsers?.[0]+ if (first === undefined) return ''+ const user = props.userMap.get(first)+ const name = user?.email ?? `#${first}`+ const extra = task.assignedUsers.length - 1+ return extra > 0 ? `${name} +${extra}` : name+}+</script>diff --git a/web/src/components/features/sprints/parts/SprintVelocityChart.vue b/web/src/components/features/sprints/parts/SprintVelocityChart.vuenew file mode 100644index 0000000..b14879e--- /dev/null+++ b/web/src/components/features/sprints/parts/SprintVelocityChart.vue@@ -0,0 +1,107 @@+<template>+ <UCard>+ <template #header>+ <h3 class="font-semibold">+ {{ t('sprints.velocity.title') }}+ </h3>+ </template>++ <p+ v-if="!points.length"+ class="py-6 text-center text-sm text-dimmed"+ >+ {{ t('sprints.velocity.empty') }}+ </p>+ <div+ v-else+ class="relative"+ :style="{ height: `${isMobile ? 200 : 320}px` }"+ >+ <canvas ref="canvas" />+ </div>+ </UCard>+</template>++<script setup lang="ts">+import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import { Chart, type ChartConfiguration } from 'chart.js'+import type { SprintVelocityPoint } from 'taskview-api'+import { registerChartJs } from '@/components/features/analytics/chart-setup'+import { useTaskView } from '@/composables/useTaskView'+import { useSprintFormat, type EstimateUnit } from '../composables/useSprintFormat'++const props = withDefaults(+ defineProps<{+ points: SprintVelocityPoint[]+ unit?: EstimateUnit+ }>(),+ {+ unit: 'points',+ },+)++const { t } = useI18n()+const { isMobile } = useTaskView()+const { unitLabel } = useSprintFormat()++registerChartJs()++const canvas = ref<HTMLCanvasElement | null>(null)+let instance: Chart | null = null++const points = computed(() => props.points)++function render() {+ if (!canvas.value || !points.value.length) return++ const config: ChartConfiguration = {+ type: 'bar',+ data: {+ labels: points.value.map((p) => p.name),+ datasets: [+ {+ label: t('sprints.velocity.planned'),+ data: points.value.map((p) => p.plannedHours),+ backgroundColor: 'rgba(161,161,170,0.6)',+ },+ {+ label: t('sprints.velocity.accepted'),+ data: points.value.map((p) => p.acceptedHours),+ backgroundColor: 'rgba(34,197,94,0.7)',+ },+ ],+ },+ options: {+ responsive: true,+ maintainAspectRatio: false,+ plugins: {+ legend: { display: true, position: 'bottom' },+ tooltip: { enabled: !isMobile.value },+ },+ scales: {+ y: { beginAtZero: true, title: { display: !isMobile.value, text: unitLabel(props.unit) } },+ },+ },+ }++ if (instance) {+ instance.destroy()+ instance = null+ }+ instance = new Chart(canvas.value, config)+}++onMounted(() => {+ if (points.value.length) render()+})++onBeforeUnmount(() => {+ instance?.destroy()+ instance = null+})++watch(points, () => {+ if (points.value.length) render()+}, { deep: true })+</script>diff --git a/web/src/components/features/tasks/TaskDetailPanel.vue b/web/src/components/features/tasks/TaskDetailPanel.vueindex ba6a989..cabc6a9 100644--- a/web/src/components/features/tasks/TaskDetailPanel.vue+++ b/web/src/components/features/tasks/TaskDetailPanel.vue@@ -104,6 +104,20 @@:transaction-type="task.transactionType":class="colClass(fieldId)"/>+ <TaskSprintSelect+ v-else-if="fieldId === 'sprint'"+ :task-id="task.id"+ :goal-id="task.goalId"+ :current-sprint-id="task.sprintId"+ :class="colClass(fieldId)"+ />+ <TaskEstimateInput+ v-else-if="fieldId === 'estimate'"+ :task-id="task.id"+ :goal-id="task.goalId"+ :estimate-value="task.estimateValue"+ :class="colClass(fieldId)"+ /><TaskTimeTrackingv-else-if="fieldId === 'timeTracking'":task-id="task.id"@@ -147,6 +161,8 @@ import TaskTimeTracking from '@/components/features/tasks/parts/TaskTimeTrackingimport 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'+import TaskSprintSelect from '@/components/features/tasks/parts/TaskSprintSelect.vue'+import TaskEstimateInput from '@/components/features/tasks/parts/TaskEstimateInput.vue'import type { TaskBase } from 'taskview-api'import { useGoalPermissions } from '@/composables/useGoalPermissions'import { useUiPreferences } from '@/composables/useUiPreferences'diff --git a/web/src/components/features/tasks/parts/TaskEstimateInput.vue b/web/src/components/features/tasks/parts/TaskEstimateInput.vuenew file mode 100644index 0000000..db464da--- /dev/null+++ b/web/src/components/features/tasks/parts/TaskEstimateInput.vue@@ -0,0 +1,78 @@+<template>+ <div class="w-full h-fit dark:bg-tv-ui-bg-elevated shadow-sm rounded-lg p-2">+ <label class="text-sm text-muted mb-2 flex items-center gap-1">+ <UIcon+ name="i-lucide-gauge"+ class="size-4"+ />+ {{ t('tasks.fields.estimate') }}+ <span>({{ unitLabel(unit, true) }})</span>+ </label>++ <UInputNumber+ :model-value="localValue"+ :disabled="!canEdit"+ :min="0"+ :step="1"+ :placeholder="t('tasks.estimatePlaceholder')"+ size="xl"+ class="w-full"+ :variant="isDark ? 'subtle' : 'soft'"+ @update:model-value="onInput"+ @blur="save"+ />+ </div>+</template>++<script setup lang="ts">+import { computed, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import { useTasksStore } from '@/stores/tasks.store'+import { useGoalsStore } from '@/stores/goals.store'+import { useColor } from '@/composables/useColotMode'+import { useGoalPermissions } from '@/composables/useGoalPermissions'+import { useSprintFormat } from '@/components/features/sprints/composables/useSprintFormat'++const props = defineProps<{+ taskId: number+ goalId: number+ estimateValue: string | number | null+}>()++const { t } = useI18n()+const tasksStore = useTasksStore()+const goalsStore = useGoalsStore()+const { isDark } = useColor()+const { canEditTaskPriority } = useGoalPermissions()+const { unitLabel } = useSprintFormat()++const unit = computed(() => goalsStore.goalMap.get(props.goalId)?.estimateUnit ?? 'points')++const canEdit = canEditTaskPriority++function toNumber(value: string | number | null): number | null {+ if (value === null || value === '') return null+ const parsed = Number(value)+ return Number.isFinite(parsed) ? parsed : null+}++const localValue = ref<number | null>(toNumber(props.estimateValue))++watch(() => props.estimateValue, (value) => {+ localValue.value = toNumber(value)+})++function onInput(value: number | null) {+ localValue.value = value+}++async function save() {+ const next = localValue.value+ if (next === toNumber(props.estimateValue)) return++ await tasksStore.updateTaskEstimate({+ id: props.taskId,+ estimateValue: next,+ })+}+</script>diff --git a/web/src/components/features/tasks/parts/TaskSprintSelect.vue b/web/src/components/features/tasks/parts/TaskSprintSelect.vuenew file mode 100644index 0000000..7f31706--- /dev/null+++ b/web/src/components/features/tasks/parts/TaskSprintSelect.vue@@ -0,0 +1,135 @@+<template>+ <div+ v-if="canView"+ class="w-full h-fit dark:bg-tv-ui-bg-elevated shadow-sm rounded-lg p-2"+ >+ <label class="text-sm text-muted mb-2 block">{{ t('tasks.fields.sprint') }}</label>++ <USelectMenu+ v-if="canAssign"+ :model-value="currentSprintId ?? NO_SPRINT_VALUE"+ :items="sprintItems"+ :placeholder="t('tasks.fields.sprint')"+ :loading="loading"+ value-key="value"+ class="w-full"+ size="xl"+ variant="subtle"+ @update:model-value="selectSprint"+ @update:open="onOpen"+ >+ <template #leading>+ <UIcon+ name="i-lucide-rocket"+ class="size-4 text-muted"+ />+ </template>+ <template #item-label="{ item }">+ <span class="flex items-center gap-2">+ {{ item.label }}+ <UBadge+ v-if="item.status"+ :label="t(`sprints.status.${item.status}`)"+ :color="statusColor(item.status)"+ variant="subtle"+ size="sm"+ />+ </span>+ </template>+ </USelectMenu>++ <div+ v-else+ class="flex items-center gap-2 text-default px-1 py-2"+ >+ <UIcon+ name="i-lucide-rocket"+ class="size-4 text-muted"+ />+ <span>{{ currentSprintName ?? t('tasks.sprintNone') }}</span>+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed, ref } from 'vue'+import { useI18n } from 'vue-i18n'+import type { Sprint, SprintStatus } from 'taskview-api'+import { $tvApi } from '@/plugins/axios'+import { useTasksStore } from '@/stores/tasks.store'+import { useGoalsStore } from '@/stores/goals.store'+import { useGoalPermissionsFor } from '@/composables/useGoalPermissions'+import { useSprintFormat } from '@/components/features/sprints/composables/useSprintFormat'+import { logError } from '@/helpers/Helper'++const props = defineProps<{+ taskId: number+ goalId: number+ currentSprintId: number | null+}>()++const NO_SPRINT_VALUE = -1++const { t } = useI18n()+const toast = useToast()+const tasksStore = useTasksStore()+const goalsStore = useGoalsStore()+const { statusColor } = useSprintFormat()++const sprints = ref<Sprint[]>([])+const loadedGoalId = ref<number | null>(null)+const loading = ref(false)++const goal = computed(() => goalsStore.goalMap.get(props.goalId) ?? null)+const { canViewSprints: canView, canAssignSprintTasks: canAssign } = useGoalPermissionsFor(goal)++const currentSprintName = computed(() => {+ if (props.currentSprintId === null) return null+ return sprints.value.find(s => s.id === props.currentSprintId)?.name ?? null+})++const sprintItems = computed(() => [+ { label: t('tasks.sprintNone'), value: NO_SPRINT_VALUE, status: undefined as SprintStatus | undefined },+ ...sprints.value+ .filter(s => s.status !== 'completed')+ .map(s => ({ label: s.name, value: s.id, status: s.status as SprintStatus | undefined })),+])++async function loadSprints() {+ if (loadedGoalId.value === props.goalId) return+ loading.value = true+ const result = await $tvApi.sprints.listForGoal({ goalId: props.goalId }).catch(logError)+ loading.value = false+ if (!result) return+ sprints.value = result+ loadedGoalId.value = props.goalId+}++function onOpen(open: boolean) {+ if (open) loadSprints()+}++async function selectSprint(value: number) {+ const sprintId = value === NO_SPRINT_VALUE ? null : value+ if (sprintId === props.currentSprintId) return++ const result = await $tvApi.sprints+ .setTaskSprint({ taskId: props.taskId, sprintId })+ .catch(logError)++ if (!result) {+ toast.add({+ title: t('tasks.sprintUpdateFailed'),+ color: 'error',+ })+ return+ }++ const selected = tasksStore.selectedTask+ if (selected && selected.id === props.taskId) {+ selected.sprintId = sprintId+ }+}++loadSprints()+</script>diff --git a/web/src/composables/useFiltersFromQuery.ts b/web/src/composables/useFiltersFromQuery.tsindex f77eb40..f00c8d5 100644--- a/web/src/composables/useFiltersFromQuery.ts+++ b/web/src/composables/useFiltersFromQuery.ts@@ -19,37 +19,59 @@ export const useFiltersFromQuery = () => {const sameIds = (a: number[], b: number[]) =>a.length === b.length && a.every((v, i) => v === b[i])+ const parseSprint = (raw: unknown): number | null => {+ if (typeof raw === 'string' && raw) {+ const id = Number(raw)+ if (Number.isFinite(id)) return id+ }+ return null+ }++ const serializeSprint = (id: number | null): string | undefined =>+ id != null ? String(id) : undefined+const selectedListIds = ref<number[]>(parseIds(route.query.lists))const selectedAssigneeIds = ref<number[]>(parseIds(route.query.assignees))+ const selectedSprintId = ref<number | null>(parseSprint(route.query.sprint))- watch([selectedListIds, selectedAssigneeIds], ([lists, assignees]) => {+ watch([selectedListIds, selectedAssigneeIds, selectedSprintId], ([lists, assignees, sprint]) => {const next = { ...route.query }const listsStr = serializeIds(lists)const assigneesStr = serializeIds(assignees)+ const sprintStr = serializeSprint(sprint)if (listsStr) next.lists = listsStrelse delete next.listsif (assigneesStr) next.assignees = assigneesStrelse delete next.assignees+ if (sprintStr) next.sprint = sprintStr+ else delete next.sprintrouter.replace({ query: next })- })+ }, { deep: true })watch(- () => [route.query.lists, route.query.assignees] as const,- ([lists, assignees]) => {+ () => [route.query.lists, route.query.assignees, route.query.sprint] as const,+ ([lists, assignees, sprint]) => {const nextLists = parseIds(lists)const nextAssignees = parseIds(assignees)+ const nextSprint = parseSprint(sprint)if (!sameIds(nextLists, selectedListIds.value)) {selectedListIds.value = nextLists}if (!sameIds(nextAssignees, selectedAssigneeIds.value)) {selectedAssigneeIds.value = nextAssignees}+ if (nextSprint !== selectedSprintId.value) {+ selectedSprintId.value = nextSprint+ }},)const hasActiveFilters = computed(- () => selectedListIds.value.length > 0 || selectedAssigneeIds.value.length > 0,+ () =>+ selectedListIds.value.length > 0+ || selectedAssigneeIds.value.length > 0+ || selectedSprintId.value !== null,)- return { selectedListIds, selectedAssigneeIds, hasActiveFilters }+ return { selectedListIds, selectedAssigneeIds, selectedSprintId, hasActiveFilters }}diff --git a/web/src/composables/useGoalPermissions.ts b/web/src/composables/useGoalPermissions.tsindex f8d1451..b082e24 100644--- a/web/src/composables/useGoalPermissions.ts+++ b/web/src/composables/useGoalPermissions.ts@@ -27,6 +27,10 @@ export function useGoalPermissionsFor(goalRef: Ref<GoalItem | null>) {canViewIntegrations: computed(() => hasPermission(goalRef.value, 'INTEGRATIONS_CAN_VIEW') || hasPermission(goalRef.value, 'INTEGRATIONS_CAN_MANAGE')),canManageIntegrations: computed(() => hasPermission(goalRef.value, 'INTEGRATIONS_CAN_MANAGE')),canViewTimeTracking: computed(() => hasPermission(goalRef.value, 'TIMETRACKING_CAN_VIEW') || hasPermission(goalRef.value, 'TIMETRACKING_CAN_MANAGE_ALL')),+ canViewSprints: can('SPRINT_CAN_VIEW'),+ canManageSprints: can('SPRINT_CAN_MANAGE'),+ canAssignSprintTasks: can('SPRINT_CAN_ASSIGN_TASKS'),+ canViewSprintAnalytics: can('SPRINT_CAN_VIEW_ANALYTICS'),}}@@ -85,6 +89,11 @@ export const useGoalPermissions = () => {const canLogTime = computed(() => permissions.TIMETRACKING_CAN_LOG || permissions.TIMETRACKING_CAN_MANAGE_ALL)const canManageAllTime = computed(() => permissions.TIMETRACKING_CAN_MANAGE_ALL)+ const canViewSprints = computed(() => permissions.SPRINT_CAN_VIEW)+ const canManageSprints = computed(() => permissions.SPRINT_CAN_MANAGE)+ const canAssignSprintTasks = computed(() => permissions.SPRINT_CAN_ASSIGN_TASKS)+ const canViewSprintAnalytics = computed(() => permissions.SPRINT_CAN_VIEW_ANALYTICS)+return {permissions,canDeleteGoal,@@ -122,5 +131,9 @@ export const useGoalPermissions = () => {canViewTimeTracking,canLogTime,canManageAllTime,+ canViewSprints,+ canManageSprints,+ canAssignSprintTasks,+ canViewSprintAnalytics,}}diff --git a/web/src/locales/en.ts b/web/src/locales/en.tsindex 123e18e..afcf4d0 100644--- a/web/src/locales/en.ts+++ b/web/src/locales/en.ts@@ -94,6 +94,9 @@ export default {namePlaceholder: 'Enter project name',description: 'Description',descriptionPlaceholder: 'Enter project description',+ estimateUnit: 'Estimate unit',+ estimateUnitHours: 'Hours',+ estimateUnitPoints: 'Story points',deleteConfirm: 'Delete Project',deleteMessage: 'Are you sure you want to delete project "{name}"? All project history will be deleted, including task and list change history. This action cannot be undone.',addPlaceholder: 'Enter project name',@@ -102,6 +105,7 @@ export default {contextMenu: {kanban: 'Kanban',graph: 'Graph',+ sprints: 'Sprints',collaboration: 'Collaboration',integrations: 'Integrations',webhooks: 'Webhooks',@@ -129,6 +133,7 @@ export default {common: {cancel: 'Cancel',save: 'Save',+ edit: 'Edit',delete: 'Delete',done: 'Done',yes: 'Yes',@@ -149,6 +154,10 @@ export default {editColumn: 'Edit column',columnName: 'Column name',loadMore: 'Load more',+ sprintFilter: {+ all: 'All tasks',+ current: 'Current sprint',+ },},msg: {allTasks: 'Backlog',@@ -358,6 +367,13 @@ export default {selectList: 'Select list',searchLists: 'Search lists...',noList: 'No list',+ sprintNone: 'No sprint',+ sprintUpdateFailed: 'Failed to update sprint',+ estimatePlaceholder: 'Story points',+ fields: {+ sprint: 'Sprint',+ estimate: 'Estimate',+ },status: 'Status',selectStatus: 'Select status',searchStatuses: 'Search statuses...',@@ -579,6 +595,8 @@ export default {priority: 'Priority',assignees: 'Assignees',list: 'List',+ sprint: 'Sprint',+ estimate: 'Estimate',tags: 'Tags',deadline: 'Deadline',amount: 'Amount',@@ -770,4 +788,146 @@ export default {noPermissionHint: 'Ask a project admin for the time-tracking view permission to access reports.',},},+ sprints: {+ title: 'Sprints',+ create: 'New sprint',+ editTitle: 'Edit sprint',+ empty: 'No sprints yet',+ noActive: 'No active sprint',+ noPermission: 'You don\'t have permission to view sprints',+ paused: 'Paused',+ deleteConfirm: 'Delete sprint "{name}"? This cannot be undone.',+ tabs: {+ backlog: 'Backlog',+ active: 'Active',+ planned: 'Planned',+ completed: 'Completed',+ },+ status: {+ draft: 'Draft',+ planned: 'Planned',+ active: 'Active',+ review: 'Review',+ completed: 'Completed',+ },+ fields: {+ name: 'Name',+ namePlaceholder: 'e.g. Sprint 14',+ goal: 'Sprint goal',+ goalPlaceholder: 'What success looks like for this sprint',+ startDate: 'Start date',+ endDate: 'End date',+ capacity: 'Capacity (SP)',+ capacityPlaceholder: 'Story points',+ estimate: 'Estimate',+ },+ units: {+ points: 'story points',+ pointsShort: 'SP',+ hours: 'hours',+ hoursShort: 'h',+ },+ actions: {+ activate: 'Activate',+ startReview: 'Start review',+ close: 'Close sprint',+ pause: 'Pause',+ resume: 'Resume',+ delete: 'Delete',+ saveRetro: 'Save retro',+ plan: 'Plan',+ },+ metrics: {+ capacityUtilization: 'Capacity utilization',+ noCapacity: 'No capacity set',+ planned: 'Planned',+ accepted: 'Accepted',+ goal: 'Goal',+ goalAchieved: 'Achieved',+ goalMissed: 'Missed',+ },+ taskList: {+ title: 'Tasks',+ empty: 'No tasks in this sprint',+ estimate: 'Est',+ },+ burndown: {+ title: 'Burndown',+ empty: 'No burndown data available',+ ideal: 'Ideal',+ actual: 'Actual',+ },+ velocity: {+ title: 'Velocity',+ empty: 'No velocity data yet',+ lastN: 'Last {n} sprints',+ planned: 'Planned',+ accepted: 'Accepted',+ },+ retro: {+ title: 'Retrospective',+ wentWell: 'What went well',+ wentWellPlaceholder: 'Things that worked',+ wentBad: 'What went bad',+ wentBadPlaceholder: 'Things to improve',+ actionItems: 'Action items',+ actionItemsPlaceholder: 'What to change next sprint',+ },+ review: {+ title: 'Close sprint',+ hint: 'Set an outcome for each task before closing the sprint.',+ noTasks: 'No tasks to review',+ goalAchieved: 'Sprint goal achieved',+ carryTo: 'Carry over to',+ backlogOption: 'Backlog',+ },+ outcomes: {+ accepted: 'Accepted',+ carriedOver: 'Carried over',+ dropped: 'Dropped',+ },+ carryOver: {+ backlog: 'Move to backlog',+ next: 'Move to next sprint',+ keep: 'Keep in sprint',+ },+ planning: {+ title: 'Sprint planning',+ backlog: 'Backlog',+ backlogEmpty: 'No backlog tasks',+ inSprint: 'In sprint',+ sprintEmpty: 'No tasks assigned yet',+ loadError: 'Failed to load tasks',+ retry: 'Retry',+ },+ cadence: {+ button: 'Auto-sprints',+ title: 'Automatic sprints',+ description: 'Generate sprints on a fixed schedule, like Linear. The current and upcoming sprints are created for you — activate each one manually when you\'re ready.',+ enable: 'Enable auto-sprints',+ enableHint: 'You can still create and close sprints manually.',+ length: 'Sprint length',+ weeks: '{n} week | {n} weeks',+ startDate: 'First sprint starts',+ startDateHint: 'Anchor date — every sprint counts forward from here.',+ lookahead: 'Sprints ahead',+ lookaheadHint: 'How many future sprints to keep created beyond the current one.',+ nameTemplate: 'Name template',+ nameTemplateHint: 'Use {\'{n}\'} where the sprint number should appear.',+ saved: 'Auto-sprint settings saved',+ },+ notifications: {+ starting: 'Sprint starting soon',+ ending: 'Sprint ending soon',+ completed: 'Sprint completed',+ },+ toasts: {+ created: 'Sprint created',+ updated: 'Sprint updated',+ closed: 'Sprint closed',+ retroSaved: 'Retrospective saved',+ assignFailed: 'Failed to update task',+ closeFailed: 'Failed to close sprint',+ },+ },}diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.tsindex 8d4e421..f58146a 100644--- a/web/src/locales/ru.ts+++ b/web/src/locales/ru.ts@@ -94,6 +94,9 @@ export default {namePlaceholder: 'Введите название проекта',description: 'Описание',descriptionPlaceholder: 'Введите описание проекта',+ estimateUnit: 'Единица оценки',+ estimateUnitHours: 'Часы',+ estimateUnitPoints: 'Стори-поинты',deleteConfirm: 'Удалить проект',deleteMessage: 'Вы уверены, что хотите удалить проект "{name}"? Будет удалена вся история проекта, включая историю изменений задач и списков. Это действие нельзя отменить.',addPlaceholder: 'Введите название проекта',@@ -102,6 +105,7 @@ export default {contextMenu: {kanban: 'Канбан',graph: 'Граф',+ sprints: 'Спринты',collaboration: 'Совместная работа',integrations: 'Интеграции',webhooks: 'Вебхуки',@@ -129,6 +133,7 @@ export default {common: {cancel: 'Отмена',save: 'Сохранить',+ edit: 'Редактировать',delete: 'Удалить',done: 'Готово',yes: 'Да',@@ -149,6 +154,10 @@ export default {editColumn: 'Редактировать колонку',columnName: 'Название колонки',loadMore: 'Загрузить ещё',+ sprintFilter: {+ all: 'Все задачи',+ current: 'Текущий спринт',+ },},msg: {allTasks: 'Backlog',@@ -331,6 +340,13 @@ export default {selectList: 'Выбрать список',searchLists: 'Поиск списков...',noList: 'Без списка',+ sprintNone: 'Без спринта',+ sprintUpdateFailed: 'Не удалось обновить спринт',+ estimatePlaceholder: 'Стори-поинты',+ fields: {+ sprint: 'Спринт',+ estimate: 'Оценка',+ },status: 'Статус',selectStatus: 'Выбрать статус',searchStatuses: 'Поиск статусов...',@@ -552,6 +568,8 @@ export default {priority: 'Приоритет',assignees: 'Исполнители',list: 'Список',+ sprint: 'Спринт',+ estimate: 'Оценка',tags: 'Теги',deadline: 'Дедлайн',amount: 'Сумма',@@ -703,4 +721,146 @@ export default {noPermissionHint: 'Попросите администратора проекта выдать вам право на просмотр учёта времени.',},},+ sprints: {+ title: 'Спринты',+ create: 'Новый спринт',+ editTitle: 'Редактировать спринт',+ empty: 'Спринтов пока нет',+ noActive: 'Нет активного спринта',+ noPermission: 'У вас нет прав на просмотр спринтов',+ paused: 'На паузе',+ deleteConfirm: 'Удалить спринт «{name}»? Это действие необратимо.',+ tabs: {+ backlog: 'Бэклог',+ active: 'Активный',+ planned: 'Запланированные',+ completed: 'Завершённые',+ },+ status: {+ draft: 'Черновик',+ planned: 'Запланирован',+ active: 'Активный',+ review: 'Ревью',+ completed: 'Завершён',+ },+ fields: {+ name: 'Название',+ namePlaceholder: 'напр. Спринт 14',+ goal: 'Цель спринта',+ goalPlaceholder: 'Что считаем успехом этого спринта',+ startDate: 'Дата начала',+ endDate: 'Дата окончания',+ capacity: 'Capacity (SP)',+ capacityPlaceholder: 'Стори-поинты',+ estimate: 'Оценка',+ },+ units: {+ points: 'стори-поинты',+ pointsShort: 'SP',+ hours: 'часы',+ hoursShort: 'ч',+ },+ actions: {+ activate: 'Активировать',+ startReview: 'Начать ревью',+ close: 'Закрыть спринт',+ pause: 'Пауза',+ resume: 'Возобновить',+ delete: 'Удалить',+ saveRetro: 'Сохранить ретро',+ plan: 'Планировать',+ },+ metrics: {+ capacityUtilization: 'Загрузка capacity',+ noCapacity: 'Capacity не задана',+ planned: 'Запланировано',+ accepted: 'Принято',+ goal: 'Цель',+ goalAchieved: 'Достигнута',+ goalMissed: 'Не достигнута',+ },+ taskList: {+ title: 'Задачи',+ empty: 'В спринте нет задач',+ estimate: 'Оценка',+ },+ burndown: {+ title: 'Burndown',+ empty: 'Нет данных для burndown',+ ideal: 'Идеал',+ actual: 'Факт',+ },+ velocity: {+ title: 'Velocity',+ empty: 'Пока нет данных velocity',+ lastN: 'Последние {n} спринтов',+ planned: 'Запланировано',+ accepted: 'Принято',+ },+ retro: {+ title: 'Ретроспектива',+ wentWell: 'Что хорошо',+ wentWellPlaceholder: 'Что сработало',+ wentBad: 'Что плохо',+ wentBadPlaceholder: 'Что улучшить',+ actionItems: 'Действия',+ actionItemsPlaceholder: 'Что менять в следующем спринте',+ },+ review: {+ title: 'Закрытие спринта',+ hint: 'Проставьте исход для каждой задачи перед закрытием спринта.',+ noTasks: 'Нет задач для ревью',+ goalAchieved: 'Цель спринта достигнута',+ carryTo: 'Перенести в',+ backlogOption: 'Бэклог',+ },+ outcomes: {+ accepted: 'Принято',+ carriedOver: 'Перенесено',+ dropped: 'Отменено',+ },+ carryOver: {+ backlog: 'Вернуть в бэклог',+ next: 'Перенести в следующий спринт',+ keep: 'Оставить в спринте',+ },+ planning: {+ title: 'Планирование спринта',+ backlog: 'Бэклог',+ backlogEmpty: 'Нет задач в бэклоге',+ inSprint: 'В спринте',+ sprintEmpty: 'Задачи ещё не назначены',+ loadError: 'Не удалось загрузить задачи',+ retry: 'Повторить',+ },+ cadence: {+ button: 'Авто-спринты',+ title: 'Автоматические спринты',+ description: 'Создавайте спринты по фиксированному расписанию, как в Linear. Текущий и будущие спринты создаются автоматически — активируйте каждый вручную, когда будете готовы.',+ enable: 'Включить авто-спринты',+ enableHint: 'Вы по-прежнему можете создавать и закрывать спринты вручную.',+ length: 'Длительность спринта',+ weeks: '{n} неделя | {n} недели | {n} недель',+ startDate: 'Первый спринт начинается',+ startDateHint: 'Опорная дата — каждый спринт отсчитывается от неё.',+ lookahead: 'Спринтов вперёд',+ lookaheadHint: 'Сколько будущих спринтов держать созданными помимо текущего.',+ nameTemplate: 'Шаблон названия',+ nameTemplateHint: 'Используйте {\'{n}\'} там, где должен быть номер спринта.',+ saved: 'Настройки авто-спринтов сохранены',+ },+ notifications: {+ starting: 'Спринт скоро начнётся',+ ending: 'Спринт скоро закончится',+ completed: 'Спринт завершён',+ },+ toasts: {+ created: 'Спринт создан',+ updated: 'Спринт обновлён',+ closed: 'Спринт закрыт',+ retroSaved: 'Ретроспектива сохранена',+ assignFailed: 'Не удалось обновить задачу',+ closeFailed: 'Не удалось закрыть спринт',+ },+ },}diff --git a/web/src/main.ts b/web/src/main.tsindex c8ee5bb..92f89d2 100644--- a/web/src/main.ts+++ b/web/src/main.ts@@ -54,6 +54,11 @@ const router = createRouter({name: 'graph',component: () => import('./pages/user/graph.vue'),},+ {+ path: ':projectId/sprints',+ name: 'sprints',+ component: () => import('./pages/user/sprints.vue'),+ },{path: ':projectId/collaboration',name: 'collaboration',diff --git a/web/src/pages/user/graph.vue b/web/src/pages/user/graph.vueindex 0015a87..ff79dc7 100644--- a/web/src/pages/user/graph.vue+++ b/web/src/pages/user/graph.vue@@ -35,6 +35,8 @@<TvKanbanFiltersv-model:list-ids="selectedListIds"v-model:assignee-ids="selectedAssigneeIds"+ v-model:sprint-id="selectedSprintId"+ :goal-id="projectId"show-reset-label/></div>@@ -42,6 +44,7 @@<ProjectGraphv-model:list-ids="selectedListIds"v-model:assignee-ids="selectedAssigneeIds"+ v-model:sprint-id="selectedSprintId"class="h-full w-full"/></div>@@ -67,7 +70,7 @@ const { projectId } = useAppRouteInfo()const goalsStore = useGoalsStore()const projectName = computed(() => goalsStore.goalMap.get(projectId.value)?.name ?? '')-const { selectedListIds, selectedAssigneeIds, hasActiveFilters } = useFiltersFromQuery()+const { selectedListIds, selectedAssigneeIds, selectedSprintId, hasActiveFilters } = useFiltersFromQuery()const showFilters = ref(hasActiveFilters.value)useProjectDataLoader(projectId)diff --git a/web/src/pages/user/kanban.vue b/web/src/pages/user/kanban.vueindex 5ab14ec..1b2139e 100644--- a/web/src/pages/user/kanban.vue+++ b/web/src/pages/user/kanban.vue@@ -17,6 +17,8 @@<TvKanbanFiltersv-model:list-ids="selectedListIds"v-model:assignee-ids="selectedAssigneeIds"+ v-model:sprint-id="selectedSprintId"+ :goal-id="projectId"show-reset-label/></div>@@ -40,6 +42,8 @@<TvKanbanFiltersv-model:list-ids="selectedListIds"v-model:assignee-ids="selectedAssigneeIds"+ v-model:sprint-id="selectedSprintId"+ :goal-id="projectId"/></div></div>@@ -71,12 +75,12 @@ const goalsStore = useGoalsStore()const kanbanStore = useKanbanStore()const projectName = computed(() => goalsStore.goalMap.get(projectId.value)?.name ?? '')-const { selectedListIds, selectedAssigneeIds, hasActiveFilters } = useFiltersFromQuery()+const { selectedListIds, selectedAssigneeIds, selectedSprintId, hasActiveFilters } = useFiltersFromQuery()const showFilters = ref(hasActiveFilters.value)-watch([selectedListIds, selectedAssigneeIds], ([listIds, assigneeIds]) => {- kanbanStore.setFilters({ listIds, assigneeIds })-}, { immediate: true })+watch([selectedListIds, selectedAssigneeIds, selectedSprintId], ([listIds, assigneeIds, sprintId]) => {+ kanbanStore.setFilters({ listIds, assigneeIds, sprintId: sprintId ?? undefined })+}, { immediate: true, deep: true })useProjectDataLoader(projectId)</script>diff --git a/web/src/pages/user/sprints.vue b/web/src/pages/user/sprints.vuenew file mode 100644index 0000000..5c5ce01--- /dev/null+++ b/web/src/pages/user/sprints.vue@@ -0,0 +1,400 @@+<template>+ <UDashboardPanel id="sprints">+ <template #header>+ <UDashboardNavbar :title="`${projectName} - ${t('sprints.title')}`">+ <template #leading>+ <TvCollapseSidebarDesktop />+ </template>+ <template #right>+ <UButton+ v-if="canManage"+ icon="i-lucide-repeat"+ :label="t('sprints.cadence.button')"+ color="neutral"+ variant="ghost"+ @click="cadenceOpen = true"+ />+ <UButton+ v-if="canManage"+ icon="i-lucide-plus"+ :label="t('sprints.create')"+ @click="openCreate"+ />+ </template>+ </UDashboardNavbar>+ </template>++ <template #body>+ <div+ v-if="!canView"+ class="flex flex-col items-center gap-2 py-16 text-center"+ >+ <UIcon+ name="i-lucide-lock"+ class="size-8 text-dimmed"+ />+ <p class="text-muted">+ {{ t('sprints.noPermission') }}+ </p>+ </div>++ <div+ v-else+ class="flex flex-col gap-4"+ >+ <UTabs+ v-model="activeTab"+ :items="tabItems"+ class="w-full"+ />++ <div+ v-if="loading"+ class="flex justify-center py-10"+ >+ <UIcon+ name="i-lucide-loader-circle"+ class="size-6 animate-spin text-dimmed"+ />+ </div>++ <template v-else-if="activeTab === 'active'">+ <div+ v-if="activeSprint"+ class="flex flex-col gap-4"+ >+ <SprintHeader+ :sprint="activeSprint"+ :tasks="activeSprintTasks"+ >+ <template #actions>+ <UButton+ v-if="canAssign"+ icon="i-lucide-list-plus"+ :label="t('sprints.actions.plan')"+ size="sm"+ variant="soft"+ @click="planningOpen = true"+ />+ <UDropdownMenu+ v-if="canManage"+ :items="activeSprintMenu"+ >+ <UButton+ icon="i-lucide-ellipsis-vertical"+ color="neutral"+ variant="ghost"+ size="sm"+ />+ </UDropdownMenu>+ </template>+ </SprintHeader>++ <SprintBurndownChart+ v-if="canViewAnalytics"+ :burndown="burndown"+ :unit="estimateUnit"+ />+ <SprintTaskList+ :tasks="activeSprintTasks"+ :user-map="userMap"+ :unit="estimateUnit"+ />+ </div>+ <p+ v-else+ class="py-12 text-center text-muted"+ >+ {{ t('sprints.noActive') }}+ </p>+ </template>++ <template v-else>+ <p+ v-if="!visibleSprints.length"+ class="py-12 text-center text-muted"+ >+ {{ t('sprints.empty') }}+ </p>+ <UCard+ v-for="sprint in visibleSprints"+ :key="sprint.id"+ class="cursor-pointer hover:bg-elevated/50"+ @click="selectSprint(sprint)"+ >+ <div class="flex flex-wrap items-center justify-between gap-2">+ <div class="flex items-center gap-2">+ <span class="font-medium">{{ sprint.name }}</span>+ <UBadge+ :color="statusColor(sprint.status)"+ variant="subtle"+ size="sm"+ >+ {{ t(`sprints.status.${sprint.status}`) }}+ </UBadge>+ </div>+ <div class="flex items-center gap-2">+ <span class="text-sm text-dimmed">{{ formatRange(sprint) }}</span>+ <template v-if="canManage && (sprint.status === 'draft' || sprint.status === 'planned')">+ <UButton+ icon="i-lucide-play"+ :label="t('sprints.actions.activate')"+ size="xs"+ @click.stop="activate(sprint)"+ />+ <UButton+ icon="i-lucide-pencil"+ color="neutral"+ variant="ghost"+ size="xs"+ @click.stop="openEdit(sprint)"+ />+ <UButton+ icon="i-lucide-trash-2"+ color="error"+ variant="ghost"+ size="xs"+ :loading="deletingId === sprint.id"+ @click.stop="remove(sprint)"+ />+ </template>+ </div>+ </div>+ </UCard>+ </template>++ <template v-if="activeTab === 'completed' && currentSprint">+ <SprintRetroPanel+ :sprint-id="currentSprint.id"+ :retro="currentSprint.retro"+ :can-manage="canManage"+ />+ <SprintVelocityChart+ v-if="canViewAnalytics"+ :points="velocity"+ :unit="estimateUnit"+ />+ </template>+ </div>+ </template>+ </UDashboardPanel>++ <SprintFormDialog+ v-if="canManage"+ v-model:open="formOpen"+ :goal-id="projectId"+ :sprint="editSprint"+ @saved="onSaved"+ />++ <SprintReviewDialog+ v-if="canManage && activeSprint"+ v-model:open="reviewOpen"+ :sprint="activeSprint"+ :tasks="activeSprintTasks"+ @closed="onClosed"+ />++ <SprintPlanningDialog+ v-if="canAssign && activeSprint"+ v-model:open="planningOpen"+ :sprint="activeSprint"+ @changed="reloadTasks"+ />++ <SprintCadenceDialog+ v-if="canManage"+ v-model:open="cadenceOpen"+ :goal-id="projectId"+ @saved="loadAll"+ />+</template>++<script setup lang="ts">+import { computed, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import { storeToRefs } from 'pinia'+import { useDateFormat } from '@vueuse/core'+import type { Sprint } from 'taskview-api'+import TvCollapseSidebarDesktop from '@/components/features/base/TvCollapseSidebarDesktop.vue'+import SprintHeader from '@/components/features/sprints/parts/SprintHeader.vue'+import SprintTaskList from '@/components/features/sprints/parts/SprintTaskList.vue'+import SprintBurndownChart from '@/components/features/sprints/parts/SprintBurndownChart.vue'+import SprintVelocityChart from '@/components/features/sprints/parts/SprintVelocityChart.vue'+import SprintRetroPanel from '@/components/features/sprints/parts/SprintRetroPanel.vue'+import SprintFormDialog from '@/components/features/sprints/parts/SprintFormDialog.vue'+import SprintReviewDialog from '@/components/features/sprints/parts/SprintReviewDialog.vue'+import SprintPlanningDialog from '@/components/features/sprints/parts/SprintPlanningDialog.vue'+import SprintCadenceDialog from '@/components/features/sprints/parts/SprintCadenceDialog.vue'+import { useSprintFormat } from '@/components/features/sprints/composables/useSprintFormat'+import { useAppRouteInfo } from '@/composables/useAppRouteInfo'+import { useProjectDataLoader } from '@/composables/useProjectDataLoader'+import { useGoalsStore } from '@/stores/goals.store'+import { useSprintsStore } from '@/stores/sprints.store'+import { useCollaborationStore } from '@/stores/collaboration.store'+import { $tvApi } from '@/plugins/axios'+import { logError } from '@/helpers/Helper'+import { useGoalPermissionsFor } from '@/composables/useGoalPermissions'+import type { SprintTask } from '@/types/sprints.types'++type SprintTab = 'active' | 'planned' | 'backlog' | 'completed'++const { t } = useI18n()+const { projectId } = useAppRouteInfo()+const goalsStore = useGoalsStore()+const sprintsStore = useSprintsStore()+const collaborationStore = useCollaborationStore()+const { statusColor } = useSprintFormat()++const { activeSprint, currentSprint, velocity, loading } = storeToRefs(sprintsStore)+const { userMap } = storeToRefs(collaborationStore)++useProjectDataLoader(projectId)++const projectName = computed(() => goalsStore.goalMap.get(projectId.value)?.name ?? '')+const goal = computed(() => goalsStore.goalMap.get(projectId.value) ?? null)+const estimateUnit = computed(() => goalsStore.goalMap.get(projectId.value)?.estimateUnit ?? 'points')++const {+ canViewSprints: canView,+ canManageSprints: canManage,+ canAssignSprintTasks: canAssign,+ canViewSprintAnalytics: canViewAnalytics,+} = useGoalPermissionsFor(goal)++const activeTab = ref<SprintTab>('active')+const tabItems = computed(() => [+ { value: 'active', label: t('sprints.tabs.active') },+ { value: 'planned', label: t('sprints.tabs.planned') },+ { value: 'backlog', label: t('sprints.tabs.backlog') },+ { value: 'completed', label: t('sprints.tabs.completed') },+])++const allTasks = ref<SprintTask[]>([])+const formOpen = ref(false)+const editSprint = ref<Sprint | null>(null)+const reviewOpen = ref(false)+const planningOpen = ref(false)+const cadenceOpen = ref(false)+const burndown = computed(() => (activeSprint.value ? sprintsStore.burndownById[activeSprint.value.id] ?? null : null))++const visibleSprints = computed(() => {+ const status = activeTab.value === 'backlog' ? 'draft' : activeTab.value+ return sprintsStore.sprints.filter((s) => s.status === status)+})++const activeSprintTasks = computed(() =>+ activeSprint.value ? allTasks.value.filter((task) => task.sprintId === activeSprint.value?.id) : [],+)++const activeSprintMenu = computed(() => {+ if (!activeSprint.value) return []+ const sprint = activeSprint.value+ const items = []+ if (sprint.status === 'active') {+ items.push({+ label: t('sprints.actions.startReview'),+ icon: 'i-lucide-clipboard-check',+ onSelect: () => { reviewOpen.value = true },+ })+ items.push(+ sprint.pausedAt+ ? { label: t('sprints.actions.resume'), icon: 'i-lucide-play', onSelect: () => sprintsStore.resumeSprint(sprint.id) }+ : { label: t('sprints.actions.pause'), icon: 'i-lucide-pause', onSelect: () => sprintsStore.pauseSprint(sprint.id) },+ )+ }+ if (sprint.status === 'review') {+ items.push({+ label: t('sprints.actions.close'),+ icon: 'i-lucide-flag',+ onSelect: () => { reviewOpen.value = true },+ })+ }+ items.push({ label: t('common.edit'), icon: 'i-lucide-pencil', onSelect: () => openEdit(sprint) })+ return items+})++function formatRange(sprint: Sprint): string {+ const start = useDateFormat(new Date(sprint.startDate), 'DD MMM').value+ const end = useDateFormat(new Date(sprint.endDate), 'DD MMM YYYY').value+ return `${start} – ${end}`+}++function openCreate() {+ editSprint.value = null+ formOpen.value = true+}++function openEdit(sprint: Sprint) {+ editSprint.value = sprint+ formOpen.value = true+}++function selectSprint(sprint: Sprint) {+ sprintsStore.fetchSprint(sprint.id)+}++async function activate(sprint: Sprint) {+ const result = await sprintsStore.activateSprint(sprint.id)+ if (!result) return+ activeTab.value = 'active'+ await loadAll()+}++const deletingId = ref<number | null>(null)+async function remove(sprint: Sprint) {+ if (!window.confirm(t('sprints.deleteConfirm', { name: sprint.name }))) return+ deletingId.value = sprint.id+ const ok = await sprintsStore.removeSprint(sprint.id).finally(() => {+ deletingId.value = null+ })+ if (ok) await loadAll()+}++async function reloadTasks() {+ if (projectId.value <= 0) return+ const tasks = await $tvApi.tasks+ .fetch({+ goalId: projectId.value,+ componentId: -1401,+ page: 0,+ // ignoreCompleted skips the complete-filter entirely so we get BOTH+ // incomplete (backlog) AND completed (in-sprint / burndown) tasks.+ // (showCompleted: 1 alone would return ONLY completed tasks.)+ showCompleted: 1,+ ignoreCompleted: true,+ firstNew: 1,+ unlimited: true,+ })+ .catch(logError)+ if (tasks) allTasks.value = tasks as SprintTask[]+}++async function loadAll() {+ if (projectId.value <= 0 || !canView.value) return+ await Promise.all([+ sprintsStore.fetchSprintsForGoal({ goalId: projectId.value }),+ reloadTasks(),+ ])+ if (canViewAnalytics.value && activeSprint.value) {+ await sprintsStore.fetchBurndown(activeSprint.value.id)+ }+ if (canViewAnalytics.value) {+ await sprintsStore.fetchVelocity({ goalId: projectId.value, lastN: 6 })+ }+}++function onSaved() {+ loadAll()+}++function onClosed() {+ loadAll()+}++watch([projectId, canView], () => loadAll(), { immediate: true })++watch(activeSprint, (sprint) => {+ if (sprint && canViewAnalytics.value) sprintsStore.fetchBurndown(sprint.id)+})+</script>diff --git a/web/src/stores/sprints.store.ts b/web/src/stores/sprints.store.tsnew file mode 100644index 0000000..1cc17cc--- /dev/null+++ b/web/src/stores/sprints.store.ts@@ -0,0 +1,179 @@+import { defineStore } from 'pinia'+import type {+ Sprint,+ SprintCadence,+ SprintCloseArgs,+ SprintCreateArgs,+ SprintListFilterArgs,+ SprintPlanningArgs,+ SprintPlanningPage,+ SprintSaveRetroArgs,+ SprintSetCadenceArgs,+ SprintSetTaskArgs,+ SprintUpdateArgs,+ SprintVelocityArgs,+} from 'taskview-api'+import { $tvApi } from '@/plugins/axios'+import { logError } from '@/helpers/Helper'+import type { SprintsStoreState } from '@/types/sprints.types'++export const useSprintsStore = defineStore('sprints', {+ state: (): SprintsStoreState => ({+ sprints: [],+ activeSprint: null,+ currentSprint: null,+ burndownById: {},+ velocity: [],+ cadence: null,+ loading: false,+ }),+ getters: {+ sprintsByStatus: (state) => (status: Sprint['status']) =>+ state.sprints.filter((s) => s.status === status),+ },+ actions: {+ upsertSprint(sprint: Sprint) {+ const index = this.sprints.findIndex((s) => s.id === sprint.id)+ if (index !== -1) {+ this.sprints[index] = sprint+ } else {+ this.sprints.unshift(sprint)+ }+ if (sprint.status === 'active' || sprint.status === 'review') {+ this.activeSprint = sprint+ } else if (this.activeSprint?.id === sprint.id) {+ this.activeSprint = null+ }+ if (this.currentSprint?.id === sprint.id) {+ this.currentSprint = { ...this.currentSprint, ...sprint }+ }+ },++ async fetchSprintsForGoal(args: SprintListFilterArgs): Promise<void> {+ this.loading = true+ const sprints = await $tvApi.sprints+ .listForGoal(args)+ .catch(logError)+ .finally(() => {+ this.loading = false+ })+ if (!sprints) return+ this.sprints = sprints+ this.activeSprint = sprints.find((s) => s.status === 'active' || s.status === 'review') ?? null+ },++ async fetchSprint(sprintId: number): Promise<void> {+ const sprint = await $tvApi.sprints.getById(sprintId).catch(logError)+ if (!sprint) return+ this.currentSprint = sprint+ this.upsertSprint(sprint)+ },++ async fetchBurndown(sprintId: number): Promise<void> {+ const burndown = await $tvApi.sprints.getBurndown(sprintId).catch(logError)+ if (!burndown) return+ this.burndownById[sprintId] = burndown+ },++ async fetchVelocity(args: SprintVelocityArgs): Promise<void> {+ const velocity = await $tvApi.sprints.getVelocity(args).catch(logError)+ if (!velocity) return+ this.velocity = velocity+ },++ async createSprint(args: SprintCreateArgs): Promise<Sprint | null> {+ const sprint = await $tvApi.sprints.create(args).catch(logError)+ if (!sprint) return null+ this.upsertSprint(sprint)+ return sprint+ },++ async updateSprint(args: SprintUpdateArgs): Promise<Sprint | null> {+ const sprint = await $tvApi.sprints.update(args).catch(logError)+ if (!sprint) return null+ this.upsertSprint(sprint)+ return sprint+ },++ async activateSprint(sprintId: number): Promise<Sprint | null> {+ const sprint = await $tvApi.sprints.activate(sprintId).catch(logError)+ if (!sprint) return null+ this.upsertSprint(sprint)+ return sprint+ },++ async startReview(sprintId: number): Promise<Sprint | null> {+ const sprint = await $tvApi.sprints.startReview(sprintId).catch(logError)+ if (!sprint) return null+ this.upsertSprint(sprint)+ return sprint+ },++ async closeSprint(args: SprintCloseArgs): Promise<Sprint | null> {+ const sprint = await $tvApi.sprints.close(args).catch(logError)+ if (!sprint) return null+ this.upsertSprint(sprint)+ return sprint+ },++ async pauseSprint(sprintId: number): Promise<Sprint | null> {+ const sprint = await $tvApi.sprints.pause(sprintId).catch(logError)+ if (!sprint) return null+ this.upsertSprint(sprint)+ return sprint+ },++ async resumeSprint(sprintId: number): Promise<Sprint | null> {+ const sprint = await $tvApi.sprints.resume(sprintId).catch(logError)+ if (!sprint) return null+ this.upsertSprint(sprint)+ return sprint+ },++ async removeSprint(sprintId: number): Promise<boolean> {+ const result = await $tvApi.sprints.remove(sprintId).catch(logError)+ if (!result) return false+ const index = this.sprints.findIndex((s) => s.id === sprintId)+ if (index !== -1) this.sprints.splice(index, 1)+ if (this.activeSprint?.id === sprintId) this.activeSprint = null+ if (this.currentSprint?.id === sprintId) this.currentSprint = null+ delete this.burndownById[sprintId]+ return true+ },++ async saveRetro(args: SprintSaveRetroArgs): Promise<boolean> {+ const result = await $tvApi.sprints.saveRetro(args).catch(logError)+ if (!result) return false+ if (this.currentSprint?.id === args.sprintId) {+ this.currentSprint.retro = {+ wentWell: args.wentWell ?? this.currentSprint.retro?.wentWell ?? null,+ wentBad: args.wentBad ?? this.currentSprint.retro?.wentBad ?? null,+ actionItems: args.actionItems ?? this.currentSprint.retro?.actionItems ?? null,+ }+ }+ return true+ },++ async setTaskSprint(args: SprintSetTaskArgs): Promise<boolean> {+ const result = await $tvApi.sprints.setTaskSprint(args).catch(logError)+ return !!result+ },++ async fetchPlanningTasks(args: SprintPlanningArgs): Promise<SprintPlanningPage | null> {+ const page = await $tvApi.sprints.getPlanningTasks(args).catch(logError)+ return page ?? null+ },++ async fetchCadence(goalId: number): Promise<void> {+ const cadence = await $tvApi.sprints.getCadence(goalId).catch(logError)+ this.cadence = cadence ?? null+ },++ async saveCadence(args: SprintSetCadenceArgs): Promise<SprintCadence | null> {+ const cadence = await $tvApi.sprints.setCadence(args).catch(logError)+ if (!cadence) return null+ this.cadence = cadence+ return cadence+ },+ },+})diff --git a/web/src/stores/tasks.store.ts b/web/src/stores/tasks.store.tsindex ede525c..902d699 100644--- a/web/src/stores/tasks.store.ts+++ b/web/src/stores/tasks.store.ts@@ -549,5 +549,26 @@ export const useTasksStore = defineStore('tasks', {Object.assign(this.selectedTask, task)}},++ async updateTaskEstimate(data: TaskArgUpdate) {+ this.loading = true+ const task = await $tvApi.tasks+ .updateTask(data)+ .catch(logError)+ .finally(() => {+ this.loading = false+ })++ if (!task) return++ const localTask = this.tasks.find(({ id }) => id === task.id)++ if (localTask) {+ Object.assign(localTask, task)+ this.updateSelectedTask(task)+ } else if (this.selectedTask?.id === task.id) {+ Object.assign(this.selectedTask, task)+ }+ },},})diff --git a/web/src/types/collaboration-permissions.types.ts b/web/src/types/collaboration-permissions.types.tsindex 413e9da..b5a69e0 100644--- a/web/src/types/collaboration-permissions.types.ts+++ b/web/src/types/collaboration-permissions.types.ts@@ -1,13 +1,14 @@import type { CollaborationPermission } from 'taskview-api'import type { TI18nLocalesInApp } from './app.types'-export type PermissioinGroupsIds = 1 | 2 | 3 | 4;+export type PermissioinGroupsIds = 1 | 2 | 3 | 4 | 5;export const PermissionGroups: Record<PermissioinGroupsIds, Record<keyof TI18nLocalesInApp, string>> = {1: { en: 'Applicarion level', ru: 'Уровня приложения' },2: { en: 'Project', ru: 'Проект' },3: { en: 'Task list', ru: 'Список задач' },4: { en: 'Tasks', ru: 'Задачи' },+ 5: { en: 'Sprints', ru: 'Спринты' },}export type CollaborationPermissionsState = {diff --git a/web/src/types/goals.types.ts b/web/src/types/goals.types.tsindex 9e377e6..9b99326 100644--- a/web/src/types/goals.types.ts+++ b/web/src/types/goals.types.ts@@ -11,6 +11,7 @@ export const DEFAULT_GOAL_ITEM: GoalItem = {archive: 0,dateCreation: null,organizationId: null,+ estimateUnit: 'points',}export const AllGoalPermissions = TvPermissionsdiff --git a/web/src/types/sprints.types.ts b/web/src/types/sprints.types.tsnew file mode 100644index 0000000..f5a06a8--- /dev/null+++ b/web/src/types/sprints.types.ts@@ -0,0 +1,47 @@+import type {+ Sprint,+ SprintBurndown,+ SprintCadence,+ SprintStatus,+ SprintVelocityPoint,+ SprintWithRetro,+ Task,+} from 'taskview-api'++/**+ * Tasks carry sprint-related fields at runtime (added by the backend+ * migration) that are not yet part of the shared `Task` type.+ */+export type SprintTask = Task & {+ sprintId?: number | null+ estimateValue?: string | null+ completedAt?: string | null+}++export type SprintsStoreState = {+ sprints: Sprint[]+ activeSprint: Sprint | null+ currentSprint: SprintWithRetro | null+ burndownById: Record<number, SprintBurndown>+ velocity: SprintVelocityPoint[]+ cadence: SprintCadence | null+ loading: boolean+}++export type SprintCadenceFormValue = {+ enabled: boolean+ lengthWeeks: number+ startDate: string | null+ lookahead: number+ nameTemplate: string+}++export type SprintFormValue = {+ name: string+ goalText: string+ startDate: string | null+ endDate: string | null+ capacity: number | null+}++export const SprintStatusOrder: SprintStatus[] = ['draft', 'planned', 'active', 'review', 'completed']diff --git a/web/src/uiCustomization/sections/tasks.types.ts b/web/src/uiCustomization/sections/tasks.types.tsindex 52b591d..6dd27ae 100644--- a/web/src/uiCustomization/sections/tasks.types.ts+++ b/web/src/uiCustomization/sections/tasks.types.ts@@ -12,6 +12,8 @@ export const TASK_DETAIL_FIELDS = [{ id: 'priority', width: 'narrow' },{ id: 'assignees', width: 'narrow' },{ id: 'list', width: 'narrow' },+ { id: 'sprint', width: 'narrow' },+ { id: 'estimate', width: 'narrow' },{ id: 'tags', width: 'narrow' },{ id: 'deadline', width: 'narrow' },{ id: 'amount', width: 'wide' },