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: automation
Nikolai Giman79f9c5941b1c
diff --git a/api/src/App.ts b/api/src/App.tsindex 2cbcabe..41dcde0 100644--- a/api/src/App.ts+++ b/api/src/App.ts@@ -67,6 +67,8 @@ export default class App {this.app.use(corsMiddleware);this.app.use(cookieParser());this.app.use(express.json({+ // RFC 7644 §3.1: SCIM clients (Entra ID, Okta, OneLogin) send application/scim+json+ type: ['application/json', 'application/scim+json'],verify: (req: any, _res, buf) => {// Store raw body for webhook signature verification github and gitlab integrationsif (req.url?.includes('/webhook/')) {diff --git a/api/src/core/AppUser.ts b/api/src/core/AppUser.tsindex d4271d4..444ea84 100644--- a/api/src/core/AppUser.ts+++ b/api/src/core/AppUser.ts@@ -18,6 +18,7 @@ import { UiPreferencesManager } from '../tv-modules/ui-preferences/UiPreferencesimport { SprintsManager } from '../tv-modules/sprints/SprintsManager';import { RecurrenceManager } from '../tv-modules/recurrence/RecurrenceManager';import { FilesManager } from '../tv-modules/files/FilesManager';+import { AutomationsManager } from '../tv-modules/automations/AutomationsManager';import type { UserDbRecord, UserJwtPayload } from '../types/auth.types';import { GoalPermissionsFetcher } from './GoalPermissionsFetcher';@@ -49,6 +50,7 @@ export class AppUser {public readonly sprintsManager: SprintsManager;public readonly recurrenceManager: RecurrenceManager;public readonly filesManager: FilesManager;+ public readonly automationsManager: AutomationsManager;constructor(userData?: UserJwtPayload) {this.userData = userData;@@ -73,6 +75,7 @@ export class AppUser {this.sprintsManager = new SprintsManager(this);this.recurrenceManager = new RecurrenceManager(this);this.filesManager = new FilesManager(this);+ this.automationsManager = new AutomationsManager(this);}getTokenId(): number | undefined {diff --git a/api/src/core/CentrifugoClient.ts b/api/src/core/CentrifugoClient.tsindex 949265d..e40a14e 100644--- a/api/src/core/CentrifugoClient.ts+++ b/api/src/core/CentrifugoClient.ts@@ -1,10 +1,6 @@import jwt from 'jsonwebtoken';import { $logger } from '../modules/logget';--interface CentrifugoPublishPayload {- channel: string;- data: Record<string, unknown>;-}+import type { CentrifugoApiCall, CentrifugoBroadcastToUsersArgs } from '../types/centrifugo.types';export class CentrifugoClient {private readonly apiUrl: string;@@ -24,11 +20,23 @@ export class CentrifugoClient {}async publish(channel: string, data: Record<string, unknown>): Promise<boolean> {+ return this.call({ method: 'publish', payload: { channel, data } });+ }++ async broadcastToUsers(args: CentrifugoBroadcastToUsersArgs): Promise<boolean> {+ if (args.userIds.length === 0) return true;+ return this.call({+ method: 'broadcast',+ payload: { channels: args.userIds.map((id) => `personal:#${id}`), data: { event: args.event, ...args.data } },+ });+ }++ private async call(args: CentrifugoApiCall): Promise<boolean> {if (!this.enabled) return false;+ const { method, payload } = args;try {- const payload: CentrifugoPublishPayload = { channel, data };- const response = await fetch(`${this.apiUrl}/api/publish`, {+ const response = await fetch(`${this.apiUrl}/api/${method}`, {method: 'POST',headers: {'Content-Type': 'application/json',@@ -38,13 +46,13 @@ export class CentrifugoClient {});if (!response.ok) {- $logger.error({ status: response.status }, '[Centrifugo] Publish failed');+ $logger.error({ status: response.status, method }, '[Centrifugo] Publish failed');return false;}return true;} catch (err) {- $logger.error({ err }, '[Centrifugo] Publish error');+ $logger.error({ err, method }, '[Centrifugo] Publish error');return false;}}diff --git a/api/src/core/EventBus.ts b/api/src/core/EventBus.tsindex 69c56ae..552e822 100644--- a/api/src/core/EventBus.ts+++ b/api/src/core/EventBus.ts@@ -9,6 +9,7 @@ export interface AppEvents {'task.created': { task: TasksSchemaTypeForSelect; initiatorId: number };'task.updated': { task: TasksSchemaTypeForSelect; changes: Record<string, unknown>; initiatorId: number };'task.assigneesChanged': { taskId: number; userIds: number[]; initiatorId: number };+ 'task.tagsChanged': { taskId: number; tagId: number; added: boolean; initiatorId: number };'task.deleted': { taskId: number; goalId: number; initiatorId: number };// A task (with the subtasks in taskIds) moved to another project; the copy mode emits task.created instead'task.moved': { task: TasksSchemaTypeForSelect; taskIds: number[]; fromGoalId: number; toGoalId: number; initiatorId: number };@@ -42,6 +43,9 @@ export interface AppEvents {'recurrence.ended': { ruleId: number; goalId: number; initiatorId: number };'recurrence.deleted': { ruleId: number; goalId: number; initiatorId: number };'recurrence.instanceSkipped': { ruleId: number; goalId: number; date: string; initiatorId: number };+ 'kanban.statusDeleted': { statusId: number; goalId: number; initiatorId: number };+ 'tag.deleted': { tagId: number; goalId: number; initiatorId: number };+ 'list.deleted': { listId: number; goalId: number; initiatorId: number };'files.changed': { goalId: number; taskIds: number[]; initiatorId: number };[FileEvents.Uploaded]: FileEventPayload;[FileEvents.Renamed]: FileEventPayload;diff --git a/api/src/core/__tests__/CentrifugoClient.spec.ts b/api/src/core/__tests__/CentrifugoClient.spec.tsnew file mode 100644index 0000000..5cdb991--- /dev/null+++ b/api/src/core/__tests__/CentrifugoClient.spec.ts@@ -0,0 +1,37 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { CentrifugoClient } from '../CentrifugoClient';++describe('CentrifugoClient.broadcastToUsers', () => {+ afterEach(() => {+ vi.unstubAllEnvs();+ vi.unstubAllGlobals();+ });++ it('sends one broadcast to the personal channels of all users', async () => {+ vi.stubEnv('CENTRIFUGO_API_URL', 'http://centrifugo:8000');+ vi.stubEnv('CENTRIFUGO_API_KEY', 'secret');+ const fetchMock = vi.fn(async () => new Response('{}', { status: 200 }));+ vi.stubGlobal('fetch', fetchMock);++ const sent = await new CentrifugoClient().broadcastToUsers({ userIds: [1, 2], event: 'tasks.changed', data: { goalId: 10 } });++ expect(sent).toBe(true);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toBe('http://centrifugo:8000/api/broadcast');+ expect(JSON.parse(init.body as string)).toEqual({+ channels: ['personal:#1', 'personal:#2'],+ data: { event: 'tasks.changed', goalId: 10 },+ });+ });++ it('does nothing for an empty audience', async () => {+ vi.stubEnv('CENTRIFUGO_API_URL', 'http://centrifugo:8000');+ vi.stubEnv('CENTRIFUGO_API_KEY', 'secret');+ const fetchMock = vi.fn();+ vi.stubGlobal('fetch', fetchMock);++ expect(await new CentrifugoClient().broadcastToUsers({ userIds: [], event: 'tasks.changed', data: {} })).toBe(true);+ expect(fetchMock).not.toHaveBeenCalled();+ });+});diff --git a/api/src/core/all-events.ts b/api/src/core/all-events.tsindex 0ff0a6c..025e964 100644--- a/api/src/core/all-events.ts+++ b/api/src/core/all-events.ts@@ -9,6 +9,7 @@ import { RecurrenceDispatcher } from '../tv-modules/recurrence/RecurrenceDispatcimport { MessagingDispatcher } from '../tv-modules/messaging/MessagingDispatcher';import { InviteEmailDispatcher } from '../tv-modules/collaboration/InviteEmailDispatcher';import { FilesDispatcher } from '../tv-modules/files/FilesDispatcher';+import { AutomationsDispatcher } from '../tv-modules/automations/AutomationsDispatcher';const dispatchers: Dispatcher[] = [new NotificationDispatcher(),@@ -20,6 +21,7 @@ const dispatchers: Dispatcher[] = [new MessagingDispatcher(),new InviteEmailDispatcher(),new FilesDispatcher(),+ new AutomationsDispatcher(),];export function registerAllEventHandlers() {diff --git a/api/src/migrations/taskview/migrate.json b/api/src/migrations/taskview/migrate.jsonindex c7ad81f..96c73f4 100644--- a/api/src/migrations/taskview/migrate.json+++ b/api/src/migrations/taskview/migrate.json@@ -828,5 +828,19 @@"New column tv_auth.organizations.file_quota_mb (megabytes, NULL by default). Every organization has its own file storage quota: this column when set, otherwise the instance default FILE_QUOTA_ORGANIZATION_MB.","Quotas are enforced by default (100 MB per organization, FILE_QUOTA_ORGANIZATION_MB); FILE_QUOTA_MODE=off disables them."]+ },+ "64": {+ "version": "1.69.0",+ "name": "Automations: project automation rules",+ "releaseDate": "20261010",+ "scripts": [+ "/1.69.0/0.create-automation-rules.sql",+ "/1.69.0/1.automation-permissions.sql",+ "/1.69.0/all-triggers.sql"+ ],+ "description": [+ "New schema tv_automations with the rules table. A rule belongs to a project and links a trigger (module, event, params) to an action (module, action, params); actions run on behalf of the rule creator with their current project permissions.",+ "New permission group 8 'automations' with automation_can_view and automation_can_manage. New projects grant them to editor (both) and executor (view) through the updated add_roles_and_permissions() trigger. Existing projects are not backfilled: owners grant the permissions to their roles in the role editor."+ ]}}diff --git a/api/src/migrations/taskview/sql/1.69.0/0.create-automation-rules.sql b/api/src/migrations/taskview/sql/1.69.0/0.create-automation-rules.sqlnew file mode 100644index 0000000..85e3bcf--- /dev/null+++ b/api/src/migrations/taskview/sql/1.69.0/0.create-automation-rules.sql@@ -0,0 +1,19 @@+CREATE SCHEMA IF NOT EXISTS tv_automations;++CREATE TABLE IF NOT EXISTS tv_automations.rules (+ id SERIAL PRIMARY KEY,+ goal_id INTEGER NOT NULL REFERENCES tasks.goals(id) ON DELETE CASCADE,+ creator_id INTEGER NOT NULL REFERENCES tv_auth.users(id) ON DELETE CASCADE,+ name VARCHAR(255) NOT NULL,+ enabled BOOLEAN NOT NULL DEFAULT TRUE,+ trigger_module VARCHAR(64) NOT NULL,+ trigger_event VARCHAR(64) NOT NULL,+ trigger_params JSONB NOT NULL DEFAULT '{}'::jsonb,+ action_module VARCHAR(64) NOT NULL,+ action_name VARCHAR(64) NOT NULL,+ action_params JSONB NOT NULL DEFAULT '{}'::jsonb,+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),+ edited_at TIMESTAMP NOT NULL DEFAULT NOW()+);++CREATE INDEX IF NOT EXISTS rules_goal_enabled_idx ON tv_automations.rules(goal_id, enabled);diff --git a/api/src/migrations/taskview/sql/1.69.0/1.automation-permissions.sql b/api/src/migrations/taskview/sql/1.69.0/1.automation-permissions.sqlnew file mode 100644index 0000000..f258695--- /dev/null+++ b/api/src/migrations/taskview/sql/1.69.0/1.automation-permissions.sql@@ -0,0 +1,26 @@+-- Permission group 8 = automations (shown in the role editor)+INSERT INTO tv_auth.permissions_group (id, name)+VALUES (8, 'automations')+ON CONFLICT (id) DO NOTHING;++INSERT INTO tv_auth.permissions (name, description, permission_group, description_locales)+VALUES+ ('automation_can_view', 'View project automation rules', 8,+ '{+ "en": "View automations. See the project automation rules.",+ "ru": "Просмотр автоматизаций. Видеть правила автоматизации проекта.",+ "de": "Automatisierungen ansehen. Die Automatisierungsregeln des Projekts sehen.",+ "es": "Ver automatizaciones. Ver las reglas de automatización del proyecto.",+ "pt-BR": "Ver automações. Ver as regras de automação do projeto."+ }'::jsonb),+ ('automation_can_manage', 'Create, edit, enable, disable and delete project automation rules', 8,+ '{+ "en": "Manage automations. Create, edit, enable, disable and delete project automation rules.",+ "ru": "Управление автоматизациями. Создавать, изменять, включать, выключать и удалять правила автоматизации проекта.",+ "de": "Automatisierungen verwalten. Automatisierungsregeln des Projekts erstellen, bearbeiten, aktivieren, deaktivieren und löschen.",+ "es": "Gestionar automatizaciones. Crear, editar, activar, desactivar y eliminar las reglas de automatización del proyecto.",+ "pt-BR": "Gerenciar automações. Criar, editar, ativar, desativar e excluir as regras de automação do projeto."+ }'::jsonb)+ON CONFLICT (name) DO NOTHING;++-- Existing projects are NOT backfilled: owners grant the permissions to their roles in the role editor.diff --git a/api/src/migrations/taskview/sql/1.69.0/all-triggers.sql b/api/src/migrations/taskview/sql/1.69.0/all-triggers.sqlnew file mode 100644index 0000000..5ad3836--- /dev/null+++ b/api/src/migrations/taskview/sql/1.69.0/all-triggers.sql@@ -0,0 +1,647 @@+--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',+ 'file_can_view',+ 'file_can_manage',+ 'automation_can_view',+ 'automation_can_manage'+ );++ -- 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',+ 'file_can_view',+ 'automation_can_view'+ );++ 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 d086dab..7cdee9d 100644--- a/api/src/routes/index.ts+++ b/api/src/routes/index.ts@@ -27,6 +27,7 @@ import RecurrenceRoutes from '../tv-modules/recurrence/RecurrenceRoutes';import BillingRoutes from '../tv-modules/billing/BillingRoutes';import InvoicesRoutes from '../tv-modules/invoices/InvoicesRoutes';import FilesRoutes from '../tv-modules/files/FilesRoutes';+import AutomationsRoutes from '../tv-modules/automations/AutomationsRoutes';import type { Routable } from '../types/routable.type';type RoutableConstructor = new (...args: any[]) => Routable;@@ -59,6 +60,7 @@ const routes: Record<string, RoutableConstructor> = {'/module/billing': BillingRoutes,'/module/invoices': InvoicesRoutes,'/module/files': FilesRoutes,+ '/module/automations': AutomationsRoutes,'/scim/v2': ScimRoutes,'/.well-known': OAuthWellKnownRoutes,};diff --git a/api/src/tv-modules/automations/AutomationActorFactory.ts b/api/src/tv-modules/automations/AutomationActorFactory.tsnew file mode 100644index 0000000..6b026f7--- /dev/null+++ b/api/src/tv-modules/automations/AutomationActorFactory.ts@@ -0,0 +1,12 @@+import { AppUser } from '../../core/AppUser';++export class AutomationActorFactory {+ async forUser(userId: number): Promise<AppUser | null> {+ const user = await new AppUser().authManager.repository.fetchUserById(userId);+ if (!user || user.block !== 0) return null;++ const actor = new AppUser({ id: 0, userData: { id: user.id, login: user.login, email: user.email } });+ actor.setUserDataFromDb(user);+ return actor;+ }+}diff --git a/api/src/tv-modules/automations/AutomationCycleDetector.ts b/api/src/tv-modules/automations/AutomationCycleDetector.tsnew file mode 100644index 0000000..254b591--- /dev/null+++ b/api/src/tv-modules/automations/AutomationCycleDetector.ts@@ -0,0 +1,64 @@+import type { AutomationCatalog } from './catalog/AutomationCatalog';+import type {+ AutomationCycleNextRulesArgs,+ AutomationCycleTriggersArgs,+ AutomationParamsCompatibleArgs,+ AutomationRuleShape,+} from './types';++type VisitState = 'new' | 'active' | 'done';++export class AutomationCycleDetector {+ private readonly catalog: AutomationCatalog;++ constructor(catalog: AutomationCatalog) {+ this.catalog = catalog;+ }++ findCycle(rules: AutomationRuleShape[]): AutomationRuleShape[] | null {+ const edges = new Map(rules.map((rule) => [rule.id, this.nextRules({ rule, rules })]));+ const state = new Map<number, VisitState>(rules.map((rule) => [rule.id, 'new']));+ const stack: AutomationRuleShape[] = [];++ const visit = (rule: AutomationRuleShape): AutomationRuleShape[] | null => {+ state.set(rule.id, 'active');+ stack.push(rule);+ for (const next of edges.get(rule.id) ?? []) {+ const nextState = state.get(next.id);+ if (nextState === 'active') return stack.slice(stack.indexOf(next));+ if (nextState === 'new') {+ const found = visit(next);+ if (found) return found;+ }+ }+ stack.pop();+ state.set(rule.id, 'done');+ return null;+ };++ for (const rule of rules) {+ if (state.get(rule.id) !== 'new') continue;+ const found = visit(rule);+ if (found) return found;+ }+ return null;+ }++ private nextRules(args: AutomationCycleNextRulesArgs): AutomationRuleShape[] {+ const action = this.catalog.findAction(args.rule.action);+ const emitted = action?.emits(args.rule.action.params) ?? null;+ if (!emitted) return [];+ return args.rules.filter((other) => this.triggers({ emitted, rule: other }));+ }++ private triggers(args: AutomationCycleTriggersArgs): boolean {+ const { emitted, rule } = args;+ if (emitted.module !== rule.trigger.module || emitted.event !== rule.trigger.event) return false;+ return this.paramsCompatible({ emitted: emitted.params, expected: rule.trigger.params });+ }++ private paramsCompatible(args: AutomationParamsCompatibleArgs): boolean {+ if (!args.emitted) return true;+ return Object.entries(args.expected).every(([key, value]) => args.emitted?.[key] === undefined || args.emitted[key] === value);+ }+}diff --git a/api/src/tv-modules/automations/AutomationEngine.ts b/api/src/tv-modules/automations/AutomationEngine.tsnew file mode 100644index 0000000..c052a76--- /dev/null+++ b/api/src/tv-modules/automations/AutomationEngine.ts@@ -0,0 +1,151 @@+import { AsyncLocalStorage } from 'node:async_hooks';+import type { AppUser } from '../../core/AppUser';+import { $logger } from '../../modules/logget';+import { TasksRepository } from '../tasks/TasksRepository';+import { AutomationActorFactory } from './AutomationActorFactory';+import { AutomationPermissions } from './AutomationPermissions';+import type { AutomationRunQueue } from './AutomationRunQueue';+import { AutomationsRepository } from './AutomationsRepository';+import type { AutomationCatalog } from './catalog/AutomationCatalog';+import {+ AUTOMATION_CHAIN_MAX_DEPTH,+ type AutomationActorForArgs,+ type AutomationBusEvent,+ type AutomationChain,+ type AutomationEngineDeps,+ type AutomationParams,+ type AutomationRuleMatchArgs,+ type AutomationRunJob,+ type AutomationRunRuleArgs,+ type AutomationTaskBusEvent,+} from './types';++export class AutomationEngine {+ private readonly chainStorage = new AsyncLocalStorage<AutomationChain>();+ private readonly catalog: AutomationCatalog;+ private readonly queue: AutomationRunQueue;+ private readonly repository = new AutomationsRepository();+ private readonly tasksRepository = new TasksRepository();+ private readonly actorFactory = new AutomationActorFactory();++ constructor(deps: AutomationEngineDeps) {+ this.catalog = deps.catalog;+ this.queue = deps.queue;+ }++ handle(busEvent: AutomationBusEvent): Promise<void> {+ return this.track(this.schedule(busEvent));+ }++ handleForTask(busEvent: AutomationTaskBusEvent): Promise<void> {+ return this.track(this.loadAndSchedule(busEvent));+ }++ async run(job: AutomationRunJob): Promise<void> {+ const chain: AutomationChain = {+ depth: job.chain.depth,+ firedRuleIds: new Set(job.chain.firedRuleIds),+ actors: new Map(),+ pending: [],+ };++ let failure: unknown = null;+ for (const ref of job.rules) {+ try {+ await this.chainStorage.run(chain, () => this.runRule({ ref, job, chain }));+ } catch (err) {+ $logger.error(err, `[Automations] rule=${ref.id} crashed for task=${job.taskId}`);+ failure ??= err;+ }+ }++ await Promise.all(chain.pending);+ if (failure) throw failure;+ }++ private track(scheduled: Promise<void>): Promise<void> {+ this.chainStorage.getStore()?.pending.push(scheduled);+ return scheduled;+ }++ private async loadAndSchedule(busEvent: AutomationTaskBusEvent): Promise<void> {+ if (!this.catalog.listensTo(busEvent.name)) return;+ const task = await this.tasksRepository.fetchTaskByIdNew(busEvent.taskId);+ if (!task) return;+ await this.schedule({ name: busEvent.name, task, changes: busEvent.changes });+ }++ private async schedule(busEvent: AutomationBusEvent): Promise<void> {+ if (!this.catalog.listensTo(busEvent.name)) return;++ const chain = this.chainStorage.getStore();+ const depth = chain?.depth ?? 0;+ if (depth >= AUTOMATION_CHAIN_MAX_DEPTH) {+ $logger.warn(`[Automations] chain depth limit reached for task=${busEvent.task.id}`);+ return;+ }++ const rules = await this.repository.listEnabledForGoal(busEvent.task.goalId);+ if (!rules) throw new Error(`[Automations] can not load rules for goal=${busEvent.task.goalId}`);++ const fired = chain?.firedRuleIds ?? new Set<number>();+ const matched = rules.filter((rule) => !fired.has(rule.id) && this.matches({ rule, busEvent }));+ if (matched.length === 0) return;++ for (const rule of matched) fired.add(rule.id);+ await this.queue.enqueue({+ goalId: busEvent.task.goalId,+ taskId: busEvent.task.id,+ rules: matched.map((rule) => ({ id: rule.id, editedAt: rule.editedAt.toISOString() })),+ chain: { depth: depth + 1, firedRuleIds: [...fired] },+ });+ }++ private matches(args: AutomationRuleMatchArgs): boolean {+ const { rule, busEvent } = args;+ const event = this.catalog.findEvent({ module: rule.triggerModule, event: rule.triggerEvent });+ if (!event || !event.busEvents.includes(busEvent.name)) return false;+ return event.match({ busEvent, params: rule.triggerParams as AutomationParams });+ }++ private async runRule(args: AutomationRunRuleArgs): Promise<void> {+ const { ref, job } = args;+ const rule = await this.repository.getById(ref.id);+ if (!rule || !rule.enabled || rule.goalId !== job.goalId || rule.editedAt.toISOString() !== ref.editedAt) {+ $logger.info(`[Automations] rule=${ref.id} skipped: changed after it was scheduled`);+ return;+ }++ const action = this.catalog.findAction({ module: rule.actionModule, action: rule.actionName });+ if (!action) return;++ const task = await this.tasksRepository.fetchTaskByIdNew(job.taskId);+ if (!task || task.goalId !== rule.goalId) return;++ const actor = await this.actorFor({ chain: args.chain, userId: rule.creatorId });+ if (!actor) {+ $logger.info(`[Automations] rule=${rule.id} skipped: creator ${rule.creatorId} is unavailable`);+ return;+ }++ const allowed = await AutomationPermissions.canRun({ actor, goalId: rule.goalId, action });+ if (!allowed) {+ $logger.info(`[Automations] rule=${rule.id} skipped: creator ${rule.creatorId} lacks permissions`);+ return;+ }++ const outcome = await action.execute({ actor, task, params: rule.actionParams as AutomationParams });+ if (outcome === 'failed') {+ $logger.warn(`[Automations] rule=${rule.id} action ${rule.actionModule}/${rule.actionName} failed for task=${task.id}`);+ }+ }++ private actorFor(args: AutomationActorForArgs): Promise<AppUser | null> {+ let actor = args.chain.actors.get(args.userId);+ if (!actor) {+ actor = this.actorFactory.forUser(args.userId);+ args.chain.actors.set(args.userId, actor);+ }+ return actor;+ }+}diff --git a/api/src/tv-modules/automations/AutomationOptionRemovalHandler.ts b/api/src/tv-modules/automations/AutomationOptionRemovalHandler.tsnew file mode 100644index 0000000..4940116--- /dev/null+++ b/api/src/tv-modules/automations/AutomationOptionRemovalHandler.ts@@ -0,0 +1,39 @@+import { $logger } from '../../modules/logget';+import { AutomationRuleMapper } from './AutomationRuleMapper';+import { AutomationsRepository } from './AutomationsRepository';+import type { AutomationCatalog } from './catalog/AutomationCatalog';+import type { AutomationOptionRemovedArgs, AutomationRuleUsesOptionArgs } from './types';++export class AutomationOptionRemovalHandler {+ private readonly catalog: AutomationCatalog;+ private readonly repository = new AutomationsRepository();++ constructor(catalog: AutomationCatalog) {+ this.catalog = catalog;+ }++ async handle(args: AutomationOptionRemovedArgs): Promise<void> {+ const rows = await this.repository.listEnabledForGoal(args.goalId);+ if (!rows) return;++ const ruleIds = rows+ .filter((row) => this.ruleUsesOption({ rule: AutomationRuleMapper.toShape(row), source: args.source, id: args.id }))+ .map((row) => row.id);++ const disabled = await this.repository.disableMany({ goalId: args.goalId, ruleIds });+ if (disabled.length > 0) {+ $logger.info(`[Automations] ${args.source}=${args.id} removed, disabled rules ${disabled.join(',')} in goal=${args.goalId}`);+ }+ }++ private ruleUsesOption(args: AutomationRuleUsesOptionArgs): boolean {+ const { rule } = args;+ const steps = [+ { definitions: this.catalog.findEvent(rule.trigger)?.params ?? [], params: rule.trigger.params },+ { definitions: this.catalog.findAction(rule.action)?.params ?? [], params: rule.action.params },+ ];+ return steps.some((step) =>+ step.definitions.some((definition) => definition.source === args.source && step.params[definition.key] === args.id)+ );+ }+}diff --git a/api/src/tv-modules/automations/AutomationPermissions.ts b/api/src/tv-modules/automations/AutomationPermissions.tsnew file mode 100644index 0000000..991ba1e--- /dev/null+++ b/api/src/tv-modules/automations/AutomationPermissions.ts@@ -0,0 +1,30 @@+import { GoalPermissionsFetcher } from '../../core/GoalPermissionsFetcher';+import { logError } from '../../utils/api';+import { GoalPermissions } from '../../types/auth.types';+import type { AutomationCanRunArgs, AutomationHasPermissionsArgs } from './types';++export class AutomationPermissions {+ static async hasAll(args: AutomationHasPermissionsArgs): Promise<boolean> {+ const checker = await args.actor.permissionsFetcher+ .getPermissionsForType(args.goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)+ .catch(logError);+ if (!checker) return false;+ return args.permissions.every((permission) => checker.hasPermissions(permission));+ }++ static async hasAny(args: AutomationHasPermissionsArgs): Promise<boolean> {+ const checker = await args.actor.permissionsFetcher+ .getPermissionsForType(args.goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)+ .catch(logError);+ if (!checker) return false;+ return args.permissions.some((permission) => checker.hasPermissions(permission));+ }++ static async canRun(args: AutomationCanRunArgs): Promise<boolean> {+ return AutomationPermissions.hasAll({+ actor: args.actor,+ goalId: args.goalId,+ permissions: [GoalPermissions.AUTOMATION_CAN_MANAGE, ...args.action.requiredPermissions],+ });+ }+}diff --git a/api/src/tv-modules/automations/AutomationRuleMapper.ts b/api/src/tv-modules/automations/AutomationRuleMapper.tsnew file mode 100644index 0000000..d0cac63--- /dev/null+++ b/api/src/tv-modules/automations/AutomationRuleMapper.ts@@ -0,0 +1,26 @@+import type { AutomationRuleForClient, AutomationRuleRow, AutomationRuleShape } from './types';++export class AutomationRuleMapper {+ static toShape(row: AutomationRuleRow): AutomationRuleShape {+ return {+ id: row.id,+ trigger: { module: row.triggerModule, event: row.triggerEvent, params: row.triggerParams as Record<string, number> },+ action: { module: row.actionModule, action: row.actionName, params: row.actionParams as Record<string, number> },+ };+ }++ static toClient(row: AutomationRuleRow): AutomationRuleForClient {+ const shape = AutomationRuleMapper.toShape(row);+ return {+ id: row.id,+ goalId: row.goalId,+ creatorId: row.creatorId,+ name: row.name,+ enabled: row.enabled,+ trigger: shape.trigger,+ action: shape.action,+ createdAt: row.createdAt.toISOString(),+ editedAt: row.editedAt.toISOString(),+ };+ }+}diff --git a/api/src/tv-modules/automations/AutomationRunQueue.ts b/api/src/tv-modules/automations/AutomationRunQueue.tsnew file mode 100644index 0000000..d07e845--- /dev/null+++ b/api/src/tv-modules/automations/AutomationRunQueue.ts@@ -0,0 +1,37 @@+import { getJobQueue } from '../../core/JobQueue';+import {+ AUTOMATION_RUN_CONCURRENCY,+ AUTOMATION_RUN_POLLING_SECONDS,+ AUTOMATION_RUN_QUEUE,+ AUTOMATION_RUN_RETRY_LIMIT,+ type AutomationRunJob,+ type AutomationRunJobHandler,+} from './types';++export class AutomationRunQueue {+ private workerId: string | null = null;++ async work(handler: AutomationRunJobHandler): Promise<void> {+ const boss = getJobQueue();+ await boss.createQueue(AUTOMATION_RUN_QUEUE);+ this.workerId = await boss.work<AutomationRunJob>(+ AUTOMATION_RUN_QUEUE,+ {+ localConcurrency: AUTOMATION_RUN_CONCURRENCY,+ groupConcurrency: 1,+ pollingIntervalSeconds: AUTOMATION_RUN_POLLING_SECONDS,+ },+ async ([job]) => handler(job.data)+ );+ }++ async enqueue(job: AutomationRunJob): Promise<void> {+ const boss = getJobQueue();+ await boss.send(AUTOMATION_RUN_QUEUE, job, {+ group: { id: String(job.taskId) },+ retryLimit: AUTOMATION_RUN_RETRY_LIMIT,+ retryBackoff: true,+ });+ if (this.workerId) boss.notifyWorker(this.workerId);+ }+}diff --git a/api/src/tv-modules/automations/AutomationsController.ts b/api/src/tv-modules/automations/AutomationsController.tsnew file mode 100644index 0000000..18c0a6d--- /dev/null+++ b/api/src/tv-modules/automations/AutomationsController.ts@@ -0,0 +1,64 @@+import { type } from 'arktype';+import type { Request, Response } from 'express';+import {+ AutomationArkTypeGoalIdParam,+ AutomationArkTypeOptionsParams,+ AutomationArkTypeRuleIdParam,+ AutomationArkTypeRuleInput,+ AutomationArkTypeRulePatch,+ type AutomationErrorCode,+ type AutomationResult,+} from './types';++const codeToStatus: Record<AutomationErrorCode, number> = {+ not_found: 404,+ forbidden: 403,+ invalid: 400,+ cycle: 409,+ limit_reached: 409,+};++export default class AutomationsController {+ private sendResult<T>(res: Response, result: AutomationResult<T>) {+ if (result.ok) return res.tvJson(result.data);+ return res.status(codeToStatus[result.code]).json({ code: result.code, message: result.message ?? null });+ }++ catalog = (req: Request, res: Response) => {+ return res.tvJson(req.appUser.automationsManager.catalog());+ };++ options = async (req: Request, res: Response) => {+ const params = AutomationArkTypeOptionsParams(req.params);+ if (params instanceof type.errors) return res.status(400).send(params.summary);+ return this.sendResult(res, await req.appUser.automationsManager.options(params));+ };++ list = async (req: Request, res: Response) => {+ const params = AutomationArkTypeGoalIdParam(req.params);+ if (params instanceof type.errors) return res.status(400).send(params.summary);+ return res.tvJson(await req.appUser.automationsManager.list(params.goalId));+ };++ create = async (req: Request, res: Response) => {+ const params = AutomationArkTypeGoalIdParam(req.params);+ if (params instanceof type.errors) return res.status(400).send(params.summary);+ const input = AutomationArkTypeRuleInput(req.body);+ if (input instanceof type.errors) return res.status(400).send(input.summary);+ return this.sendResult(res, await req.appUser.automationsManager.create({ goalId: params.goalId, input }));+ };++ update = async (req: Request, res: Response) => {+ const params = AutomationArkTypeRuleIdParam(req.params);+ if (params instanceof type.errors) return res.status(400).send(params.summary);+ const patch = AutomationArkTypeRulePatch(req.body);+ if (patch instanceof type.errors) return res.status(400).send(patch.summary);+ return this.sendResult(res, await req.appUser.automationsManager.update({ ruleId: params.ruleId, patch }));+ };++ remove = async (req: Request, res: Response) => {+ const params = AutomationArkTypeRuleIdParam(req.params);+ if (params instanceof type.errors) return res.status(400).send(params.summary);+ return this.sendResult(res, await req.appUser.automationsManager.remove(params.ruleId));+ };+}diff --git a/api/src/tv-modules/automations/AutomationsDispatcher.ts b/api/src/tv-modules/automations/AutomationsDispatcher.tsnew file mode 100644index 0000000..687ad93--- /dev/null+++ b/api/src/tv-modules/automations/AutomationsDispatcher.ts@@ -0,0 +1,29 @@+import type { Dispatcher } from '../../core/Dispatcher';+import { eventBus } from '../../core/EventBus';+import { AutomationEngine } from './AutomationEngine';+import { AutomationOptionRemovalHandler } from './AutomationOptionRemovalHandler';+import { AutomationRunQueue } from './AutomationRunQueue';+import { automationCatalog } from './catalog/AutomationCatalog';++export class AutomationsDispatcher implements Dispatcher {+ private readonly queue = new AutomationRunQueue();+ private readonly engine = new AutomationEngine({ catalog: automationCatalog, queue: this.queue });+ private readonly optionRemoval = new AutomationOptionRemovalHandler(automationCatalog);++ register(): void {+ eventBus.on('task.created', (data) => this.engine.handle({ name: 'task.created', task: data.task, changes: {} }));+ eventBus.on('task.updated', (data) => this.engine.handle({ name: 'task.updated', task: data.task, changes: data.changes }));+ eventBus.on('task.tagsChanged', (data) =>+ this.engine.handleForTask({ name: 'task.tagsChanged', taskId: data.taskId, changes: { tagId: data.tagId, added: data.added } })+ );+ eventBus.on('kanban.statusDeleted', (data) =>+ this.optionRemoval.handle({ goalId: data.goalId, source: 'kanban.statuses', id: data.statusId })+ );+ eventBus.on('tag.deleted', (data) => this.optionRemoval.handle({ goalId: data.goalId, source: 'tags.goalTags', id: data.tagId }));+ eventBus.on('list.deleted', (data) => this.optionRemoval.handle({ goalId: data.goalId, source: 'lists.goalLists', id: data.listId }));+ }++ async registerWorkers(): Promise<void> {+ await this.queue.work((job) => this.engine.run(job));+ }+}diff --git a/api/src/tv-modules/automations/AutomationsManager.ts b/api/src/tv-modules/automations/AutomationsManager.tsnew file mode 100644index 0000000..17f58aa--- /dev/null+++ b/api/src/tv-modules/automations/AutomationsManager.ts@@ -0,0 +1,226 @@+import type { AppUser } from '../../core/AppUser';+import { AutomationCycleDetector } from './AutomationCycleDetector';+import { AutomationPermissions } from './AutomationPermissions';+import { AutomationRuleMapper } from './AutomationRuleMapper';+import { AutomationsRepository } from './AutomationsRepository';+import { automationCatalog } from './catalog/AutomationCatalog';+import {+ AUTOMATION_RULE_NAME_MAX_LENGTH,+ AUTOMATION_RULES_PER_GOAL_LIMIT,+ type AutomationCatalogForClient,+ type AutomationCheckCycleArgs,+ type AutomationCreateRuleArgs,+ type AutomationNormalizeParamsArgs,+ type AutomationOption,+ type AutomationOptionsArgs,+ type AutomationParams,+ type AutomationResult,+ type AutomationRuleForClient,+ type AutomationRuleShape,+ type AutomationUpdateRuleArgs,+ type AutomationValidateRuleArgs,+} from './types';++export class AutomationsManager {+ private readonly user: AppUser;+ private readonly repository: AutomationsRepository;+ private readonly cycleDetector: AutomationCycleDetector;++ constructor(user: AppUser) {+ this.user = user;+ this.repository = new AutomationsRepository();+ this.cycleDetector = new AutomationCycleDetector(automationCatalog);+ }++ catalog(): AutomationCatalogForClient {+ return automationCatalog.toClient();+ }++ async options(args: AutomationOptionsArgs): Promise<AutomationResult<AutomationOption[]>> {+ const source = automationCatalog.findDataSource(args.source);+ if (!source) return { ok: false, code: 'not_found', message: 'Unknown data source' };+ const allowed = await AutomationPermissions.hasAny({ actor: this.user, goalId: args.goalId, permissions: source.viewPermissions });+ if (!allowed) return { ok: false, code: 'forbidden' };+ return { ok: true, data: await source.load({ actor: this.user, goalId: args.goalId }) };+ }++ async list(goalId: number): Promise<AutomationRuleForClient[]> {+ const rows = await this.repository.listForGoal(goalId);+ return rows.map((row) => AutomationRuleMapper.toClient(row));+ }++ async getGoalIdOfRule(ruleId: number): Promise<number | null> {+ return (await this.repository.getById(ruleId))?.goalId ?? null;+ }++ async create(args: AutomationCreateRuleArgs): Promise<AutomationResult<AutomationRuleForClient>> {+ const userId = this.user.getUserData()?.id;+ if (!userId) return { ok: false, code: 'forbidden' };++ if ((await this.repository.countForGoal(args.goalId)) >= AUTOMATION_RULES_PER_GOAL_LIMIT) {+ return { ok: false, code: 'limit_reached', message: `A project can have at most ${AUTOMATION_RULES_PER_GOAL_LIMIT} automation rules` };+ }++ const validated = await this.validateRule({+ goalId: args.goalId,+ rule: {+ id: 0,+ trigger: { module: args.input.trigger.module, event: args.input.trigger.event, params: args.input.trigger.params ?? {} },+ action: { module: args.input.action.module, action: args.input.action.action, params: args.input.action.params ?? {} },+ },+ });+ if (!validated.ok) return validated;++ const name = this.normalizeName(args.input.name);+ if (!name) return { ok: false, code: 'invalid', message: 'name is required' };++ const enabled = args.input.enabled ?? true;+ if (enabled) {+ const cycle = await this.checkCycle({ goalId: args.goalId, candidate: validated.data, candidateName: name });+ if (!cycle.ok) return cycle;+ }++ const row = await this.repository.insert({+ goalId: args.goalId,+ creatorId: userId,+ name,+ enabled,+ triggerModule: validated.data.trigger.module,+ triggerEvent: validated.data.trigger.event,+ triggerParams: validated.data.trigger.params,+ actionModule: validated.data.action.module,+ actionName: validated.data.action.action,+ actionParams: validated.data.action.params,+ });+ if (!row) return { ok: false, code: 'invalid', message: 'Can not save the rule' };+ return { ok: true, data: AutomationRuleMapper.toClient(row) };+ }++ async update(args: AutomationUpdateRuleArgs): Promise<AutomationResult<AutomationRuleForClient>> {+ const userId = this.user.getUserData()?.id;+ if (!userId) return { ok: false, code: 'forbidden' };++ const current = await this.repository.getById(args.ruleId);+ if (!current) return { ok: false, code: 'not_found' };++ const { patch } = args;+ const name = patch.name !== undefined ? this.normalizeName(patch.name) : undefined;+ const enabled = patch.enabled ?? current.enabled;+ if (name === '') return { ok: false, code: 'invalid', message: 'name is required' };++ const changesDefinition = patch.trigger !== undefined || patch.action !== undefined;+ const enabling = patch.enabled === true && !current.enabled;++ if (!changesDefinition && !enabling) {+ const row = await this.repository.update({ ruleId: args.ruleId, patch: { name, enabled: patch.enabled } });+ if (!row) return { ok: false, code: 'not_found' };+ return { ok: true, data: AutomationRuleMapper.toClient(row) };+ }++ const currentShape = AutomationRuleMapper.toShape(current);+ const validated = await this.validateRule({+ goalId: current.goalId,+ rule: {+ id: current.id,+ trigger: patch.trigger+ ? { module: patch.trigger.module, event: patch.trigger.event, params: patch.trigger.params ?? {} }+ : currentShape.trigger,+ action: patch.action+ ? { module: patch.action.module, action: patch.action.action, params: patch.action.params ?? {} }+ : currentShape.action,+ },+ });+ if (!validated.ok) return validated;++ if (enabled) {+ const cycle = await this.checkCycle({ goalId: current.goalId, candidate: validated.data, candidateName: name ?? current.name });+ if (!cycle.ok) return cycle;+ }++ const row = await this.repository.update({+ ruleId: args.ruleId,+ patch: {+ creatorId: userId,+ name,+ enabled: patch.enabled,+ triggerModule: validated.data.trigger.module,+ triggerEvent: validated.data.trigger.event,+ triggerParams: validated.data.trigger.params,+ actionModule: validated.data.action.module,+ actionName: validated.data.action.action,+ actionParams: validated.data.action.params,+ },+ });+ if (!row) return { ok: false, code: 'not_found' };+ return { ok: true, data: AutomationRuleMapper.toClient(row) };+ }++ async remove(ruleId: number): Promise<AutomationResult<true>> {+ const deleted = await this.repository.deleteById(ruleId);+ return deleted ? { ok: true, data: true } : { ok: false, code: 'not_found' };+ }++ private async validateRule(args: AutomationValidateRuleArgs): Promise<AutomationResult<AutomationRuleShape>> {+ const { rule, goalId } = args;+ const event = automationCatalog.findEvent(rule.trigger);+ if (!event) return { ok: false, code: 'invalid', message: `Unknown event ${rule.trigger.module}/${rule.trigger.event}` };++ const action = automationCatalog.findAction(rule.action);+ if (!action) return { ok: false, code: 'invalid', message: `Unknown action ${rule.action.module}/${rule.action.action}` };++ const allowed = await AutomationPermissions.hasAll({ actor: this.user, goalId, permissions: action.requiredPermissions });+ if (!allowed) return { ok: false, code: 'forbidden', message: 'You do not have the permissions this action needs' };++ const triggerParams = await this.normalizeParams({ goalId, definitions: event.params, params: rule.trigger.params });+ if (!triggerParams.ok) return triggerParams;++ const actionParams = await this.normalizeParams({ goalId, definitions: action.params, params: rule.action.params });+ if (!actionParams.ok) return actionParams;++ return {+ ok: true,+ data: {+ id: rule.id,+ trigger: { module: rule.trigger.module, event: rule.trigger.event, params: triggerParams.data },+ action: { module: rule.action.module, action: rule.action.action, params: actionParams.data },+ },+ };+ }++ private async normalizeParams(args: AutomationNormalizeParamsArgs): Promise<AutomationResult<AutomationParams>> {+ const normalized: AutomationParams = {};+ for (const definition of args.definitions) {+ const value = args.params[definition.key];+ if (value === undefined) return { ok: false, code: 'invalid', message: `${definition.key} is required` };++ const source = automationCatalog.findDataSource(definition.source);+ const options = source ? await source.load({ actor: this.user, goalId: args.goalId }) : [];+ if (!options.some((option) => option.id === value)) {+ return { ok: false, code: 'invalid', message: `${definition.key} ${value} is not available in this project` };+ }+ normalized[definition.key] = value;+ }+ return { ok: true, data: normalized };+ }++ private async checkCycle(args: AutomationCheckCycleArgs): Promise<AutomationResult<true>> {+ const rows = await this.repository.listEnabledForGoal(args.goalId);+ if (!rows) return { ok: false, code: 'invalid', message: 'Can not check the rule for cycles' };+ const rules = rows+ .filter((row) => row.id !== args.candidate.id)+ .map((row) => AutomationRuleMapper.toShape(row));+ rules.push(args.candidate);++ const cycle = this.cycleDetector.findCycle(rules);+ if (!cycle) return { ok: true, data: true };++ const names = new Map(rows.map((row) => [row.id, row.name]));+ names.set(args.candidate.id, args.candidateName);+ const path = cycle.map((rule) => names.get(rule.id)).join(' → ');+ return { ok: false, code: 'cycle', message: path };+ }++ private normalizeName(name: string): string {+ return name.trim().slice(0, AUTOMATION_RULE_NAME_MAX_LENGTH);+ }+}diff --git a/api/src/tv-modules/automations/AutomationsRepository.ts b/api/src/tv-modules/automations/AutomationsRepository.tsnew file mode 100644index 0000000..c17917c--- /dev/null+++ b/api/src/tv-modules/automations/AutomationsRepository.ts@@ -0,0 +1,125 @@+import { and, asc, count, eq, inArray } from 'drizzle-orm';+import { AutomationRulesSchema, TagsSchema, type TagsSchemaTypeForSelect } from 'taskview-db-schemas';+import { Database } from '../../modules/db';+import { callWithCatch } from '../../utils/helpers';+import type { AutomationRuleInsertArgs, AutomationRuleRow, AutomationRulesDisableArgs, AutomationRuleUpdateArgs } from './types';++export class AutomationsRepository {+ private readonly db: Database;++ constructor() {+ this.db = Database.getInstance();+ }++ async getById(ruleId: number): Promise<AutomationRuleRow | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.select().from(AutomationRulesSchema).where(eq(AutomationRulesSchema.id, ruleId)).limit(1)+ );+ return result?.[0] ?? null;+ }++ async listForGoal(goalId: number): Promise<AutomationRuleRow[]> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(AutomationRulesSchema)+ .where(eq(AutomationRulesSchema.goalId, goalId))+ .orderBy(asc(AutomationRulesSchema.id))+ );+ return result ?? [];+ }++ async listEnabledForGoal(goalId: number): Promise<AutomationRuleRow[] | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(AutomationRulesSchema)+ .where(and(eq(AutomationRulesSchema.goalId, goalId), eq(AutomationRulesSchema.enabled, true)))+ .orderBy(asc(AutomationRulesSchema.id))+ );+ return result;+ }++ async countForGoal(goalId: number): Promise<number> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.select({ value: count() }).from(AutomationRulesSchema).where(eq(AutomationRulesSchema.goalId, goalId))+ );+ return result?.[0]?.value ?? 0;+ }++ async insert(args: AutomationRuleInsertArgs): Promise<AutomationRuleRow | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .insert(AutomationRulesSchema)+ .values({+ goalId: args.goalId,+ creatorId: args.creatorId,+ name: args.name,+ enabled: args.enabled,+ triggerModule: args.triggerModule,+ triggerEvent: args.triggerEvent,+ triggerParams: args.triggerParams,+ actionModule: args.actionModule,+ actionName: args.actionName,+ actionParams: args.actionParams,+ })+ .returning()+ );+ return result?.[0] ?? null;+ }++ async update(args: AutomationRuleUpdateArgs): Promise<AutomationRuleRow | null> {+ const { patch } = args;+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .update(AutomationRulesSchema)+ .set({+ creatorId: patch.creatorId,+ name: patch.name,+ enabled: patch.enabled,+ triggerModule: patch.triggerModule,+ triggerEvent: patch.triggerEvent,+ triggerParams: patch.triggerParams,+ actionModule: patch.actionModule,+ actionName: patch.actionName,+ actionParams: patch.actionParams,+ editedAt: new Date(),+ })+ .where(eq(AutomationRulesSchema.id, args.ruleId))+ .returning()+ );+ return result?.[0] ?? null;+ }++ async disableMany(args: AutomationRulesDisableArgs): Promise<number[]> {+ if (args.ruleIds.length === 0) return [];+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .update(AutomationRulesSchema)+ .set({ enabled: false, editedAt: new Date() })+ .where(+ and(+ eq(AutomationRulesSchema.goalId, args.goalId),+ eq(AutomationRulesSchema.enabled, true),+ inArray(AutomationRulesSchema.id, args.ruleIds)+ )+ )+ .returning({ id: AutomationRulesSchema.id })+ );+ return result?.map((row) => row.id) ?? [];+ }++ async deleteById(ruleId: number): Promise<boolean> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.delete(AutomationRulesSchema).where(eq(AutomationRulesSchema.id, ruleId)).returning({ id: AutomationRulesSchema.id })+ );+ return (result?.length ?? 0) > 0;+ }++ async fetchGoalTags(goalId: number): Promise<TagsSchemaTypeForSelect[]> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.select().from(TagsSchema).where(eq(TagsSchema.goalId, goalId)).orderBy(asc(TagsSchema.name))+ );+ return result ?? [];+ }+}diff --git a/api/src/tv-modules/automations/AutomationsRoutes.ts b/api/src/tv-modules/automations/AutomationsRoutes.tsnew file mode 100644index 0000000..d381ec0--- /dev/null+++ b/api/src/tv-modules/automations/AutomationsRoutes.ts@@ -0,0 +1,35 @@+import { Router } from 'express';+import type { Routable } from '../../types/routable.type';+import { GoalPermissions } from '../../types/auth.types';+import { IsLoggedIn } from '../auth/middlewares/is-logged-in';+import AutomationsController from './AutomationsController';+import { goalIdFromParam, goalIdFromRule } from './middlewares/goal-id-resolvers';+import { requireAutomationPermission } from './middlewares/require-automation-permission';++export default class AutomationsRoutes implements Routable {+ private readonly router: ReturnType<typeof Router>;+ private readonly controller: AutomationsController;++ constructor() {+ this.router = Router();+ this.controller = new AutomationsController();+ this.initRoutes();+ }++ getRouter() {+ return this.router;+ }++ initRoutes() {+ const canView = requireAutomationPermission({ permission: GoalPermissions.AUTOMATION_CAN_VIEW, resolveGoalId: goalIdFromParam });+ const canManage = requireAutomationPermission({ permission: GoalPermissions.AUTOMATION_CAN_MANAGE, resolveGoalId: goalIdFromParam });+ const canManageRule = requireAutomationPermission({ permission: GoalPermissions.AUTOMATION_CAN_MANAGE, resolveGoalId: goalIdFromRule });++ this.router.get('/catalog', [IsLoggedIn], this.controller.catalog);+ this.router.get('/goal/:goalId/options/:source', [IsLoggedIn, canView], this.controller.options);+ this.router.get('/goal/:goalId/rules', [IsLoggedIn, canView], this.controller.list);+ this.router.post('/goal/:goalId/rules', [IsLoggedIn, canManage], this.controller.create);+ this.router.patch('/rule/:ruleId', [IsLoggedIn, canManageRule], this.controller.update);+ this.router.delete('/rule/:ruleId', [IsLoggedIn, canManageRule], this.controller.remove);+ }+}diff --git a/api/src/tv-modules/automations/__tests__/AutomationCycleDetector.spec.ts b/api/src/tv-modules/automations/__tests__/AutomationCycleDetector.spec.tsnew file mode 100644index 0000000..65692fe--- /dev/null+++ b/api/src/tv-modules/automations/__tests__/AutomationCycleDetector.spec.ts@@ -0,0 +1,88 @@+import { describe, expect, it, vi } from 'vitest';+import { AutomationCycleDetector } from '../AutomationCycleDetector';+import { automationCatalog } from '../catalog/AutomationCatalog';+import type { AutomationRuleShape } from '../types';++vi.mock('../AutomationsRepository', () => ({ AutomationsRepository: vi.fn() }));++const DONE = 5;+const REVIEW = 9;++const completedToDone: AutomationRuleShape = {+ id: 1,+ trigger: { module: 'tasks', event: 'task.completed', params: {} },+ action: { module: 'kanban', action: 'change.status', params: { statusId: DONE } },+};++const doneReopens: AutomationRuleShape = {+ id: 2,+ trigger: { module: 'kanban', event: 'task.movedToColumn', params: { statusId: DONE } },+ action: { module: 'tasks', action: 'reopen', params: {} },+};++const reopenedCompletes: AutomationRuleShape = {+ id: 3,+ trigger: { module: 'tasks', event: 'task.reopened', params: {} },+ action: { module: 'tasks', action: 'complete', params: {} },+};++const completedAddsTag: AutomationRuleShape = {+ id: 4,+ trigger: { module: 'tasks', event: 'task.completed', params: {} },+ action: { module: 'tags', action: 'add.tag', params: { tagId: 3 } },+};++const detector = new AutomationCycleDetector(automationCatalog);++describe('AutomationCycleDetector', () => {+ it('accepts a chain that ends', () => {+ expect(detector.findCycle([completedToDone, doneReopens])).toBeNull();+ });++ it('rejects rules that keep completing and reopening the task', () => {+ const cycle = detector.findCycle([completedToDone, doneReopens, reopenedCompletes]);+ expect(cycle?.map((rule) => rule.id)).toEqual([1, 2, 3]);+ });++ it('rejects a rule that triggers itself', () => {+ const selfLoop: AutomationRuleShape = {+ id: 5,+ trigger: { module: 'kanban', event: 'task.movedToColumn', params: { statusId: DONE } },+ action: { module: 'kanban', action: 'change.status', params: { statusId: DONE } },+ };+ expect(detector.findCycle([selfLoop])?.map((rule) => rule.id)).toEqual([5]);+ });++ it('ignores a column move that cannot reach the other rule', () => {+ const toReview: AutomationRuleShape = {+ id: 6,+ trigger: { module: 'tasks', event: 'task.reopened', params: {} },+ action: { module: 'kanban', action: 'change.status', params: { statusId: REVIEW } },+ };+ expect(detector.findCycle([doneReopens, toReview])).toBeNull();+ });++ it('ends the chain when no rule listens to what the action does', () => {+ expect(detector.findCycle([completedAddsTag, completedToDone])).toBeNull();+ });++ it('rejects tag rules that keep adding each other', () => {+ const tagAddsOther = (id: number, from: number, to: number): AutomationRuleShape => ({+ id,+ trigger: { module: 'tags', event: 'tag.addedToTask', params: { tagId: from } },+ action: { module: 'tags', action: 'add.tag', params: { tagId: to } },+ });+ expect(detector.findCycle([tagAddsOther(7, 3, 4), tagAddsOther(8, 4, 3)])?.map((rule) => rule.id)).toEqual([7, 8]);+ expect(detector.findCycle([tagAddsOther(7, 3, 4), tagAddsOther(8, 4, 5)])).toBeNull();+ });++ it('rejects list rules that keep moving the task between lists', () => {+ const listMovesTo = (id: number, from: number, to: number): AutomationRuleShape => ({+ id,+ trigger: { module: 'lists', event: 'task.addedToList', params: { goalListId: from } },+ action: { module: 'lists', action: 'move.toList', params: { goalListId: to } },+ });+ expect(detector.findCycle([listMovesTo(9, 1, 2), listMovesTo(10, 2, 1)])?.map((rule) => rule.id)).toEqual([9, 10]);+ expect(detector.findCycle([listMovesTo(9, 1, 2), listMovesTo(10, 2, 3)])).toBeNull();+ });+});diff --git a/api/src/tv-modules/automations/__tests__/AutomationEngine.spec.ts b/api/src/tv-modules/automations/__tests__/AutomationEngine.spec.tsnew file mode 100644index 0000000..86ff00a--- /dev/null+++ b/api/src/tv-modules/automations/__tests__/AutomationEngine.spec.ts@@ -0,0 +1,325 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { TasksSchemaTypeForSelect } from 'taskview-db-schemas';+import { AutomationActorFactory } from '../AutomationActorFactory';+import { AutomationEngine } from '../AutomationEngine';+import { AutomationPermissions } from '../AutomationPermissions';+import type { AutomationRunQueue } from '../AutomationRunQueue';+import { AutomationsRepository } from '../AutomationsRepository';+import { AutomationCatalog } from '../catalog/AutomationCatalog';+import { TasksRepository } from '../../tasks/TasksRepository';+import { $logger } from '../../../modules/logget';+import type {+ AutomationActionExecuteArgs,+ AutomationEventMatchArgs,+ AutomationModuleDefinition,+ AutomationRuleRow,+ AutomationRunJob,+} from '../types';++vi.mock('../AutomationsRepository', () => ({ AutomationsRepository: vi.fn() }));+vi.mock('../../tasks/TasksRepository', () => ({ TasksRepository: vi.fn() }));+vi.mock('../AutomationActorFactory', () => ({ AutomationActorFactory: vi.fn() }));+vi.mock('../AutomationPermissions', () => ({ AutomationPermissions: { canRun: vi.fn() } }));+vi.mock('../../../modules/logget', () => ({ $logger: { warn: vi.fn(), info: vi.fn(), error: vi.fn() } }));++const GOAL_ID = 10;+const CREATOR_ID = 7;+const EDITED_AT = new Date('2026-10-01T10:00:00.000Z');+const actor = { id: 'actor' };++function task(overrides: Partial<TasksSchemaTypeForSelect> = {}): TasksSchemaTypeForSelect {+ return { id: 1, goalId: GOAL_ID, complete: false, statusId: 1, ...overrides } as TasksSchemaTypeForSelect;+}++function rule(overrides: Partial<AutomationRuleRow>): AutomationRuleRow {+ return {+ id: 1,+ goalId: GOAL_ID,+ creatorId: CREATOR_ID,+ name: 'rule',+ enabled: true,+ triggerModule: 'test',+ triggerEvent: 'ping',+ triggerParams: {},+ actionModule: 'test',+ actionName: 'record',+ actionParams: {},+ createdAt: EDITED_AT,+ editedAt: EDITED_AT,+ ...overrides,+ };+}++function setup(rules: AutomationRuleRow[], fetched: Partial<TasksSchemaTypeForSelect> | null = {}) {+ const executed: number[] = [];+ const jobs: AutomationRunJob[] = [];+ let engine: AutomationEngine;++ const module = {+ name: 'test',+ events: [+ { name: 'ping', busEvents: ['task.updated'], params: [], match: ({ busEvent }: AutomationEventMatchArgs) => busEvent.changes.ping === true },+ {+ name: 'step',+ busEvents: ['task.updated'],+ params: [{ key: 'n', source: 'kanban.statuses' }],+ match: ({ busEvent, params }: AutomationEventMatchArgs) => busEvent.changes.step === params.n,+ },+ {+ name: 'tagged',+ busEvents: ['task.tagsChanged'],+ params: [],+ match: ({ busEvent }: AutomationEventMatchArgs) => busEvent.changes.added === true,+ },+ { name: 'touched', busEvents: ['task.created', 'task.updated'], params: [], match: () => true },+ ],+ actions: [+ {+ name: 'record',+ params: [{ key: 'n', source: 'kanban.statuses' }],+ requiredPermissions: [],+ emits: () => null,+ execute: async ({ params }: AutomationActionExecuteArgs) => {+ executed.push(params.n);+ return 'applied' as const;+ },+ },+ {+ name: 'next',+ params: [{ key: 'n', source: 'kanban.statuses' }],+ requiredPermissions: [],+ emits: () => null,+ execute: async ({ task: current, params }: AutomationActionExecuteArgs) => {+ executed.push(params.n);+ void engine.handle({ name: 'task.updated', task: current, changes: { step: params.n + 1, ping: true } });+ return 'applied' as const;+ },+ },+ {+ name: 'tagNext',+ params: [{ key: 'n', source: 'kanban.statuses' }],+ requiredPermissions: [],+ emits: () => null,+ execute: async ({ task: current, params }: AutomationActionExecuteArgs) => {+ executed.push(params.n);+ void engine.handleForTask({ name: 'task.tagsChanged', taskId: current.id, changes: { added: true } });+ return 'applied' as const;+ },+ },+ { name: 'fail', params: [], requiredPermissions: [], emits: () => null, execute: async () => 'failed' as const },+ {+ name: 'crash',+ params: [],+ requiredPermissions: [],+ emits: () => null,+ execute: async () => {+ throw new Error('database is down');+ },+ },+ ],+ dataSources: {},+ } as unknown as AutomationModuleDefinition;++ const forUser = vi.fn(async () => actor);+ const enqueue = vi.fn(async (job: AutomationRunJob) => {+ jobs.push(job);+ });+ vi.mocked(AutomationsRepository).mockImplementation(+ () =>+ ({+ listEnabledForGoal: vi.fn(async () => rules.filter((item) => item.enabled)),+ getById: vi.fn(async (id: number) => rules.find((item) => item.id === id) ?? null),+ }) as any+ );+ const fetchTaskByIdNew = vi.fn(async (id: number) => (fetched === null ? null : task({ id, ...fetched })));+ vi.mocked(TasksRepository).mockImplementation(() => ({ fetchTaskByIdNew }) as any);+ vi.mocked(AutomationActorFactory).mockImplementation(() => ({ forUser }) as any);+ vi.mocked(AutomationPermissions.canRun).mockResolvedValue(true);++ engine = new AutomationEngine({ catalog: new AutomationCatalog([module]), queue: { enqueue } as unknown as AutomationRunQueue });++ async function drain() {+ while (jobs.length > 0) {+ await engine.run(jobs.shift() as AutomationRunJob);+ }+ }++ async function emit(changes: Record<string, unknown>) {+ await engine.handle({ name: 'task.updated', task: task(), changes });+ await drain();+ }++ return { engine, executed, jobs, enqueue, forUser, drain, emit };+}++describe('AutomationEngine', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('schedules one job with the matching rules and runs it', async () => {+ const { engine, executed, jobs, drain } = setup([rule({ id: 1, actionParams: { n: 42 } }), rule({ id: 2, actionParams: { n: 43 } })]);+ await engine.handle({ name: 'task.updated', task: task(), changes: { ping: true } });++ expect(jobs).toEqual([+ {+ goalId: GOAL_ID,+ taskId: 1,+ rules: [+ { id: 1, editedAt: EDITED_AT.toISOString() },+ { id: 2, editedAt: EDITED_AT.toISOString() },+ ],+ chain: { depth: 1, firedRuleIds: [1, 2] },+ },+ ]);+ expect(executed).toEqual([]);++ await drain();+ expect(executed).toEqual([42, 43]);+ });++ it('does not schedule anything when no rule matches', async () => {+ const { engine, enqueue } = setup([rule({ actionParams: { n: 42 } })]);+ await engine.handle({ name: 'task.updated', task: task(), changes: { ping: false } });+ await engine.handle({ name: 'task.created', task: task(), changes: { ping: true } });+ expect(enqueue).not.toHaveBeenCalled();+ });++ it('matches event params', async () => {+ const { executed, emit } = setup([+ rule({ id: 1, triggerEvent: 'step', triggerParams: { n: 1 }, actionParams: { n: 100 } }),+ rule({ id: 2, triggerEvent: 'step', triggerParams: { n: 2 }, actionParams: { n: 200 } }),+ ]);+ await emit({ step: 2 });+ expect(executed).toEqual([200]);+ });++ it('skips a rule that was edited after it was scheduled', async () => {+ const rules = [rule({ actionParams: { n: 42 } })];+ const { engine, executed, drain } = setup(rules);+ await engine.handle({ name: 'task.updated', task: task(), changes: { ping: true } });+ rules[0].editedAt = new Date('2026-10-02T10:00:00.000Z');+ await drain();+ expect(executed).toEqual([]);+ });++ it('skips a rule that was disabled after it was scheduled', async () => {+ const rules = [rule({ actionParams: { n: 42 } })];+ const { engine, executed, drain } = setup(rules);+ await engine.handle({ name: 'task.updated', task: task(), changes: { ping: true } });+ rules[0].enabled = false;+ await drain();+ expect(executed).toEqual([]);+ });++ it('skips the rule when its creator lost the permissions', async () => {+ const { executed, emit } = setup([rule({ actionParams: { n: 42 } })]);+ vi.mocked(AutomationPermissions.canRun).mockResolvedValue(false);+ await emit({ ping: true });+ expect(executed).toEqual([]);+ });++ it('skips the rule when the task moved to another project', async () => {+ const { executed, emit } = setup([rule({ actionParams: { n: 42 } })], { goalId: 99 });+ await emit({ ping: true });+ expect(executed).toEqual([]);+ });++ it('runs every rule at most once per chain', async () => {+ const { executed, emit } = setup([rule({ id: 1, actionName: 'next', actionParams: { n: 1 } })]);+ await emit({ ping: true });+ expect(executed).toEqual([1]);+ });++ it('carries the chain to the next job and stops at the depth limit', async () => {+ const rules = Array.from({ length: 8 }, (_, index) =>+ rule({ id: index + 1, triggerEvent: 'step', triggerParams: { n: index + 1 }, actionName: 'next', actionParams: { n: index + 1 } })+ );+ const { executed, enqueue, emit } = setup(rules);+ await emit({ step: 1 });+ expect(executed).toEqual([1, 2, 3, 4, 5]);+ expect(enqueue.mock.calls.map(([job]) => job.chain)).toEqual([+ { depth: 1, firedRuleIds: [1] },+ { depth: 2, firedRuleIds: [1, 2] },+ { depth: 3, firedRuleIds: [1, 2, 3] },+ { depth: 4, firedRuleIds: [1, 2, 3, 4] },+ { depth: 5, firedRuleIds: [1, 2, 3, 4, 5] },+ ]);+ });++ it('starts a new chain for every outside event', async () => {+ const { executed, emit } = setup([rule({ actionParams: { n: 42 } })]);+ await emit({ ping: true });+ await emit({ ping: true });+ expect(executed).toEqual([42, 42]);+ });++ it('loads every creator once per job', async () => {+ const { executed, forUser, emit } = setup([+ rule({ id: 1, actionParams: { n: 1 } }),+ rule({ id: 2, actionParams: { n: 2 } }),+ rule({ id: 3, creatorId: 8, actionParams: { n: 3 } }),+ ]);+ await emit({ ping: true });+ expect(executed).toEqual([1, 2, 3]);+ expect(forUser.mock.calls).toEqual([[CREATOR_ID], [8]]);+ });++ it('logs an action that failed without retrying the job', async () => {+ const { engine, jobs } = setup([rule({ id: 3, actionName: 'fail' })]);+ await engine.handle({ name: 'task.updated', task: task(), changes: { ping: true } });+ await expect(engine.run(jobs[0])).resolves.toBeUndefined();+ expect($logger.warn).toHaveBeenCalledWith(expect.stringContaining('rule=3 action test/fail failed'));+ });++ it('runs the other rules and fails the job when an action crashes, so the queue retries it', async () => {+ const { engine, executed, jobs } = setup([rule({ id: 1, actionName: 'crash' }), rule({ id: 2, actionParams: { n: 42 } })]);+ await engine.handle({ name: 'task.updated', task: task(), changes: { ping: true } });+ await expect(engine.run(jobs[0])).rejects.toThrow('database is down');+ expect(executed).toEqual([42]);+ });++ it('finishes a job only after the next step is scheduled', async () => {+ const { engine, jobs, enqueue } = setup([+ rule({ id: 1, triggerEvent: 'step', triggerParams: { n: 1 }, actionName: 'next', actionParams: { n: 1 } }),+ rule({ id: 2, triggerEvent: 'step', triggerParams: { n: 2 }, actionParams: { n: 2 } }),+ ]);+ await engine.handle({ name: 'task.updated', task: task(), changes: { step: 1 } });+ const first = jobs.shift() as AutomationRunJob;++ enqueue.mockRejectedValueOnce(new Error('queue is down'));+ await expect(engine.run(first)).rejects.toThrow('queue is down');+ });++ it('loads the task for an event that carries only its id', async () => {+ const { engine, jobs, executed, drain } = setup([rule({ id: 4, triggerEvent: 'tagged', actionParams: { n: 7 } })]);+ await engine.handleForTask({ name: 'task.tagsChanged', taskId: 3, changes: { added: true } });+ expect(jobs.map((job) => job.taskId)).toEqual([3]);+ await drain();+ expect(executed).toEqual([7]);+ });++ it('skips an event for a task that no longer exists', async () => {+ const { engine, enqueue } = setup([rule({ triggerEvent: 'tagged' })], null);+ await engine.handleForTask({ name: 'task.tagsChanged', taskId: 3, changes: { added: true } });+ expect(enqueue).not.toHaveBeenCalled();+ });++ it('chains an action into an event that carries only the task id', async () => {+ const { executed, jobs, emit } = setup([+ rule({ id: 1, actionName: 'tagNext', actionParams: { n: 1 } }),+ rule({ id: 2, triggerEvent: 'tagged', actionParams: { n: 2 } }),+ ]);+ await emit({ ping: true });+ expect(executed).toEqual([1, 2]);+ expect(jobs).toEqual([]);+ });++ it('matches an event that listens to several bus events', async () => {+ const { engine, enqueue } = setup([rule({ triggerEvent: 'touched' })]);+ await engine.handle({ name: 'task.created', task: task(), changes: {} });+ await engine.handle({ name: 'task.updated', task: task(), changes: {} });+ await engine.handle({ name: 'task.tagsChanged', task: task(), changes: {} });+ expect(enqueue).toHaveBeenCalledTimes(2);+ });+});diff --git a/api/src/tv-modules/automations/__tests__/AutomationModuleEvents.spec.ts b/api/src/tv-modules/automations/__tests__/AutomationModuleEvents.spec.tsnew file mode 100644index 0000000..aec463d--- /dev/null+++ b/api/src/tv-modules/automations/__tests__/AutomationModuleEvents.spec.ts@@ -0,0 +1,44 @@+import { describe, expect, it, vi } from 'vitest';+import type { TasksSchemaTypeForSelect } from 'taskview-db-schemas';+import { automationCatalog } from '../catalog/AutomationCatalog';+import type { AutomationBusEvent, AutomationFindEventArgs, AutomationParams } from '../types';++vi.mock('../AutomationsRepository', () => ({ AutomationsRepository: vi.fn() }));++const task = (overrides: Partial<TasksSchemaTypeForSelect> = {}) => ({ id: 1, goalId: 10, goalListId: null, ...overrides }) as TasksSchemaTypeForSelect;++function matches(ref: AutomationFindEventArgs, busEvent: AutomationBusEvent, params: AutomationParams): boolean {+ const event = automationCatalog.findEvent(ref);+ if (!event) throw new Error(`Unknown event ${ref.module}/${ref.event}`);+ return event.busEvents.includes(busEvent.name) && event.match({ busEvent, params });+}++describe('Lists and tags automation events', () => {+ const addedToList = { module: 'lists', event: 'task.addedToList' };++ it('fires when a task is moved into the list', () => {+ expect(matches(addedToList, { name: 'task.updated', task: task({ goalListId: 4 }), changes: { goalListId: 4 } }, { goalListId: 4 })).toBe(true);+ expect(matches(addedToList, { name: 'task.updated', task: task({ goalListId: 5 }), changes: { goalListId: 5 } }, { goalListId: 4 })).toBe(false);+ });++ it('does not fire when another field of a task in the list changes', () => {+ expect(matches(addedToList, { name: 'task.updated', task: task({ goalListId: 4 }), changes: { description: 'x' } }, { goalListId: 4 })).toBe(false);+ });++ it('fires when a task is created right in the list', () => {+ expect(matches(addedToList, { name: 'task.created', task: task({ goalListId: 4 }), changes: {} }, { goalListId: 4 })).toBe(true);+ expect(matches(addedToList, { name: 'task.created', task: task(), changes: {} }, { goalListId: 4 })).toBe(false);+ });++ it('tells a tag that was added from one that was removed', () => {+ const added = { module: 'tags', event: 'tag.addedToTask' };+ const removed = { module: 'tags', event: 'tag.removedFromTask' };+ const tagged = (isAdded: boolean): AutomationBusEvent => ({ name: 'task.tagsChanged', task: task(), changes: { tagId: 3, added: isAdded } });++ expect(matches(added, tagged(true), { tagId: 3 })).toBe(true);+ expect(matches(added, tagged(false), { tagId: 3 })).toBe(false);+ expect(matches(added, tagged(true), { tagId: 4 })).toBe(false);+ expect(matches(removed, tagged(false), { tagId: 3 })).toBe(true);+ expect(matches(removed, tagged(true), { tagId: 3 })).toBe(false);+ });+});diff --git a/api/src/tv-modules/automations/__tests__/AutomationOptionRemovalHandler.spec.ts b/api/src/tv-modules/automations/__tests__/AutomationOptionRemovalHandler.spec.tsnew file mode 100644index 0000000..982482d--- /dev/null+++ b/api/src/tv-modules/automations/__tests__/AutomationOptionRemovalHandler.spec.ts@@ -0,0 +1,76 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { AutomationOptionRemovalHandler } from '../AutomationOptionRemovalHandler';+import { AutomationsRepository } from '../AutomationsRepository';+import { AutomationCatalog } from '../catalog/AutomationCatalog';+import type { AutomationModuleDefinition, AutomationRuleRow } from '../types';++vi.mock('../AutomationsRepository', () => ({ AutomationsRepository: vi.fn() }));++const GOAL_ID = 10;++const module = {+ name: 'kanban',+ events: [{ name: 'moved', busEvents: ['task.updated'], params: [{ key: 'statusId', source: 'kanban.statuses' }], match: () => true }],+ actions: [+ { name: 'move', params: [{ key: 'statusId', source: 'kanban.statuses' }], requiredPermissions: [], emits: () => null, execute: vi.fn() },+ { name: 'tag', params: [{ key: 'tagId', source: 'tags.goalTags' }], requiredPermissions: [], emits: () => null, execute: vi.fn() },+ { name: 'noop', params: [], requiredPermissions: [], emits: () => null, execute: vi.fn() },+ ],+ dataSources: {},+} as unknown as AutomationModuleDefinition;++function rule(overrides: Partial<AutomationRuleRow>): AutomationRuleRow {+ return {+ id: 1,+ goalId: GOAL_ID,+ creatorId: 7,+ name: 'rule',+ enabled: true,+ triggerModule: 'kanban',+ triggerEvent: 'moved',+ triggerParams: { statusId: 1 },+ actionModule: 'kanban',+ actionName: 'noop',+ actionParams: {},+ createdAt: new Date(),+ editedAt: new Date(),+ ...overrides,+ };+}++function setup(rows: AutomationRuleRow[] | null) {+ const disableMany = vi.fn(async () => [] as number[]);+ vi.mocked(AutomationsRepository).mockImplementation(() => ({ listEnabledForGoal: vi.fn(async () => rows), disableMany }) as any);+ return { handler: new AutomationOptionRemovalHandler(new AutomationCatalog([module])), disableMany };+}++describe('AutomationOptionRemovalHandler', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('disables rules that use the removed value in the trigger or the action', async () => {+ const { handler, disableMany } = setup([+ rule({ id: 1, triggerParams: { statusId: 5 } }),+ rule({ id: 2, triggerParams: { statusId: 1 }, actionName: 'move', actionParams: { statusId: 5 } }),+ rule({ id: 3, triggerParams: { statusId: 1 }, actionName: 'move', actionParams: { statusId: 6 } }),+ ]);+ await handler.handle({ goalId: GOAL_ID, source: 'kanban.statuses', id: 5 });+ expect(disableMany).toHaveBeenCalledWith({ goalId: GOAL_ID, ruleIds: [1, 2] });+ });++ it('ignores the same id coming from another data source', async () => {+ const { handler, disableMany } = setup([+ rule({ id: 1, triggerParams: { statusId: 5 } }),+ rule({ id: 2, actionName: 'tag', actionParams: { tagId: 5 } }),+ ]);+ await handler.handle({ goalId: GOAL_ID, source: 'tags.goalTags', id: 5 });+ expect(disableMany).toHaveBeenCalledWith({ goalId: GOAL_ID, ruleIds: [2] });+ });++ it('does nothing when the rules can not be loaded', async () => {+ const { handler, disableMany } = setup(null);+ await handler.handle({ goalId: GOAL_ID, source: 'kanban.statuses', id: 5 });+ expect(disableMany).not.toHaveBeenCalled();+ });+});diff --git a/api/src/tv-modules/automations/__tests__/Automations.integration.spec.ts b/api/src/tv-modules/automations/__tests__/Automations.integration.spec.tsnew file mode 100644index 0000000..ec46274--- /dev/null+++ b/api/src/tv-modules/automations/__tests__/Automations.integration.spec.ts@@ -0,0 +1,481 @@+import axios, { type AxiosInstance } from 'axios';+import { and, eq } from 'drizzle-orm';+import fs from 'fs/promises';+import http from 'http';+import { join } from 'path';+import { TasksSchema, TasksToTagsSchema } from 'taskview-db-schemas';+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';+import App from '../../../App';+import { Database } from '../../../modules/db';+import { GoalPermissions } from '../../../types/auth.types';+import type { AutomationErrorCode, AutomationRuleForClient } from '../types';++type AutomationRuleResponse = { response: AutomationRuleForClient; code?: AutomationErrorCode; message?: string | null };++vi.mock('emailjs', () => ({+ SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),+}));++const port = 1828;+const url = `http://localhost:${port}`;+const MIGRATION_DIR = join(__dirname, '../../../migrations/taskview/sql/1.69.0');+const LOGIN = '[email protected]';+const PASSWORD = 'user1!#Q';++const api: AxiosInstance = axios.create({+ baseURL: url,+ validateStatus: () => true,+ httpAgent: new http.Agent({ keepAlive: false }),+});++let server: http.Server;+let jwt = '';+let goalId = 0;+let otherGoalId = 0;+let doneColumnId = 0;+let reviewColumnId = 0;+let otherGoalColumnId = 0;+let tagId = 0;+const createdTokenIds: number[] = [];++const asUser = () => ({ headers: { Authorization: `Bearer ${jwt}` } });++async function createGoal(name: string): Promise<number> {+ const response = await api.post('/module/goals', { name: `${name}-${Date.now()}` }, asUser());+ expect(response.status).toBe(200);+ return response.data.response.id;+}++async function createColumn(inGoal: number, name: string): Promise<number> {+ const response = await api.post('/module/kanban/add-status', { goalId: inGoal, name }, asUser());+ expect(response.status).toBe(200);+ return response.data.response.id;+}++async function createTask(description: string): Promise<number> {+ const response = await api.post('/module/tasks', { goalId, description }, asUser());+ expect(response.status).toBe(200);+ return response.data.response.id;+}++async function createRule(body: Record<string, unknown>) {+ return api.post<AutomationRuleResponse>(`/module/automations/goal/${goalId}/rules`, body, asUser());+}++async function deleteAllRules() {+ const listed = await api.get<{ response: AutomationRuleForClient[] }>(`/module/automations/goal/${goalId}/rules`, asUser());+ for (const rule of listed.data.response ?? []) {+ await api.delete(`/module/automations/rule/${rule.id}`, asUser());+ }+}++async function fetchTask(taskId: number) {+ const rows = await Database.getInstance().dbDrizzle.select().from(TasksSchema).where(eq(TasksSchema.id, taskId));+ return rows[0];+}++async function taskHasTag(taskId: number): Promise<boolean> {+ const rows = await Database.getInstance()+ .dbDrizzle.select()+ .from(TasksToTagsSchema)+ .where(and(eq(TasksToTagsSchema.taskId, taskId), eq(TasksToTagsSchema.tagId, tagId)));+ return rows.length > 0;+}++async function waitFor(check: () => Promise<boolean>): Promise<boolean> {+ for (let attempt = 0; attempt < 100; attempt += 1) {+ if (await check()) return true;+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ return false;+}++async function issueToken(allowedPermissions: string[]) {+ const response = await api.post('/module/api-tokens', { name: 'automations-probe', allowedPermissions, allowedGoalIds: [] }, asUser());+ expect(response.status).toBe(200);+ createdTokenIds.push(response.data.response.item.id);+ return { headers: { Authorization: `Bearer ${response.data.response.token}` } };+}++describe('Automations module', () => {+ beforeAll(async () => {+ const db = Database.getInstance();+ const client = await db.getClient();+ server = new App(port).listen();++ const login = await api.post('/module/auth/login', { login: LOGIN, password: PASSWORD });+ expect(login.status).toBe(200);+ jwt = login.data.access;++ // Other specs re-apply older all-triggers.sql in parallel; projects are created under the lock so they get this version's role grants.+ await client.query('SELECT pg_advisory_lock(1401067)');+ try {+ for (const file of (await fs.readdir(MIGRATION_DIR)).sort()) {+ await client.query(await fs.readFile(join(MIGRATION_DIR, file), 'utf-8'));+ }+ goalId = await createGoal('automations-it');+ otherGoalId = await createGoal('automations-it-other');+ } finally {+ await client.query('SELECT pg_advisory_unlock(1401067)');+ client.release();+ }++ doneColumnId = await createColumn(goalId, 'Done');+ reviewColumnId = await createColumn(goalId, 'Review');+ otherGoalColumnId = await createColumn(otherGoalId, 'Foreign');++ const tag = await api.post('/module/tags', { name: 'automated', color: '#22c55e', goalId }, asUser());+ expect(tag.status).toBe(200);+ tagId = tag.data.response.id;+ });++ afterAll(async () => {+ for (const id of [goalId, otherGoalId]) {+ if (id) await api.delete('/module/goals', { ...asUser(), data: { goalId: id } });+ }+ for (const id of createdTokenIds) {+ await api.delete('/module/api-tokens', { ...asUser(), data: { id } });+ }+ await new Promise<void>((resolve) => server.close(() => resolve()));+ }, 30_000);++ it('seeds the automations permission group with localized descriptions', async () => {+ const result = await Database.getInstance().query<{ name: string; description_locales: Record<string, string> }>(+ 'SELECT name, description_locales FROM tv_auth.permissions WHERE permission_group = 8 ORDER BY name'+ );+ expect(result.rows.map((r) => r.name)).toEqual(['automation_can_manage', 'automation_can_view']);+ expect(result.rows[0].description_locales.ru).toBeTruthy();+ });++ it('grants automation permissions to the roles of a new project', async () => {+ const result = await Database.getInstance().query<{ role: string; permission: string }>(+ `SELECT r.name AS role, p.name AS permission+ FROM collaboration.roles r+ JOIN collaboration.permissions_to_role pr ON pr.role_id = r.id+ JOIN tv_auth.permissions p ON p.id = pr.permission_id+ WHERE r.goal_id = $1 AND p.name LIKE 'automation_%'+ ORDER BY r.name, p.name`,+ [goalId]+ );+ const byRole = new Map<string, string[]>();+ for (const r of result.rows) byRole.set(r.role, [...(byRole.get(r.role) ?? []), r.permission]);+ expect(byRole.get('editor')).toEqual(['automation_can_manage', 'automation_can_view']);+ expect(byRole.get('executor')).toEqual(['automation_can_view']);+ });++ it('serves the catalog of modules, events and actions', async () => {+ const response = await api.get('/module/automations/catalog', asUser());+ expect(response.status).toBe(200);+ const modules = response.data.response.modules as { name: string; events: { name: string }[]; actions: { name: string }[] }[];+ expect(modules.map((m) => m.name)).toEqual(['tasks', 'kanban', 'lists', 'tags']);+ expect(modules.find((m) => m.name === 'kanban')?.actions.map((a) => a.name)).toEqual(['change.status']);+ });++ it('lists the options of a data source for the project only', async () => {+ const response = await api.get(`/module/automations/goal/${goalId}/options/kanban.statuses`, asUser());+ expect(response.status).toBe(200);+ const ids = (response.data.response as { id: number }[]).map((o) => o.id);+ expect(ids).toEqual(expect.arrayContaining([doneColumnId, reviewColumnId]));+ expect(ids).not.toContain(otherGoalColumnId);++ for (const source of ['unknown.source', 'constructor', '__proto__', 'hasOwnProperty']) {+ expect((await api.get(`/module/automations/goal/${goalId}/options/${source}`, asUser())).status).toBe(400);+ }+ expect((await api.get('/module/automations/catalog', asUser())).status).toBe(200);+ });++ it('hides data source options from users who cannot see that data', async () => {+ const automationsOnly = await issueToken([GoalPermissions.AUTOMATION_CAN_VIEW]);+ expect((await api.get(`/module/automations/goal/${goalId}/options/kanban.statuses`, automationsOnly)).status).toBe(403);+ expect((await api.get(`/module/automations/goal/${goalId}/options/tags.goalTags`, automationsOnly)).status).toBe(403);+ });++ it('refuses to move a task of another project through the kanban board', async () => {+ const otherTask = await api.post('/module/tasks', { goalId: otherGoalId, description: 'not yours to move' }, asUser());+ expect(otherTask.status).toBe(200);+ const otherTaskId = otherTask.data.response.id;++ const crossTask = await api.patch(+ '/module/kanban/update-tasks-order-and-column',+ { goalId, columnId: otherGoalColumnId, taskId: otherTaskId, prevTaskId: null, nextTaskId: null },+ asUser()+ );+ expect(crossTask.status).toBe(404);++ const ownTask = await createTask('stays in its project');+ const crossColumn = await api.patch(+ '/module/kanban/update-tasks-order-and-column',+ { goalId, columnId: otherGoalColumnId, taskId: ownTask, prevTaskId: null, nextTaskId: null },+ asUser()+ );+ expect(crossColumn.status).toBe(404);+ expect((await fetchTask(otherTaskId))?.statusId).toBeNull();+ expect((await fetchTask(ownTask))?.statusId).toBeNull();+ });++ it('adds a tag to new tasks through the idempotent insert', async () => {+ await deleteAllRules();+ const created = await createRule({+ name: 'Tag new tasks',+ trigger: { module: 'tasks', event: 'task.created' },+ action: { module: 'tags', action: 'add.tag', params: { tagId } },+ });+ expect(created.status).toBe(200);+ const tagged = await createTask('tagged by the rule');+ expect(await waitFor(() => taskHasTag(tagged))).toBe(true);+ await deleteAllRules();+ });++ it('moves a completed task to the Done column', async () => {+ await deleteAllRules();+ const created = await createRule({+ name: 'Completed to Done',+ trigger: { module: 'tasks', event: 'task.completed' },+ action: { module: 'kanban', action: 'change.status', params: { statusId: doneColumnId } },+ });+ expect(created.status).toBe(200);+ expect(created.data.response).toMatchObject({ goalId, enabled: true, action: { params: { statusId: doneColumnId } } });++ const taskId = await createTask('complete me');+ expect((await api.patch('/module/tasks', { id: taskId, complete: true }, asUser())).status).toBe(200);++ expect(await waitFor(async () => (await fetchTask(taskId))?.statusId === doneColumnId)).toBe(true);+ });++ it('fires column rules when a card is dragged on the kanban board', async () => {+ await deleteAllRules();+ const created = await createRule({+ name: 'Review gets tagged',+ trigger: { module: 'kanban', event: 'task.movedToColumn', params: { statusId: reviewColumnId } },+ action: { module: 'tags', action: 'add.tag', params: { tagId } },+ });+ expect(created.status).toBe(200);++ const taskId = await createTask('drag me');+ const moved = await api.patch(+ '/module/kanban/update-tasks-order-and-column',+ { goalId, columnId: reviewColumnId, taskId, prevTaskId: null, nextTaskId: null },+ asUser()+ );+ expect(moved.status).toBe(200);++ expect(await waitFor(() => taskHasTag(taskId))).toBe(true);+ });++ it('chains rules: Done column reopens the task that was just completed', async () => {+ await deleteAllRules();+ expect(+ (+ await createRule({+ name: 'Completed to Done',+ trigger: { module: 'tasks', event: 'task.completed' },+ action: { module: 'kanban', action: 'change.status', params: { statusId: doneColumnId } },+ })+ ).status+ ).toBe(200);+ expect(+ (+ await createRule({+ name: 'Done reopens',+ trigger: { module: 'kanban', event: 'task.movedToColumn', params: { statusId: doneColumnId } },+ action: { module: 'tasks', action: 'reopen' },+ })+ ).status+ ).toBe(200);++ const taskId = await createTask('chain me');+ expect((await api.patch('/module/tasks', { id: taskId, complete: true }, asUser())).status).toBe(200);++ expect(+ await waitFor(async () => {+ const task = await fetchTask(taskId);+ return task?.statusId === doneColumnId && task.complete === false;+ })+ ).toBe(true);+ });++ it('rejects a rule that closes an endless loop', async () => {+ const response = await createRule({+ name: 'Reopened completes again',+ trigger: { module: 'tasks', event: 'task.reopened' },+ action: { module: 'tasks', action: 'complete' },+ });+ expect(response.status).toBe(409);+ expect(response.data).toMatchObject({ code: 'cycle' });+ expect(response.data.message).toContain('Completed to Done');+ });++ it('allows the loop rule when it is saved disabled, and refuses to enable it', async () => {+ const created = await createRule({+ name: 'Reopened completes again',+ enabled: false,+ trigger: { module: 'tasks', event: 'task.reopened' },+ action: { module: 'tasks', action: 'complete' },+ });+ expect(created.status).toBe(200);++ const enabled = await api.patch(`/module/automations/rule/${created.data.response.id}`, { enabled: true }, asUser());+ expect(enabled.status).toBe(409);+ expect(enabled.data.code).toBe('cycle');+ });++ it('does not run disabled rules', async () => {+ await deleteAllRules();+ const created = await createRule({+ name: 'Disabled tagger',+ trigger: { module: 'tasks', event: 'task.created' },+ action: { module: 'tags', action: 'add.tag', params: { tagId } },+ });+ expect(created.status).toBe(200);+ const disabled = await api.patch(`/module/automations/rule/${created.data.response.id}`, { enabled: false }, asUser());+ expect(disabled.status).toBe(200);+ expect(disabled.data.response.enabled).toBe(false);++ const taskId = await createTask('no tag for me');+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(await taskHasTag(taskId)).toBe(false);+ });++ it('rejects values from another project, unknown events and missing params', async () => {+ const foreign = await createRule({+ name: 'Foreign column',+ trigger: { module: 'tasks', event: 'task.completed' },+ action: { module: 'kanban', action: 'change.status', params: { statusId: otherGoalColumnId } },+ });+ expect(foreign.status).toBe(400);+ expect(foreign.data.code).toBe('invalid');++ const unknown = await createRule({+ name: 'Unknown',+ trigger: { module: 'tasks', event: 'task.exploded' },+ action: { module: 'tasks', action: 'complete' },+ });+ expect(unknown.status).toBe(400);++ const missing = await createRule({+ name: 'Missing column',+ trigger: { module: 'tasks', event: 'task.completed' },+ action: { module: 'kanban', action: 'change.status' },+ });+ expect(missing.status).toBe(400);++ const blankName = await createRule({+ name: ' ',+ trigger: { module: 'tasks', event: 'task.completed' },+ action: { module: 'tasks', action: 'reopen' },+ });+ expect(blankName.status).toBe(400);+ });++ it('drops undeclared params instead of storing them', async () => {+ await deleteAllRules();+ const created = await createRule({+ name: 'Extra params',+ trigger: { module: 'tasks', event: 'task.completed', params: { injected: 1 } },+ action: { module: 'kanban', action: 'change.status', params: { statusId: doneColumnId, goalId: otherGoalId } },+ });+ expect(created.status).toBe(200);+ expect(created.data.response.trigger.params).toEqual({});+ expect(created.data.response.action.params).toEqual({ statusId: doneColumnId });+ });++ it('lets a view-only token read rules but not change them', async () => {+ const viewer = await issueToken([GoalPermissions.AUTOMATION_CAN_VIEW]);+ expect((await api.get(`/module/automations/goal/${goalId}/rules`, viewer)).status).toBe(200);++ const created = await api.post(+ `/module/automations/goal/${goalId}/rules`,+ { name: 'Nope', trigger: { module: 'tasks', event: 'task.completed' }, action: { module: 'tasks', action: 'reopen' } },+ viewer+ );+ expect(created.status).toBe(403);++ const listed = await api.get<{ response: AutomationRuleForClient[] }>(`/module/automations/goal/${goalId}/rules`, asUser());+ const ruleId = listed.data.response[0].id;+ expect((await api.delete(`/module/automations/rule/${ruleId}`, viewer)).status).toBe(403);+ });++ it('refuses a rule whose action needs permissions the author lacks', async () => {+ const manager = await issueToken([GoalPermissions.AUTOMATION_CAN_VIEW, GoalPermissions.AUTOMATION_CAN_MANAGE]);+ const created = await api.post(+ `/module/automations/goal/${goalId}/rules`,+ {+ name: 'Escalation',+ trigger: { module: 'tasks', event: 'task.completed' },+ action: { module: 'kanban', action: 'change.status', params: { statusId: doneColumnId } },+ },+ manager+ );+ expect(created.status).toBe(403);+ expect(created.data.code).toBe('forbidden');+ });++ it('hides rules from users without access to the project', async () => {+ const noAccess = await issueToken([GoalPermissions.KANBAN_CAN_VIEW]);+ expect((await api.get(`/module/automations/goal/${goalId}/rules`, noAccess)).status).toBe(403);+ expect((await api.patch('/module/automations/rule/999999999', { enabled: false }, asUser())).status).toBe(404);+ });++ it('disables the rules that use a deleted column or tag', async () => {+ await deleteAllRules();+ const tempColumnId = await createColumn(goalId, 'Temporary');+ const tempTag = await api.post('/module/tags', { name: 'temporary', color: '#f97316', goalId }, asUser());+ expect(tempTag.status).toBe(200);+ const tempTagId: number = tempTag.data.response.id;++ const ruleIds: Record<string, number> = {};+ const rules = {+ moveToTemp: {+ trigger: { module: 'tasks', event: 'task.completed' },+ action: { module: 'kanban', action: 'change.status', params: { statusId: tempColumnId } },+ },+ fromTemp: {+ trigger: { module: 'kanban', event: 'task.movedToColumn', params: { statusId: tempColumnId } },+ action: { module: 'tags', action: 'add.tag', params: { tagId } },+ },+ addTempTag: {+ trigger: { module: 'kanban', event: 'task.movedToColumn', params: { statusId: reviewColumnId } },+ action: { module: 'tags', action: 'add.tag', params: { tagId: tempTagId } },+ },+ unrelated: {+ trigger: { module: 'tasks', event: 'task.created' },+ action: { module: 'tags', action: 'add.tag', params: { tagId } },+ },+ };+ for (const [name, rule] of Object.entries(rules)) {+ const created = await createRule({ name, ...rule });+ expect(created.status).toBe(200);+ ruleIds[name] = created.data.response.id;+ }++ const enabledRules = async () => {+ const listed = await api.get<{ response: AutomationRuleForClient[] }>(`/module/automations/goal/${goalId}/rules`, asUser());+ return new Set(listed.data.response.filter((rule) => rule.enabled).map((rule) => rule.id));+ };++ expect((await api.post('/module/kanban/delete-status', { id: tempColumnId }, asUser())).status).toBe(200);+ expect(await waitFor(async () => !(await enabledRules()).has(ruleIds.moveToTemp))).toBe(true);+ expect(await enabledRules()).toEqual(new Set([ruleIds.addTempTag, ruleIds.unrelated]));++ expect((await api.delete('/module/tags', { ...asUser(), data: { tagId: tempTagId } })).status).toBe(200);+ expect(await waitFor(async () => !(await enabledRules()).has(ruleIds.addTempTag))).toBe(true);+ expect(await enabledRules()).toEqual(new Set([ruleIds.unrelated]));++ const reenabled = await api.patch(`/module/automations/rule/${ruleIds.moveToTemp}`, { enabled: true }, asUser());+ expect(reenabled.status).toBe(400);+ await deleteAllRules();+ });++ it('deletes a rule', async () => {+ await deleteAllRules();+ const created = await createRule({+ name: 'Short-lived',+ trigger: { module: 'tasks', event: 'task.completed' },+ action: { module: 'tasks', action: 'reopen' },+ });+ expect(created.status).toBe(200);+ expect((await api.delete(`/module/automations/rule/${created.data.response.id}`, asUser())).status).toBe(200);+ const listed = await api.get<{ response: AutomationRuleForClient[] }>(`/module/automations/goal/${goalId}/rules`, asUser());+ expect(listed.data.response).toEqual([]);+ });+});diff --git a/api/src/tv-modules/automations/automation.js b/api/src/tv-modules/automations/automation.jsnew file mode 100644index 0000000..db541c1--- /dev/null+++ b/api/src/tv-modules/automations/automation.js@@ -0,0 +1,32 @@+const maps = {+ modules:{+ tasks: {+ title: 'Task module',+ events: [+ {+ name: 'task.completed',+ originalEvent: 'task.updated',+ match: (task)=>task.completed === true+ }+ ],+ actions:[++ ]+ },+ kanban:{+ title: 'Kanban module',+ events: [+ 'kanban.created',+ 'task.updated'+ ],+ actions:[+ {+ title:'change.status',+ handler: 'Class.changeTaskStatus',+ getData: 'DataClass.fetchAvailableStatuses'+ }+ ]+ },+ }+}+// we want when task is completed => change task statusId\ No newline at end of filediff --git a/api/src/tv-modules/automations/automation.md b/api/src/tv-modules/automations/automation.mdnew file mode 100644index 0000000..1544098--- /dev/null+++ b/api/src/tv-modules/automations/automation.md@@ -0,0 +1,15 @@+Automation module++Requirements+- module has config+- config defines all opportunities about automation and what we can do+- UI loads all data from config+- avoid circular deps+- module has permission AUTOMATION_CAN_MANAGE AUTOMATION_CAN_VIEW+- user can set automation rules in UI+ - it looks like this [When => event => action ] for some action we need data for example when task completed we need move task to specific column base on this requirements we need to have specific data structure to configure automation+ - UI looks like bellow+ When section+ [Module selector, event selector]+ Then section+ [Module selector, action selector, data selector for action]\ No newline at end of filediff --git a/api/src/tv-modules/automations/automation.scenarios.js b/api/src/tv-modules/automations/automation.scenarios.jsnew file mode 100644index 0000000..ae7d787--- /dev/null+++ b/api/src/tv-modules/automations/automation.scenarios.js@@ -0,0 +1,290 @@+// Companion to automation.js. Same module map, plus rule calls and what each call does.+// A module publishes events and actions. A rule takes an event from one module+// and an action from another. originalEvent is the bus name; match decides+// whether this module event actually happened.++const maps = {+ modules: {+ tasks: {+ title: 'Task module',+ events: [+ {+ name: 'task.completed',+ originalEvent: 'task.updated',+ match: (payload) => payload.changes.complete === true,+ },+ {+ name: 'task.reopened',+ originalEvent: 'task.updated',+ match: (payload) => payload.changes.complete === false,+ },+ ],+ actions: [+ {+ title: 'set.complete',+ handler: 'Class.setComplete',+ emits: (params) => (params.complete === true ? 'task.completed' : 'task.reopened'),+ },+ ],+ },+ kanban: {+ title: 'Kanban module',+ events: [+ {+ name: 'kanban.created',+ originalEvent: 'kanban.created',+ match: () => true,+ },+ {+ name: 'task.movedToColumn',+ originalEvent: 'task.updated',+ match: (payload) => Object.prototype.hasOwnProperty.call(payload.changes, 'statusId'),+ paramsMatch: (payload, params) => payload.changes.statusId === params.statusId,+ },+ ],+ actions: [+ {+ title: 'change.status',+ handler: 'Class.changeTaskStatus',+ getData: 'DataClass.fetchAvailableStatuses',+ emits: () => 'task.movedToColumn',+ },+ ],+ },+ tags: {+ title: 'Tags module',+ events: [],+ actions: [+ {+ title: 'add.tag',+ handler: 'Class.addTag',+ getData: 'DataClass.fetchTags',+ emits: () => null,+ },+ ],+ },+ },+}++const dataSources = {+ 'DataClass.fetchAvailableStatuses': () => [+ { id: 1, name: 'Backlog' },+ { id: 5, name: 'Done' },+ { id: 9, name: 'Review' },+ ],+ 'DataClass.fetchTags': () => [+ { id: 3, name: 'urgent' },+ { id: 8, name: 'billing' },+ ],+}++const handlers = {+ 'Class.changeTaskStatus'(task, params) {+ if (task.statusId === params.statusId) return null+ task.statusId = params.statusId+ return { originalEvent: 'task.updated', changes: { statusId: params.statusId } }+ },+ 'Class.setComplete'(task, params) {+ if (task.complete === params.complete) return null+ task.complete = params.complete+ return { originalEvent: 'task.updated', changes: { complete: params.complete } }+ },+ 'Class.addTag'(task, params) {+ if (task.tagIds.includes(params.tagId)) return null+ task.tagIds.push(params.tagId)+ return null+ },+}++function moduleOf(name) {+ const module = maps.modules[name]+ if (!module) throw new Error(`Unknown module ${name}`)+ return module+}++function findEvent(moduleName, eventName) {+ const event = moduleOf(moduleName).events.find((item) => item.name === eventName)+ if (!event) throw new Error(`${moduleName} has no event ${eventName}`)+ return event+}++function findAction(moduleName, actionTitle) {+ const action = moduleOf(moduleName).actions.find((item) => item.title === actionTitle)+ if (!action) throw new Error(`${moduleName} has no action ${actionTitle}`)+ return action+}++function optionsFor(action) {+ if (!action.getData) return null+ return dataSources[action.getData]()+}++function createRule({ when, then }) {+ const event = findEvent(when.module, when.event)+ const action = findAction(then.module, then.action)+ const options = optionsFor(action)+ const paramId = then.params?.statusId ?? then.params?.tagId+ if (options && !options.some((option) => option.id === paramId)) {+ throw new Error(`${action.getData}() has no id ${paramId}`)+ }+ return { when, then, event, action }+}++function emittedEventName(rule) {+ return rule.action.emits(rule.then.params ?? {})+}++function findCycle(rules) {+ const edges = rules.map((rule) => {+ const emitted = emittedEventName(rule)+ const next = rules.filter((other) => {+ if (!emitted || other.event.name !== emitted) return false+ if (other.event.name !== 'task.movedToColumn') return true+ if (rule.action.title !== 'change.status') return true+ return rule.then.params.statusId === other.when.params?.statusId+ })+ return next+ })++ const color = rules.map(() => 'white')+ const stack = []++ function visit(index) {+ color[index] = 'gray'+ stack.push(index)+ for (const next of edges[index]) {+ const nextIndex = rules.indexOf(next)+ if (color[nextIndex] === 'gray') return stack.slice(stack.indexOf(nextIndex)).map((i) => rules[i])+ if (color[nextIndex] === 'white') {+ const found = visit(nextIndex)+ if (found) return found+ }+ }+ stack.pop()+ color[index] = 'black'+ return null+ }++ for (let index = 0; index < rules.length; index += 1) {+ if (color[index] === 'white') {+ const found = visit(index)+ if (found) return found+ }+ }+ return null+}++function ruleMatches(rule, busEvent, task) {+ if (rule.event.originalEvent !== busEvent.originalEvent) return false+ const payload = { task, changes: busEvent.changes, ruleParams: rule.when.params }+ if (!rule.event.match(payload)) return false+ if (rule.event.paramsMatch && !rule.event.paramsMatch(payload, rule.when.params ?? {})) return false+ return true+}++function run(busEvent, task, rules) {+ const trace = []+ const queue = [busEvent]+ const visited = new Set()+ let depth = 0++ while (queue.length > 0 && depth < 5) {+ const current = queue.shift()+ depth += 1+ for (const rule of rules) {+ const id = `${rule.when.module}.${rule.when.event}->${rule.then.module}.${rule.then.action}`+ if (visited.has(id) || !ruleMatches(rule, current, task)) continue+ visited.add(id)+ const before = { statusId: task.statusId, complete: task.complete, tagIds: [...task.tagIds] }+ const emitted = handlers[rule.action.handler](task, rule.then.params ?? {})+ trace.push({ rule: id, before, after: { statusId: task.statusId, complete: task.complete, tagIds: [...task.tagIds] } })+ if (emitted) queue.push({ ...emitted, task })+ }+ }++ return { task, trace, stopped: queue.length > 0 }+}++function task(overrides = {}) {+ return { id: 1, complete: false, statusId: 1, tagIds: [], ...overrides }+}++function show(title, result) {+ console.log(`\n${title}`)+ for (const step of result.trace) {+ console.log(` ${step.rule}`)+ console.log(` ${JSON.stringify(step.before)} -> ${JSON.stringify(step.after)}`)+ }+ if (result.trace.length === 0) console.log(' no rule ran')+ console.log(` end ${JSON.stringify(result.task)}`)+}++const doneColumn = dataSources['DataClass.fetchAvailableStatuses']().find((column) => column.name === 'Done')+const urgentTag = dataSources['DataClass.fetchTags']().find((tag) => tag.name === 'urgent')++const completedToDone = createRule({+ when: { module: 'tasks', event: 'task.completed' },+ then: { module: 'kanban', action: 'change.status', params: { statusId: doneColumn.id } },+})++const completedAddsTag = createRule({+ when: { module: 'tasks', event: 'task.completed' },+ then: { module: 'tags', action: 'add.tag', params: { tagId: urgentTag.id } },+})++const doneColumnReopens = createRule({+ when: { module: 'kanban', event: 'task.movedToColumn', params: { statusId: doneColumn.id } },+ then: { module: 'tasks', action: 'set.complete', params: { complete: false } },+})++const reopenedCompletesAgain = createRule({+ when: { module: 'tasks', event: 'task.reopened' },+ then: { module: 'tasks', action: 'set.complete', params: { complete: true } },+})++const completedClearsItself = createRule({+ when: { module: 'tasks', event: 'task.completed' },+ then: { module: 'tasks', action: 'set.complete', params: { complete: false } },+})++const userCompleted = { originalEvent: 'task.updated', changes: { complete: true } }++const justCompleted = () => task({ complete: true })++show(+ '1. task completed => change statusId to Done',+ run(userCompleted, justCompleted(), [completedToDone]),+)++show(+ '2. same event, two rules in order: column, then tag',+ run(userCompleted, justCompleted(), [completedToDone, completedAddsTag]),+)++show(+ '3. completed => Done, and that column => not completed',+ run(userCompleted, justCompleted(), [completedToDone, doneColumnReopens]),+)++show(+ '4. already in Done: change.status is a no-op and emits nothing',+ run(userCompleted, task({ complete: true, statusId: doneColumn.id }), [completedToDone]),+)++show(+ '5. kanban.created does not run task.completed rules',+ run({ originalEvent: 'kanban.created', changes: {} }, task(), [completedToDone, completedAddsTag]),+)++show(+ '6. completed => set not completed. Chain stops on reopened',+ run(userCompleted, task({ complete: true }), [completedClearsItself]),+)++const loop = findCycle([completedToDone, doneColumnReopens, reopenedCompletesAgain])+console.log('\n7. save rejects a loop that completes the task again')+console.log(` ${loop.map((rule) => `${rule.when.event} -> ${rule.then.action}`).join(' | ')}`)++const allowed = findCycle([completedToDone, doneColumnReopens])+console.log('\n8. completed => Done, and Done => not completed, is not a cycle')+console.log(` ${allowed ? 'rejected' : 'saved'}`)diff --git a/api/src/tv-modules/automations/automations/KanbanAutomations.ts b/api/src/tv-modules/automations/automations/KanbanAutomations.tsnew file mode 100644index 0000000..49bd881--- /dev/null+++ b/api/src/tv-modules/automations/automations/KanbanAutomations.ts@@ -0,0 +1,36 @@+import { GoalPermissions } from '../../../types/auth.types';+import type { AutomationModuleDefinition } from '../types';++export const kanbanAutomations: AutomationModuleDefinition = {+ name: 'kanban',+ events: [+ {+ name: 'task.movedToColumn',+ busEvents: ['task.updated'],+ params: [{ key: 'statusId', source: 'kanban.statuses' }],+ match: ({ busEvent, params }) => 'statusId' in busEvent.changes && busEvent.changes.statusId === params.statusId,+ },+ ],+ actions: [+ {+ name: 'change.status',+ params: [{ key: 'statusId', source: 'kanban.statuses' }],+ requiredPermissions: [GoalPermissions.KANBAN_CAN_MANAGE],+ emits: (params) => ({ module: 'kanban', event: 'task.movedToColumn', params: { statusId: params.statusId } }),+ execute: async ({ actor, task, params }) => {+ if (task.statusId === params.statusId) return 'skipped';+ const result = await actor.tasksManager.updateTask({ id: task.id, statusId: params.statusId });+ return result.ok ? 'applied' : 'failed';+ },+ },+ ],+ dataSources: {+ 'kanban.statuses': {+ viewPermissions: [GoalPermissions.KANBAN_CAN_VIEW, GoalPermissions.KANBAN_CAN_MANAGE],+ load: async ({ actor, goalId }) => {+ const statuses = await actor.kanbanManager.getAllStatusesForGoal(goalId);+ return statuses.map((status) => ({ id: status.id, label: status.name }));+ },+ },+ },+};diff --git a/api/src/tv-modules/automations/automations/ListsAutomations.ts b/api/src/tv-modules/automations/automations/ListsAutomations.tsnew file mode 100644index 0000000..1649812--- /dev/null+++ b/api/src/tv-modules/automations/automations/ListsAutomations.ts@@ -0,0 +1,39 @@+import { GoalPermissions } from '../../../types/auth.types';+import type { AutomationModuleDefinition } from '../types';++export const listsAutomations: AutomationModuleDefinition = {+ name: 'lists',+ events: [+ {+ name: 'task.addedToList',+ busEvents: ['task.created', 'task.updated'],+ params: [{ key: 'goalListId', source: 'lists.goalLists' }],+ match: ({ busEvent, params }) => {+ if (busEvent.name === 'task.created') return busEvent.task.goalListId === params.goalListId;+ return 'goalListId' in busEvent.changes && busEvent.changes.goalListId === params.goalListId;+ },+ },+ ],+ actions: [+ {+ name: 'move.toList',+ params: [{ key: 'goalListId', source: 'lists.goalLists' }],+ requiredPermissions: [GoalPermissions.COMPONENT_CAN_WATCH_CONTENT],+ emits: (params) => ({ module: 'lists', event: 'task.addedToList', params: { goalListId: params.goalListId } }),+ execute: async ({ actor, task, params }) => {+ if (task.goalListId === params.goalListId) return 'skipped';+ const result = await actor.tasksManager.updateTask({ id: task.id, goalListId: params.goalListId });+ return result.ok ? 'applied' : 'failed';+ },+ },+ ],+ dataSources: {+ 'lists.goalLists': {+ viewPermissions: [GoalPermissions.COMPONENT_CAN_WATCH_CONTENT],+ load: async ({ actor, goalId }) => {+ const lists = await actor.goalListManager.fetchListsNew({ goalId });+ return lists.map((list) => ({ id: list.id, label: list.name }));+ },+ },+ },+};diff --git a/api/src/tv-modules/automations/automations/TagsAutomations.ts b/api/src/tv-modules/automations/automations/TagsAutomations.tsnew file mode 100644index 0000000..97ade50--- /dev/null+++ b/api/src/tv-modules/automations/automations/TagsAutomations.ts@@ -0,0 +1,43 @@+import { GoalPermissions } from '../../../types/auth.types';+import { AutomationsRepository } from '../AutomationsRepository';+import type { AutomationModuleDefinition } from '../types';++export const tagsAutomations: AutomationModuleDefinition = {+ name: 'tags',+ events: [+ {+ name: 'tag.addedToTask',+ busEvents: ['task.tagsChanged'],+ params: [{ key: 'tagId', source: 'tags.goalTags' }],+ match: ({ busEvent, params }) => busEvent.changes.added === true && busEvent.changes.tagId === params.tagId,+ },+ {+ name: 'tag.removedFromTask',+ busEvents: ['task.tagsChanged'],+ params: [{ key: 'tagId', source: 'tags.goalTags' }],+ match: ({ busEvent, params }) => busEvent.changes.added === false && busEvent.changes.tagId === params.tagId,+ },+ ],+ actions: [+ {+ name: 'add.tag',+ params: [{ key: 'tagId', source: 'tags.goalTags' }],+ requiredPermissions: [GoalPermissions.TASKS_CAN_EDIT_TAGS],+ emits: (params) => ({ module: 'tags', event: 'tag.addedToTask', params: { tagId: params.tagId } }),+ execute: async ({ actor, task, params }) => {+ const added = await actor.tagsManager.addTagToTaskIfAbsent({ tagId: params.tagId, taskId: task.id });+ if (added === null) return 'failed';+ return added ? 'applied' : 'skipped';+ },+ },+ ],+ dataSources: {+ 'tags.goalTags': {+ viewPermissions: [GoalPermissions.TASKS_CAN_WATCH_TAGS, GoalPermissions.TASKS_CAN_EDIT_TAGS],+ load: async ({ goalId }) => {+ const tags = await new AutomationsRepository().fetchGoalTags(goalId);+ return tags.map((tag) => ({ id: tag.id, label: tag.name, color: tag.color }));+ },+ },+ },+};diff --git a/api/src/tv-modules/automations/automations/TasksAutomations.ts b/api/src/tv-modules/automations/automations/TasksAutomations.tsnew file mode 100644index 0000000..3ce9c02--- /dev/null+++ b/api/src/tv-modules/automations/automations/TasksAutomations.ts@@ -0,0 +1,51 @@+import { GoalPermissions } from '../../../types/auth.types';+import type { AutomationModuleDefinition } from '../types';++export const tasksAutomations: AutomationModuleDefinition = {+ name: 'tasks',+ events: [+ {+ name: 'task.created',+ busEvents: ['task.created'],+ params: [],+ match: () => true,+ },+ {+ name: 'task.completed',+ busEvents: ['task.updated'],+ params: [],+ match: ({ busEvent }) => busEvent.changes.complete === true,+ },+ {+ name: 'task.reopened',+ busEvents: ['task.updated'],+ params: [],+ match: ({ busEvent }) => busEvent.changes.complete === false,+ },+ ],+ actions: [+ {+ name: 'complete',+ params: [],+ requiredPermissions: [GoalPermissions.TASKS_CAN_EDIT_STATUS],+ emits: () => ({ module: 'tasks', event: 'task.completed' }),+ execute: async ({ actor, task }) => {+ if (task.complete) return 'skipped';+ const result = await actor.tasksManager.updateTask({ id: task.id, complete: true });+ return result.ok ? 'applied' : 'failed';+ },+ },+ {+ name: 'reopen',+ params: [],+ requiredPermissions: [GoalPermissions.TASKS_CAN_EDIT_STATUS],+ emits: () => ({ module: 'tasks', event: 'task.reopened' }),+ execute: async ({ actor, task }) => {+ if (!task.complete) return 'skipped';+ const result = await actor.tasksManager.updateTask({ id: task.id, complete: false });+ return result.ok ? 'applied' : 'failed';+ },+ },+ ],+ dataSources: {},+};diff --git a/api/src/tv-modules/automations/catalog/AutomationCatalog.ts b/api/src/tv-modules/automations/catalog/AutomationCatalog.tsnew file mode 100644index 0000000..3d571ad--- /dev/null+++ b/api/src/tv-modules/automations/catalog/AutomationCatalog.ts@@ -0,0 +1,56 @@+import { kanbanAutomations } from '../automations/KanbanAutomations';+import { listsAutomations } from '../automations/ListsAutomations';+import { tagsAutomations } from '../automations/TagsAutomations';+import { tasksAutomations } from '../automations/TasksAutomations';+import type {+ AutomationActionDefinition,+ AutomationBusEventName,+ AutomationCatalogForClient,+ AutomationDataSource,+ AutomationDataSourceName,+ AutomationEventDefinition,+ AutomationFindActionArgs,+ AutomationFindEventArgs,+ AutomationModuleDefinition,+} from '../types';++export class AutomationCatalog {+ private readonly modules: AutomationModuleDefinition[];++ constructor(modules: AutomationModuleDefinition[] = [tasksAutomations, kanbanAutomations, listsAutomations, tagsAutomations]) {+ this.modules = modules;+ }++ findEvent(args: AutomationFindEventArgs): AutomationEventDefinition | null {+ const module = this.modules.find((item) => item.name === args.module);+ return module?.events.find((item) => item.name === args.event) ?? null;+ }++ findAction(args: AutomationFindActionArgs): AutomationActionDefinition | null {+ const module = this.modules.find((item) => item.name === args.module);+ return module?.actions.find((item) => item.name === args.action) ?? null;+ }++ findDataSource(name: AutomationDataSourceName): AutomationDataSource | null {+ for (const module of this.modules) {+ if (Object.prototype.hasOwnProperty.call(module.dataSources, name)) return module.dataSources[name] ?? null;+ }+ return null;+ }++ listensTo(busEvent: AutomationBusEventName): boolean {+ return this.modules.some((module) => module.events.some((event) => event.busEvents.includes(busEvent)));+ }++ toClient(): AutomationCatalogForClient {+ return {+ modules: this.modules.map((module) => ({+ name: module.name,+ events: module.events.map((event) => ({ name: event.name, params: event.params })),+ actions: module.actions.map((action) => ({ name: action.name, params: action.params })),+ })),+ };+ }+}++export const automationCatalog = new AutomationCatalog();diff --git a/api/src/tv-modules/automations/middlewares/goal-id-resolvers.ts b/api/src/tv-modules/automations/middlewares/goal-id-resolvers.tsnew file mode 100644index 0000000..5c3ca79--- /dev/null+++ b/api/src/tv-modules/automations/middlewares/goal-id-resolvers.ts@@ -0,0 +1,13 @@+import type { Request } from 'express';+import { AutomationsRepository } from '../AutomationsRepository';++export function goalIdFromParam(req: Request): number | null {+ const goalId = Number(req.params.goalId);+ return Number.isInteger(goalId) && goalId > 0 ? goalId : null;+}++export async function goalIdFromRule(req: Request): Promise<number | null> {+ const ruleId = Number(req.params.ruleId);+ if (!Number.isInteger(ruleId) || ruleId <= 0) return null;+ return (await new AutomationsRepository().getById(ruleId))?.goalId ?? null;+}diff --git a/api/src/tv-modules/automations/middlewares/require-automation-permission.ts b/api/src/tv-modules/automations/middlewares/require-automation-permission.tsnew file mode 100644index 0000000..5508d8a--- /dev/null+++ b/api/src/tv-modules/automations/middlewares/require-automation-permission.ts@@ -0,0 +1,28 @@+import type { NextFunction, Request, Response } from 'express';+import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';+import { $logger } from '../../../modules/logget';+import { GoalPermissions } from '../../../types/auth.types';+import { logError } from '../../../utils/api';+import type { RequireAutomationPermissionArgs } from '../types';++export function requireAutomationPermission({ permission, resolveGoalId }: RequireAutomationPermissionArgs) {+ return async (req: Request, res: Response, next: NextFunction) => {+ const goalId = await resolveGoalId(req);+ if (!goalId) return res.status(404).end();++ const permissions = await req.appUser.permissionsFetcher+ .getPermissionsForType(goalId, GoalPermissionsFetcher.PERMISSION_TYPE_FOR_GOAL)+ .catch(logError);++ if (!permissions) {+ $logger.error('Can not resolve automation permissions');+ return res.status(500).end();+ }++ const granted =+ permissions.hasPermissions(permission) ||+ (permission === GoalPermissions.AUTOMATION_CAN_VIEW && permissions.hasPermissions(GoalPermissions.AUTOMATION_CAN_MANAGE));+ if (granted) return next();+ return res.status(403).end();+ };+}diff --git a/api/src/tv-modules/automations/types.ts b/api/src/tv-modules/automations/types.tsnew file mode 100644index 0000000..92808b7--- /dev/null+++ b/api/src/tv-modules/automations/types.ts@@ -0,0 +1,309 @@+import { type } from 'arktype';+import type { Request } from 'express';+import type { AutomationRulesSchemaTypeForSelect, TasksSchemaTypeForSelect } from 'taskview-db-schemas';+import type { AppUser } from '../../core/AppUser';+import type { GoalPermissionType } from '../../types/auth.types';+import type { AutomationRunQueue } from './AutomationRunQueue';+import type { AutomationCatalog } from './catalog/AutomationCatalog';++export const AUTOMATION_RULES_PER_GOAL_LIMIT = 100;+export const AUTOMATION_CHAIN_MAX_DEPTH = 5;+export const AUTOMATION_RULE_NAME_MAX_LENGTH = 255;+export const AUTOMATION_RUN_QUEUE = 'automations-run';+export const AUTOMATION_RUN_RETRY_LIMIT = 3;+export const AUTOMATION_RUN_CONCURRENCY = 5;+export const AUTOMATION_RUN_POLLING_SECONDS = 0.5;++const toNumber = type('string | number').pipe((v) => Number(v));++export const AutomationArkTypeGoalIdParam = type({ goalId: toNumber });+export const AutomationArkTypeRuleIdParam = type({ ruleId: toNumber });+export const AutomationArkTypeOptionsParams = type({ goalId: toNumber, source: "'kanban.statuses' | 'tags.goalTags' | 'lists.goalLists'" });++const ruleParams = type({ '[string]': 'number.integer' });++export const AutomationArkTypeRuleInput = type({+ name: 'string > 0',+ 'enabled?': 'boolean',+ trigger: { module: 'string > 0', event: 'string > 0', 'params?': ruleParams },+ action: { module: 'string > 0', action: 'string > 0', 'params?': ruleParams },+});++export const AutomationArkTypeRulePatch = type({+ 'name?': 'string > 0',+ 'enabled?': 'boolean',+ 'trigger?': { module: 'string > 0', event: 'string > 0', 'params?': ruleParams },+ 'action?': { module: 'string > 0', action: 'string > 0', 'params?': ruleParams },+});++export type AutomationRuleInput = typeof AutomationArkTypeRuleInput.infer;+export type AutomationRulePatch = typeof AutomationArkTypeRulePatch.infer;++export type AutomationParams = Record<string, number>;++export type AutomationModuleName = 'tasks' | 'kanban' | 'tags' | 'lists';++export type AutomationBusEventName = 'task.created' | 'task.updated' | 'task.tagsChanged';++export type AutomationDataSourceName = 'kanban.statuses' | 'tags.goalTags' | 'lists.goalLists';++export type AutomationOption = {+ id: number;+ label: string;+ color?: string;+};++export type AutomationParamDefinition = {+ key: string;+ source: AutomationDataSourceName;+};++export type AutomationBusEvent = {+ name: AutomationBusEventName;+ task: TasksSchemaTypeForSelect;+ changes: Record<string, unknown>;+};++export type AutomationTaskBusEvent = {+ name: AutomationBusEventName;+ taskId: number;+ changes: Record<string, unknown>;+};++export type AutomationEventMatchArgs = {+ busEvent: AutomationBusEvent;+ params: AutomationParams;+};++export type AutomationEventDefinition = {+ name: string;+ busEvents: AutomationBusEventName[];+ params: AutomationParamDefinition[];+ match: (args: AutomationEventMatchArgs) => boolean;+};++export type AutomationEventRef = {+ module: AutomationModuleName;+ event: string;+ params?: AutomationParams;+};++export type AutomationActionExecuteArgs = {+ actor: AppUser;+ task: TasksSchemaTypeForSelect;+ params: AutomationParams;+};++export type AutomationActionOutcome = 'applied' | 'skipped' | 'failed';++export type AutomationActionDefinition = {+ name: string;+ params: AutomationParamDefinition[];+ requiredPermissions: GoalPermissionType[];+ emits: (params: AutomationParams) => AutomationEventRef | null;+ execute: (args: AutomationActionExecuteArgs) => Promise<AutomationActionOutcome>;+};++export type AutomationDataSourceArgs = {+ actor: AppUser;+ goalId: number;+};++export type AutomationDataSource = {+ viewPermissions: GoalPermissionType[];+ load: (args: AutomationDataSourceArgs) => Promise<AutomationOption[]>;+};++export type AutomationModuleDefinition = {+ name: AutomationModuleName;+ events: AutomationEventDefinition[];+ actions: AutomationActionDefinition[];+ dataSources: Partial<Record<AutomationDataSourceName, AutomationDataSource>>;+};++export type AutomationFindEventArgs = {+ module: string;+ event: string;+};++export type AutomationFindActionArgs = {+ module: string;+ action: string;+};++export type AutomationCatalogParamForClient = AutomationParamDefinition;++export type AutomationCatalogForClient = {+ modules: {+ name: AutomationModuleName;+ events: { name: string; params: AutomationCatalogParamForClient[] }[];+ actions: { name: string; params: AutomationCatalogParamForClient[] }[];+ }[];+};++export type AutomationRuleForClient = {+ id: number;+ goalId: number;+ creatorId: number;+ name: string;+ enabled: boolean;+ trigger: { module: string; event: string; params: AutomationParams };+ action: { module: string; action: string; params: AutomationParams };+ createdAt: string;+ editedAt: string;+};++export type AutomationRuleShape = {+ id: number;+ trigger: { module: string; event: string; params: AutomationParams };+ action: { module: string; action: string; params: AutomationParams };+};++export type AutomationChain = {+ depth: number;+ firedRuleIds: Set<number>;+ actors: Map<number, Promise<AppUser | null>>;+ pending: Promise<void>[];+};++export type AutomationRunRuleRef = {+ id: number;+ editedAt: string;+};++export type AutomationRunJob = {+ goalId: number;+ taskId: number;+ rules: AutomationRunRuleRef[];+ chain: { depth: number; firedRuleIds: number[] };+};++export type AutomationRunJobHandler = (job: AutomationRunJob) => Promise<void>;++export type AutomationEngineDeps = {+ catalog: AutomationCatalog;+ queue: AutomationRunQueue;+};++export type AutomationRuleMatchArgs = {+ rule: AutomationRuleRow;+ busEvent: AutomationBusEvent;+};++export type AutomationActorForArgs = {+ chain: AutomationChain;+ userId: number;+};++export type AutomationErrorCode = 'not_found' | 'forbidden' | 'invalid' | 'cycle' | 'limit_reached';++export type AutomationResult<T> = { ok: true; data: T } | { ok: false; code: AutomationErrorCode; message?: string };++export type AutomationRuleRow = AutomationRulesSchemaTypeForSelect;++export type AutomationRuleInsertArgs = {+ goalId: number;+ creatorId: number;+ name: string;+ enabled: boolean;+ triggerModule: string;+ triggerEvent: string;+ triggerParams: AutomationParams;+ actionModule: string;+ actionName: string;+ actionParams: AutomationParams;+};++export type AutomationRuleUpdateArgs = {+ ruleId: number;+ patch: Partial<Omit<AutomationRuleInsertArgs, 'goalId'>>;+};++export type AutomationCreateRuleArgs = {+ goalId: number;+ input: AutomationRuleInput;+};++export type AutomationUpdateRuleArgs = {+ ruleId: number;+ patch: AutomationRulePatch;+};++export type AutomationValidateRuleArgs = {+ goalId: number;+ rule: AutomationRuleShape;+};++export type AutomationCheckCycleArgs = {+ goalId: number;+ candidate: AutomationRuleShape;+ candidateName: string;+};++export type AutomationOptionRemovedArgs = {+ goalId: number;+ source: AutomationDataSourceName;+ id: number;+};++export type AutomationRuleUsesOptionArgs = {+ rule: AutomationRuleShape;+ source: AutomationDataSourceName;+ id: number;+};++export type AutomationRulesDisableArgs = {+ goalId: number;+ ruleIds: number[];+};++export type AutomationOptionsArgs = {+ goalId: number;+ source: AutomationDataSourceName;+};++export type AutomationRunRuleArgs = {+ ref: AutomationRunRuleRef;+ job: AutomationRunJob;+ chain: AutomationChain;+};++export type AutomationGoalIdResolver = (req: Request) => Promise<number | null> | number | null;++export type RequireAutomationPermissionArgs = {+ permission: GoalPermissionType;+ resolveGoalId: AutomationGoalIdResolver;+};++export type AutomationCycleNextRulesArgs = {+ rule: AutomationRuleShape;+ rules: AutomationRuleShape[];+};++export type AutomationCycleTriggersArgs = {+ emitted: AutomationEventRef;+ rule: AutomationRuleShape;+};++export type AutomationParamsCompatibleArgs = {+ emitted?: AutomationParams;+ expected: AutomationParams;+};++export type AutomationNormalizeParamsArgs = {+ goalId: number;+ definitions: AutomationParamDefinition[];+ params: AutomationParams;+};++export type AutomationHasPermissionsArgs = {+ actor: AppUser;+ goalId: number;+ permissions: GoalPermissionType[];+};++export type AutomationCanRunArgs = {+ actor: AppUser;+ goalId: number;+ action: AutomationActionDefinition;+};diff --git a/api/src/tv-modules/files/FilesDispatcher.ts b/api/src/tv-modules/files/FilesDispatcher.tsindex 430944a..bf729bd 100644--- a/api/src/tv-modules/files/FilesDispatcher.ts+++ b/api/src/tv-modules/files/FilesDispatcher.ts@@ -1,19 +1,14 @@-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 { RealtimeRepository } from '../realtime/RealtimeRepository';const FILES_RT_EVENT = 'files.changed';export class FilesDispatcher implements Dispatcher {+ private readonly realtime = new RealtimeRepository();+register(): void {eventBus.on('files.changed', (d) => this.notifyGoalMembers(d.goalId, { taskIds: d.taskIds }));}@@ -21,33 +16,13 @@ export class FilesDispatcher implements Dispatcher {async registerWorkers(): Promise<void> {}private async notifyGoalMembers(goalId: number, payload: Record<string, unknown>): Promise<void> {+ const centrifugo = getCentrifugoClient();+ if (!centrifugo.isEnabled()) return;try {- const memberIds = await this.resolveGoalMemberIds(goalId);- if (memberIds.length === 0) return;- const centrifugo = getCentrifugoClient();- await Promise.all(- memberIds.map((userId) => centrifugo.publishToUser(userId, FILES_RT_EVENT, { goalId, ...payload }))- );+ const userIds = await this.realtime.fetchGoalMemberIds(goalId);+ await centrifugo.broadcastToUsers({ userIds, event: FILES_RT_EVENT, data: { goalId, ...payload } });} catch (err) {$logger.error(err, '[FilesDispatcher] 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);- for (const row of collabRows) ids.add(row.id);- return [...ids];- }}diff --git a/api/src/tv-modules/kanban/KanbanController.ts b/api/src/tv-modules/kanban/KanbanController.tsindex d2df594..aa2f111 100644--- a/api/src/tv-modules/kanban/KanbanController.ts+++ b/api/src/tv-modules/kanban/KanbanController.ts@@ -79,6 +79,8 @@ export class KanbanController {return res.status(400).send(data.summary);}- return res.tvJson(await req.appUser.kanbanManager.updateTasksOrderAndColumn(data));+ const result = await req.appUser.kanbanManager.updateTasksOrderAndColumn(data);+ if (!result) return res.status(404).end();+ return res.tvJson(result);};}diff --git a/api/src/tv-modules/kanban/KanbanManager.ts b/api/src/tv-modules/kanban/KanbanManager.tsindex a8d55ce..a3fda09 100644--- a/api/src/tv-modules/kanban/KanbanManager.ts+++ b/api/src/tv-modules/kanban/KanbanManager.ts@@ -1,5 +1,6 @@import { chunk } from '../../utils/helpers';import type { AppUser } from '../../core/AppUser';+import { eventBus } from '../../core/EventBus';import type { TaskForClientNew } from '../tasks/tasks.server.types';import { KanbanRepository } from './KanbanRepository';import {@@ -33,7 +34,16 @@ export class KanbanManager {}async deleteStatus(data: DeleteKanbanStatus) {- return await this.repository.deleteStatus(data.id);+ const status = await this.repository.fetchStatus(data.id);+ const deleted = await this.repository.deleteStatus(data.id);+ if (status && deleted) {+ eventBus.emit('kanban.statusDeleted', {+ statusId: status.id,+ goalId: status.goal_id,+ initiatorId: this.user.getUserData()?.id as number,+ });+ }+ return deleted;}async addStatus(data: KanbanAddStatus): Promise<KanbanStatusForClient | null> {@@ -92,10 +102,17 @@ export class KanbanManager {return tasksWithNewOrder;}- async updateTasksOrderAndColumn(data: KanbanArgUpdateTasksOrder): Promise<{ tasks: { id: number, kanbanOrder: number | null }[], columnVersion: number | null }> {+ async updateTasksOrderAndColumn(data: KanbanArgUpdateTasksOrder): Promise<{ tasks: { id: number, kanbanOrder: number | null }[], columnVersion: number | null } | null> {const KANBAN_GAP = 16384;const MIN_GAP_THRESHOLD = 1e-6;+ const previous = await this.user.tasksManager.repository.fetchTaskByIdNew(data.taskId);+ if (!previous || previous.goalId !== data.goalId) return null;+ if (data.columnId !== null) {+ const columns = await this.repository.getAllStatusesForGoal(data.goalId);+ if (!columns.some((column) => column.id === data.columnId)) return null;+ }+// Получаем порядки предыдущей и следующей задачlet prevTask = data.prevTaskId? (await this.repository.getTaskById(data.prevTaskId))?.kanbanOrder ?? null@@ -181,11 +198,18 @@ export class KanbanManager {}if (newOrder !== null) {- await this.user.tasksManager.repository.updateTask({+ const task = await this.user.tasksManager.repository.updateTask({id: data.taskId,kanbanOrder: newOrder,statusId: data.columnId,});+ if (task && previous.statusId !== task.statusId) {+ eventBus.emit('task.updated', {+ task,+ changes: { statusId: task.statusId, kanbanOrder: newOrder },+ initiatorId: this.user.getUserData()?.id as number,+ });+ }}const result = await this.repository.getTasksOrderForColumnAndCursor(diff --git a/api/src/tv-modules/lists/GoalListManager.ts b/api/src/tv-modules/lists/GoalListManager.tsindex adf9daa..825ee9a 100644--- a/api/src/tv-modules/lists/GoalListManager.ts+++ b/api/src/tv-modules/lists/GoalListManager.ts@@ -1,5 +1,6 @@import type { GoalsListSchemaTypeForSelect } from 'taskview-db-schemas';import type { AppUser } from '../../core/AppUser';+import { eventBus } from '../../core/EventBus';import type { GoalListInDb } from '../../types/goal-list.types';import { GoalListItemForClient } from './GoalListItemForClient';import { GoalListsRepository } from './GoalListsRepository';@@ -71,7 +72,10 @@ export class GoalListManager {}async deleteListNew(data: GoalListArgDelete): Promise<boolean> {- return await this.repository.deleteListNew(data);+ const deleted = await this.repository.deleteListNew(data);+ if (!deleted) return false;+ eventBus.emit('list.deleted', { listId: deleted.id, goalId: deleted.goalId, initiatorId: this.user.getUserData()?.id as number });+ return true;}async updateArchive(listId: number, archive: GoalListInDb['archive']): Promise<boolean> {diff --git a/api/src/tv-modules/lists/GoalListsRepository.ts b/api/src/tv-modules/lists/GoalListsRepository.tsindex 7ff7c39..19b05ab 100644--- a/api/src/tv-modules/lists/GoalListsRepository.ts+++ b/api/src/tv-modules/lists/GoalListsRepository.ts@@ -129,14 +129,11 @@ export class GoalListsRepository {return !!(del.rowCount && del.rowCount > 0);}- async deleteListNew(data: GoalListArgDelete): Promise<boolean> {+ async deleteListNew(data: GoalListArgDelete): Promise<GoalsListSchemaTypeForSelect | null> {const result = await callWithCatch(() =>this.db.dbDrizzle.delete(GoalsListSchema).where(eq(GoalsListSchema.id, data.id)).returning());- if (!result) {- return false;- }- return !!result.length;+ return result?.[0] ?? null;}async updateArchive(listId: number, archive: GoalListInDb['archive']): Promise<boolean> {diff --git a/api/src/tv-modules/realtime/RealtimeDispatcher.ts b/api/src/tv-modules/realtime/RealtimeDispatcher.tsindex bba307a..03aca5d 100644--- a/api/src/tv-modules/realtime/RealtimeDispatcher.ts+++ b/api/src/tv-modules/realtime/RealtimeDispatcher.ts@@ -4,12 +4,24 @@ import { getCentrifugoClient } from '../../core/CentrifugoClient';import type { Dispatcher } from '../../core/Dispatcher';import { eventBus, type AppEvents } from '../../core/EventBus';import { Database } from '../../modules/db';+import { $logger } from '../../modules/logget';+import { RealtimeRepository } from './RealtimeRepository';+import { REALTIME_TASKS_CHANGED_EVENT, type RealtimeTasksChangedArgs } from './types';export class RealtimeDispatcher implements Dispatcher {+ private readonly repository = new RealtimeRepository();+register(): void {eventBus.on('collaboration.userAdded', (data) => this.onCollaborationUserAdded(data));eventBus.on('collaboration.userRemoved', (data) => this.onCollaborationUserRemoved(data));eventBus.on('collaboration.rolesChanged', (data) => this.onCollaborationRolesChanged(data));++ eventBus.on('task.created', (data) => this.publishTasksChanged({ goalId: data.task.goalId, taskIds: [data.task.id], kind: 'created' }));+ eventBus.on('task.updated', (data) => this.publishTasksChanged({ goalId: data.task.goalId, taskIds: [data.task.id], kind: 'updated' }));+ eventBus.on('task.deleted', (data) => this.publishTasksChanged({ goalId: data.goalId, taskIds: [data.taskId], kind: 'deleted' }));+ eventBus.on('task.moved', (data) => this.onTaskMoved(data));+ eventBus.on('task.assigneesChanged', (data) => this.onTaskRelationsChanged(data.taskId));+ eventBus.on('task.tagsChanged', (data) => this.onTaskRelationsChanged(data.taskId));}async registerWorkers(): Promise<void> {}@@ -35,6 +47,33 @@ export class RealtimeDispatcher implements Dispatcher {await this.publishToUser(userId, 'goals.changed', { goalId: data.goalId });}+ private async onTaskMoved(data: AppEvents['task.moved']): Promise<void> {+ await Promise.all([+ this.publishTasksChanged({ goalId: data.fromGoalId, taskIds: data.taskIds, kind: 'deleted' }),+ this.publishTasksChanged({ goalId: data.toGoalId, taskIds: [data.task.id], kind: 'created' }),+ ]);+ }++ private async onTaskRelationsChanged(taskId: number): Promise<void> {+ if (!getCentrifugoClient().isEnabled()) return;+ const goalId = await this.repository.fetchTaskGoalId(taskId).catch((err) => {+ $logger.error(err, '[RealtimeDispatcher] can not resolve the project of a task');+ return null;+ });+ if (goalId) await this.publishTasksChanged({ goalId, taskIds: [taskId], kind: 'updated' });+ }++ private async publishTasksChanged(args: RealtimeTasksChangedArgs): Promise<void> {+ const centrifugo = getCentrifugoClient();+ if (!centrifugo.isEnabled()) return;+ try {+ const memberIds = await this.repository.fetchGoalMemberIds(args.goalId);+ await centrifugo.broadcastToUsers({ userIds: memberIds, event: REALTIME_TASKS_CHANGED_EVENT, data: args });+ } catch (err) {+ $logger.error(err, '[RealtimeDispatcher] tasks.changed publish failed');+ }+ }+private async publishToUser(userId: number, event: string, data: Record<string, unknown>): Promise<void> {const centrifugo = getCentrifugoClient();await centrifugo.publishToUser(userId, event, data);diff --git a/api/src/tv-modules/realtime/RealtimeRepository.ts b/api/src/tv-modules/realtime/RealtimeRepository.tsnew file mode 100644index 0000000..99d721d--- /dev/null+++ b/api/src/tv-modules/realtime/RealtimeRepository.ts@@ -0,0 +1,32 @@+import { eq } from 'drizzle-orm';+import { alias } from 'drizzle-orm/pg-core';+import { CollaborationUsersSchema, CollaborationUsersToGoalsSchema, GoalsSchema, TasksSchema, UsersSchema } from 'taskview-db-schemas';+import { Database } from '../../modules/db';++const AuthUsers = alias(UsersSchema, 'auth_users');++export class RealtimeRepository {+ private readonly db = Database.getInstance();++ async fetchGoalMemberIds(goalId: number): Promise<number[]> {+ const [ownerRows, collabRows] = await Promise.all([+ this.db.dbDrizzle.select({ id: GoalsSchema.owner }).from(GoalsSchema).where(eq(GoalsSchema.id, goalId)).limit(1),+ this.db.dbDrizzle+ .select({ id: AuthUsers.id })+ .from(CollaborationUsersToGoalsSchema)+ .innerJoin(CollaborationUsersSchema, eq(CollaborationUsersToGoalsSchema.userId, CollaborationUsersSchema.id))+ .innerJoin(AuthUsers, eq(CollaborationUsersSchema.email, AuthUsers.email))+ .where(eq(CollaborationUsersToGoalsSchema.goalId, goalId)),+ ]);++ const ids = new Set<number>();+ if (ownerRows[0]?.id) ids.add(ownerRows[0].id);+ for (const row of collabRows) ids.add(row.id);+ return [...ids];+ }++ async fetchTaskGoalId(taskId: number): Promise<number | null> {+ const rows = await this.db.dbDrizzle.select({ goalId: TasksSchema.goalId }).from(TasksSchema).where(eq(TasksSchema.id, taskId)).limit(1);+ return rows[0]?.goalId ?? null;+ }+}diff --git a/api/src/tv-modules/realtime/__tests__/GoalMemberBroadcasts.spec.ts b/api/src/tv-modules/realtime/__tests__/GoalMemberBroadcasts.spec.tsnew file mode 100644index 0000000..30c4f0a--- /dev/null+++ b/api/src/tv-modules/realtime/__tests__/GoalMemberBroadcasts.spec.ts@@ -0,0 +1,69 @@+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import type { SprintsSchemaTypeForSelect, TasksSchemaTypeForSelect } from 'taskview-db-schemas';+import { eventBus } from '../../../core/EventBus';+import type { CentrifugoBroadcastToUsersArgs } from '../../../types/centrifugo.types';+import { FilesDispatcher } from '../../files/FilesDispatcher';+import { RecurrenceDispatcher } from '../../recurrence/RecurrenceDispatcher';+import { SprintsDispatcher } from '../../sprints/SprintsDispatcher';++const centrifugo = vi.hoisted(() => ({ isEnabled: vi.fn(() => true), broadcastToUsers: vi.fn(async (_args: CentrifugoBroadcastToUsersArgs) => true) }));+const repository = vi.hoisted(() => ({ fetchGoalMemberIds: vi.fn(async () => [1, 2]) }));++vi.mock('../../../core/CentrifugoClient', () => ({ getCentrifugoClient: () => centrifugo }));+vi.mock('../RealtimeRepository', () => ({ RealtimeRepository: vi.fn(() => repository) }));+vi.mock('../../recurrence/RecurrenceGenerator', () => ({ RecurrenceGenerator: vi.fn(() => ({})) }));+vi.mock('../../recurrence/RecurrenceRepository', () => ({ RecurrenceRepository: vi.fn(() => ({})) }));+vi.mock('../../sprints/SprintScheduler', () => ({ SprintScheduler: vi.fn(() => ({})) }));++async function settle() {+ for (let i = 0; i < 10; i += 1) await new Promise((resolve) => setImmediate(resolve));+}++function broadcasts() {+ return centrifugo.broadcastToUsers.mock.calls.map(([args]) => args);+}++describe('Files, sprints and recurrence real-time broadcasts', () => {+ beforeAll(() => {+ new FilesDispatcher().register();+ new SprintsDispatcher().register();+ new RecurrenceDispatcher().register();+ });++ beforeEach(() => {+ vi.clearAllMocks();+ centrifugo.isEnabled.mockReturnValue(true);+ });++ it('sends one broadcast to the project members when files change', async () => {+ eventBus.emit('files.changed', { goalId: 10, taskIds: [5], initiatorId: 1 });+ await settle();+ expect(repository.fetchGoalMemberIds).toHaveBeenCalledWith(10);+ expect(broadcasts()).toEqual([{ userIds: [1, 2], event: 'files.changed', data: { goalId: 10, taskIds: [5] } }]);+ });++ it('sends one broadcast to the project members when a sprint changes', async () => {+ eventBus.emit('sprint.created', { sprint: { id: 3, goalId: 10 } as SprintsSchemaTypeForSelect, initiatorId: 1 });+ await settle();+ expect(broadcasts()).toEqual([{ userIds: [1, 2], event: 'sprints.changed', data: { goalId: 10, sprintId: 3 } }]);+ });++ it('announces a new instance of a recurring task without its content', async () => {+ const task = { id: 5, goalId: 10, recurrenceRuleId: 7 } as TasksSchemaTypeForSelect;+ eventBus.emit('task.created', { task, initiatorId: 1 });+ await settle();+ expect(broadcasts()).toEqual([+ { userIds: [1, 2], event: 'recurrence.instanceCreated', data: { goalId: 10, ruleId: 7, taskId: 5 } },+ ]);+ });++ it('does not touch the database when real-time is not configured', async () => {+ centrifugo.isEnabled.mockReturnValue(false);+ eventBus.emit('files.changed', { goalId: 10, taskIds: [5], initiatorId: 1 });+ eventBus.emit('sprint.deleted', { sprintId: 3, goalId: 10, initiatorId: 1 });+ eventBus.emit('task.created', { task: { id: 5, goalId: 10, recurrenceRuleId: 7 } as TasksSchemaTypeForSelect, initiatorId: 1 });+ await settle();+ expect(repository.fetchGoalMemberIds).not.toHaveBeenCalled();+ expect(centrifugo.broadcastToUsers).not.toHaveBeenCalled();+ });+});diff --git a/api/src/tv-modules/realtime/__tests__/RealtimeDispatcher.spec.ts b/api/src/tv-modules/realtime/__tests__/RealtimeDispatcher.spec.tsnew file mode 100644index 0000000..61d46b7--- /dev/null+++ b/api/src/tv-modules/realtime/__tests__/RealtimeDispatcher.spec.ts@@ -0,0 +1,79 @@+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import type { TasksSchemaTypeForSelect } from 'taskview-db-schemas';+import { eventBus } from '../../../core/EventBus';+import type { CentrifugoBroadcastToUsersArgs } from '../../../types/centrifugo.types';+import { RealtimeDispatcher } from '../RealtimeDispatcher';++const centrifugo = vi.hoisted(() => ({ isEnabled: vi.fn(() => true), broadcastToUsers: vi.fn(async (_args: CentrifugoBroadcastToUsersArgs) => true) }));+const repository = vi.hoisted(() => ({ fetchGoalMemberIds: vi.fn(async () => [1, 2]), fetchTaskGoalId: vi.fn(async () => 20) }));++vi.mock('../../../core/CentrifugoClient', () => ({ getCentrifugoClient: () => centrifugo }));+vi.mock('../RealtimeRepository', () => ({ RealtimeRepository: vi.fn(() => repository) }));++const task = { id: 5, goalId: 10 } as TasksSchemaTypeForSelect;++async function settle() {+ for (let i = 0; i < 10; i += 1) await new Promise((resolve) => setImmediate(resolve));+}++function broadcasts() {+ return centrifugo.broadcastToUsers.mock.calls.map(([args]) => args);+}++describe('RealtimeDispatcher tasks.changed', () => {+ beforeAll(() => {+ new RealtimeDispatcher().register();+ });++ beforeEach(() => {+ vi.clearAllMocks();+ centrifugo.isEnabled.mockReturnValue(true);+ });++ it('tells every project member that a task changed, without its content', async () => {+ eventBus.emit('task.updated', { task, changes: { statusId: 3 }, initiatorId: 1 });+ await settle();+ expect(repository.fetchGoalMemberIds).toHaveBeenCalledWith(10);+ expect(broadcasts()).toEqual([{ userIds: [1, 2], event: 'tasks.changed', data: { goalId: 10, taskIds: [5], kind: 'updated' } }]);+ });++ it('reports created and deleted tasks', async () => {+ eventBus.emit('task.created', { task, initiatorId: 1 });+ eventBus.emit('task.deleted', { taskId: 6, goalId: 10, initiatorId: 1 });+ await settle();+ expect(broadcasts().map(({ data }) => data)).toEqual([+ { goalId: 10, taskIds: [5], kind: 'created' },+ { goalId: 10, taskIds: [6], kind: 'deleted' },+ ]);+ });++ it('removes a moved task from the old project and adds it to the new one', async () => {+ eventBus.emit('task.moved', { task: { ...task, goalId: 11 }, taskIds: [5, 7], fromGoalId: 10, toGoalId: 11, initiatorId: 1 });+ await settle();+ expect(broadcasts().map(({ data }) => data)).toEqual([+ { goalId: 10, taskIds: [5, 7], kind: 'deleted' },+ { goalId: 11, taskIds: [5], kind: 'created' },+ ]);+ });++ it('resolves the project for tag and assignee changes', async () => {+ eventBus.emit('task.tagsChanged', { taskId: 8, tagId: 3, added: true, initiatorId: 1 });+ eventBus.emit('task.assigneesChanged', { taskId: 9, userIds: [], initiatorId: 1 });+ await settle();+ expect(repository.fetchTaskGoalId.mock.calls).toEqual([[8], [9]]);+ expect(broadcasts().map(({ data }) => data)).toEqual([+ { goalId: 20, taskIds: [8], kind: 'updated' },+ { goalId: 20, taskIds: [9], kind: 'updated' },+ ]);+ });++ it('does not touch the database when real-time is not configured', async () => {+ centrifugo.isEnabled.mockReturnValue(false);+ eventBus.emit('task.updated', { task, changes: {}, initiatorId: 1 });+ eventBus.emit('task.tagsChanged', { taskId: 8, tagId: 3, added: true, initiatorId: 1 });+ await settle();+ expect(repository.fetchGoalMemberIds).not.toHaveBeenCalled();+ expect(repository.fetchTaskGoalId).not.toHaveBeenCalled();+ expect(centrifugo.broadcastToUsers).not.toHaveBeenCalled();+ });+});diff --git a/api/src/tv-modules/realtime/__tests__/RealtimeRepository.integration.spec.ts b/api/src/tv-modules/realtime/__tests__/RealtimeRepository.integration.spec.tsnew file mode 100644index 0000000..3fad2c4--- /dev/null+++ b/api/src/tv-modules/realtime/__tests__/RealtimeRepository.integration.spec.ts@@ -0,0 +1,57 @@+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { eq, inArray } from 'drizzle-orm';+import { CollaborationUsersSchema, CollaborationUsersToGoalsSchema, GoalsSchema, OrganizationsSchema, TasksSchema, UsersSchema } from 'taskview-db-schemas';+import { Database } from '../../../modules/db';+import { RealtimeRepository } from '../RealtimeRepository';++const stamp = `${Date.now()}-${Math.round(Math.random() * 1e6)}`;+const db = () => Database.getInstance().dbDrizzle;++let ownerId = 0;+let collaboratorId = 0;+let collabUserId = 0;+let goalId = 0;+let taskId = 0;++describe('RealtimeRepository', () => {+ beforeAll(async () => {+ const users = await db()+ .insert(UsersSchema)+ .values([+ { login: `rt-owner-${stamp}`, email: `rt-owner-${stamp}@test.local`, password: 'x' },+ { login: `rt-member-${stamp}`, email: `rt-member-${stamp}@test.local`, password: 'x' },+ ])+ .returning({ id: UsersSchema.id });+ [ownerId, collaboratorId] = users.map((user) => user.id);++ const [{ id: organizationId }] = await db()+ .insert(OrganizationsSchema)+ .values({ name: `rt-${stamp}`, slug: `rt-${stamp}`, ownerId })+ .returning({ id: OrganizationsSchema.id });+ [{ id: goalId }] = await db()+ .insert(GoalsSchema)+ .values({ name: `rt-${stamp}`, owner: ownerId, organizationId })+ .returning({ id: GoalsSchema.id });+ [{ id: collabUserId }] = await db()+ .insert(CollaborationUsersSchema)+ .values({ email: `rt-member-${stamp}@test.local` })+ .returning({ id: CollaborationUsersSchema.id });+ await db().insert(CollaborationUsersToGoalsSchema).values({ userId: collabUserId, goalId });+ [{ id: taskId }] = await db().insert(TasksSchema).values({ goalId, description: 'realtime' }).returning({ id: TasksSchema.id });+ });++ afterAll(async () => {+ await db().delete(CollaborationUsersSchema).where(eq(CollaborationUsersSchema.id, collabUserId));+ await db().delete(UsersSchema).where(inArray(UsersSchema.id, [ownerId, collaboratorId]));+ });++ it('lists the owner and the collaborators of a project as auth user ids', async () => {+ const ids = await new RealtimeRepository().fetchGoalMemberIds(goalId);+ expect(ids.sort()).toEqual([ownerId, collaboratorId].sort());+ });++ it('resolves the project of a task', async () => {+ expect(await new RealtimeRepository().fetchTaskGoalId(taskId)).toBe(goalId);+ expect(await new RealtimeRepository().fetchTaskGoalId(2_147_483_000)).toBeNull();+ });+});diff --git a/api/src/tv-modules/realtime/types.ts b/api/src/tv-modules/realtime/types.tsnew file mode 100644index 0000000..f388ace--- /dev/null+++ b/api/src/tv-modules/realtime/types.ts@@ -0,0 +1,9 @@+export const REALTIME_TASKS_CHANGED_EVENT = 'tasks.changed';++export type RealtimeTaskChangeKind = 'created' | 'updated' | 'deleted';++export type RealtimeTasksChangedArgs = {+ goalId: number;+ taskIds: number[];+ kind: RealtimeTaskChangeKind;+};diff --git a/api/src/tv-modules/recurrence/RecurrenceDispatcher.ts b/api/src/tv-modules/recurrence/RecurrenceDispatcher.tsindex 71e31a8..4872cd9 100644--- a/api/src/tv-modules/recurrence/RecurrenceDispatcher.ts+++ b/api/src/tv-modules/recurrence/RecurrenceDispatcher.ts@@ -1,17 +1,10 @@-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 type { AppEvents } from '../../core/EventBus';import { eventBus } from '../../core/EventBus';import { getJobQueue } from '../../core/JobQueue';-import { Database } from '../../modules/db';import { $logger } from '../../modules/logget';+import { RealtimeRepository } from '../realtime/RealtimeRepository';import { RecurrenceGenerator } from './RecurrenceGenerator';import { RecurrenceRepository } from './RecurrenceRepository';@@ -21,6 +14,7 @@ const RECURRENCE_RT_EVENT = 'recurrence.instanceCreated';export class RecurrenceDispatcher implements Dispatcher {private readonly generator = new RecurrenceGenerator();private readonly repository = new RecurrenceRepository();+ private readonly realtime = new RealtimeRepository();register(): void {// The heart of the lazy model: completing the open instance materializes the next one.@@ -86,24 +80,20 @@ export class RecurrenceDispatcher implements Dispatcher {private async onTaskCreated(data: AppEvents['task.created']): Promise<void> {if (!data.task.recurrenceRuleId) return;+ const centrifugo = getCentrifugoClient();+ if (!centrifugo.isEnabled()) return;try {- const memberIds = await this.resolveGoalMemberIds(data.task.goalId);- if (memberIds.length === 0) return;- const centrifugo = getCentrifugoClient();+ const userIds = await this.realtime.fetchGoalMemberIds(data.task.goalId);// Task fields are gated per role (TaskFieldPermissionsForWatching),// and recipients have different roles — so the broadcast carries ids// only, never content (same thin-event convention as goals.changed).// Each client fetches the task through REST, where fields are// cleaned for that user (fail closed).- await Promise.all(- memberIds.map((userId) =>- centrifugo.publishToUser(userId, RECURRENCE_RT_EVENT, {- goalId: data.task.goalId,- ruleId: data.task.recurrenceRuleId,- taskId: data.task.id,- })- )- );+ await centrifugo.broadcastToUsers({+ userIds,+ event: RECURRENCE_RT_EVENT,+ data: { goalId: data.task.goalId, ruleId: data.task.recurrenceRuleId, taskId: data.task.id },+ });} catch (err) {$logger.error(err, '[RecurrenceDispatcher] real-time publish failed');}@@ -115,25 +105,4 @@ export class RecurrenceDispatcher implements Dispatcher {collabUserId: data.collaborationUserId,});}-- 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);- for (const row of collabRows) ids.add(row.id);- return [...ids];- }}diff --git a/api/src/tv-modules/scim/ScimController.ts b/api/src/tv-modules/scim/ScimController.tsindex 9322da0..8a9b591 100644--- a/api/src/tv-modules/scim/ScimController.ts+++ b/api/src/tv-modules/scim/ScimController.ts@@ -47,7 +47,11 @@ export class ScimController {const { scimOrg, scimConfig } = res.localsconst email = decodeURIComponent(req.params.id)- const operations = req.body.Operations || []+ const operations = req.body.Operations++ if (!Array.isArray(operations) || operations.length === 0) {+ return res.status(400).json(toScimError(400, 'Operations must be a non-empty array'))+ }for (const op of operations) {if (op.op === 'replace' && (op.path === 'active' || op.value?.active !== undefined)) {diff --git a/api/src/tv-modules/scim/ScimRoutes.ts b/api/src/tv-modules/scim/ScimRoutes.tsindex f88efc8..abb3773 100644--- a/api/src/tv-modules/scim/ScimRoutes.ts+++ b/api/src/tv-modules/scim/ScimRoutes.ts@@ -1,6 +1,7 @@import { Router } from 'express'import type { Routable } from '../../types/routable.type'import { ScimAuth } from './middlewares/ScimAuth'+import { ScimContentType } from './middlewares/ScimContentType'import { ScimController } from './ScimController'export default class ScimRoutes implements Routable {@@ -18,6 +19,7 @@ export default class ScimRoutes implements Routable {}initRoutes() {+ this.router.use(ScimContentType)this.router.use(ScimAuth)this.router.get('/Users', this.controller.listUsers)diff --git a/api/src/tv-modules/scim/middlewares/ScimContentType.ts b/api/src/tv-modules/scim/middlewares/ScimContentType.tsnew file mode 100644index 0000000..d99fd24--- /dev/null+++ b/api/src/tv-modules/scim/middlewares/ScimContentType.ts@@ -0,0 +1,6 @@+import type { NextFunction, Request, Response } from 'express'++export const ScimContentType = (_req: Request, res: Response, next: NextFunction) => {+ res.type('application/scim+json')+ next()+}diff --git a/api/src/tv-modules/sprints/SprintsDispatcher.ts b/api/src/tv-modules/sprints/SprintsDispatcher.tsindex 0c8cf3b..c0dec65 100644--- a/api/src/tv-modules/sprints/SprintsDispatcher.ts+++ b/api/src/tv-modules/sprints/SprintsDispatcher.ts@@ -1,21 +1,15 @@-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 { RealtimeRepository } from '../realtime/RealtimeRepository';import { SprintScheduler } from './SprintScheduler';const SPRINT_RT_EVENT = 'sprints.changed';export class SprintsDispatcher implements Dispatcher {private readonly scheduler = new SprintScheduler();+ private readonly realtime = new RealtimeRepository();register(): void {eventBus.on('sprint.created', (d) => this.notifyGoalMembers(d.sprint.goalId, { sprintId: d.sprint.id }));@@ -36,36 +30,13 @@ export class SprintsDispatcher implements Dispatcher {}private async notifyGoalMembers(goalId: number, payload: Record<string, unknown>): Promise<void> {+ const centrifugo = getCentrifugoClient();+ if (!centrifugo.isEnabled()) return;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 }))- );+ const userIds = await this.realtime.fetchGoalMemberIds(goalId);+ await centrifugo.broadcastToUsers({ userIds, event: SPRINT_RT_EVENT, data: { 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/tags/TagsManager.ts b/api/src/tv-modules/tags/TagsManager.tsindex b4f4d25..36c0814 100644--- a/api/src/tv-modules/tags/TagsManager.ts+++ b/api/src/tv-modules/tags/TagsManager.ts@@ -1,15 +1,19 @@import type { TagsSchemaTypeForSelect } from 'taskview-db-schemas';import type { AppUser } from '../../core/AppUser';+import { eventBus } from '../../core/EventBus';import { $logger } from '../../modules/logget';import { TagItemForClient } from './TagItemForClient';import { TagsRepository } from './TagsRepository';import type {AddTagArg,DeleteTagArg,+ TagAddToTaskIfAbsentArgs,TagItemArgAdd,TagItemArgDelete,TagItemArgToggle,TagItemArgUpdate,+ TagItemInDb,+ TaskTagChange,ToggleTagArg,UpdateTagArgs,} from './tags.types';@@ -67,24 +71,40 @@ export class TagsManager {if (tagExists) {await this.repository.deleteTagFromTask(args.tagId, args.taskId);+ this.emitTagsChanged({ taskId: args.taskId, tagId: args.tagId, added: false });return 'delete';}await this.repository.addTagToTask(args.tagId, args.taskId);+ this.emitTagsChanged({ taskId: args.taskId, tagId: args.tagId, added: true });return 'add';}async toggleTagNew(data: TagItemArgToggle): Promise<'delete' | 'add' | null> {- return await this.repository.toggleTagNew(data.tagId, data.taskId);+ const result = await this.repository.toggleTagNew(data.tagId, data.taskId);+ if (result) this.emitTagsChanged({ taskId: data.taskId, tagId: data.tagId, added: result === 'add' });+ return result;+ }++ async addTagToTaskIfAbsent(args: TagAddToTaskIfAbsentArgs): Promise<boolean | null> {+ const added = await this.repository.addTagToTaskIfAbsent(args);+ if (added) this.emitTagsChanged({ taskId: args.taskId, tagId: args.tagId, added: true });+ return added;}/** @deprecated use deleteTagNew instead */async deleteTag(args: DeleteTagArg): Promise<boolean> {- return await this.repository.deleteTag(args.tagId);+ const tag = await this.repository.fetchTagById(args.tagId);+ const deleted = await this.repository.deleteTag(args.tagId);+ if (deleted && tag) this.emitTagDeleted(tag);+ return deleted;}async deleteTagNew(data: TagItemArgDelete): Promise<boolean> {- return await this.repository.deleteTagNew(data.tagId);+ const tag = await this.repository.fetchTagById(data.tagId);+ const deleted = await this.repository.deleteTagNew(data.tagId);+ if (deleted && tag) this.emitTagDeleted(tag);+ return deleted;}/** @deprecated use updateTagNew instead */@@ -100,4 +120,13 @@ export class TagsManager {async updateTagNew(data: TagItemArgUpdate): Promise<TagsSchemaTypeForSelect | null> {return await this.repository.updateTagNew(data);}++ private emitTagsChanged(change: TaskTagChange): void {+ eventBus.emit('task.tagsChanged', { ...change, initiatorId: this.user.getUserData()?.id as number });+ }++ private emitTagDeleted(tag: TagItemInDb): void {+ if (tag.goal_id === null) return;+ eventBus.emit('tag.deleted', { tagId: tag.id, goalId: tag.goal_id, initiatorId: this.user.getUserData()?.id as number });+ }}diff --git a/api/src/tv-modules/tags/TagsRepository.ts b/api/src/tv-modules/tags/TagsRepository.tsindex 0d1840c..1667933 100644--- a/api/src/tv-modules/tags/TagsRepository.ts+++ b/api/src/tv-modules/tags/TagsRepository.ts@@ -6,7 +6,7 @@ import { Database } from '../../modules/db';import { GoalPermissions } from '../../types/auth.types';import { logError } from '../../utils/api';import { callWithCatch } from '../../utils/helpers';-import type { TagItemArgAdd, TagItemArgUpdate, TagItemInDb } from './tags.types';+import type { TagAddToTaskIfAbsentArgs, TagItemArgAdd, TagItemArgUpdate, TagItemInDb } from './tags.types';export class TagsRepository {private readonly db: Database;@@ -214,6 +214,18 @@ export class TagsRepository {}}+ async addTagToTaskIfAbsent(args: TagAddToTaskIfAbsentArgs): Promise<boolean | null> {+ const inserted = await callWithCatch(() =>+ this.db.dbDrizzle+ .insert(TasksToTagsSchema)+ .values({ tagId: args.tagId, taskId: args.taskId })+ .onConflictDoNothing()+ .returning({ taskId: TasksToTagsSchema.taskId })+ );+ if (!inserted) return null;+ return inserted.length > 0;+ }+async addTagToTask(tagId: number, taskId: number): Promise<boolean> {const query = 'INSERT INTO tasks.tasks_to_tags (tag_id, task_id) VALUES ($1, $2);';const result = await this.db.query(query, [tagId, taskId]).catch(logError);diff --git a/api/src/tv-modules/tags/tags.types.ts b/api/src/tv-modules/tags/tags.types.tsindex cd85402..7b769da 100644--- a/api/src/tv-modules/tags/tags.types.ts+++ b/api/src/tv-modules/tags/tags.types.ts@@ -78,3 +78,14 @@ export const TagItemArkTypeToggle = type({});export type TagItemArgToggle = typeof TagItemArkTypeToggle.infer;++export type TaskTagChange = {+ taskId: number;+ tagId: number;+ added: boolean;+};++export type TagAddToTaskIfAbsentArgs = {+ tagId: number;+ taskId: number;+};diff --git a/api/src/types/auth.types.ts b/api/src/types/auth.types.tsindex ea516ad..5a0fa64 100644--- a/api/src/types/auth.types.ts+++ b/api/src/types/auth.types.ts@@ -208,6 +208,9 @@ export const GoalPermissions = {FILE_CAN_VIEW: 'file_can_view',FILE_CAN_MANAGE: 'file_can_manage',++ AUTOMATION_CAN_VIEW: 'automation_can_view',+ AUTOMATION_CAN_MANAGE: 'automation_can_manage',} as const;export type PermissionsEntityType =diff --git a/api/src/types/centrifugo.types.ts b/api/src/types/centrifugo.types.tsnew file mode 100644index 0000000..524333b--- /dev/null+++ b/api/src/types/centrifugo.types.ts@@ -0,0 +1,19 @@+export type CentrifugoPublishPayload = {+ channel: string;+ data: Record<string, unknown>;+};++export type CentrifugoBroadcastPayload = {+ channels: string[];+ data: Record<string, unknown>;+};++export type CentrifugoApiCall =+ | { method: 'publish'; payload: CentrifugoPublishPayload }+ | { method: 'broadcast'; payload: CentrifugoBroadcastPayload };++export type CentrifugoBroadcastToUsersArgs = {+ userIds: number[];+ event: string;+ data: Record<string, unknown>;+};diff --git a/taskview-packages/taskview-api/src/api/__tests__/automations-test-helpers.ts b/taskview-packages/taskview-api/src/api/__tests__/automations-test-helpers.tsnew file mode 100644index 0000000..ec18c32--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/automations-test-helpers.ts@@ -0,0 +1,87 @@+import { expect } from 'vitest'+import type {+ AutomationsCreateProjectArgs,+ AutomationsCreateTaskArgs,+ AutomationsExpectErrorArgs,+ AutomationsShareGoalArgs,+ AutomationsSharedGoal,+ AutomationsTestProject,+} from './automations-test-helpers.types'++const WAIT_TIMEOUT_MS = 10_000+const WAIT_STEP_MS = 100++export async function waitFor(check: () => Promise<boolean>): Promise<boolean> {+ const deadline = Date.now() + WAIT_TIMEOUT_MS+ while (Date.now() < deadline) {+ if (await check()) return true+ await new Promise((resolve) => setTimeout(resolve, WAIT_STEP_MS))+ }+ return false+}++export async function expectApiError(args: AutomationsExpectErrorArgs): Promise<void> {+ const error = await args.request.then(+ () => null,+ (err: { response?: { status: number; data?: { code?: string } } }) => err,+ )+ expect(error, `Expected HTTP ${args.status}, but the request succeeded`).not.toBeNull()+ expect(error?.response?.status).toBe(args.status)+ if (args.code) expect(error?.response?.data?.code).toBe(args.code)+}++export async function createAutomationsProject(args: AutomationsCreateProjectArgs): Promise<AutomationsTestProject> {+ const { api } = args+ const goal = await api.goals.createGoal({ name: `${args.name} ${Date.now()}` })+ if (!goal) throw new Error('Failed to create goal')++ const todo = await api.kanban.addColumn({ goalId: goal.id, name: 'Todo' })+ const done = await api.kanban.addColumn({ goalId: goal.id, name: 'Done' })+ const review = await api.kanban.addColumn({ goalId: goal.id, name: 'Review' })+ const tagA = await api.tags.createTag({ goalId: goal.id, name: `auto-a-${Date.now()}`, color: '#22c55e' })+ const tagB = await api.tags.createTag({ goalId: goal.id, name: `auto-b-${Date.now()}`, color: '#3b82f6' })+ const listA = await api.goalLists.createList({ goalId: goal.id, name: 'Inbox' })+ const listB = await api.goalLists.createList({ goalId: goal.id, name: 'Bugs' })+ if (!todo || !done || !review || !tagA || !tagB || !listA || !listB) throw new Error('Failed to prepare the project')++ return {+ goalId: goal.id,+ todoId: todo.id,+ doneId: done.id,+ reviewId: review.id,+ tagAId: tagA.id,+ tagBId: tagB.id,+ listAId: listA.id,+ listBId: listB.id,+ }+}++export async function createTask(args: AutomationsCreateTaskArgs): Promise<number> {+ const task = await args.api.tasks.createTask({+ goalId: args.goalId,+ description: `automation task ${Date.now()}`,+ ...(args.statusId !== undefined ? { statusId: args.statusId } : {}),+ ...(args.goalListId !== undefined ? { goalListId: args.goalListId } : {}),+ })+ if (!task) throw new Error('Failed to create task')+ return task.id+}++export async function shareGoalWith(args: AutomationsShareGoalArgs): Promise<AutomationsSharedGoal> {+ const { ownerApi, goalId } = args+ const collaborator = await ownerApi.collaboration.inviteUserToGoal({ email: args.email, goalId })+ if (!collaborator) throw new Error('Failed to invite the collaborator')++ const role = await ownerApi.collaboration.createRoleForGoal({ goalId, roleName: `Automations role ${Date.now()}` })+ if (!role) throw new Error('Failed to create role')++ for (const name of args.permissions) {+ const permissionId = args.permissionIdByName.get(name)+ if (!permissionId) throw new Error(`Permission "${name}" is not in DB`)+ const toggled = await ownerApi.collaboration.toggleRolePermission({ roleId: role.id, permissionId })+ if (!toggled || toggled.add !== true) throw new Error(`Expected "${name}" to be added, got ${JSON.stringify(toggled)}`)+ }++ await ownerApi.collaboration.toggleUserRoles({ goalId, userId: collaborator.id, roles: [role.id] })+ return { roleId: role.id }+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/automations-test-helpers.types.ts b/taskview-packages/taskview-api/src/api/__tests__/automations-test-helpers.types.tsnew file mode 100644index 0000000..8d0edb5--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/automations-test-helpers.types.ts@@ -0,0 +1,43 @@+import type { TvApi } from '@/tv'+import type { AutomationErrorCode } from '@/api/automations.types'++export type AutomationsTestProject = {+ goalId: number+ todoId: number+ doneId: number+ reviewId: number+ tagAId: number+ tagBId: number+ listAId: number+ listBId: number+}++export type AutomationsCreateProjectArgs = {+ api: TvApi+ name: string+}++export type AutomationsExpectErrorArgs = {+ request: Promise<unknown>+ status: number+ code?: AutomationErrorCode+}++export type AutomationsShareGoalArgs = {+ ownerApi: TvApi+ goalId: number+ email: string+ permissionIdByName: Map<string, number>+ permissions: string[]+}++export type AutomationsSharedGoal = {+ roleId: number+}++export type AutomationsCreateTaskArgs = {+ api: TvApi+ goalId: number+ statusId?: number+ goalListId?: number+}diff --git a/taskview-packages/taskview-api/src/api/__tests__/automations.access.test.ts b/taskview-packages/taskview-api/src/api/__tests__/automations.access.test.tsnew file mode 100644index 0000000..e2db654--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/automations.access.test.ts@@ -0,0 +1,143 @@+import { TvApi } from '@/tv'+import { TvPermissions } from '@/api/permissions'+import type { AutomationRuleCreateArgs } from '@/api/automations.types'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { initApi } from './init-api'+import { createAutomationsProject, createTask, expectApiError, shareGoalWith, waitFor } from './automations-test-helpers'+import type { AutomationsTestProject } from './automations-test-helpers.types'++/**+ * Automation rules act on behalf of their author, so every permission a rule+ * relies on is checked both when the rule is saved and every time it runs.+ */+describe('Automations permission boundaries', () => {+ let ownerApi: TvApi+ let memberApi: TvApi+ let memberEmail: string+ let deleteAllGoals: () => Promise<void>+ const permissionIdByName = new Map<string, number>()++ beforeAll(async () => {+ const init = await initApi()+ ownerApi = init.$tvApi+ memberApi = init.$tvApiForSecondUser+ memberEmail = init.user2Email+ deleteAllGoals = init.deleteAllGoals++ for (const permission of await ownerApi.collaboration.fetchAllPermissions()) {+ permissionIdByName.set(permission.name, permission.id)+ }+ })++ afterAll(async () => {+ await deleteAllGoals()+ })++ const project = () => createAutomationsProject({ api: ownerApi, name: 'Automations access' })++ const share = (goalId: number, permissions: string[]) =>+ shareGoalWith({ ownerApi, goalId, email: memberEmail, permissionIdByName, permissions })++ const createdAddsTag = (p: AutomationsTestProject, tagId: number): AutomationRuleCreateArgs => ({+ goalId: p.goalId,+ name: `Created adds tag ${tagId}`,+ trigger: { module: 'tasks', event: 'task.created', params: {} },+ action: { module: 'tags', action: 'add.tag', params: { tagId } },+ })++ const completedToDone = (p: AutomationsTestProject): AutomationRuleCreateArgs => ({+ goalId: p.goalId,+ name: 'Completed to Done',+ trigger: { module: 'tasks', event: 'task.completed', params: {} },+ action: { module: 'kanban', action: 'change.status', params: { statusId: p.doneId } },+ })++ const taskTags = async (taskId: number) => (await ownerApi.tasks.fetchTaskById(taskId))?.tags ?? []++ it('hides the rules of a project from users who are not in it', async () => {+ const p = await project()+ const rule = await ownerApi.automations.createRule(createdAddsTag(p, p.tagAId))++ await expectApiError({ request: memberApi.automations.listRules(p.goalId), status: 403 })+ await expectApiError({ request: memberApi.automations.createRule(createdAddsTag(p, p.tagAId)), status: 403 })+ await expectApiError({ request: memberApi.automations.updateRule({ ruleId: rule.id, enabled: false }), status: 403 })+ await expectApiError({ request: memberApi.automations.deleteRule(rule.id), status: 403 })+ await expectApiError({ request: memberApi.automations.getOptions({ goalId: p.goalId, source: 'tags.goalTags' }), status: 403 })++ expect((await ownerApi.automations.listRules(p.goalId))[0]).toMatchObject({ id: rule.id, enabled: true })+ })++ it('answers 404 for a rule that does not exist', async () => {+ await expectApiError({ request: ownerApi.automations.updateRule({ ruleId: 2_000_000_000, enabled: false }), status: 404 })+ await expectApiError({ request: ownerApi.automations.deleteRule(2_000_000_000), status: 404 })+ })++ it('lets a viewer read the rules but not change them', async () => {+ const p = await project()+ const rule = await ownerApi.automations.createRule(createdAddsTag(p, p.tagAId))+ await share(p.goalId, [TvPermissions.AUTOMATION_CAN_VIEW])++ expect((await memberApi.automations.listRules(p.goalId)).map(({ id }) => id)).toEqual([rule.id])++ await expectApiError({ request: memberApi.automations.createRule(createdAddsTag(p, p.tagAId)), status: 403 })+ await expectApiError({ request: memberApi.automations.updateRule({ ruleId: rule.id, name: 'Hijacked' }), status: 403 })+ await expectApiError({ request: memberApi.automations.deleteRule(rule.id), status: 403 })+ expect((await ownerApi.automations.listRules(p.goalId))[0].name).toBe(rule.name)+ })++ it('shows columns and tags as rule values only to users who can see them', async () => {+ const p = await project()+ await share(p.goalId, [TvPermissions.AUTOMATION_CAN_VIEW, TvPermissions.KANBAN_CAN_VIEW])++ const columns = await memberApi.automations.getOptions({ goalId: p.goalId, source: 'kanban.statuses' })+ expect(columns.map(({ id }) => id)).toContain(p.doneId)+ await expectApiError({ request: memberApi.automations.getOptions({ goalId: p.goalId, source: 'tags.goalTags' }), status: 403 })+ })++ it('refuses a rule whose action needs a permission the author does not have', async () => {+ const p = await project()+ await share(p.goalId, [TvPermissions.AUTOMATION_CAN_MANAGE, TvPermissions.TASK_CAN_EDIT_TAGS])++ await expectApiError({ request: memberApi.automations.createRule(completedToDone(p)), status: 403, code: 'forbidden' })++ const allowed = await memberApi.automations.createRule(createdAddsTag(p, p.tagAId))+ expect(allowed.enabled).toBe(true)+ })++ it('stops running the rules of an author who lost the right to manage automations', async () => {+ const p = await project()+ const { roleId } = await share(p.goalId, [TvPermissions.AUTOMATION_CAN_MANAGE, TvPermissions.TASK_CAN_EDIT_TAGS])+ await memberApi.automations.createRule(createdAddsTag(p, p.tagBId))+ await ownerApi.automations.createRule(createdAddsTag(p, p.tagAId))++ const before = await createTask({ api: ownerApi, goalId: p.goalId })+ expect(await waitFor(async () => (await taskTags(before)).includes(p.tagBId))).toBe(true)++ const manageId = permissionIdByName.get(TvPermissions.AUTOMATION_CAN_MANAGE)+ if (!manageId) throw new Error('automation_can_manage is not in DB')+ const revoked = await ownerApi.collaboration.toggleRolePermission({ roleId, permissionId: manageId })+ expect(revoked?.add).toBe(false)++ const after = await createTask({ api: ownerApi, goalId: p.goalId })+ expect(await waitFor(async () => (await taskTags(after)).includes(p.tagAId))).toBe(true)+ expect(await taskTags(after)).not.toContain(p.tagBId)+ })++ it('makes the editor the author, so a rule never runs with someone else\'s rights', async () => {+ const p = await project()+ const rule = await ownerApi.automations.createRule(createdAddsTag(p, p.tagAId))+ await share(p.goalId, [TvPermissions.AUTOMATION_CAN_MANAGE, TvPermissions.TASK_CAN_EDIT_TAGS])++ await expectApiError({+ request: memberApi.automations.updateRule({ ruleId: rule.id, action: completedToDone(p).action }),+ status: 403,+ code: 'forbidden',+ })++ const edited = await memberApi.automations.updateRule({ ruleId: rule.id, action: { module: 'tags', action: 'add.tag', params: { tagId: p.tagBId } } })+ expect(edited.creatorId).not.toBe(rule.creatorId)++ const renamed = await ownerApi.automations.updateRule({ ruleId: rule.id, name: 'Renamed by the owner' })+ expect(renamed.creatorId).toBe(edited.creatorId)+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/automations.test.ts b/taskview-packages/taskview-api/src/api/__tests__/automations.test.tsnew file mode 100644index 0000000..be443e3--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/automations.test.ts@@ -0,0 +1,446 @@+import { TvApi } from '@/tv'+import type { AutomationRule, AutomationRuleCreateArgs } from '@/api/automations.types'+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { initApi } from './init-api'+import { createAutomationsProject, createTask, expectApiError, waitFor } from './automations-test-helpers'+import type { AutomationsTestProject } from './automations-test-helpers.types'++/**+ * Rules run in the pg-boss worker of the real API container, so every+ * execution check polls the task through the public API until the+ * automation result shows up. One job runs its rules one by one in id order,+ * so a negative check creates the rule under test first and waits for a+ * control rule created after it.+ */+describe('Automations', () => {+ let api: TvApi+ let deleteAllGoals: () => Promise<void>++ beforeAll(async () => {+ const init = await initApi()+ api = init.$tvApi+ deleteAllGoals = init.deleteAllGoals+ })++ afterAll(async () => {+ await deleteAllGoals()+ })++ const project = (name: string) => createAutomationsProject({ api, name })++ const fetchTask = async (taskId: number) => {+ const task = await api.tasks.fetchTaskById(taskId)+ if (!task) throw new Error(`Task ${taskId} is not readable`)+ return task+ }++ const createRule = async (args: AutomationRuleCreateArgs): Promise<AutomationRule> => {+ const rule = await api.automations.createRule(args)+ expect(rule.id).toBeGreaterThan(0)+ return rule+ }++ const completedToDone = (p: AutomationsTestProject): AutomationRuleCreateArgs => ({+ goalId: p.goalId,+ name: 'Completed to Done',+ trigger: { module: 'tasks', event: 'task.completed', params: {} },+ action: { module: 'kanban', action: 'change.status', params: { statusId: p.doneId } },+ })++ const createdAddsTag = (p: AutomationsTestProject, tagId: number): AutomationRuleCreateArgs => ({+ goalId: p.goalId,+ name: `Created adds tag ${tagId}`,+ trigger: { module: 'tasks', event: 'task.created', params: {} },+ action: { module: 'tags', action: 'add.tag', params: { tagId } },+ })++ describe('catalog and options', () => {+ it('describes the modules, events and actions the UI builds rules from', async () => {+ const catalog = await api.automations.getCatalog()+ const byName = new Map(catalog.modules.map((module) => [module.name, module]))++ expect([...byName.keys()].sort()).toEqual(['kanban', 'lists', 'tags', 'tasks'])+ expect(byName.get('tasks')?.events.map(({ name }) => name).sort()).toEqual(['task.completed', 'task.created', 'task.reopened'])+ expect(byName.get('tasks')?.actions.map(({ name }) => name).sort()).toEqual(['complete', 'reopen'])+ expect(byName.get('kanban')?.events).toEqual([+ { name: 'task.movedToColumn', params: [{ key: 'statusId', source: 'kanban.statuses' }] },+ ])+ expect(byName.get('kanban')?.actions).toEqual([+ { name: 'change.status', params: [{ key: 'statusId', source: 'kanban.statuses' }] },+ ])+ expect(byName.get('tags')?.events).toEqual([+ { name: 'tag.addedToTask', params: [{ key: 'tagId', source: 'tags.goalTags' }] },+ { name: 'tag.removedFromTask', params: [{ key: 'tagId', source: 'tags.goalTags' }] },+ ])+ expect(byName.get('tags')?.actions).toEqual([{ name: 'add.tag', params: [{ key: 'tagId', source: 'tags.goalTags' }] }])+ expect(byName.get('lists')?.events).toEqual([+ { name: 'task.addedToList', params: [{ key: 'goalListId', source: 'lists.goalLists' }] },+ ])+ expect(byName.get('lists')?.actions).toEqual([+ { name: 'move.toList', params: [{ key: 'goalListId', source: 'lists.goalLists' }] },+ ])+ })++ it('offers the columns and tags of the project only', async () => {+ const p = await project('Automation options')+ const other = await project('Automation options other')++ const columns = await api.automations.getOptions({ goalId: p.goalId, source: 'kanban.statuses' })+ const columnIds = columns.map(({ id }) => id)+ expect(columnIds).toEqual(expect.arrayContaining([p.todoId, p.doneId, p.reviewId]))+ expect(columnIds).not.toContain(other.doneId)+ expect(columns.find(({ id }) => id === p.doneId)?.label).toBe('Done')++ const tags = await api.automations.getOptions({ goalId: p.goalId, source: 'tags.goalTags' })+ expect(tags.map(({ id }) => id).sort((a, b) => a - b)).toEqual([p.tagAId, p.tagBId].sort((a, b) => a - b))++ const lists = await api.automations.getOptions({ goalId: p.goalId, source: 'lists.goalLists' })+ expect(lists.map(({ id }) => id).sort((a, b) => a - b)).toEqual([p.listAId, p.listBId].sort((a, b) => a - b))+ expect(lists.find(({ id }) => id === p.listBId)?.label).toBe('Bugs')+ })++ it('rejects an unknown data source', async () => {+ const p = await project('Automation unknown source')+ await expectApiError({+ request: api.automations.getOptions({ goalId: p.goalId, source: 'constructor' as never }),+ status: 400,+ })+ })+ })++ const addedToListAddsTag = (p: AutomationsTestProject, list: { goalListId: number; tagId: number }): AutomationRuleCreateArgs => ({+ goalId: p.goalId,+ name: `List ${list.goalListId} adds tag ${list.tagId}`,+ trigger: { module: 'lists', event: 'task.addedToList', params: { goalListId: list.goalListId } },+ action: { module: 'tags', action: 'add.tag', params: { tagId: list.tagId } },+ })++ const tagAddedAddsTag = (p: AutomationsTestProject, tags: { from: number; to: number }): AutomationRuleCreateArgs => ({+ goalId: p.goalId,+ name: `Tag ${tags.from} adds tag ${tags.to}`,+ trigger: { module: 'tags', event: 'tag.addedToTask', params: { tagId: tags.from } },+ action: { module: 'tags', action: 'add.tag', params: { tagId: tags.to } },+ })++ describe('managing rules', () => {+ it('creates, lists, renames, toggles and deletes a rule', async () => {+ const p = await project('Automation CRUD')+ const created = await createRule(completedToDone(p))+ expect(created).toMatchObject({+ goalId: p.goalId,+ name: 'Completed to Done',+ enabled: true,+ trigger: { module: 'tasks', event: 'task.completed', params: {} },+ action: { module: 'kanban', action: 'change.status', params: { statusId: p.doneId } },+ })++ expect((await api.automations.listRules(p.goalId)).map(({ id }) => id)).toEqual([created.id])++ const renamed = await api.automations.updateRule({ ruleId: created.id, name: ' Move finished work ' })+ expect(renamed.name).toBe('Move finished work')++ expect((await api.automations.updateRule({ ruleId: created.id, enabled: false })).enabled).toBe(false)+ expect((await api.automations.updateRule({ ruleId: created.id, enabled: true })).enabled).toBe(true)++ expect(await api.automations.deleteRule(created.id)).toBe(true)+ expect(await api.automations.listRules(p.goalId)).toEqual([])+ await expectApiError({ request: api.automations.deleteRule(created.id), status: 404 })+ })++ it('rejects unknown events, missing params and values of another project', async () => {+ const p = await project('Automation validation')+ const other = await project('Automation validation other')++ await expectApiError({+ request: api.automations.createRule({ ...completedToDone(p), trigger: { module: 'tasks', event: 'task.exploded', params: {} } }),+ status: 400,+ code: 'invalid',+ })+ await expectApiError({+ request: api.automations.createRule({ ...completedToDone(p), action: { module: 'kanban', action: 'change.status', params: {} } }),+ status: 400,+ code: 'invalid',+ })+ await expectApiError({+ request: api.automations.createRule({+ ...completedToDone(p),+ action: { module: 'kanban', action: 'change.status', params: { statusId: other.doneId } },+ }),+ status: 400,+ code: 'invalid',+ })+ await expectApiError({ request: api.automations.createRule({ ...completedToDone(p), name: ' ' }), status: 400 })+ })++ it('drops params the event or action does not declare', async () => {+ const p = await project('Automation undeclared params')+ const rule = await createRule({+ ...completedToDone(p),+ trigger: { module: 'tasks', event: 'task.completed', params: { injected: 1 } },+ action: { module: 'kanban', action: 'change.status', params: { statusId: p.doneId, goalId: 999_999 } },+ })+ expect(rule.trigger.params).toEqual({})+ expect(rule.action.params).toEqual({ statusId: p.doneId })+ })++ it('refuses a rule that closes an endless loop, unless it is saved disabled', async () => {+ const p = await project('Automation cycle')+ await createRule(completedToDone(p))+ const closingLoop: AutomationRuleCreateArgs = {+ goalId: p.goalId,+ name: 'Done completes again',+ trigger: { module: 'kanban', event: 'task.movedToColumn', params: { statusId: p.doneId } },+ action: { module: 'tasks', action: 'complete', params: {} },+ }++ await expectApiError({ request: api.automations.createRule(closingLoop), status: 409, code: 'cycle' })++ const disabled = await createRule({ ...closingLoop, enabled: false })+ expect(disabled.enabled).toBe(false)+ await expectApiError({ request: api.automations.updateRule({ ruleId: disabled.id, enabled: true }), status: 409, code: 'cycle' })+ })++ it('refuses tag rules that would keep adding each other', async () => {+ const p = await project('Automation tag cycle')+ await createRule(tagAddedAddsTag(p, { from: p.tagAId, to: p.tagBId }))++ await expectApiError({+ request: api.automations.createRule(tagAddedAddsTag(p, { from: p.tagBId, to: p.tagAId })),+ status: 409,+ code: 'cycle',+ })+ })++ it('refuses list rules that would keep moving a task back and forth', async () => {+ const p = await project('Automation list cycle')+ const moveBetween = (from: number, to: number): AutomationRuleCreateArgs => ({+ goalId: p.goalId,+ name: `List ${from} to ${to}`,+ trigger: { module: 'lists', event: 'task.addedToList', params: { goalListId: from } },+ action: { module: 'lists', action: 'move.toList', params: { goalListId: to } },+ })+ await createRule(moveBetween(p.listAId, p.listBId))++ await expectApiError({ request: api.automations.createRule(moveBetween(p.listBId, p.listAId)), status: 409, code: 'cycle' })+ })++ it('limits a project to 100 rules', async () => {+ const p = await project('Automation limit')+ for (let index = 0; index < 100; index += 1) {+ await createRule({ ...createdAddsTag(p, p.tagAId), name: `Rule ${index}` })+ }+ await expectApiError({ request: api.automations.createRule(createdAddsTag(p, p.tagAId)), status: 409, code: 'limit_reached' })+ })+ })++ describe('running rules', () => {+ it('moves a completed task to the Done column', async () => {+ const p = await project('Automation completed to Done')+ await createRule(completedToDone(p))+ const taskId = await createTask({ api, goalId: p.goalId })++ await api.tasks.updateTask({ id: taskId, complete: true })++ expect(await waitFor(async () => (await fetchTask(taskId)).statusId === p.doneId)).toBe(true)+ })++ it('tags a task as soon as it is created', async () => {+ const p = await project('Automation created tag')+ await createRule(createdAddsTag(p, p.tagAId))++ const taskId = await createTask({ api, goalId: p.goalId })++ expect(await waitFor(async () => (await fetchTask(taskId)).tags.includes(p.tagAId))).toBe(true)+ })++ it('reacts to a card dragged into a column on the board', async () => {+ const p = await project('Automation kanban drag')+ await createRule({+ goalId: p.goalId,+ name: 'Review gets a tag',+ trigger: { module: 'kanban', event: 'task.movedToColumn', params: { statusId: p.reviewId } },+ action: { module: 'tags', action: 'add.tag', params: { tagId: p.tagAId } },+ })+ const taskId = await createTask({ api, goalId: p.goalId })++ await api.kanban.updateTasksOrderAndColumn({ goalId: p.goalId, columnId: p.reviewId, taskId, prevTaskId: null, nextTaskId: null })++ expect(await waitFor(async () => (await fetchTask(taskId)).tags.includes(p.tagAId))).toBe(true)+ })++ it('chains rules: the move made by one rule triggers the next one', async () => {+ const p = await project('Automation chain')+ await createRule(completedToDone(p))+ await createRule({+ goalId: p.goalId,+ name: 'Done gets a tag',+ trigger: { module: 'kanban', event: 'task.movedToColumn', params: { statusId: p.doneId } },+ action: { module: 'tags', action: 'add.tag', params: { tagId: p.tagAId } },+ })+ const taskId = await createTask({ api, goalId: p.goalId })++ await api.tasks.updateTask({ id: taskId, complete: true })++ expect(+ await waitFor(async () => {+ const task = await fetchTask(taskId)+ return task.statusId === p.doneId && task.tags.includes(p.tagAId)+ }),+ ).toBe(true)+ })++ it('does not run a disabled rule', async () => {+ const p = await project('Automation disabled')+ await createRule({ ...createdAddsTag(p, p.tagBId), enabled: false })+ await createRule(createdAddsTag(p, p.tagAId))++ const taskId = await createTask({ api, goalId: p.goalId })++ expect(await waitFor(async () => (await fetchTask(taskId)).tags.includes(p.tagAId))).toBe(true)+ expect((await fetchTask(taskId)).tags).not.toContain(p.tagBId)+ })++ it('does not run the rules of another project', async () => {+ const p = await project('Automation isolation')+ const other = await project('Automation isolation other')+ await createRule(createdAddsTag(other, other.tagAId))+ await createRule(createdAddsTag(p, p.tagAId))++ const taskId = await createTask({ api, goalId: p.goalId })++ expect(await waitFor(async () => (await fetchTask(taskId)).tags.includes(p.tagAId))).toBe(true)+ expect((await fetchTask(taskId)).tags).toEqual([p.tagAId])+ })+ })++ describe('running list and tag rules', () => {+ it('reacts to a task moved into a list, and only into that list', async () => {+ const p = await project('Automation moved to list')+ await createRule(addedToListAddsTag(p, { goalListId: p.listBId, tagId: p.tagBId }))+ await createRule(addedToListAddsTag(p, { goalListId: p.listAId, tagId: p.tagAId }))+ const taskId = await createTask({ api, goalId: p.goalId })++ await api.tasks.updateTask({ id: taskId, goalListId: p.listAId })++ expect(await waitFor(async () => (await fetchTask(taskId)).tags.includes(p.tagAId))).toBe(true)+ expect((await fetchTask(taskId)).tags).not.toContain(p.tagBId)+ })++ it('reacts to a task created right in the list', async () => {+ const p = await project('Automation created in list')+ await createRule(addedToListAddsTag(p, { goalListId: p.listBId, tagId: p.tagAId }))++ const taskId = await createTask({ api, goalId: p.goalId, goalListId: p.listBId })++ expect(await waitFor(async () => (await fetchTask(taskId)).tags.includes(p.tagAId))).toBe(true)+ })++ it('moves a completed task to a list', async () => {+ const p = await project('Automation move to list')+ await createRule({ ...completedToDone(p), action: { module: 'lists', action: 'move.toList', params: { goalListId: p.listBId } } })+ const taskId = await createTask({ api, goalId: p.goalId, goalListId: p.listAId })++ await api.tasks.updateTask({ id: taskId, complete: true })++ expect(await waitFor(async () => (await fetchTask(taskId)).goalListId === p.listBId)).toBe(true)+ })++ it('reacts to a tag added to a task by hand', async () => {+ const p = await project('Automation tag added')+ await createRule(tagAddedAddsTag(p, { from: p.tagAId, to: p.tagBId }))+ const taskId = await createTask({ api, goalId: p.goalId })++ await api.tags.toggleTag({ tagId: p.tagAId, taskId })++ expect(await waitFor(async () => (await fetchTask(taskId)).tags.includes(p.tagBId))).toBe(true)+ })++ it('reacts to a tag removed from a task, not to a tag added', async () => {+ const p = await project('Automation tag removed')+ await createRule({+ goalId: p.goalId,+ name: 'Untagged goes to Bugs',+ trigger: { module: 'tags', event: 'tag.removedFromTask', params: { tagId: p.tagAId } },+ action: { module: 'lists', action: 'move.toList', params: { goalListId: p.listBId } },+ })+ await createRule(tagAddedAddsTag(p, { from: p.tagAId, to: p.tagBId }))+ const taskId = await createTask({ api, goalId: p.goalId })++ await api.tags.toggleTag({ tagId: p.tagAId, taskId })+ expect(await waitFor(async () => (await fetchTask(taskId)).tags.includes(p.tagBId))).toBe(true)+ expect((await fetchTask(taskId)).goalListId).not.toBe(p.listBId)++ await api.tags.toggleTag({ tagId: p.tagAId, taskId })+ expect(await waitFor(async () => (await fetchTask(taskId)).goalListId === p.listBId)).toBe(true)+ })++ it('chains a tag added by one rule into the next rule', async () => {+ const p = await project('Automation tag chain')+ await createRule(createdAddsTag(p, p.tagAId))+ await createRule(tagAddedAddsTag(p, { from: p.tagAId, to: p.tagBId }))++ const taskId = await createTask({ api, goalId: p.goalId })++ expect(await waitFor(async () => (await fetchTask(taskId)).tags.includes(p.tagBId))).toBe(true)+ })+ })++ describe('deleted columns, tags and lists', () => {+ it('turns off the rules that use a deleted column and keeps them off', async () => {+ const p = await project('Automation deleted column')+ const temp = await api.kanban.addColumn({ goalId: p.goalId, name: 'Temporary' })+ if (!temp) throw new Error('Failed to add column')++ const moveToTemp = await createRule({ ...completedToDone(p), action: { module: 'kanban', action: 'change.status', params: { statusId: temp.id } } })+ const fromTemp = await createRule({+ goalId: p.goalId,+ name: 'Temporary gets a tag',+ trigger: { module: 'kanban', event: 'task.movedToColumn', params: { statusId: temp.id } },+ action: { module: 'tags', action: 'add.tag', params: { tagId: p.tagAId } },+ })+ const unrelated = await createRule(createdAddsTag(p, p.tagAId))++ expect(await api.kanban.deleteColumn({ id: temp.id })).toBeTruthy()++ const enabledIds = async () => (await api.automations.listRules(p.goalId)).filter(({ enabled }) => enabled).map(({ id }) => id)+ expect(await waitFor(async () => (await enabledIds()).length === 1)).toBe(true)+ expect(await enabledIds()).toEqual([unrelated.id])++ await expectApiError({ request: api.automations.updateRule({ ruleId: moveToTemp.id, enabled: true }), status: 400, code: 'invalid' })+ await expectApiError({ request: api.automations.updateRule({ ruleId: fromTemp.id, enabled: true }), status: 400, code: 'invalid' })+ })++ it('turns off the rules that add a deleted tag', async () => {+ const p = await project('Automation deleted tag')+ const tagged = await createRule(createdAddsTag(p, p.tagBId))+ const unrelated = await createRule(createdAddsTag(p, p.tagAId))++ expect(await api.tags.deleteTag({ tagId: p.tagBId })).toBeTruthy()++ expect(+ await waitFor(async () => {+ const rules = await api.automations.listRules(p.goalId)+ return rules.find(({ id }) => id === tagged.id)?.enabled === false+ }),+ ).toBe(true)+ expect((await api.automations.listRules(p.goalId)).find(({ id }) => id === unrelated.id)?.enabled).toBe(true)+ })++ it('turns off the rules that use a deleted list', async () => {+ const p = await project('Automation deleted list')+ const fromList = await createRule(addedToListAddsTag(p, { goalListId: p.listBId, tagId: p.tagAId }))+ const unrelated = await createRule(createdAddsTag(p, p.tagAId))++ expect(await api.goalLists.deleteList(p.listBId)).toBe(true)++ expect(+ await waitFor(async () => {+ const rules = await api.automations.listRules(p.goalId)+ return rules.find(({ id }) => id === fromList.id)?.enabled === false+ }),+ ).toBe(true)+ expect((await api.automations.listRules(p.goalId)).find(({ id }) => id === unrelated.id)?.enabled).toBe(true)+ await expectApiError({ request: api.automations.updateRule({ ruleId: fromList.id, enabled: true }), status: 400, code: 'invalid' })+ })+ })+})diff --git a/taskview-packages/taskview-api/src/api/__tests__/scim.test.ts b/taskview-packages/taskview-api/src/api/__tests__/scim.test.tsindex 0a73665..34537c7 100644--- a/taskview-packages/taskview-api/src/api/__tests__/scim.test.ts+++ b/taskview-packages/taskview-api/src/api/__tests__/scim.test.ts@@ -249,3 +249,66 @@ describe('SCIM: isolation between organizations', () => {}})})++describe('SCIM: application/scim+json content type (RFC 7644 §3.1)', () => {+ const scimJsonHeaders = () => ({+ Authorization: `Bearer ${scimToken}`,+ 'Content-Type': 'application/scim+json',+ })++ it('should create user with userName only', async () => {+ const email = `scim-json-create-${Date.now()}@scim-e2e.example`++ const res = await axios.post(`${scimUrl}/Users`, { userName: email }, {+ headers: scimJsonHeaders(),+ validateStatus: () => true,+ })++ expect(res.status).toBe(201)+ expect(res.data.userName).toBe(email)+ expect(res.headers['content-type']).toContain('application/scim+json')++ const list = await axios.get(`${scimUrl}/Users`, { headers: scimHeaders() })+ expect(list.data.Resources.map((r: any) => r.userName)).toContain(email)+ })++ it('should deactivate user', async () => {+ const email = `scim-json-deactivate-${Date.now()}@scim-e2e.example`+ await axios.post(`${scimUrl}/Users`, { userName: email }, { headers: scimHeaders() })++ const res = await axios.patch(+ `${scimUrl}/Users/${encodeURIComponent(email)}`,+ {+ schemas: ['urn:ietf:params:scim:api:messages:2.0:PatchOp'],+ Operations: [{ op: 'replace', path: 'active', value: false }],+ },+ { headers: scimJsonHeaders(), validateStatus: () => true },+ )++ expect(res.status).toBe(200)+ expect(res.data.active).toBe(false)++ const get = await axios.get(`${scimUrl}/Users/${encodeURIComponent(email)}`, {+ headers: scimHeaders(),+ validateStatus: () => true,+ })+ expect(get.status).toBe(404)+ })++ it('should reject PATCH without Operations instead of reporting success', async () => {+ const email = `scim-json-noops-${Date.now()}@scim-e2e.example`+ await axios.post(`${scimUrl}/Users`, { userName: email }, { headers: scimHeaders() })++ const res = await axios.patch(+ `${scimUrl}/Users/${encodeURIComponent(email)}`,+ { schemas: ['urn:ietf:params:scim:api:messages:2.0:PatchOp'] },+ { headers: scimJsonHeaders(), validateStatus: () => true },+ )++ expect(res.status).toBe(400)+ expect(res.data.schemas).toContain('urn:ietf:params:scim:api:messages:2.0:Error')++ const get = await axios.get(`${scimUrl}/Users/${encodeURIComponent(email)}`, { headers: scimHeaders() })+ expect(get.data.active).toBe(true)+ })+})diff --git a/taskview-packages/taskview-api/src/api/automations.ts b/taskview-packages/taskview-api/src/api/automations.tsnew file mode 100644index 0000000..61501a9--- /dev/null+++ b/taskview-packages/taskview-api/src/api/automations.ts@@ -0,0 +1,44 @@+import TvApiBase from './base';+import type { AppResponse } from './base.types';+import type {+ AutomationCatalog,+ AutomationOption,+ AutomationOptionsArgs,+ AutomationRule,+ AutomationRuleCreateArgs,+ AutomationRuleUpdateArgs,+} from './automations.types';++export default class TvAutomationsApi extends TvApiBase {+ protected moduleUrl = '/module/automations';++ public async getCatalog() {+ return this.request(this.$axios.get<AppResponse<AutomationCatalog>>(`${this.moduleUrl}/catalog`));+ }++ public async getOptions(args: AutomationOptionsArgs) {+ return this.request(+ this.$axios.get<AppResponse<AutomationOption[]>>(+ `${this.moduleUrl}/goal/${args.goalId}/options/${encodeURIComponent(args.source)}`+ )+ );+ }++ public async listRules(goalId: number) {+ return this.request(this.$axios.get<AppResponse<AutomationRule[]>>(`${this.moduleUrl}/goal/${goalId}/rules`));+ }++ public async createRule(args: AutomationRuleCreateArgs) {+ const { goalId, ...body } = args;+ return this.request(this.$axios.post<AppResponse<AutomationRule>>(`${this.moduleUrl}/goal/${goalId}/rules`, body));+ }++ public async updateRule(args: AutomationRuleUpdateArgs) {+ const { ruleId, ...body } = args;+ return this.request(this.$axios.patch<AppResponse<AutomationRule>>(`${this.moduleUrl}/rule/${ruleId}`, body));+ }++ public async deleteRule(ruleId: number) {+ return this.request(this.$axios.delete<AppResponse<true>>(`${this.moduleUrl}/rule/${ruleId}`));+ }+}diff --git a/taskview-packages/taskview-api/src/api/automations.types.ts b/taskview-packages/taskview-api/src/api/automations.types.tsnew file mode 100644index 0000000..b538804--- /dev/null+++ b/taskview-packages/taskview-api/src/api/automations.types.ts@@ -0,0 +1,88 @@+export type AutomationModuleName = 'tasks' | 'kanban' | 'lists' | 'tags';++export type AutomationDataSourceName = 'kanban.statuses' | 'tags.goalTags' | 'lists.goalLists';++export type AutomationParams = Record<string, number>;++export type AutomationParamDefinition = {+ key: string;+ source: AutomationDataSourceName;+};++export type AutomationCatalogEvent = {+ name: string;+ params: AutomationParamDefinition[];+};++export type AutomationCatalogAction = {+ name: string;+ params: AutomationParamDefinition[];+};++export type AutomationCatalogModule = {+ name: AutomationModuleName;+ events: AutomationCatalogEvent[];+ actions: AutomationCatalogAction[];+};++export type AutomationCatalog = {+ modules: AutomationCatalogModule[];+};++export type AutomationOption = {+ id: number;+ label: string;+ color?: string;+};++export type AutomationRuleTrigger = {+ module: string;+ event: string;+ params: AutomationParams;+};++export type AutomationRuleAction = {+ module: string;+ action: string;+ params: AutomationParams;+};++export type AutomationRule = {+ id: number;+ goalId: number;+ creatorId: number;+ name: string;+ enabled: boolean;+ trigger: AutomationRuleTrigger;+ action: AutomationRuleAction;+ createdAt: string;+ editedAt: string;+};++export type AutomationOptionsArgs = {+ goalId: number;+ source: AutomationDataSourceName;+};++export type AutomationRuleCreateArgs = {+ goalId: number;+ name: string;+ enabled?: boolean;+ trigger: AutomationRuleTrigger;+ action: AutomationRuleAction;+};++export type AutomationRuleUpdateArgs = {+ ruleId: number;+ name?: string;+ enabled?: boolean;+ trigger?: AutomationRuleTrigger;+ action?: AutomationRuleAction;+};++export type AutomationErrorCode = 'not_found' | 'forbidden' | 'invalid' | 'cycle' | 'limit_reached';++export type AutomationApiError = {+ code: AutomationErrorCode;+ message: string | null;+};diff --git a/taskview-packages/taskview-api/src/api/permissions.ts b/taskview-packages/taskview-api/src/api/permissions.tsindex 5374180..9edadcd 100644--- a/taskview-packages/taskview-api/src/api/permissions.ts+++ b/taskview-packages/taskview-api/src/api/permissions.ts@@ -173,6 +173,15 @@ export const TvPermissions: Record<Uppercase<keyof GoalPermissions>, keyof GoalP* Can upload, rename, link/unlink and delete project files*/FILE_CAN_MANAGE: 'file_can_manage',++ /**+ * Can view the project's automation rules+ */+ AUTOMATION_CAN_VIEW: 'automation_can_view',+ /**+ * Can create, edit, enable, disable and delete automation rules+ */+ AUTOMATION_CAN_MANAGE: 'automation_can_manage',} as const;export type GoalPermissions = {@@ -229,4 +238,7 @@ export type GoalPermissions = {file_can_view?: true;file_can_manage?: true;++ automation_can_view?: true;+ automation_can_manage?: true;};\ No newline at end of filediff --git a/taskview-packages/taskview-api/src/index.ts b/taskview-packages/taskview-api/src/index.tsindex 69af821..714a49e 100644--- a/taskview-packages/taskview-api/src/index.ts+++ b/taskview-packages/taskview-api/src/index.ts@@ -25,4 +25,6 @@ export * from '@/api/analytics.types';export * from '@/api/time-tracking.types';export * from '@/api/ui-preferences.types';export * from '@/api/sprints.types';-export * from '@/api/recurrence.types';export * from '@/api/files.types';+export * from '@/api/recurrence.types';+export * from '@/api/files.types';+export * from '@/api/automations.types';diff --git a/taskview-packages/taskview-api/src/tv.ts b/taskview-packages/taskview-api/src/tv.tsindex bbc4528..ec03355 100644--- a/taskview-packages/taskview-api/src/tv.ts+++ b/taskview-packages/taskview-api/src/tv.ts@@ -24,6 +24,7 @@ import TvRecurrenceApi from "./api/recurrence";import TvBillingApi from "./api/billing";import TvInvoicesApi from "./api/invoices";import TvFilesApi from "./api/files";+import TvAutomationsApi from "./api/automations";export class TvApi {@@ -75,6 +76,7 @@ export class TvApi {public invoices: TvInvoicesApi;public files: TvFilesApi;+ public automations: TvAutomationsApi;constructor($axios: AxiosInstance) {this.$axios = $axios;@@ -125,6 +127,7 @@ export class TvApi {this.invoices = new TvInvoicesApi(this.$axios);this.files = new TvFilesApi(this.$axios);+ this.automations = new TvAutomationsApi(this.$axios);}public get baseUrl(): string | undefined {diff --git a/taskview-packages/taskview-db-schemas/src/index.ts b/taskview-packages/taskview-db-schemas/src/index.tsindex 796c48e..71888ea 100644--- a/taskview-packages/taskview-db-schemas/src/index.ts+++ b/taskview-packages/taskview-db-schemas/src/index.ts@@ -39,3 +39,4 @@ export * from './schemas/recurrence-template-assignees.schema';export * from './schemas/recurrence-template-tags.schema';export * from './schemas/files.schema';export * from './schemas/file-to-task.schema';+export * from './schemas/automation-rules.schema';diff --git a/taskview-packages/taskview-db-schemas/src/schemas/automation-rules.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/automation-rules.schema.tsnew file mode 100644index 0000000..187f63c--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/automation-rules.schema.ts@@ -0,0 +1,24 @@+import { boolean, index, integer, jsonb, pgSchema, serial, timestamp, varchar } from "drizzle-orm/pg-core";+import { GoalsSchema } from "./goals.schema";+import { UsersSchema } from "./users.schema";++export const AutomationRulesSchema = pgSchema('tv_automations').table('rules', {+ id: serial().primaryKey(),+ goalId: integer('goal_id').notNull().references(() => GoalsSchema.id, { onDelete: 'cascade' }),+ creatorId: integer('creator_id').notNull().references(() => UsersSchema.id, { onDelete: 'cascade' }),+ name: varchar({ length: 255 }).notNull(),+ enabled: boolean().notNull().default(true),+ triggerModule: varchar('trigger_module', { length: 64 }).notNull(),+ triggerEvent: varchar('trigger_event', { length: 64 }).notNull(),+ triggerParams: jsonb('trigger_params').$type<Record<string, unknown>>().notNull().default({}),+ actionModule: varchar('action_module', { length: 64 }).notNull(),+ actionName: varchar('action_name', { length: 64 }).notNull(),+ actionParams: jsonb('action_params').$type<Record<string, unknown>>().notNull().default({}),+ createdAt: timestamp('created_at').notNull().defaultNow(),+ editedAt: timestamp('edited_at').notNull().defaultNow(),+}, (t) => [+ index('rules_goal_enabled_idx').on(t.goalId, t.enabled),+]);++export type AutomationRulesSchemaTypeForSelect = typeof AutomationRulesSchema.$inferSelect;+export type AutomationRulesSchemaTypeForInsert = typeof AutomationRulesSchema.$inferInsert;diff --git a/web/src/bootstrap.ts b/web/src/bootstrap.tsindex c680ddb..ed5b1f0 100644--- a/web/src/bootstrap.ts+++ b/web/src/bootstrap.ts@@ -74,6 +74,11 @@ function buildRoutes(extensions: TvWebExtension[]): RouteRecordRaw[] {name: 'files',component: () => import('./pages/user/files.vue'),},+ {+ path: ':projectId/automations',+ name: 'automations',+ component: () => import('./pages/user/automations.vue'),+ },{path: ':projectId/collaboration',name: 'collaboration',diff --git a/web/src/components/features/automations/AutomationsProjectTab.vue b/web/src/components/features/automations/AutomationsProjectTab.vuenew file mode 100644index 0000000..b8c67ce--- /dev/null+++ b/web/src/components/features/automations/AutomationsProjectTab.vue@@ -0,0 +1,145 @@+<template>+ <div+ class="flex flex-col gap-4 p-2"+ data-testid="automations-project-tab"+ >+ <div class="flex items-center justify-between gap-2">+ <p class="text-sm text-muted">+ {{ t('automations.description') }}+ </p>+ <UButton+ v-if="canManage"+ :label="t('automations.create')"+ icon="i-lucide-plus"+ data-testid="automation-create"+ @click="openCreate"+ />+ </div>++ <div+ v-if="loading && rules.length === 0"+ class="flex justify-center py-12"+ >+ <UIcon+ name="i-lucide-loader-circle"+ class="size-6 animate-spin text-dimmed"+ />+ </div>++ <UEmpty+ v-else-if="rules.length === 0"+ icon="i-lucide-workflow"+ :title="t('automations.empty')"+ :description="t('automations.emptyHint')"+ />++ <div+ v-else+ class="flex flex-col gap-2"+ >+ <AutomationRuleRow+ v-for="rule in rules"+ :key="rule.id"+ :rule="rule"+ :modules="modules"+ :can-manage="canManage"+ :toggling="togglingId === rule.id"+ @toggle="(enabled) => toggle({ rule, enabled })"+ @edit="openEdit(rule)"+ @delete="ruleToDelete = rule"+ />+ </div>++ <AutomationRuleFormDialog+ v-model:open="formOpen"+ :goal-id="goalId"+ :rule="editedRule"+ />+ <AutomationRuleDeleteDialog+ v-model:rule="ruleToDelete"+ @confirm="confirmDelete"+ />+ </div>+</template>++<script setup lang="ts">+import { computed, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import type { AutomationDataSourceName, AutomationRule } from 'taskview-api'+import AutomationRuleRow from './parts/AutomationRuleRow.vue'+import AutomationRuleFormDialog from './parts/AutomationRuleFormDialog.vue'+import AutomationRuleDeleteDialog from './parts/AutomationRuleDeleteDialog.vue'+import { useAutomationsStore } from '@/stores/automations.store'+import { useAutomationLabels } from '@/composables/useAutomationLabels'+import type { AutomationToggleRuleArgs } from '@/types/automations.types'++const props = defineProps<{+ goalId: number+ canManage: boolean+}>()++const { t } = useI18n()+const toast = useToast()+const store = useAutomationsStore()+const { errorMessage } = useAutomationLabels()++const formOpen = ref(false)+const editedRule = ref<AutomationRule | null>(null)+const ruleToDelete = ref<AutomationRule | null>(null)+const togglingId = ref<number | null>(null)++const modules = computed(() => store.catalog?.modules ?? [])+const rules = computed(() => store.rulesFor(props.goalId))+const loading = computed(() => store.loadingGoals[props.goalId] ?? false)++function sourcesOf(): AutomationDataSourceName[] {+ const sources = new Set<AutomationDataSourceName>()+ for (const module of modules.value) {+ for (const item of [...module.events, ...module.actions]) {+ for (const definition of item.params) sources.add(definition.source)+ }+ }+ return [...sources]+}++async function load() {+ await store.fetchCatalog()+ await Promise.all([+ store.fetchRules(props.goalId),+ ...sourcesOf().map((source) => store.fetchOptions({ goalId: props.goalId, source })),+ ])+}++watch(() => props.goalId, load, { immediate: true })++function openCreate() {+ editedRule.value = null+ formOpen.value = true+}++function openEdit(rule: AutomationRule) {+ editedRule.value = rule+ formOpen.value = true+}++async function toggle(args: AutomationToggleRuleArgs) {+ togglingId.value = args.rule.id+ const result = await store.toggleRule(args)+ togglingId.value = null+ if (!result.ok) {+ toast.add({ title: errorMessage(result.error), color: 'error' })+ return+ }+ toast.add({ title: t(args.enabled ? 'automations.toasts.enabled' : 'automations.toasts.disabled'), color: 'success' })+}++async function confirmDelete() {+ const rule = ruleToDelete.value+ if (!rule) return+ ruleToDelete.value = null+ const deleted = await store.deleteRule(rule)+ toast.add(deleted+ ? { title: t('automations.toasts.deleted'), color: 'success' }+ : { title: t('automations.errors.deleteFailed'), color: 'error' })+}+</script>diff --git a/web/src/components/features/automations/parts/AutomationParamSelect.vue b/web/src/components/features/automations/parts/AutomationParamSelect.vuenew file mode 100644index 0000000..ef1f789--- /dev/null+++ b/web/src/components/features/automations/parts/AutomationParamSelect.vue@@ -0,0 +1,46 @@+<template>+ <UFormField :label="paramLabel(definition.key)">+ <USelect+ v-model="model"+ :items="items"+ :loading="loading"+ :placeholder="t('automations.placeholders.option')"+ class="w-full"+ :data-testid="`automation-param-${definition.key}`"+ />+ </UFormField>+</template>++<script setup lang="ts">+import { computed, onMounted, ref } from 'vue'+import { useI18n } from 'vue-i18n'+import type { AutomationParamDefinition } from 'taskview-api'+import { useAutomationsStore } from '@/stores/automations.store'+import { useAutomationLabels } from '@/composables/useAutomationLabels'++const props = defineProps<{+ goalId: number+ definition: AutomationParamDefinition+}>()++const model = defineModel<number | undefined>()++const { t } = useI18n()+const store = useAutomationsStore()+const { paramLabel } = useAutomationLabels()++const loading = ref(false)++const items = computed(() =>+ (store.optionsByGoal[props.goalId]?.[props.definition.source] ?? []).map((option) => ({+ label: option.label,+ value: option.id,+ })),+)++onMounted(async () => {+ loading.value = true+ await store.fetchOptions({ goalId: props.goalId, source: props.definition.source })+ loading.value = false+})+</script>diff --git a/web/src/components/features/automations/parts/AutomationRuleDeleteDialog.vue b/web/src/components/features/automations/parts/AutomationRuleDeleteDialog.vuenew file mode 100644index 0000000..0e91682--- /dev/null+++ b/web/src/components/features/automations/parts/AutomationRuleDeleteDialog.vue@@ -0,0 +1,54 @@+<template>+ <UModal+ v-model:open="open"+ :fullscreen="isMobile"+ :title="t('automations.delete.title')"+ :ui="{ content: 'max-w-md' }"+ >+ <template #body>+ <p class="text-sm text-muted">+ {{ t('automations.delete.confirm', { name: rule?.name ?? '' }) }}+ </p>+ </template>+ <template #footer>+ <div class="flex justify-end gap-2 w-full">+ <UButton+ :label="t('common.cancel')"+ color="neutral"+ variant="ghost"+ @click="open = false"+ />+ <UButton+ :label="t('common.delete')"+ icon="i-lucide-trash-2"+ color="error"+ data-testid="automation-delete-confirm"+ @click="emit('confirm')"+ />+ </div>+ </template>+ </UModal>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import type { AutomationRule } from 'taskview-api'+import { useTaskView } from '@/composables/useTaskView'++const rule = defineModel<AutomationRule | null>('rule', { default: null })++const emit = defineEmits<{+ confirm: []+}>()++const { t } = useI18n()+const { isMobile } = useTaskView()++const open = computed({+ get: () => rule.value !== null,+ set: (value: boolean) => {+ if (!value) rule.value = null+ },+})+</script>diff --git a/web/src/components/features/automations/parts/AutomationRuleForm.vue b/web/src/components/features/automations/parts/AutomationRuleForm.vuenew file mode 100644index 0000000..b65662a--- /dev/null+++ b/web/src/components/features/automations/parts/AutomationRuleForm.vue@@ -0,0 +1,97 @@+<template>+ <div class="flex flex-col gap-4">+ <UFormField :label="t('automations.fields.name')">+ <UInput+ v-model="model.name"+ :placeholder="t('automations.fields.namePlaceholder')"+ autofocus+ class="w-full"+ data-testid="automation-name"+ />+ </UFormField>++ <AutomationRuleStepFields+ v-model:module="model.triggerModule"+ v-model:item="model.triggerEvent"+ v-model:params="model.triggerParams"+ :goal-id="goalId"+ kind="event"+ :title="t('automations.when')"+ :modules="modules"+ />++ <div class="flex justify-center text-dimmed">+ <UIcon+ name="i-lucide-arrow-down"+ class="size-5"+ />+ </div>++ <AutomationRuleStepFields+ v-model:module="model.actionModule"+ v-model:item="model.actionName"+ v-model:params="model.actionParams"+ :goal-id="goalId"+ kind="action"+ :title="t('automations.then')"+ :modules="modules"+ />++ <p class="text-xs text-dimmed">+ {{ t('automations.runsAsHint') }}+ </p>++ <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="!isComplete"+ data-testid="automation-submit"+ @click="emit('submit')"+ />+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import type { AutomationCatalogModule } from 'taskview-api'+import AutomationRuleStepFields from './AutomationRuleStepFields.vue'+import type { AutomationHasParamsArgs, AutomationRuleFormValue } from '@/types/automations.types'++const props = defineProps<{+ goalId: number+ modules: AutomationCatalogModule[]+ submitLabel: string+ loading?: boolean+}>()++const model = defineModel<AutomationRuleFormValue>({ required: true })++const emit = defineEmits<{+ submit: []+ cancel: []+}>()++const { t } = useI18n()++const hasAll = (args: AutomationHasParamsArgs) =>+ !!args.definitions && args.definitions.every((definition) => args.params[definition.key] !== undefined)++const isComplete = computed(() => {+ const value = model.value+ const module = (name: string) => props.modules.find((item) => item.name === name)+ const event = module(value.triggerModule)?.events.find((item) => item.name === value.triggerEvent)+ const action = module(value.actionModule)?.actions.find((item) => item.name === value.actionName)+ return value.name.trim().length > 0+ && hasAll({ definitions: event?.params, params: value.triggerParams })+ && hasAll({ definitions: action?.params, params: value.actionParams })+})+</script>diff --git a/web/src/components/features/automations/parts/AutomationRuleFormDialog.vue b/web/src/components/features/automations/parts/AutomationRuleFormDialog.vuenew file mode 100644index 0000000..dce7d2c--- /dev/null+++ b/web/src/components/features/automations/parts/AutomationRuleFormDialog.vue@@ -0,0 +1,95 @@+<template>+ <UModal+ v-model:open="open"+ :fullscreen="isMobile"+ >+ <template #content>+ <UCard>+ <template #header>+ <div class="flex items-center justify-between">+ <h3 class="font-semibold">+ {{ rule ? t('automations.editTitle') : t('automations.createTitle') }}+ </h3>+ <UButton+ icon="i-lucide-x"+ variant="ghost"+ color="neutral"+ @click="open = false"+ />+ </div>+ </template>++ <AutomationRuleForm+ v-model="formValue"+ :goal-id="goalId"+ :modules="modules"+ :submit-label="rule ? t('common.save') : t('automations.create')"+ :loading="loading"+ @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 { AutomationRule } from 'taskview-api'+import AutomationRuleForm from './AutomationRuleForm.vue'+import { useTaskView } from '@/composables/useTaskView'+import { useAutomationLabels } from '@/composables/useAutomationLabels'+import { useAutomationsStore } from '@/stores/automations.store'+import type { AutomationRuleFormValue } from '@/types/automations.types'++const open = defineModel<boolean>('open', { default: false })++const props = defineProps<{+ goalId: number+ rule?: AutomationRule | null+}>()++const { t } = useI18n()+const toast = useToast()+const { isMobile } = useTaskView()+const store = useAutomationsStore()+const { errorMessage } = useAutomationLabels()++const loading = ref(false)+const modules = computed(() => store.catalog?.modules ?? [])++function toFormValue(rule: AutomationRule | null | undefined): AutomationRuleFormValue {+ if (!rule) {+ return { name: '', triggerModule: '', triggerEvent: '', triggerParams: {}, actionModule: '', actionName: '', actionParams: {} }+ }+ return {+ name: rule.name,+ triggerModule: rule.trigger.module,+ triggerEvent: rule.trigger.event,+ triggerParams: { ...rule.trigger.params },+ actionModule: rule.action.module,+ actionName: rule.action.action,+ actionParams: { ...rule.action.params },+ }+}++const formValue = ref<AutomationRuleFormValue>(toFormValue(props.rule))++watch(open, (value) => {+ if (value) formValue.value = toFormValue(props.rule)+})++async function submit() {+ loading.value = true+ const result = await store.saveRule({ goalId: props.goalId, ruleId: props.rule?.id ?? null, value: formValue.value })+ loading.value = false++ if (!result.ok) {+ toast.add({ title: errorMessage(result.error), color: 'error' })+ return+ }+ toast.add({ title: t(props.rule ? 'automations.toasts.updated' : 'automations.toasts.created'), color: 'success' })+ open.value = false+}+</script>diff --git a/web/src/components/features/automations/parts/AutomationRuleRow.vue b/web/src/components/features/automations/parts/AutomationRuleRow.vuenew file mode 100644index 0000000..f2fa745--- /dev/null+++ b/web/src/components/features/automations/parts/AutomationRuleRow.vue@@ -0,0 +1,132 @@+<template>+ <div+ class="flex flex-col gap-2 rounded-xl border border-default p-3 lg:flex-row lg:items-center"+ :class="{ 'opacity-60': !rule.enabled }"+ data-testid="automation-rule"+ >+ <div class="flex min-w-0 flex-1 flex-col gap-1.5">+ <div class="flex min-w-0 items-center gap-2">+ <span class="truncate font-medium">{{ rule.name }}</span>+ <UTooltip+ v-if="broken"+ :text="t('automations.brokenHint')"+ >+ <UBadge+ :label="t('automations.broken')"+ icon="i-lucide-triangle-alert"+ color="warning"+ variant="subtle"+ size="sm"+ class="shrink-0"+ data-testid="automation-rule-broken"+ />+ </UTooltip>+ </div>+ <div class="flex flex-wrap items-center gap-1.5 text-sm">+ <UBadge+ :label="t('automations.when')"+ color="neutral"+ variant="subtle"+ size="sm"+ />+ <span class="text-muted">{{ describe(trigger) }}</span>+ <UIcon+ name="i-lucide-arrow-right"+ class="size-4 text-dimmed"+ />+ <UBadge+ :label="t('automations.then')"+ color="primary"+ variant="subtle"+ size="sm"+ />+ <span class="text-muted">{{ describe(action) }}</span>+ </div>+ </div>++ <div class="flex items-center gap-2 self-end lg:self-center">+ <USwitch+ :model-value="rule.enabled"+ :disabled="!canManage || toggling"+ :aria-label="t('automations.enabled')"+ data-testid="automation-rule-toggle"+ @update:model-value="(value) => emit('toggle', value)"+ />+ <UDropdownMenu+ v-if="canManage"+ :items="menuItems"+ :content="{ align: 'end' }"+ >+ <UButton+ icon="i-lucide-ellipsis-vertical"+ color="neutral"+ variant="ghost"+ size="xs"+ data-testid="automation-rule-menu"+ />+ </UDropdownMenu>+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import type { DropdownMenuItem } from '@nuxt/ui'+import type { AutomationCatalogModule, AutomationRule } from 'taskview-api'+import { useAutomationLabels } from '@/composables/useAutomationLabels'+import type { AutomationStepDescription } from '@/types/automations.types'++const props = defineProps<{+ rule: AutomationRule+ modules: AutomationCatalogModule[]+ canManage: boolean+ toggling?: boolean+}>()++const emit = defineEmits<{+ toggle: [enabled: boolean]+ edit: []+ delete: []+}>()++const { t } = useI18n()+const { moduleLabel, eventLabel, actionLabel, optionLabel, isOptionMissing } = useAutomationLabels()++const moduleOf = (name: string) => props.modules.find((module) => module.name === name)++const trigger = computed<AutomationStepDescription>(() => ({+ module: props.rule.trigger.module,+ label: eventLabel(props.rule.trigger.event),+ definitions: moduleOf(props.rule.trigger.module)?.events.find((item) => item.name === props.rule.trigger.event)?.params ?? [],+ params: props.rule.trigger.params,+}))++const action = computed<AutomationStepDescription>(() => ({+ module: props.rule.action.module,+ label: actionLabel(props.rule.action.action),+ definitions: moduleOf(props.rule.action.module)?.actions.find((item) => item.name === props.rule.action.action)?.params ?? [],+ params: props.rule.action.params,+}))++const broken = computed(() =>+ [trigger.value, action.value].some((step) =>+ step.definitions.some((definition) => {+ const id = step.params[definition.key]+ return id !== undefined && isOptionMissing({ goalId: props.rule.goalId, source: definition.source, id })+ }),+ ),+)++function describe(step: AutomationStepDescription): string {+ const values = step.definitions+ .filter((definition) => step.params[definition.key] !== undefined)+ .map((definition) => `«${optionLabel({ goalId: props.rule.goalId, source: definition.source, id: step.params[definition.key] as number })}»`)+ return [`${moduleLabel(step.module)} · ${step.label}`, ...values].join(' ')+}++const menuItems = computed<DropdownMenuItem[][]>(() => [+ [{ label: t('common.edit'), icon: 'i-lucide-pencil', onSelect: () => emit('edit') }],+ [{ label: t('common.delete'), icon: 'i-lucide-trash-2', color: 'error', onSelect: () => emit('delete') }],+])+</script>diff --git a/web/src/components/features/automations/parts/AutomationRuleStepFields.vue b/web/src/components/features/automations/parts/AutomationRuleStepFields.vuenew file mode 100644index 0000000..0405070--- /dev/null+++ b/web/src/components/features/automations/parts/AutomationRuleStepFields.vue@@ -0,0 +1,110 @@+<template>+ <div+ class="flex flex-col gap-3 rounded-xl bg-elevated/50 p-3"+ :data-testid="`automation-${kind}-step`"+ >+ <span class="text-xs font-semibold uppercase tracking-wide text-muted">{{ title }}</span>++ <div class="flex flex-col gap-3 lg:flex-row">+ <UFormField+ :label="t('automations.fields.module')"+ class="flex-1"+ >+ <USelect+ v-model="moduleName"+ :items="moduleItems"+ :placeholder="t('automations.placeholders.module')"+ class="w-full"+ :data-testid="`automation-${kind}-module`"+ />+ </UFormField>++ <UFormField+ :label="t(kind === 'event' ? 'automations.fields.event' : 'automations.fields.action')"+ class="flex-1"+ >+ <USelect+ v-model="itemName"+ :items="stepItems"+ :disabled="!moduleName"+ :placeholder="t(kind === 'event' ? 'automations.placeholders.event' : 'automations.placeholders.action')"+ class="w-full"+ :data-testid="`automation-${kind}-name`"+ />+ </UFormField>+ </div>++ <AutomationParamSelect+ v-for="definition in selectedItem?.params ?? []"+ :key="`${itemName}-${definition.key}`"+ :model-value="params[definition.key]"+ :goal-id="goalId"+ :definition="definition"+ @update:model-value="(value) => setParam({ key: definition.key, value })"+ />+ </div>+</template>++<script setup lang="ts">+import { computed, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import type { AutomationCatalogModule, AutomationParams } from 'taskview-api'+import AutomationParamSelect from './AutomationParamSelect.vue'+import { useAutomationLabels } from '@/composables/useAutomationLabels'+import type { AutomationSelectItem, AutomationSetParamArgs } from '@/types/automations.types'++const props = defineProps<{+ goalId: number+ kind: 'event' | 'action'+ title: string+ modules: AutomationCatalogModule[]+}>()++const moduleName = defineModel<string>('module', { required: true })+const itemName = defineModel<string>('item', { required: true })+const params = defineModel<AutomationParams>('params', { required: true })++const { t } = useI18n()+const { moduleLabel, eventLabel, actionLabel } = useAutomationLabels()++const itemsOf = (module: AutomationCatalogModule) => (props.kind === 'event' ? module.events : module.actions)++const moduleItems = computed<AutomationSelectItem[]>(() =>+ props.modules+ .filter((module) => itemsOf(module).length > 0)+ .map((module) => ({ label: moduleLabel(module.name), value: module.name })),+)++const selectedModule = computed(() => props.modules.find((module) => module.name === moduleName.value) ?? null)++const stepItems = computed<AutomationSelectItem[]>(() =>+ (selectedModule.value ? itemsOf(selectedModule.value) : []).map((item) => ({+ label: props.kind === 'event' ? eventLabel(item.name) : actionLabel(item.name),+ value: item.name,+ })),+)++const selectedItem = computed(() =>+ selectedModule.value ? itemsOf(selectedModule.value).find((item) => item.name === itemName.value) ?? null : null,+)++function setParam(args: AutomationSetParamArgs) {+ const next = { ...params.value }+ if (args.value === undefined) delete next[args.key]+ else next[args.key] = args.value+ params.value = next+}++watch(moduleName, (value, previous) => {+ if (previous !== undefined && value !== previous) itemName.value = ''+})++watch(selectedItem, (item) => {+ const keys = new Set(item?.params.map((definition) => definition.key) ?? [])+ const next: AutomationParams = {}+ for (const [key, value] of Object.entries(params.value)) {+ if (keys.has(key)) next[key] = value+ }+ params.value = next+})+</script>diff --git a/web/src/components/sidebars/dashboard-second/SidebarTools.vue b/web/src/components/sidebars/dashboard-second/SidebarTools.vueindex f229d4a..2ec13f7 100644--- a/web/src/components/sidebars/dashboard-second/SidebarTools.vue+++ b/web/src/components/sidebars/dashboard-second/SidebarTools.vue@@ -68,6 +68,7 @@ const {canViewGraph,canViewSprints,canViewFiles,+ canViewAutomations,canManageUsers,canViewIntegrations,canViewTimeTracking,@@ -99,6 +100,9 @@ const tools = computed<Tool[]>(() => {if (canViewFiles.value) {list.push({ key: 'files', label: t('contextMenu.files'), icon: 'i-lucide-paperclip', to: { name: 'files', params: { projectId: id } }, active: () => route.name === 'files' })}+ if (canViewAutomations.value) {+ list.push({ key: 'automations', label: t('contextMenu.automations'), icon: 'i-lucide-workflow', to: { name: 'automations', params: { projectId: id } }, active: () => route.name === 'automations' })+ }if (canManageUsers.value) {list.push({ key: 'collaboration', label: t('contextMenu.collaboration'), icon: 'i-lucide-users', to: { name: 'collaboration', params: { projectId: id } }, active: () => route.name === 'collaboration' })}diff --git a/web/src/composables/useAutomationLabels.ts b/web/src/composables/useAutomationLabels.tsnew file mode 100644index 0000000..8b83268--- /dev/null+++ b/web/src/composables/useAutomationLabels.ts@@ -0,0 +1,33 @@+import { useI18n } from 'vue-i18n'+import type { AutomationApiError } from 'taskview-api'+import { useAutomationsStore } from '@/stores/automations.store'+import type { AutomationOptionLabelArgs } from '@/types/automations.types'++const toKey = (name: string) => name.replace(/\./g, '_')++export function useAutomationLabels() {+ const { t } = useI18n()+ const store = useAutomationsStore()++ const optionsOf = (args: AutomationOptionLabelArgs) => store.optionsByGoal[args.goalId]?.[args.source]++ return {+ moduleLabel: (name: string) => t(`automations.modules.${name}`),+ eventLabel: (name: string) => t(`automations.events.${toKey(name)}`),+ actionLabel: (name: string) => t(`automations.actions.${toKey(name)}`),+ paramLabel: (key: string) => t(`automations.params.${key}`),+ optionLabel: (args: AutomationOptionLabelArgs) => {+ const options = optionsOf(args)+ if (!options) return '…'+ return options.find((option) => option.id === args.id)?.label ?? t('automations.unavailableOption')+ },+ isOptionMissing: (args: AutomationOptionLabelArgs) => {+ const options = optionsOf(args)+ return !!options && !options.some((option) => option.id === args.id)+ },+ errorMessage: (error: AutomationApiError) =>+ error.code === 'cycle'+ ? t('automations.errors.cycle', { path: error.message ?? '' })+ : t(`automations.errors.${error.code}`),+ }+}diff --git a/web/src/composables/useCentrifugo/handlers/index.ts b/web/src/composables/useCentrifugo/handlers/index.tsindex 4efb943..3dd71e7 100644--- a/web/src/composables/useCentrifugo/handlers/index.ts+++ b/web/src/composables/useCentrifugo/handlers/index.ts@@ -3,6 +3,7 @@ import { handleNotification } from './notification'import { handleGoalsChanged } from './goals-changed'import { handleRecurrenceInstanceCreated } from './recurrence'import { handleFilesChanged } from './files'+import { handleTasksChanged } from './tasks'import {handleTimeEntryCreated,handleTimeEntryDeleted,@@ -21,4 +22,5 @@ export const eventHandlers: { [K in keyof RealtimeEventMap]: RealtimeHandler<K>'time-entry.deleted': handleTimeEntryDeleted,'recurrence.instanceCreated': handleRecurrenceInstanceCreated,'files.changed': handleFilesChanged,+ 'tasks.changed': handleTasksChanged,}diff --git a/web/src/composables/useCentrifugo/handlers/tasks.ts b/web/src/composables/useCentrifugo/handlers/tasks.tsnew file mode 100644index 0000000..5e97341--- /dev/null+++ b/web/src/composables/useCentrifugo/handlers/tasks.ts@@ -0,0 +1,86 @@+import { $tvApi } from '@/plugins/axios'+import { useBaseScreenStore } from '@/stores/base-screen.store'+import { useGraphStore } from '@/stores/graph.store'+import { useKanbanStore } from '@/stores/kanban.store'+import { useTasksStore } from '@/stores/tasks.store'+import type { RealtimeEventMap, RealtimeTaskRefresh } from '../types'++const REFRESH_DELAY_MS = 300++const scheduled = new Map<number, { timer: ReturnType<typeof setTimeout>; created: boolean }>()+const inFlight = new Map<number, { seq: number; created: boolean }>()+let refreshSeq = 0++export function handleTasksChanged(data: RealtimeEventMap['tasks.changed']) {+ for (const taskId of data.taskIds) {+ if (data.kind === 'deleted') {+ cancelRefresh(taskId)+ removeTaskEverywhere(taskId)+ } else {+ scheduleRefresh({ taskId, goalId: data.goalId, created: data.kind === 'created' })+ }+ }+}++function scheduleRefresh(request: RealtimeTaskRefresh) {+ const previous = scheduled.get(request.taskId)+ if (previous) clearTimeout(previous.timer)++ const created = request.created || !!previous?.created+ const timer = setTimeout(() => {+ scheduled.delete(request.taskId)+ void refreshTask({ ...request, created })+ }, REFRESH_DELAY_MS)+ scheduled.set(request.taskId, { timer, created })+}++function cancelRefresh(taskId: number) {+ inFlight.delete(taskId)+ const previous = scheduled.get(taskId)+ if (!previous) return+ clearTimeout(previous.timer)+ scheduled.delete(taskId)+}++function isShown(request: RealtimeTaskRefresh): boolean {+ const tasksStore = useTasksStore()+ const kanbanStore = useKanbanStore()+ if (+ tasksStore.selectedTask?.id === request.taskId+ || tasksStore.findLoadedTask(request.taskId)+ || kanbanStore.hasTask(request.taskId)+ || useGraphStore().hasTask(request.taskId)+ || useBaseScreenStore().hasTask(request.taskId)+ ) {+ return true+ }+ return request.created && (Number(tasksStore.fetchRules.goalId) === request.goalId || kanbanStore.goalId === request.goalId)+}++async function refreshTask(request: RealtimeTaskRefresh) {+ if (!isShown(request)) return++ // A newer refresh of the same task supersedes the one in flight, whose+ // response may be stale — it inherits the "created" flag so the insert is not lost+ const seq = ++refreshSeq+ const created = request.created || !!inFlight.get(request.taskId)?.created+ inFlight.set(request.taskId, { seq, created })+ const task = await $tvApi.tasks.fetchTaskById(request.taskId).catch(() => null)+ if (inFlight.get(request.taskId)?.seq !== seq) return+ inFlight.delete(request.taskId)+ if (!task) return++ useTasksStore().applyRemoteTask({ task, created })+ const kanbanStore = useKanbanStore()+ kanbanStore.syncTask(task)+ if (created) kanbanStore.insertTask(task)+ useGraphStore().syncTask(task)+ useBaseScreenStore().syncTask(task)+}++function removeTaskEverywhere(taskId: number) {+ useTasksStore().removeTaskLocally(taskId)+ useKanbanStore().removeTask(taskId)+ useGraphStore().removeTask(taskId)+ useBaseScreenStore().removeTask(taskId)+}diff --git a/web/src/composables/useCentrifugo/types.ts b/web/src/composables/useCentrifugo/types.tsindex 12362ef..0aaf321 100644--- a/web/src/composables/useCentrifugo/types.ts+++ b/web/src/composables/useCentrifugo/types.ts@@ -47,6 +47,20 @@ export type RealtimeEventMap = {goalId: numbertaskIds: number[]}+ 'tasks.changed': {+ event: 'tasks.changed'+ goalId: number+ taskIds: number[]+ kind: RealtimeTaskChangeKind+ }+}++export type RealtimeTaskChangeKind = 'created' | 'updated' | 'deleted'++export type RealtimeTaskRefresh = {+ taskId: number+ goalId: number+ created: boolean}export type RealtimeEvent = RealtimeEventMap[keyof RealtimeEventMap]diff --git a/web/src/composables/useGoalPermissions.ts b/web/src/composables/useGoalPermissions.tsindex 0577f2f..9e70394 100644--- a/web/src/composables/useGoalPermissions.ts+++ b/web/src/composables/useGoalPermissions.ts@@ -33,6 +33,8 @@ export function useGoalPermissionsFor(goalRef: Ref<GoalItem | null>) {canViewSprintAnalytics: can('SPRINT_CAN_VIEW_ANALYTICS'),canViewFiles: computed(() => hasPermission(goalRef.value, 'FILE_CAN_VIEW') || hasPermission(goalRef.value, 'FILE_CAN_MANAGE')),canManageFiles: can('FILE_CAN_MANAGE'),+ canViewAutomations: computed(() => hasPermission(goalRef.value, 'AUTOMATION_CAN_VIEW') || hasPermission(goalRef.value, 'AUTOMATION_CAN_MANAGE')),+ canManageAutomations: can('AUTOMATION_CAN_MANAGE'),}}@@ -98,6 +100,8 @@ export const useGoalPermissions = () => {const canViewFiles = computed(() => permissions.FILE_CAN_VIEW || permissions.FILE_CAN_MANAGE)const canManageFiles = computed(() => permissions.FILE_CAN_MANAGE)+ const canViewAutomations = computed(() => permissions.AUTOMATION_CAN_VIEW || permissions.AUTOMATION_CAN_MANAGE)+ const canManageAutomations = computed(() => permissions.AUTOMATION_CAN_MANAGE)return {permissions,@@ -142,5 +146,7 @@ export const useGoalPermissions = () => {canViewSprintAnalytics,canViewFiles,canManageFiles,+ canViewAutomations,+ canManageAutomations,}}diff --git a/web/src/composables/useProjectContext.ts b/web/src/composables/useProjectContext.tsindex b4a20b8..752c96c 100644--- a/web/src/composables/useProjectContext.ts+++ b/web/src/composables/useProjectContext.ts@@ -12,8 +12,8 @@ import { useKanbanStore } from '@/stores/kanban.store'export type ProjectContext = {tags: ComputedRef<TagItem[]>users: ComputedRef<CollaborationResponseFetchAllUsers[]>- statuses: Ref<KanbanColumnItem[]>- lists: Ref<GoalListItem[]>+ statuses: ComputedRef<KanbanColumnItem[]>+ lists: ComputedRef<GoalListItem[]>}const PROJECT_CONTEXT_KEY: InjectionKey<ProjectContext> = Symbol('projectContext')@@ -22,6 +22,8 @@ export function provideProjectContext(goalId: Ref<number>) {const tagsStore = useTagsStore()const goalsStore = useGoalsStore()const collaborationStore = useCollaborationStore()+ const kanbanStore = useKanbanStore()+ const goalListsStore = useGoalListsStore()const tags = computed(() => {const id = goalId.value@@ -36,16 +38,24 @@ export function provideProjectContext(goalId: Ref<number>) {const users = computed(() =>isCurrentProject.value ? collaborationStore.users : fetchedUsers.value,)- const statuses = ref<KanbanColumnItem[]>([])- const lists = ref<GoalListItem[]>([])+ const fetchedStatuses = ref<KanbanColumnItem[]>([])+ const fetchedLists = ref<GoalListItem[]>([])+ // The current project reads the global stores live: they may still be+ // loading, and fetching replaces their arrays rather than filling them+ const statuses = computed(() =>+ isCurrentProject.value ? kanbanStore.statuses : fetchedStatuses.value,+ )+ const lists = computed(() =>+ isCurrentProject.value ? goalListsStore.lists : fetchedLists.value,+ )let requestId = 0watch(goalId, async (id) => {if (id <= 0) {fetchedUsers.value = []isCurrentProject.value = false- statuses.value = []- lists.value = []+ fetchedStatuses.value = []+ fetchedLists.value = []return}@@ -55,11 +65,7 @@ export function provideProjectContext(goalId: Ref<number>) {// If we're inside this project already, reuse data from global storesif (goalsStore.selectedItemId === id) {- const kanbanStore = useKanbanStore()- const goalListsStore = useGoalListsStore()isCurrentProject.value = true- statuses.value = kanbanStore.statuses- lists.value = goalListsStore.listsreturn}isCurrentProject.value = false@@ -77,12 +83,12 @@ export function provideProjectContext(goalId: Ref<number>) {if (usersResult) fetchedUsers.value = usersResultif (columnsResult) {- statuses.value = [+ fetchedStatuses.value = [{ id: DEFAULT_ID, name: 'msg.allTasks', goalId: id, viewOrder: 0 },...columnsResult,]}- if (listsResult) lists.value = listsResult+ if (listsResult) fetchedLists.value = listsResult}, { immediate: true })const context: ProjectContext = { tags, users, statuses, lists }diff --git a/web/src/helpers/Helper.ts b/web/src/helpers/Helper.tsindex 40856cc..414fe17 100644--- a/web/src/helpers/Helper.ts+++ b/web/src/helpers/Helper.ts@@ -56,3 +56,12 @@ export function isValidHttpUrl(string: string) {return url.protocol === 'http:' || url.protocol === 'https:'}++export function hasActiveFilters(filters: object): boolean {+ return Object.values(filters).some((value) => {+ if (value === undefined || value === null) return false+ if (Array.isArray(value)) return value.length > 0+ if (typeof value === 'object') return Object.keys(value).length > 0+ return true+ })+}diff --git a/web/src/locales/de.ts b/web/src/locales/de.tsindex 79f02f2..73546a2 100644--- a/web/src/locales/de.ts+++ b/web/src/locales/de.ts@@ -101,6 +101,7 @@ export default {graph: 'Graph',sprints: 'Sprints',files: 'Dateien',+ automations: 'Automatisierungen',collaboration: 'Zusammenarbeit',integrations: 'Integrationen',webhooks: 'Webhooks',@@ -977,6 +978,8 @@ export default {4: 'Aufgaben',5: 'Sprints',6: 'Organisation',+ 7: 'Dateien',+ 8: 'Automatisierungen',},oauth: {consent: {@@ -1544,4 +1547,80 @@ export default {linkFailed: 'Datei konnte nicht angehängt werden',},},+ automations: {+ title: 'Automatisierungen',+ noPermission: 'Sie haben keinen Zugriff auf die Automatisierungen dieses Projekts',+ description: 'Regeln, die Routinearbeit erledigen, wenn im Projekt etwas passiert.',+ empty: 'Noch keine Automatisierungsregeln',+ emptyHint: 'Zum Beispiel: Wenn eine Aufgabe erledigt ist, verschiebe sie in die Spalte „Fertig“.',+ create: 'Neue Regel',+ createTitle: 'Neue Automatisierungsregel',+ editTitle: 'Automatisierungsregel bearbeiten',+ when: 'Wenn',+ then: 'Dann',+ enabled: 'Aktiv',+ runsAsHint: 'Aktionen laufen mit den Rechten der Person, die die Regel zuletzt gespeichert hat.',+ unavailableOption: 'gelöschter Wert',+ broken: 'Funktioniert nicht',+ brokenHint: 'Eine ausgewählte Spalte, ein Tag oder eine Liste wurde gelöscht, daher wurde die Regel deaktiviert. Bearbeiten Sie sie und wählen Sie einen neuen Wert.',+ fields: {+ name: 'Name',+ namePlaceholder: 'Erledigte Aufgaben nach „Fertig“ verschieben',+ module: 'Modul',+ event: 'Ereignis',+ action: 'Aktion',+ },+ placeholders: {+ module: 'Modul wählen',+ event: 'Ereignis wählen',+ action: 'Aktion wählen',+ option: 'Wert wählen',+ },+ modules: {+ tasks: 'Aufgaben',+ kanban: 'Kanban',+ lists: 'Listen',+ tags: 'Tags',+ },+ events: {+ task_created: 'Aufgabe erstellt',+ task_completed: 'Aufgabe erledigt',+ task_reopened: 'Aufgabe wieder geöffnet',+ task_movedToColumn: 'Aufgabe in Spalte verschoben',+ task_addedToList: 'Aufgabe zur Liste hinzugefügt',+ tag_addedToTask: 'Tag zur Aufgabe hinzugefügt',+ tag_removedFromTask: 'Tag von der Aufgabe entfernt',+ },+ actions: {+ complete: 'Aufgabe erledigen',+ reopen: 'Aufgabe wieder öffnen',+ change_status: 'In Spalte verschieben',+ move_toList: 'In Liste verschieben',+ add_tag: 'Tag hinzufügen',+ },+ params: {+ statusId: 'Spalte',+ tagId: 'Tag',+ goalListId: 'Liste',+ },+ delete: {+ title: 'Regel löschen',+ confirm: 'Regel „{name}“ löschen? Dies kann nicht rückgängig gemacht werden.',+ },+ toasts: {+ created: 'Regel erstellt',+ updated: 'Regel gespeichert',+ deleted: 'Regel gelöscht',+ enabled: 'Regel aktiviert',+ disabled: 'Regel deaktiviert',+ },+ errors: {+ invalid: 'Prüfen Sie die Regel: Einige Werte fehlen oder sind im Projekt nicht mehr verfügbar',+ forbidden: 'Ihnen fehlen die Rechte, die diese Aktion benötigt',+ cycle: 'Diese Regeln würden sich endlos gegenseitig auslösen: {path}',+ limit_reached: 'Das Projekt hat das Limit für Automatisierungsregeln erreicht',+ not_found: 'Die Regel existiert nicht mehr',+ deleteFailed: 'Regel konnte nicht gelöscht werden',+ },+ },}diff --git a/web/src/locales/en.ts b/web/src/locales/en.tsindex 463a6e4..e13e272 100644--- a/web/src/locales/en.ts+++ b/web/src/locales/en.ts@@ -115,6 +115,7 @@ export default {graph: 'Graph',sprints: 'Sprints',files: 'Files',+ automations: 'Automations',collaboration: 'Collaboration',integrations: 'Integrations',webhooks: 'Webhooks',@@ -991,6 +992,8 @@ export default {4: 'Tasks',5: 'Sprints',6: 'Organization',+ 7: 'Files',+ 8: 'Automations',},oauth: {consent: {@@ -1558,4 +1561,80 @@ export default {linkFailed: 'Failed to attach the file',},},+ automations: {+ title: 'Automations',+ noPermission: 'You don\'t have access to this project\'s automations',+ description: 'Rules that do routine work for you when something happens in the project.',+ empty: 'No automation rules yet',+ emptyHint: 'For example: when a task is completed, move it to the Done column.',+ create: 'New rule',+ createTitle: 'New automation rule',+ editTitle: 'Edit automation rule',+ when: 'When',+ then: 'Then',+ enabled: 'Enabled',+ runsAsHint: 'Actions run with the permissions of the person who last saved the rule.',+ unavailableOption: 'deleted value',+ broken: 'Not working',+ brokenHint: 'A selected column, tag or list was deleted, so the rule was turned off. Edit it and pick a new value.',+ fields: {+ name: 'Name',+ namePlaceholder: 'Move completed tasks to Done',+ module: 'Module',+ event: 'Event',+ action: 'Action',+ },+ placeholders: {+ module: 'Select a module',+ event: 'Select an event',+ action: 'Select an action',+ option: 'Select a value',+ },+ modules: {+ tasks: 'Tasks',+ kanban: 'Kanban',+ lists: 'Lists',+ tags: 'Tags',+ },+ events: {+ task_created: 'Task created',+ task_completed: 'Task completed',+ task_reopened: 'Task reopened',+ task_movedToColumn: 'Task moved to column',+ task_addedToList: 'Task added to list',+ tag_addedToTask: 'Tag added to task',+ tag_removedFromTask: 'Tag removed from task',+ },+ actions: {+ complete: 'Complete the task',+ reopen: 'Reopen the task',+ change_status: 'Move to column',+ move_toList: 'Move to list',+ add_tag: 'Add tag',+ },+ params: {+ statusId: 'Column',+ tagId: 'Tag',+ goalListId: 'List',+ },+ delete: {+ title: 'Delete rule',+ confirm: 'Delete the rule "{name}"? This cannot be undone.',+ },+ toasts: {+ created: 'Rule created',+ updated: 'Rule saved',+ deleted: 'Rule deleted',+ enabled: 'Rule enabled',+ disabled: 'Rule disabled',+ },+ errors: {+ invalid: 'Check the rule: some values are missing or no longer available in this project',+ forbidden: 'You don\'t have the permissions this action needs',+ cycle: 'These rules would trigger each other endlessly: {path}',+ limit_reached: 'This project has reached the automation rules limit',+ not_found: 'The rule no longer exists',+ deleteFailed: 'Failed to delete the rule',+ },+ },}diff --git a/web/src/locales/es.ts b/web/src/locales/es.tsindex 51c76b9..35dc897 100644--- a/web/src/locales/es.ts+++ b/web/src/locales/es.ts@@ -101,6 +101,7 @@ export default {graph: 'Gráfico',sprints: 'Sprints',files: 'Archivos',+ automations: 'Automatizaciones',collaboration: 'Colaboración',integrations: 'Integraciones',webhooks: 'Webhooks',@@ -977,6 +978,8 @@ export default {4: 'Tareas',5: 'Sprints',6: 'Organización',+ 7: 'Archivos',+ 8: 'Automatizaciones',},oauth: {consent: {@@ -1544,4 +1547,80 @@ export default {linkFailed: 'No se pudo adjuntar el archivo',},},+ automations: {+ title: 'Automatizaciones',+ noPermission: 'No tienes acceso a las automatizaciones de este proyecto',+ description: 'Reglas que hacen el trabajo rutinario por ti cuando algo ocurre en el proyecto.',+ empty: 'Aún no hay reglas de automatización',+ emptyHint: 'Por ejemplo: cuando una tarea se completa, moverla a la columna «Hecho».',+ create: 'Nueva regla',+ createTitle: 'Nueva regla de automatización',+ editTitle: 'Editar regla de automatización',+ when: 'Cuando',+ then: 'Entonces',+ enabled: 'Activada',+ runsAsHint: 'Las acciones se ejecutan con los permisos de la persona que guardó la regla por última vez.',+ unavailableOption: 'valor eliminado',+ broken: 'No funciona',+ brokenHint: 'Se eliminó una columna, etiqueta o lista seleccionada, por lo que la regla se desactivó. Edítala y elige un nuevo valor.',+ fields: {+ name: 'Nombre',+ namePlaceholder: 'Mover las tareas completadas a «Hecho»',+ module: 'Módulo',+ event: 'Evento',+ action: 'Acción',+ },+ placeholders: {+ module: 'Selecciona un módulo',+ event: 'Selecciona un evento',+ action: 'Selecciona una acción',+ option: 'Selecciona un valor',+ },+ modules: {+ tasks: 'Tareas',+ kanban: 'Kanban',+ lists: 'Listas',+ tags: 'Etiquetas',+ },+ events: {+ task_created: 'Tarea creada',+ task_completed: 'Tarea completada',+ task_reopened: 'Tarea reabierta',+ task_movedToColumn: 'Tarea movida a la columna',+ task_addedToList: 'Tarea añadida a la lista',+ tag_addedToTask: 'Etiqueta añadida a la tarea',+ tag_removedFromTask: 'Etiqueta quitada de la tarea',+ },+ actions: {+ complete: 'Completar la tarea',+ reopen: 'Reabrir la tarea',+ change_status: 'Mover a la columna',+ move_toList: 'Mover a la lista',+ add_tag: 'Añadir etiqueta',+ },+ params: {+ statusId: 'Columna',+ tagId: 'Etiqueta',+ goalListId: 'Lista',+ },+ delete: {+ title: 'Eliminar regla',+ confirm: '¿Eliminar la regla «{name}»? No se puede deshacer.',+ },+ toasts: {+ created: 'Regla creada',+ updated: 'Regla guardada',+ deleted: 'Regla eliminada',+ enabled: 'Regla activada',+ disabled: 'Regla desactivada',+ },+ errors: {+ invalid: 'Revisa la regla: faltan valores o ya no están disponibles en el proyecto',+ forbidden: 'No tienes los permisos que necesita esta acción',+ cycle: 'Estas reglas se activarían entre sí sin fin: {path}',+ limit_reached: 'El proyecto alcanzó el límite de reglas de automatización',+ not_found: 'La regla ya no existe',+ deleteFailed: 'No se pudo eliminar la regla',+ },+ },}diff --git a/web/src/locales/pt-br.ts b/web/src/locales/pt-br.tsindex ab602ec..2af5f03 100644--- a/web/src/locales/pt-br.ts+++ b/web/src/locales/pt-br.ts@@ -114,6 +114,7 @@ export default {graph: 'Gráfico',sprints: 'Sprints',files: 'Arquivos',+ automations: 'Automações',collaboration: 'Colaboração',integrations: 'Integrações',webhooks: 'Webhooks',@@ -988,6 +989,8 @@ export default {4: 'Tarefas',5: 'Sprints',6: 'Organização',+ 7: 'Arquivos',+ 8: 'Automações',},oauth: {consent: {@@ -1555,4 +1558,80 @@ export default {linkFailed: 'Não foi possível anexar o arquivo',},},+ automations: {+ title: 'Automações',+ noPermission: 'Você não tem acesso às automações deste projeto',+ description: 'Regras que fazem o trabalho rotineiro por você quando algo acontece no projeto.',+ empty: 'Ainda não há regras de automação',+ emptyHint: 'Por exemplo: quando uma tarefa é concluída, movê-la para a coluna «Concluído».',+ create: 'Nova regra',+ createTitle: 'Nova regra de automação',+ editTitle: 'Editar regra de automação',+ when: 'Quando',+ then: 'Então',+ enabled: 'Ativada',+ runsAsHint: 'As ações são executadas com as permissões de quem salvou a regra por último.',+ unavailableOption: 'valor excluído',+ broken: 'Não funciona',+ brokenHint: 'Uma coluna, tag ou lista selecionada foi excluída, então a regra foi desativada. Edite-a e escolha um novo valor.',+ fields: {+ name: 'Nome',+ namePlaceholder: 'Mover tarefas concluídas para «Concluído»',+ module: 'Módulo',+ event: 'Evento',+ action: 'Ação',+ },+ placeholders: {+ module: 'Selecione um módulo',+ event: 'Selecione um evento',+ action: 'Selecione uma ação',+ option: 'Selecione um valor',+ },+ modules: {+ tasks: 'Tarefas',+ kanban: 'Kanban',+ lists: 'Listas',+ tags: 'Tags',+ },+ events: {+ task_created: 'Tarefa criada',+ task_completed: 'Tarefa concluída',+ task_reopened: 'Tarefa reaberta',+ task_movedToColumn: 'Tarefa movida para a coluna',+ task_addedToList: 'Tarefa adicionada à lista',+ tag_addedToTask: 'Tag adicionada à tarefa',+ tag_removedFromTask: 'Tag removida da tarefa',+ },+ actions: {+ complete: 'Concluir a tarefa',+ reopen: 'Reabrir a tarefa',+ change_status: 'Mover para a coluna',+ move_toList: 'Mover para a lista',+ add_tag: 'Adicionar tag',+ },+ params: {+ statusId: 'Coluna',+ tagId: 'Tag',+ goalListId: 'Lista',+ },+ delete: {+ title: 'Excluir regra',+ confirm: 'Excluir a regra «{name}»? Isso não pode ser desfeito.',+ },+ toasts: {+ created: 'Regra criada',+ updated: 'Regra salva',+ deleted: 'Regra excluída',+ enabled: 'Regra ativada',+ disabled: 'Regra desativada',+ },+ errors: {+ invalid: 'Verifique a regra: faltam valores ou eles não estão mais disponíveis no projeto',+ forbidden: 'Você não tem as permissões que esta ação exige',+ cycle: 'Estas regras disparariam umas às outras sem fim: {path}',+ limit_reached: 'O projeto atingiu o limite de regras de automação',+ not_found: 'A regra não existe mais',+ deleteFailed: 'Não foi possível excluir a regra',+ },+ },}diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.tsindex 97fc907..fa812b8 100644--- a/web/src/locales/ru.ts+++ b/web/src/locales/ru.ts@@ -115,6 +115,7 @@ export default {graph: 'Граф',sprints: 'Спринты',files: 'Файлы',+ automations: 'Автоматизации',collaboration: 'Совместная работа',integrations: 'Интеграции',webhooks: 'Вебхуки',@@ -972,6 +973,8 @@ export default {4: 'Задачи',5: 'Спринты',6: 'Организация',+ 7: 'Файлы',+ 8: 'Автоматизации',},oauth: {consent: {@@ -1493,4 +1496,80 @@ export default {linkFailed: 'Не удалось прикрепить файл',},},+ automations: {+ title: 'Автоматизации',+ noPermission: 'У вас нет доступа к автоматизациям этого проекта',+ description: 'Правила, которые сами выполняют рутинную работу, когда в проекте что-то происходит.',+ empty: 'Правил автоматизации пока нет',+ emptyHint: 'Например: когда задача завершена, переместить её в колонку «Готово».',+ create: 'Новое правило',+ createTitle: 'Новое правило автоматизации',+ editTitle: 'Редактирование правила',+ when: 'Когда',+ then: 'Тогда',+ enabled: 'Включено',+ runsAsHint: 'Действия выполняются с правами того, кто последним сохранил правило.',+ unavailableOption: 'удалённое значение',+ broken: 'Не работает',+ brokenHint: 'Выбранная колонка, тег или список удалены, поэтому правило выключено. Отредактируйте его и выберите новое значение.',+ fields: {+ name: 'Название',+ namePlaceholder: 'Переносить завершённые задачи в «Готово»',+ module: 'Модуль',+ event: 'Событие',+ action: 'Действие',+ },+ placeholders: {+ module: 'Выберите модуль',+ event: 'Выберите событие',+ action: 'Выберите действие',+ option: 'Выберите значение',+ },+ modules: {+ tasks: 'Задачи',+ kanban: 'Канбан',+ lists: 'Списки',+ tags: 'Теги',+ },+ events: {+ task_created: 'Задача создана',+ task_completed: 'Задача завершена',+ task_reopened: 'Задача переоткрыта',+ task_movedToColumn: 'Задача перемещена в колонку',+ task_addedToList: 'Задача добавлена в список',+ tag_addedToTask: 'Тег добавлен к задаче',+ tag_removedFromTask: 'Тег снят с задачи',+ },+ actions: {+ complete: 'Завершить задачу',+ reopen: 'Переоткрыть задачу',+ change_status: 'Переместить в колонку',+ move_toList: 'Переместить в список',+ add_tag: 'Добавить тег',+ },+ params: {+ statusId: 'Колонка',+ tagId: 'Тег',+ goalListId: 'Список',+ },+ delete: {+ title: 'Удаление правила',+ confirm: 'Удалить правило «{name}»? Это действие нельзя отменить.',+ },+ toasts: {+ created: 'Правило создано',+ updated: 'Правило сохранено',+ deleted: 'Правило удалено',+ enabled: 'Правило включено',+ disabled: 'Правило выключено',+ },+ errors: {+ invalid: 'Проверьте правило: не все значения заполнены или они больше не доступны в проекте',+ forbidden: 'У вас нет прав, которые нужны для этого действия',+ cycle: 'Эти правила будут бесконечно запускать друг друга: {path}',+ limit_reached: 'В проекте достигнут лимит правил автоматизации',+ not_found: 'Правило больше не существует',+ deleteFailed: 'Не удалось удалить правило',+ },+ },}diff --git a/web/src/pages/user/automations.vue b/web/src/pages/user/automations.vuenew file mode 100644index 0000000..b1f3fed--- /dev/null+++ b/web/src/pages/user/automations.vue@@ -0,0 +1,52 @@+<template>+ <UDashboardPanel id="automations">+ <template #header>+ <UDashboardNavbar :title="`${projectName} - ${t('automations.title')}`">+ <template #leading>+ <TvCollapseSidebarDesktop />+ </template>+ </UDashboardNavbar>+ </template>++ <template #body>+ <div+ v-if="!canViewAutomations"+ class="flex flex-col items-center gap-2 px-4 py-16 text-center"+ >+ <UIcon+ name="i-lucide-lock"+ class="size-8 text-dimmed"+ />+ <p class="text-muted">+ {{ t('automations.noPermission') }}+ </p>+ </div>+ <AutomationsProjectTab+ v-else+ :goal-id="projectId"+ :can-manage="canManageAutomations"+ />+ </template>+ </UDashboardPanel>+</template>++<script setup lang="ts">+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import TvCollapseSidebarDesktop from '@/components/features/base/TvCollapseSidebarDesktop.vue'+import AutomationsProjectTab from '@/components/features/automations/AutomationsProjectTab.vue'+import { useAppRouteInfo } from '@/composables/useAppRouteInfo'+import { useProjectDataLoader } from '@/composables/useProjectDataLoader'+import { useGoalsStore } from '@/stores/goals.store'+import { useGoalPermissionsFor } from '@/composables/useGoalPermissions'++const { t } = useI18n()+const { projectId } = useAppRouteInfo()+const goalsStore = useGoalsStore()++useProjectDataLoader(projectId)++const projectName = computed(() => goalsStore.goalMap.get(projectId.value)?.name ?? '')+const goal = computed(() => goalsStore.goalMap.get(projectId.value) ?? null)+const { canViewAutomations, canManageAutomations } = useGoalPermissionsFor(goal)+</script>diff --git a/web/src/stores/automations.store.ts b/web/src/stores/automations.store.tsnew file mode 100644index 0000000..e7f91aa--- /dev/null+++ b/web/src/stores/automations.store.ts@@ -0,0 +1,97 @@+import { defineStore } from 'pinia'+import { isAxiosError } from 'axios'+import type { AutomationApiError, AutomationOption, AutomationRule } from 'taskview-api'+import { $tvApi } from '@/plugins/axios'+import { logError } from '@/helpers/Helper'+import type {+ AutomationFetchOptionsArgs,+ AutomationSaveResult,+ AutomationSaveRuleArgs,+ AutomationsStoreState,+ AutomationToggleRuleArgs,+} from '@/types/automations.types'++function toApiError(err: unknown): AutomationApiError {+ if (isAxiosError(err) && err.response?.data?.code) return err.response.data as AutomationApiError+ return { code: 'invalid', message: null }+}++export const useAutomationsStore = defineStore('automations', {+ state: (): AutomationsStoreState => ({+ catalog: null,+ rulesByGoal: {},+ optionsByGoal: {},+ loadingGoals: {},+ }),+ getters: {+ rulesFor: (state) => (goalId: number): AutomationRule[] => state.rulesByGoal[goalId] ?? [],+ },+ actions: {+ async fetchCatalog(): Promise<void> {+ if (this.catalog) return+ const catalog = await $tvApi.automations.getCatalog().catch(logError)+ if (catalog) this.catalog = catalog+ },++ async fetchRules(goalId: number): Promise<void> {+ this.loadingGoals[goalId] = true+ const rules = await $tvApi.automations+ .listRules(goalId)+ .catch(logError)+ .finally(() => {+ this.loadingGoals[goalId] = false+ })+ if (rules) this.rulesByGoal[goalId] = rules+ },++ async fetchOptions(args: AutomationFetchOptionsArgs): Promise<AutomationOption[]> {+ const options = await $tvApi.automations.getOptions(args).catch(logError)+ if (!options) return this.optionsByGoal[args.goalId]?.[args.source] ?? []+ this.optionsByGoal[args.goalId] = { ...this.optionsByGoal[args.goalId], [args.source]: options }+ return options+ },++ async saveRule(args: AutomationSaveRuleArgs): Promise<AutomationSaveResult> {+ const { value } = args+ const body = {+ name: value.name.trim(),+ trigger: { module: value.triggerModule, event: value.triggerEvent, params: value.triggerParams },+ action: { module: value.actionModule, action: value.actionName, params: value.actionParams },+ }+ try {+ const rule = args.ruleId === null+ ? await $tvApi.automations.createRule({ goalId: args.goalId, ...body })+ : await $tvApi.automations.updateRule({ ruleId: args.ruleId, ...body })+ this.upsertRule(rule)+ return { ok: true, rule }+ } catch (err) {+ return { ok: false, error: toApiError(err) }+ }+ },++ async toggleRule(args: AutomationToggleRuleArgs): Promise<AutomationSaveResult> {+ try {+ const rule = await $tvApi.automations.updateRule({ ruleId: args.rule.id, enabled: args.enabled })+ this.upsertRule(rule)+ return { ok: true, rule }+ } catch (err) {+ return { ok: false, error: toApiError(err) }+ }+ },++ async deleteRule(rule: AutomationRule): Promise<boolean> {+ const deleted = await $tvApi.automations.deleteRule(rule.id).catch(logError)+ if (!deleted) return false+ this.rulesByGoal[rule.goalId] = this.rulesFor(rule.goalId).filter((item) => item.id !== rule.id)+ return true+ },++ upsertRule(rule: AutomationRule) {+ const rules = this.rulesFor(rule.goalId)+ const index = rules.findIndex((item) => item.id === rule.id)+ this.rulesByGoal[rule.goalId] = index === -1+ ? [...rules, rule]+ : rules.map((item) => (item.id === rule.id ? rule : item))+ },+ },+})diff --git a/web/src/stores/base-screen.store.ts b/web/src/stores/base-screen.store.tsindex ae6084c..6df0760 100644--- a/web/src/stores/base-screen.store.ts+++ b/web/src/stores/base-screen.store.ts@@ -227,6 +227,11 @@ export const useBaseScreenStore = defineStore('base-screen-store', {}},+ hasTask(taskId: number): boolean {+ const lists = ['tasks', 'tasksToday', 'tasksUpcoming', 'tasksLastCompleted'] as const+ return lists.some((list) => this[list].some((task) => task.id === taskId))+ },+removeTask(taskId: number) {const lists = ['tasks', 'tasksToday', 'tasksUpcoming', 'tasksLastCompleted'] as constfor (const list of lists) {diff --git a/web/src/stores/graph.store.ts b/web/src/stores/graph.store.tsindex 9dfe492..4e63610 100644--- a/web/src/stores/graph.store.ts+++ b/web/src/stores/graph.store.ts@@ -87,6 +87,11 @@ export const useGraphStore = defineStore('use-graph-store', {this.edges = [...edges]},+ hasTask(taskId: number): boolean {+ const nodeId = taskId.toString()+ return this.allNodes.some((node) => node.id === nodeId)+ },+removeTask(taskId: number) {const nodeId = taskId.toString()this.allNodes = this.allNodes.filter((n) => n.id !== nodeId)diff --git a/web/src/stores/kanban.store.ts b/web/src/stores/kanban.store.tsindex cf71d15..2c1e546 100644--- a/web/src/stores/kanban.store.ts+++ b/web/src/stores/kanban.store.ts@@ -4,6 +4,7 @@ import { DEFAULT_ID } from '@/types/app.types'import type { KanbanStoreState } from '@/types/kanban.types'import { $tvApi } from '@/plugins/axios'import { TaskItem } from '@/types/tasks.types'+import { hasActiveFilters } from '@/helpers/Helper'export const useKanbanStore = defineStore('kanban', {state(): KanbanStoreState {@@ -40,7 +41,8 @@ export const useKanbanStore = defineStore('kanban', {// if (cursor === null) {// this.tasksData[columnId ?? DEFAULT_ID]!.tasks = result.tasks// } else {- this.tasksData[columnId ?? DEFAULT_ID]!.tasks.push(...result.tasks)+ // A task can already be on the board when a real-time insert lands while the page is in flight+ this.tasksData[columnId ?? DEFAULT_ID]!.tasks.push(...result.tasks.filter((task) => !this.hasTask(task.id)))// }this.tasksData[columnId ?? DEFAULT_ID]!.nextCursor = result.nextCursorthis.tasksData[columnId ?? DEFAULT_ID]!.columnVersion = result.columnVersion@@ -90,6 +92,8 @@ export const useKanbanStore = defineStore('kanban', {return}+ // The real-time insert of this task may have landed before the response+ if (this.hasTask(result.id)) returnthis.tasksData[taskArg.statusId ?? DEFAULT_ID]?.tasks.unshift(result)},@@ -156,6 +160,17 @@ export const useKanbanStore = defineStore('kanban', {}},+ hasTask(taskId: number): boolean {+ return Object.values(this.tasksData).some((column) => column?.tasks.some((task) => task.id === taskId))+ },++ insertTask(task: TaskItem) {+ if (this.goalId !== task.goalId || task.parentId || hasActiveFilters(this.filters)) return+ const column = this.tasksData[task.statusId ?? DEFAULT_ID]+ if (!column || this.hasTask(task.id)) return+ column.tasks.unshift(task)+ },+removeTask(taskId: number) {for (const columnId of Object.keys(this.tasksData)) {const column = this.tasksData[Number(columnId)]diff --git a/web/src/stores/tasks.store.ts b/web/src/stores/tasks.store.tsindex b5c5a00..0d1c868 100644--- a/web/src/stores/tasks.store.ts+++ b/web/src/stores/tasks.store.ts@@ -18,9 +18,9 @@ import {} from 'taskview-api'import { $tvApi } from '@/plugins/axios'import { DEFAULT_ID } from '@/types/app.types'-import { type TasksStoreState } from '@/types/tasks.types'+import { type TasksApplyRemoteArgs, type TasksStoreState } from '@/types/tasks.types'import { useTagsStore } from './tag.store'-import { isNotNullable, logError } from '@/helpers/Helper'+import { hasActiveFilters, isNotNullable, logError } from '@/helpers/Helper'export const useTasksStore = defineStore('tasks', {state(): TasksStoreState {@@ -642,6 +642,43 @@ export const useTasksStore = defineStore('tasks', {this.insertRecurrenceInstance(task)},+ findLoadedTask(taskId: number): Task | null {+ for (const task of this.tasks) {+ if (task.id === taskId) return task+ const subtask = task.subtasks.find(({ id }) => id === taskId)+ if (subtask) return subtask+ }+ return null+ },++ isInCurrentView(task: Task): boolean {+ const rules = this.fetchRules+ if (Number(rules.goalId) !== task.goalId) return false+ if (rules.searchText || hasActiveFilters(rules.filters)) return false+ if (!rules.showCompleted && task.complete) return false+ const listId = Number(rules.currentListId)+ return listId === ALL_TASKS_LIST_ID || listId === DEFAULT_ID || listId === task.goalListId+ },++ applyRemoteTask(args: TasksApplyRemoteArgs) {+ const { task } = args+ this.updateSelectedTask(task)++ const local = this.findLoadedTask(task.id)+ if (local) {+ Object.assign(local, task)+ return+ }+ if (!args.created) return++ if (task.parentId) {+ const parent = this.findLoadedTask(task.parentId)+ if (parent && !parent.subtasks.some(({ id }) => id === task.id)) parent.subtasks.push(task)+ return+ }+ if (this.isInCurrentView(task)) this.insertRecurrenceInstance(task)+ },+insertRecurrenceInstance(task: Task) {if (this.tasks.some(({ id }) => id === task.id)) returnif (Number(this.fetchRules.goalId) !== task.goalId) returndiff --git a/web/src/types/automations.types.ts b/web/src/types/automations.types.tsnew file mode 100644index 0000000..a0f1835--- /dev/null+++ b/web/src/types/automations.types.ts@@ -0,0 +1,74 @@+import type {+ AutomationApiError,+ AutomationCatalog,+ AutomationDataSourceName,+ AutomationOption,+ AutomationParamDefinition,+ AutomationParams,+ AutomationRule,+} from 'taskview-api'++export type AutomationsStoreState = {+ catalog: AutomationCatalog | null+ rulesByGoal: Record<number, AutomationRule[]>+ optionsByGoal: Record<number, Partial<Record<AutomationDataSourceName, AutomationOption[]>>>+ loadingGoals: Record<number, boolean>+}++export type AutomationRuleFormValue = {+ name: string+ triggerModule: string+ triggerEvent: string+ triggerParams: AutomationParams+ actionModule: string+ actionName: string+ actionParams: AutomationParams+}++export type AutomationSaveResult =+ | { ok: true, rule: AutomationRule }+ | { ok: false, error: AutomationApiError }++export type AutomationFetchOptionsArgs = {+ goalId: number+ source: AutomationDataSourceName+}++export type AutomationSaveRuleArgs = {+ goalId: number+ ruleId: number | null+ value: AutomationRuleFormValue+}++export type AutomationToggleRuleArgs = {+ rule: AutomationRule+ enabled: boolean+}++export type AutomationOptionLabelArgs = {+ goalId: number+ source: AutomationDataSourceName+ id: number+}++export type AutomationSetParamArgs = {+ key: string+ value: number | undefined+}++export type AutomationHasParamsArgs = {+ definitions: AutomationParamDefinition[] | undefined+ params: AutomationParams+}++export type AutomationStepDescription = {+ module: string+ label: string+ definitions: AutomationParamDefinition[]+ params: AutomationParams+}++export type AutomationSelectItem = {+ label: string+ value: string+}diff --git a/web/src/types/collaboration-permissions.types.ts b/web/src/types/collaboration-permissions.types.tsindex b5a69e0..36bd214 100644--- a/web/src/types/collaboration-permissions.types.ts+++ b/web/src/types/collaboration-permissions.types.ts@@ -1,7 +1,7 @@import type { CollaborationPermission } from 'taskview-api'import type { TI18nLocalesInApp } from './app.types'-export type PermissioinGroupsIds = 1 | 2 | 3 | 4 | 5;+export type PermissioinGroupsIds = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;export const PermissionGroups: Record<PermissioinGroupsIds, Record<keyof TI18nLocalesInApp, string>> = {1: { en: 'Applicarion level', ru: 'Уровня приложения' },@@ -9,6 +9,9 @@ export const PermissionGroups: Record<PermissioinGroupsIds, Record<keyof TI18nLo3: { en: 'Task list', ru: 'Список задач' },4: { en: 'Tasks', ru: 'Задачи' },5: { en: 'Sprints', ru: 'Спринты' },+ 6: { en: 'Organization', ru: 'Организация' },+ 7: { en: 'Files', ru: 'Файлы' },+ 8: { en: 'Automations', ru: 'Автоматизации' },}export type CollaborationPermissionsState = {diff --git a/web/src/types/tasks.types.ts b/web/src/types/tasks.types.tsindex 35228be..5a8f2c9 100644--- a/web/src/types/tasks.types.ts+++ b/web/src/types/tasks.types.ts@@ -4,6 +4,11 @@ export type TaskItem = Task;export type TaskItems = TaskItem[];+export type TasksApplyRemoteArgs = {+ task: Task;+ created: boolean;+};+export type PartialSome<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;export type PartialFetchRules = PartialSome<TasksStoreState['fetchRules'], 'currentPage' | 'endOfTasks'>;