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: recur tasks
Nikolai Giman76b38b8ac1bc
diff --git a/api/package.json b/api/package.jsonindex 6766820..c28886a 100644--- a/api/package.json+++ b/api/package.json@@ -24,6 +24,7 @@"@types/cors": "^2.8.17","@types/express": "^4.17.21","@types/jsonwebtoken": "^9.0.7",+ "@types/luxon": "^3.7.1","@types/node": "^22.10.3","@types/passport-apple": "^2.0.3","@types/pg": "^8.15.5",@@ -61,6 +62,7 @@"firebase-admin": "^12.7.0","helmet": "^7.1.0","jsonwebtoken": "^9.0.2",+ "luxon": "^3.7.2","openid-client": "^6.8.2","passport": "^0.7.0","passport-apple": "^2.0.2",@@ -70,6 +72,7 @@"pg-boss": "^12.14.0","pino": "^9.4.0","rotating-file-stream": "^3.2.5",+ "rrule": "^2.8.1","semver": "^7.6.3","taskview-api": "workspace:^","taskview-db-schemas": "workspace:^",diff --git a/api/src/core/AppUser.ts b/api/src/core/AppUser.tsindex d952207..b672206 100644--- a/api/src/core/AppUser.ts+++ b/api/src/core/AppUser.ts@@ -16,6 +16,7 @@ import { TasksManager } from '../tv-modules/tasks/TasksManager';import { TimeTrackingManager } from '../tv-modules/time-tracking/TimeTrackingManager';import { UiPreferencesManager } from '../tv-modules/ui-preferences/UiPreferencesManager';import { SprintsManager } from '../tv-modules/sprints/SprintsManager';+import { RecurrenceManager } from '../tv-modules/recurrence/RecurrenceManager';import type { UserDbRecord, UserJwtPayload } from '../types/auth.types';import { GoalPermissionsFetcher } from './GoalPermissionsFetcher';@@ -45,6 +46,7 @@ export class AppUser {public readonly timeTrackingManager: TimeTrackingManager;public readonly uiPreferencesManager: UiPreferencesManager;public readonly sprintsManager: SprintsManager;+ public readonly recurrenceManager: RecurrenceManager;constructor(userData?: UserJwtPayload) {this.userData = userData;@@ -67,6 +69,7 @@ export class AppUser {this.timeTrackingManager = new TimeTrackingManager(this);this.uiPreferencesManager = new UiPreferencesManager(this);this.sprintsManager = new SprintsManager(this);+ this.recurrenceManager = new RecurrenceManager(this);}getTokenId(): number | undefined {diff --git a/api/src/core/EventBus.ts b/api/src/core/EventBus.tsindex 47aef33..ab0010f 100644--- a/api/src/core/EventBus.ts+++ b/api/src/core/EventBus.ts@@ -1,5 +1,5 @@import { EventEmitter } from 'node:events';-import type { SprintsSchemaTypeForSelect, TasksSchemaTypeForSelect } from 'taskview-db-schemas';+import type { RecurrenceRulesSchemaTypeForSelect, SprintsSchemaTypeForSelect, TasksSchemaTypeForSelect } from 'taskview-db-schemas';import type { TimeEntryWithUser } from '../tv-modules/time-tracking/types';import { $logger } from '../modules/logget';@@ -31,6 +31,13 @@ export interface AppEvents {goalId: number;initiatorId: number;};+ 'recurrence.created': { rule: RecurrenceRulesSchemaTypeForSelect; initiatorId: number };+ 'recurrence.updated': { rule: RecurrenceRulesSchemaTypeForSelect; changes: Record<string, unknown>; initiatorId: number };+ 'recurrence.paused': { ruleId: number; goalId: number; initiatorId: number };+ 'recurrence.resumed': { ruleId: number; goalId: number; initiatorId: number };+ '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 };}type EventName = keyof AppEvents;diff --git a/api/src/core/all-events.ts b/api/src/core/all-events.tsindex 74a9241..cf4f532 100644--- a/api/src/core/all-events.ts+++ b/api/src/core/all-events.ts@@ -5,6 +5,7 @@ import { RealtimeDispatcher } from '../tv-modules/realtime/RealtimeDispatcher';import { WebhooksDispatcher } from '../tv-modules/webhooks/WebhooksDispatcher';import { TimeTrackingDispatcher } from '../tv-modules/time-tracking/TimeTrackingDispatcher';import { SprintsDispatcher } from '../tv-modules/sprints/SprintsDispatcher';+import { RecurrenceDispatcher } from '../tv-modules/recurrence/RecurrenceDispatcher';const dispatchers: Dispatcher[] = [new NotificationDispatcher(),@@ -12,6 +13,7 @@ const dispatchers: Dispatcher[] = [new WebhooksDispatcher(),new TimeTrackingDispatcher(),new SprintsDispatcher(),+ new RecurrenceDispatcher(),];export function registerAllEventHandlers() {diff --git a/api/src/migrations/taskview/migrate.json b/api/src/migrations/taskview/migrate.jsonindex 9c7ab26..26cb972 100644--- a/api/src/migrations/taskview/migrate.json+++ b/api/src/migrations/taskview/migrate.json@@ -600,5 +600,23 @@"Added tasks.sprint_task_outcomes.estimate_value — story-points snapshot captured at sprint close so a closed sprint's velocity is frozen (unaffected by later estimate edits or moving the task to another sprint).","Added tasks.sprint_cadence — per-project sprint auto-generation config (Linear-style): enabled, length_days, start_date anchor, lookahead, name_template, last_generated_date. A background job keeps current + lookahead future sprints created."]+ },+ "47": {+ "version": "1.54.0",+ "name": "Release 1.54.0",+ "releaseDate": "20260605",+ "scripts": [+ "/1.54.0/0.create-recurrence-rules.sql",+ "/1.54.0/1.create-recurrence-skip-dates.sql",+ "/1.54.0/2.create-recurrence-template-assignees.sql",+ "/1.54.0/3.create-recurrence-template-tags.sql",+ "/1.54.0/4.alter-tasks-add-recurrence.sql"+ ],+ "description": [+ "Recurring tasks (lazy materialization, Todoist-like UX). tasks.recurrence_rules: one row per series — RFC 5545 RRULE string, floating wall-clock dtstart, IANA timezone, state active/paused/ended, last_instance_date + instances_created drive next-occurrence computation. Template snapshot columns (description/note/priority/status/list/duration) let the series outlive its origin task.",+ "tasks.recurrence_skip_dates: per-rule skipped occurrence dates. tasks.recurrence_template_assignees / recurrence_template_tags: snapshot of assignees (collaboration.users) and tags copied onto each materialized instance.",+ "Extended tasks.tasks with recurrence_rule_id (FK SET NULL — instances survive rule deletion) and recurrence_instance_date. Partial unique index on (recurrence_rule_id, recurrence_instance_date) makes instance materialization idempotent under concurrent triggers/reconciliation.",+ "Exactly one open instance per series exists at any time: completing it materializes the next occurrence (event-driven, O(1)); a nightly pg-boss reconcile job re-creates the open instance only for series stalled by a crash. No new permissions — recurrence editing is gated by existing task_can_edit_deadline."+ ]}}\ No newline at end of filediff --git a/api/src/migrations/taskview/sql/1.54.0/0.create-recurrence-rules.sql b/api/src/migrations/taskview/sql/1.54.0/0.create-recurrence-rules.sqlnew file mode 100644index 0000000..81d2f63--- /dev/null+++ b/api/src/migrations/taskview/sql/1.54.0/0.create-recurrence-rules.sql@@ -0,0 +1,25 @@+CREATE TABLE IF NOT EXISTS tasks.recurrence_rules (+ id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,+ goal_id INTEGER NOT NULL REFERENCES tasks.goals(id) ON DELETE CASCADE,+ template_task_id INTEGER REFERENCES tasks.tasks(id) ON DELETE SET NULL,+ template_description VARCHAR(2000),+ template_note VARCHAR(2000),+ template_priority_id INTEGER,+ template_status_id INTEGER,+ template_goal_list_id INTEGER,+ template_duration_minutes INTEGER,+ rrule TEXT NOT NULL,+ dtstart TIMESTAMP NOT NULL,+ timezone VARCHAR(50) NOT NULL,+ state VARCHAR(20) NOT NULL DEFAULT 'active',+ last_instance_date DATE NOT NULL,+ instances_created INTEGER NOT NULL DEFAULT 1,+ notify_on_occurrence BOOLEAN NOT NULL DEFAULT FALSE,+ creator_id INTEGER NOT NULL REFERENCES tv_auth.users(id) ON DELETE CASCADE,+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),+ edited_at TIMESTAMP NOT NULL DEFAULT NOW(),+ CONSTRAINT recurrence_state_valid CHECK (state IN ('active', 'paused', 'ended'))+);++CREATE INDEX IF NOT EXISTS idx_recurrence_rules_goal ON tasks.recurrence_rules(goal_id);+CREATE INDEX IF NOT EXISTS idx_recurrence_rules_active ON tasks.recurrence_rules(id) WHERE state = 'active';diff --git a/api/src/migrations/taskview/sql/1.54.0/1.create-recurrence-skip-dates.sql b/api/src/migrations/taskview/sql/1.54.0/1.create-recurrence-skip-dates.sqlnew file mode 100644index 0000000..74e25db--- /dev/null+++ b/api/src/migrations/taskview/sql/1.54.0/1.create-recurrence-skip-dates.sql@@ -0,0 +1,6 @@+CREATE TABLE IF NOT EXISTS tasks.recurrence_skip_dates (+ rule_id INTEGER NOT NULL REFERENCES tasks.recurrence_rules(id) ON DELETE CASCADE,+ skip_date DATE NOT NULL,+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),+ PRIMARY KEY (rule_id, skip_date)+);diff --git a/api/src/migrations/taskview/sql/1.54.0/2.create-recurrence-template-assignees.sql b/api/src/migrations/taskview/sql/1.54.0/2.create-recurrence-template-assignees.sqlnew file mode 100644index 0000000..3c2682d--- /dev/null+++ b/api/src/migrations/taskview/sql/1.54.0/2.create-recurrence-template-assignees.sql@@ -0,0 +1,5 @@+CREATE TABLE IF NOT EXISTS tasks.recurrence_template_assignees (+ rule_id INTEGER NOT NULL REFERENCES tasks.recurrence_rules(id) ON DELETE CASCADE,+ collab_user_id INTEGER NOT NULL REFERENCES collaboration.users(id) ON DELETE CASCADE,+ PRIMARY KEY (rule_id, collab_user_id)+);diff --git a/api/src/migrations/taskview/sql/1.54.0/3.create-recurrence-template-tags.sql b/api/src/migrations/taskview/sql/1.54.0/3.create-recurrence-template-tags.sqlnew file mode 100644index 0000000..a1ad7ab--- /dev/null+++ b/api/src/migrations/taskview/sql/1.54.0/3.create-recurrence-template-tags.sql@@ -0,0 +1,5 @@+CREATE TABLE IF NOT EXISTS tasks.recurrence_template_tags (+ rule_id INTEGER NOT NULL REFERENCES tasks.recurrence_rules(id) ON DELETE CASCADE,+ tag_id INTEGER NOT NULL REFERENCES tasks.tags(id) ON DELETE CASCADE,+ PRIMARY KEY (rule_id, tag_id)+);diff --git a/api/src/migrations/taskview/sql/1.54.0/4.alter-tasks-add-recurrence.sql b/api/src/migrations/taskview/sql/1.54.0/4.alter-tasks-add-recurrence.sqlnew file mode 100644index 0000000..0deeeb3--- /dev/null+++ b/api/src/migrations/taskview/sql/1.54.0/4.alter-tasks-add-recurrence.sql@@ -0,0 +1,11 @@+ALTER TABLE tasks.tasks+ ADD COLUMN IF NOT EXISTS recurrence_rule_id INTEGER REFERENCES tasks.recurrence_rules(id) ON DELETE SET NULL,+ ADD COLUMN IF NOT EXISTS recurrence_instance_date DATE;++CREATE UNIQUE INDEX IF NOT EXISTS uniq_tasks_recurrence_instance+ ON tasks.tasks(recurrence_rule_id, recurrence_instance_date)+ WHERE recurrence_rule_id IS NOT NULL;++CREATE INDEX IF NOT EXISTS idx_tasks_recurrence_rule_id+ ON tasks.tasks(recurrence_rule_id)+ WHERE recurrence_rule_id IS NOT NULL;diff --git a/api/src/routes/index.ts b/api/src/routes/index.tsindex 3dcb145..b2b3c62 100644--- a/api/src/routes/index.ts+++ b/api/src/routes/index.ts@@ -20,6 +20,7 @@ import AnalyticsRoutes from '../tv-modules/analytics/AnalyticsRoutes';import TimeTrackingRoutes from '../tv-modules/time-tracking/TimeTrackingRoutes';import UiPreferencesRoutes from '../tv-modules/ui-preferences/UiPreferencesRoutes';import SprintsRoutes from '../tv-modules/sprints/SprintsRoutes';+import RecurrenceRoutes from '../tv-modules/recurrence/RecurrenceRoutes';import type { Routable } from '../types/routable.type';type RoutableConstructor = new (...args: any[]) => Routable;@@ -46,6 +47,7 @@ const routes: Record<string, RoutableConstructor> = {'/module/time-tracking': TimeTrackingRoutes,'/module/ui-preferences': UiPreferencesRoutes,'/module/sprints': SprintsRoutes,+ '/module/recurrence': RecurrenceRoutes,'/scim/v2': ScimRoutes,};diff --git a/api/src/tv-modules/notifications/NotificationDispatcher.ts b/api/src/tv-modules/notifications/NotificationDispatcher.tsindex f362a66..700c8eb 100644--- a/api/src/tv-modules/notifications/NotificationDispatcher.ts+++ b/api/src/tv-modules/notifications/NotificationDispatcher.ts@@ -10,6 +10,7 @@ import { NotificationMessages } from './NotificationMessages';import { NotificationsRepository } from './repositories/NotificationsRepository';import { DeviceTokensRepository } from './repositories/DeviceTokensRepository';import { DeadlineScheduler } from './schedulers/DeadlineScheduler';+import { RecurrenceRepository } from '../recurrence/RecurrenceRepository';import { NotificationType } from './types';import { parseUtcTime } from './utils';import type { Dispatcher } from '../../core/Dispatcher';@@ -44,9 +45,14 @@ export class NotificationDispatcher implements Dispatcher {}private async onTaskCreated(data: AppEvents['task.created']): Promise<void> {- if (data.task.endDate) {- await this.deadlineScheduler.schedule(data.task, data.initiatorId);+ if (!data.task.endDate) return;+ // Recurring instances remind about their deadline only when the series+ // opted in — otherwise a daily series becomes a daily notification.+ if (data.task.recurrenceRuleId) {+ const rule = await new RecurrenceRepository().getById(data.task.recurrenceRuleId);+ if (rule && !rule.notifyOnOccurrence) return;}+ await this.deadlineScheduler.schedule(data.task, data.initiatorId);}private async onTaskUpdated(data: AppEvents['task.updated']): Promise<void> {diff --git a/api/src/tv-modules/recurrence/RecurrenceController.ts b/api/src/tv-modules/recurrence/RecurrenceController.tsnew file mode 100644index 0000000..e5ab8a3--- /dev/null+++ b/api/src/tv-modules/recurrence/RecurrenceController.ts@@ -0,0 +1,72 @@+import { type } from 'arktype';+import type { Request, Response } from 'express';+import {+ RecurrenceArkTypeCreate,+ RecurrenceArkTypeRuleIdParam,+ RecurrenceArkTypeTaskIdParam,+ RecurrenceArkTypeUpdate,+} from './types';+import type { RecurrenceErrorCode, RecurrenceResult } from './types';++const codeToStatus: Record<RecurrenceErrorCode, number> = {+ not_found: 404,+ conflict: 409,+ invalid_state: 400,+ invalid_rule: 422,+};++export default class RecurrenceController {+ private sendResult<T>(res: Response, result: RecurrenceResult<T>) {+ if (result.ok) return res.tvJson(result.data);+ return res.status(codeToStatus[result.code]).send(result.message ?? result.code);+ }++ create = async (req: Request, res: Response) => {+ const data = RecurrenceArkTypeCreate(req.body);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.recurrenceManager.createRule(data));+ };++ getOne = async (req: Request, res: Response) => {+ const data = RecurrenceArkTypeRuleIdParam(req.params);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.recurrenceManager.getDetails(data.ruleId));+ };++ getForTask = async (req: Request, res: Response) => {+ const data = RecurrenceArkTypeTaskIdParam(req.params);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.recurrenceManager.getDetailsForTask(data.taskId));+ };++ update = async (req: Request, res: Response) => {+ // Route params win over body: the ruleId authorized by the middleware must be the one operated on.+ const data = RecurrenceArkTypeUpdate({ ...req.body, ruleId: Number(req.params.ruleId) });+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.recurrenceManager.updateRule(data));+ };++ pause = async (req: Request, res: Response) => {+ const data = RecurrenceArkTypeRuleIdParam(req.params);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.recurrenceManager.pauseRule(data.ruleId));+ };++ resume = async (req: Request, res: Response) => {+ const data = RecurrenceArkTypeRuleIdParam(req.params);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.recurrenceManager.resumeRule(data.ruleId));+ };++ skip = async (req: Request, res: Response) => {+ const data = RecurrenceArkTypeRuleIdParam(req.params);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.recurrenceManager.skipCurrent(data.ruleId));+ };++ remove = async (req: Request, res: Response) => {+ const data = RecurrenceArkTypeRuleIdParam(req.params);+ if (data instanceof type.errors) return res.status(400).send(data.summary);+ return this.sendResult(res, await req.appUser.recurrenceManager.deleteRule(data.ruleId));+ };+}diff --git a/api/src/tv-modules/recurrence/RecurrenceDispatcher.ts b/api/src/tv-modules/recurrence/RecurrenceDispatcher.tsnew file mode 100644index 0000000..8eda1f0--- /dev/null+++ b/api/src/tv-modules/recurrence/RecurrenceDispatcher.ts@@ -0,0 +1,138 @@+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 { RecurrenceGenerator } from './RecurrenceGenerator';+import { RecurrenceRepository } from './RecurrenceRepository';++export const RECURRENCE_RECONCILE_JOB = 'recurrence-reconcile';+const RECURRENCE_RT_EVENT = 'recurrence.instanceCreated';++export class RecurrenceDispatcher implements Dispatcher {+ private readonly generator = new RecurrenceGenerator();+ private readonly repository = new RecurrenceRepository();++ register(): void {+ // The heart of the lazy model: completing the open instance materializes the next one.+ eventBus.on('task.updated', (data) => this.onTaskUpdated(data));+ // Push the freshly materialized instance to goal members so the next card appears without a refresh.+ eventBus.on('task.created', (data) => this.onTaskCreated(data));+ // An ex-collaborator must not keep being auto-assigned to new instances:+ // project removal deletes users_to_goals, not collaboration.users, so the+ // FK CASCADE on the snapshot never fires — clean it up explicitly.+ eventBus.on('collaboration.userRemoved', (data) => this.onCollaboratorRemoved(data));+ }++ async registerWorkers(): Promise<void> {+ const boss = getJobQueue();+ await boss.createQueue(RECURRENCE_RECONCILE_JOB);+ // Safety net only: re-creates the open instance for series stalled by a+ // crash between the complete commit and the event handler. Normally a no-op.+ await boss.schedule(RECURRENCE_RECONCILE_JOB, '0 3 * * *');+ await boss.work(RECURRENCE_RECONCILE_JOB, async () => {+ const stalled = await this.repository.findStalledActiveRules();+ for (const rule of stalled) {+ await this.generator+ .materializeNext({ ruleId: rule.id, initiatorId: rule.creatorId })+ .catch((e) => $logger.error(e, `[RecurrenceDispatcher] reconcile rule=${rule.id}`));+ }+ if (stalled.length > 0) {+ $logger.info(`[RecurrenceDispatcher] reconcile recovered ${stalled.length} stalled series`);+ }+ });+ }++ private async onTaskUpdated(data: AppEvents['task.updated']): Promise<void> {+ if (!data.task.recurrenceRuleId) return;+ if (data.changes.complete === true) {+ await this.generator.materializeNext({+ ruleId: data.task.recurrenceRuleId,+ initiatorId: data.initiatorId,+ });+ return;+ }+ await this.syncTemplateFromOpenInstance(data);+ }++ /**+ * In the lazy model the open instance IS the series in the user's mind+ * (Todoist mental model): renaming the card must rename future occurrences+ * too, otherwise the next instance "reverts" to the stale snapshot.+ * Completed instances are history and never touch the template.+ */+ private async syncTemplateFromOpenInstance(data: AppEvents['task.updated']): Promise<void> {+ if (data.task.complete) return;++ const patch: Parameters<RecurrenceRepository['patch']>[0]['patch'] = {};+ if (data.changes.description !== undefined && data.task.description !== null) {+ patch.templateDescription = data.task.description;+ }+ if (data.changes.note !== undefined) patch.templateNote = data.task.note;+ if (data.changes.priorityId !== undefined) patch.templatePriorityId = data.task.priorityId;+ if (Object.keys(patch).length === 0) return;++ await this.repository.patch({ ruleId: data.task.recurrenceRuleId as number, patch });+ }++ private async onTaskCreated(data: AppEvents['task.created']): Promise<void> {+ if (!data.task.recurrenceRuleId) return;+ try {+ const memberIds = await this.resolveGoalMemberIds(data.task.goalId);+ if (memberIds.length === 0) return;+ const centrifugo = getCentrifugoClient();+ // The broadcast goes to every goal member, while notes are gated by a+ // separate per-role permission — never put them on the wire here.+ // Clients with note access get it when they open the task.+ const task = { ...data.task, note: null };+ await Promise.all(+ memberIds.map((userId) =>+ centrifugo.publishToUser(userId, RECURRENCE_RT_EVENT, {+ goalId: data.task.goalId,+ ruleId: data.task.recurrenceRuleId,+ task,+ })+ )+ );+ } catch (err) {+ $logger.error(err, '[RecurrenceDispatcher] real-time publish failed');+ }+ }++ private async onCollaboratorRemoved(data: AppEvents['collaboration.userRemoved']): Promise<void> {+ await this.repository.removeTemplateAssigneeFromGoal({+ goalId: data.goalId,+ 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/recurrence/RecurrenceGenerator.ts b/api/src/tv-modules/recurrence/RecurrenceGenerator.tsnew file mode 100644index 0000000..0925c3f--- /dev/null+++ b/api/src/tv-modules/recurrence/RecurrenceGenerator.ts@@ -0,0 +1,251 @@+import { and, asc, eq, ne, sql } from 'drizzle-orm';+import {+ GoalsListSchema,+ RecurrenceRulesSchema,+ type RecurrenceRulesSchemaTypeForSelect,+ RecurrenceSkipDatesSchema,+ RecurrenceTemplateAssigneesSchema,+ RecurrenceTemplateTagsSchema,+ TasksAssigneeSchema,+ TasksSchema,+ type TasksSchemaTypeForSelect,+ TasksStatusesSchema,+ TasksToTagsSchema,+} from 'taskview-db-schemas';+import { eventBus } from '../../core/EventBus';+import { Database } from '../../modules/db';+import { $logger } from '../../modules/logget';+import { TasksRepository } from '../tasks/TasksRepository';+import { RecurrenceParser } from './RecurrenceParser';+import type { MaterializeNextArgs } from './types';++/**+ * Materializes the next instance of a series. The lazy model invariant — at+ * most one open instance per rule — is protected on two levels: the rule row+ * is locked FOR UPDATE for the duration of the transaction (serializes the+ * complete-trigger against the reconcile job and rule edits), and the partial+ * unique index on (recurrence_rule_id, recurrence_instance_date) makes the+ * insert idempotent even across processes.+ */+export class RecurrenceGenerator {+ private readonly db: Database;++ constructor() {+ this.db = Database.getInstance();+ }++ async materializeNext(args: MaterializeNextArgs): Promise<TasksSchemaTypeForSelect | null> {+ const db = this.db.dbDrizzle;++ const outcome = await db+ .transaction(async (tx) => {+ const ruleRows = await tx+ .select()+ .from(RecurrenceRulesSchema)+ .where(eq(RecurrenceRulesSchema.id, args.ruleId))+ .for('update')+ .limit(1);+ const rule = ruleRows[0];+ if (!rule || rule.state !== 'active') return null;++ // Lazy-model invariant: at most one open instance per rule. Without+ // this guard a duplicate trigger (repeated PATCH complete=true, or+ // reconcile racing the event handler) would materialize a SECOND+ // open instance on the next date — the unique index only catches+ // same-date duplicates.+ const openRows = await tx+ .select({ id: TasksSchema.id })+ .from(TasksSchema)+ .where(+ and(+ eq(TasksSchema.recurrenceRuleId, rule.id),+ ne(sql`COALESCE(${TasksSchema.complete}, false)`, sql`true`)+ )+ )+ .limit(1);+ if (openRows[0]) return null;++ // "N materialized instances" cap for COUNT-series.+ const count = RecurrenceParser.getCount(rule.rrule);+ if (count !== null && rule.instancesCreated >= count) {+ await tx+ .update(RecurrenceRulesSchema)+ .set({ state: 'ended', editedAt: new Date() })+ .where(eq(RecurrenceRulesSchema.id, rule.id));+ return { ended: rule } as const;+ }++ const skipRows = await tx+ .select({ skipDate: RecurrenceSkipDatesSchema.skipDate })+ .from(RecurrenceSkipDatesSchema)+ .where(eq(RecurrenceSkipDatesSchema.ruleId, rule.id));+ const skipDates = new Set(skipRows.map((r) => r.skipDate));++ // Completed late → next from today, not a pile of overdue copies (Todoist behavior).+ const today = RecurrenceParser.todayInTimezone(rule.timezone);+ const afterDate = rule.lastInstanceDate > today ? rule.lastInstanceDate : today;+ const nextDate = RecurrenceParser.nextOccurrenceDate({+ rrule: rule.rrule,+ dtstart: rule.dtstart,+ afterDate,+ skipDates,+ });+ if (!nextDate) {+ await tx+ .update(RecurrenceRulesSchema)+ .set({ state: 'ended', editedAt: new Date() })+ .where(eq(RecurrenceRulesSchema.id, rule.id));+ return { ended: rule } as const;+ }++ const insertedRows = await tx+ .insert(TasksSchema)+ .values(await this.buildInstanceValues({ rule, instanceDate: nextDate, tx }))+ .onConflictDoNothing()+ .returning();+ const instance = insertedRows[0];+ // Conflict on (rule_id, instance_date): a concurrent run already materialized it.+ if (!instance) return null;++ const [assignees, tags] = await Promise.all([+ tx+ .select({ collabUserId: RecurrenceTemplateAssigneesSchema.collabUserId })+ .from(RecurrenceTemplateAssigneesSchema)+ .where(eq(RecurrenceTemplateAssigneesSchema.ruleId, rule.id)),+ tx+ .select({ tagId: RecurrenceTemplateTagsSchema.tagId })+ .from(RecurrenceTemplateTagsSchema)+ .where(eq(RecurrenceTemplateTagsSchema.ruleId, rule.id)),+ ]);+ if (assignees.length > 0) {+ await tx+ .insert(TasksAssigneeSchema)+ .values(assignees.map((a) => ({ taskId: instance.id, collabUserId: a.collabUserId })))+ .onConflictDoNothing();+ }+ if (tags.length > 0) {+ await tx+ .insert(TasksToTagsSchema)+ .values(tags.map((t) => ({ taskId: instance.id, tagId: t.tagId })))+ .onConflictDoNothing();+ }++ await tx+ .update(RecurrenceRulesSchema)+ .set({+ lastInstanceDate: nextDate,+ instancesCreated: rule.instancesCreated + 1,+ editedAt: new Date(),+ })+ .where(eq(RecurrenceRulesSchema.id, rule.id));++ return { instance, rule } as const;+ })+ .catch((err) => {+ $logger.error(err, `[RecurrenceGenerator] materializeNext failed rule=${args.ruleId}`);+ return null;+ });++ if (!outcome) return null;++ if ('ended' in outcome) {+ eventBus.emit('recurrence.ended', {+ ruleId: outcome.ended.id,+ goalId: outcome.ended.goalId,+ initiatorId: args.initiatorId,+ });+ return null;+ }++ // Standard event so DeadlineScheduler / webhooks / realtime treat the instance as a normal new task.+ eventBus.emit('task.created', { task: outcome.instance, initiatorId: args.initiatorId });+ return outcome.instance;+ }++ private async buildInstanceValues(args: {+ rule: RecurrenceRulesSchemaTypeForSelect;+ instanceDate: string;+ tx: Parameters<Parameters<Database['dbDrizzle']['transaction']>[0]>[0];+ }): Promise<typeof TasksSchema.$inferInsert> {+ const { rule, instanceDate, tx } = args;++ const statusId = await this.resolveStatusId({ rule, tx });+ const goalListId = await this.resolveGoalListId({ rule, tx });+ const kanbanOrder = await this.nextKanbanOrder({ goalId: rule.goalId, tx });++ // Tasks store UTC instants; the series is anchored to wall-clock time in+ // its timezone, so the instant is recomputed per occurrence (DST-aware).+ const window = RecurrenceParser.instanceWindowUtc({+ occurrenceDate: instanceDate,+ dtstart: rule.dtstart,+ timezone: rule.timezone,+ durationMinutes: rule.templateDurationMinutes,+ });++ return {+ goalId: rule.goalId,+ description: rule.templateDescription ?? '',+ note: rule.templateNote,+ complete: false,+ priorityId: rule.templatePriorityId,+ statusId,+ goalListId,+ creatorId: rule.creatorId,+ kanbanOrder,+ startDate: window.startDate,+ startTime: window.startTime,+ endDate: window.endDate,+ endTime: window.endTime,+ recurrenceRuleId: rule.id,+ recurrenceInstanceDate: instanceDate,+ };+ }++ /** Snapshot kanban column if it still exists, otherwise the first column of the goal. */+ private async resolveStatusId(args: {+ rule: RecurrenceRulesSchemaTypeForSelect;+ tx: Parameters<Parameters<Database['dbDrizzle']['transaction']>[0]>[0];+ }): Promise<number | null> {+ if (args.rule.templateStatusId !== null) {+ const rows = await args.tx+ .select({ id: TasksStatusesSchema.id })+ .from(TasksStatusesSchema)+ .where(and(eq(TasksStatusesSchema.id, args.rule.templateStatusId), eq(TasksStatusesSchema.goalId, args.rule.goalId)))+ .limit(1);+ if (rows[0]) return rows[0].id;+ }+ const fallback = await args.tx+ .select({ id: TasksStatusesSchema.id })+ .from(TasksStatusesSchema)+ .where(eq(TasksStatusesSchema.goalId, args.rule.goalId))+ .orderBy(asc(TasksStatusesSchema.id))+ .limit(1);+ return fallback[0]?.id ?? null;+ }++ /** Snapshot list if it still exists, otherwise no list. */+ private async resolveGoalListId(args: {+ rule: RecurrenceRulesSchemaTypeForSelect;+ tx: Parameters<Parameters<Database['dbDrizzle']['transaction']>[0]>[0];+ }): Promise<number | null> {+ if (args.rule.templateGoalListId === null) return null;+ const rows = await args.tx+ .select({ id: GoalsListSchema.id })+ .from(GoalsListSchema)+ .where(and(eq(GoalsListSchema.id, args.rule.templateGoalListId), eq(GoalsListSchema.goalId, args.rule.goalId)))+ .limit(1);+ return rows[0]?.id ?? null;+ }++ /** Same top-of-board convention as manual creation (getNextKanbanOrder), but inside the transaction. */+ private async nextKanbanOrder(args: {+ goalId: number;+ tx: Parameters<Parameters<Database['dbDrizzle']['transaction']>[0]>[0];+ }): Promise<number> {+ const rows = await args.tx+ .select({ minKanbanOrder: sql<number | null>`MIN(${TasksSchema.kanbanOrder})` })+ .from(TasksSchema)+ .where(eq(TasksSchema.goalId, args.goalId));+ return (rows[0]?.minKanbanOrder ?? 0) - TasksRepository.KANBAN_ORDER_GAP;+ }+}diff --git a/api/src/tv-modules/recurrence/RecurrenceManager.ts b/api/src/tv-modules/recurrence/RecurrenceManager.tsnew file mode 100644index 0000000..a330cc6--- /dev/null+++ b/api/src/tv-modules/recurrence/RecurrenceManager.ts@@ -0,0 +1,260 @@+import type { RecurrenceRulesSchemaTypeForSelect } from 'taskview-db-schemas';+import type { AppUser } from '../../core/AppUser';+import { eventBus } from '../../core/EventBus';+import { GoalPermissions } from '../../types/auth.types';+import { TasksRepository } from '../tasks/TasksRepository';+import { RecurrenceGenerator } from './RecurrenceGenerator';+import { RecurrenceParser } from './RecurrenceParser';+import { RecurrenceRepository } from './RecurrenceRepository';+import type {+ RecurrenceCreateArgs,+ RecurrenceErrorCode,+ RecurrenceResult,+ RecurrenceRuleDetails,+ RecurrenceUpdateArgs,+} from './types';++const ok = <T>(data: T): RecurrenceResult<T> => ({ ok: true, data });+const fail = (code: RecurrenceErrorCode, message?: string): RecurrenceResult<never> => ({ ok: false, code, message });++export class RecurrenceManager {+ private readonly user: AppUser;+ public readonly repository: RecurrenceRepository;+ private readonly generator: RecurrenceGenerator;+ private readonly tasksRepository: TasksRepository;++ constructor(user: AppUser) {+ this.user = user;+ this.repository = new RecurrenceRepository();+ this.generator = new RecurrenceGenerator();+ this.tasksRepository = new TasksRepository();+ }++ private get initiatorId(): number {+ return this.user.getUserData()?.id as number;+ }++ async createRule(args: RecurrenceCreateArgs): Promise<RecurrenceResult<RecurrenceRulesSchemaTypeForSelect>> {+ const task = await this.repository.getTaskById(args.taskId);+ if (!task) return fail('not_found', 'task not found');+ if (task.recurrenceRuleId) return fail('conflict', 'task is already part of a series');+ if (task.parentId) return fail('invalid_state', 'subtasks can not be recurring');+ if (task.complete) return fail('invalid_state', 'completed tasks can not start a series');++ if (!RecurrenceParser.isValidTimezone(args.timezone)) {+ return fail('invalid_rule', 'timezone must be a valid IANA name');+ }++ let dtstart: Date;+ try {+ RecurrenceParser.validateRuleString(args.rrule);+ dtstart = RecurrenceParser.parseDtstart(args.dtstart);+ } catch (err) {+ return fail('invalid_rule', (err as Error).message);+ }++ const originInstanceDate = RecurrenceParser.firstOccurrenceDate({ rrule: args.rrule, dtstart });+ if (!originInstanceDate) return fail('invalid_rule', 'rule produces no occurrences');++ const rule = await this.repository.create({+ goalId: task.goalId,+ templateTaskId: task.id,+ templateDescription: task.description ?? '',+ templateNote: task.note,+ templatePriorityId: task.priorityId,+ templateStatusId: task.statusId,+ templateGoalListId: task.goalListId,+ templateDurationMinutes: this.durationFromTask({+ startDate: task.startDate ?? originInstanceDate,+ startTime: task.startTime,+ endDate: task.endDate,+ endTime: task.endTime,+ }),+ rrule: args.rrule,+ dtstart,+ timezone: args.timezone,+ lastInstanceDate: originInstanceDate,+ notifyOnOccurrence: args.notifyOnOccurrence ?? false,+ creatorId: this.initiatorId,+ });+ if (!rule) return fail('invalid_state', 'could not create rule');++ // The origin task becomes the first (and only open) instance of the series.+ await this.repository.attachTaskToRule({ taskId: task.id, ruleId: rule.id, instanceDate: originInstanceDate });+ // Normalize its window into the same UTC frame future instances will use —+ // otherwise a series created through a non-browser client (MCP, raw API)+ // could leave the origin and its successors in different time frames.+ await this.repository.applyInstanceWindow({+ taskId: task.id,+ window: RecurrenceParser.instanceWindowUtc({+ occurrenceDate: originInstanceDate,+ dtstart,+ timezone: args.timezone,+ durationMinutes: rule.templateDurationMinutes,+ }),+ });++ const [assignees, tags] = await Promise.all([+ this.repository.getTaskAssignees(task.id),+ this.repository.getTaskTags(task.id),+ ]);+ await Promise.all([+ this.repository.setTemplateAssignees({ ruleId: rule.id, collabUserIds: assignees }),+ this.repository.setTemplateTags({ ruleId: rule.id, tagIds: tags }),+ ]);++ eventBus.emit('recurrence.created', { rule, initiatorId: this.initiatorId });+ return ok(rule);+ }++ async getDetails(ruleId: number): Promise<RecurrenceResult<RecurrenceRuleDetails>> {+ const rule = await this.repository.getById(ruleId);+ if (!rule) return fail('not_found');+ const [skipDates, openInstance] = await Promise.all([+ this.repository.getSkipDates(ruleId),+ this.repository.findOpenInstance(ruleId),+ ]);++ // Notes are gated by a separate permission in the task API+ // (cleanTaskFieldsRegardPermissions) — the series endpoints must not+ // become a side door to them.+ const checker = await this.user.permissionsFetcher.getCheckerForGoal(rule.goalId).catch(() => null);+ if (!checker?.hasPermissions(GoalPermissions.TASK_CAN_WATCH_NOTE)) {+ rule.templateNote = null;+ if (openInstance) openInstance.note = null;+ }++ return ok({ rule, skipDates, openInstance });+ }++ async getDetailsForTask(taskId: number): Promise<RecurrenceResult<RecurrenceRuleDetails>> {+ const rule = await this.repository.getByTaskId(taskId);+ if (!rule) return fail('not_found');+ return this.getDetails(rule.id);+ }++ async updateRule(args: RecurrenceUpdateArgs): Promise<RecurrenceResult<RecurrenceRulesSchemaTypeForSelect>> {+ const rule = await this.repository.getById(args.ruleId);+ if (!rule) return fail('not_found');+ if (rule.state === 'ended') return fail('invalid_state', 'ended series are read-only');++ const patch: Parameters<RecurrenceRepository['patch']>[0]['patch'] = {};+ if (args.rrule !== undefined) {+ try {+ RecurrenceParser.validateRuleString(args.rrule);+ } catch (err) {+ return fail('invalid_rule', (err as Error).message);+ }+ patch.rrule = args.rrule;+ }+ if (args.dtstart !== undefined) {+ try {+ patch.dtstart = RecurrenceParser.parseDtstart(args.dtstart);+ } catch (err) {+ return fail('invalid_rule', (err as Error).message);+ }+ }+ if (args.timezone !== undefined) {+ if (!RecurrenceParser.isValidTimezone(args.timezone)) {+ return fail('invalid_rule', 'timezone must be a valid IANA name');+ }+ patch.timezone = args.timezone;+ }+ if (args.notifyOnOccurrence !== undefined) patch.notifyOnOccurrence = args.notifyOnOccurrence;+ if (args.templateOverrides) {+ const o = args.templateOverrides;+ if (o.description !== undefined) patch.templateDescription = o.description;+ if (o.note !== undefined) patch.templateNote = o.note;+ if (o.priorityId !== undefined) patch.templatePriorityId = o.priorityId;+ if (o.statusId !== undefined) patch.templateStatusId = o.statusId;+ if (o.goalListId !== undefined) patch.templateGoalListId = o.goalListId;+ if (o.durationMinutes !== undefined) patch.templateDurationMinutes = o.durationMinutes;+ }+ if (Object.keys(patch).length === 0) return ok(rule);++ const updated = await this.repository.patch({ ruleId: args.ruleId, patch });+ if (!updated) return fail('invalid_state');++ eventBus.emit('recurrence.updated', { rule: updated, changes: patch, initiatorId: this.initiatorId });+ return ok(updated);+ }++ async pauseRule(ruleId: number): Promise<RecurrenceResult<RecurrenceRulesSchemaTypeForSelect>> {+ const rule = await this.repository.getById(ruleId);+ if (!rule) return fail('not_found');+ if (rule.state !== 'active') return fail('invalid_state', `can not pause a ${rule.state} series`);++ const updated = await this.repository.patch({ ruleId, patch: { state: 'paused' } });+ if (!updated) return fail('invalid_state');+ eventBus.emit('recurrence.paused', { ruleId, goalId: rule.goalId, initiatorId: this.initiatorId });+ return ok(updated);+ }++ async resumeRule(ruleId: number): Promise<RecurrenceResult<RecurrenceRulesSchemaTypeForSelect>> {+ const rule = await this.repository.getById(ruleId);+ if (!rule) return fail('not_found');+ if (rule.state !== 'paused') return fail('invalid_state', `can not resume a ${rule.state} series`);++ const updated = await this.repository.patch({ ruleId, patch: { state: 'active' } });+ if (!updated) return fail('invalid_state');++ // Occurrences missed while paused are not backfilled; if the open+ // instance was completed during the pause, restart the chain from today.+ const openInstance = await this.repository.findOpenInstance(ruleId);+ if (!openInstance) {+ await this.generator.materializeNext({ ruleId, initiatorId: this.initiatorId });+ }++ eventBus.emit('recurrence.resumed', { ruleId, goalId: rule.goalId, initiatorId: this.initiatorId });+ return ok(updated);+ }++ /** Skip the current occurrence: the open instance is removed and the card "jumps" to the next date. */+ async skipCurrent(ruleId: number): Promise<RecurrenceResult<RecurrenceRuleDetails>> {+ const rule = await this.repository.getById(ruleId);+ if (!rule) return fail('not_found');+ if (rule.state !== 'active') return fail('invalid_state', `can not skip in a ${rule.state} series`);++ const openInstance = await this.repository.findOpenInstance(ruleId);+ if (!openInstance || !openInstance.recurrenceInstanceDate) return fail('invalid_state', 'series has no open instance');++ await this.repository.addSkipDate({ ruleId, skipDate: openInstance.recurrenceInstanceDate });+ await this.tasksRepository.deleteTaskNew({ taskId: openInstance.id });+ eventBus.emit('task.deleted', { taskId: openInstance.id, goalId: rule.goalId, initiatorId: this.initiatorId });+ eventBus.emit('recurrence.instanceSkipped', {+ ruleId,+ goalId: rule.goalId,+ date: openInstance.recurrenceInstanceDate,+ initiatorId: this.initiatorId,+ });++ await this.generator.materializeNext({ ruleId, initiatorId: this.initiatorId });+ return this.getDetails(ruleId);+ }++ /** Delete the series; existing instances stay as ordinary tasks (FK SET NULL). */+ async deleteRule(ruleId: number): Promise<RecurrenceResult<{ deleted: true }>> {+ const rule = await this.repository.getById(ruleId);+ if (!rule) return fail('not_found');++ const deleted = await this.repository.deleteById(ruleId);+ if (!deleted) return fail('invalid_state');+ eventBus.emit('recurrence.deleted', { ruleId, goalId: rule.goalId, initiatorId: this.initiatorId });+ return ok({ deleted: true });+ }++ /** Wall-clock difference between the task's start and end, treating missing times as midnight. */+ private durationFromTask(args: {+ startDate: string;+ startTime: string | null;+ endDate: string | null;+ endTime: string | null;+ }): number | null {+ if (!args.endDate) return null;+ const start = new Date(`${args.startDate}T${args.startTime ?? '00:00:00'}Z`).getTime();+ const end = new Date(`${args.endDate}T${args.endTime ?? '00:00:00'}Z`).getTime();+ if (Number.isNaN(start) || Number.isNaN(end)) return null;+ const minutes = Math.round((end - start) / 60_000);+ return minutes > 0 ? minutes : null;+ }+}diff --git a/api/src/tv-modules/recurrence/RecurrenceParser.ts b/api/src/tv-modules/recurrence/RecurrenceParser.tsnew file mode 100644index 0000000..923dc48--- /dev/null+++ b/api/src/tv-modules/recurrence/RecurrenceParser.ts@@ -0,0 +1,155 @@+import { DateTime } from 'luxon';+import { RRule } from 'rrule';+import type { InstanceWindow, InstanceWindowArgs, NextOccurrenceArgs, ParseRuleArgs } from './types';++const ALLOWED_FREQUENCIES = new Set<number>([RRule.YEARLY, RRule.MONTHLY, RRule.WEEKLY, RRule.DAILY]);+const MAX_COUNT = 10000;++/**+ * All recurrence math happens in a single floating wall-clock frame:+ * `dtstart` is a Date whose UTC components equal the wall-clock components of+ * the series (the API runs with TZ=UTC, so naive DB timestamps read back this+ * way). Occurrences returned by `rrule` carry the same convention and are+ * written component-wise into tasks.start_date / start_time. The IANA timezone+ * of the rule is only used to resolve "today" for the user.+ */+export class RecurrenceParser {+ /** Throws a human-readable Error if the RRULE string is unsupported. */+ static validateRuleString(rruleString: string): void {+ let options: ReturnType<typeof RRule.parseString>;+ try {+ options = RRule.parseString(rruleString);+ } catch {+ throw new Error('Invalid RRULE string');+ }+ if (options.freq === undefined || !ALLOWED_FREQUENCIES.has(options.freq)) {+ throw new Error('FREQ must be one of DAILY, WEEKLY, MONTHLY, YEARLY');+ }+ if (options.interval !== undefined && (!Number.isInteger(options.interval) || options.interval < 1)) {+ throw new Error('INTERVAL must be a positive integer');+ }+ if (options.count !== undefined && options.count !== null && (options.count < 1 || options.count > MAX_COUNT)) {+ throw new Error(`COUNT must be between 1 and ${MAX_COUNT}`);+ }+ if (options.count && options.until) {+ throw new Error('COUNT and UNTIL are mutually exclusive (RFC 5545)');+ }+ }++ /** COUNT encoded in the RRULE string, if any. */+ static getCount(rruleString: string): number | null {+ return RRule.parseString(rruleString).count ?? null;+ }++ /**+ * First occurrence date strictly after `afterDate`, skipping explicit skip+ * dates. COUNT is intentionally stripped: the cap is "N materialized+ * instances" enforced by the caller via instances_created, not "N calendar+ * positions" (a series completed late must not silently lose remaining runs).+ * Returns 'YYYY-MM-DD' or null when the series is over (UNTIL passed / no+ * more occurrences within the search horizon).+ */+ static nextOccurrenceDate(args: NextOccurrenceArgs): string | null {+ const options = RRule.parseString(args.rrule);+ delete options.count;+ const rule = new RRule({ ...options, dtstart: args.dtstart });++ // End of the boundary day in the floating frame: "strictly after that day".+ let searchFrom = new Date(`${args.afterDate}T23:59:59.999Z`);+ // Skip dates form a finite set; each loop pass moves searchFrom forward, so this terminates.+ for (;;) {+ const occurrence = rule.after(searchFrom, false);+ if (!occurrence) return null;+ const isoDate = RecurrenceParser.toIsoDate(occurrence);+ if (!args.skipDates.has(isoDate)) return isoDate;+ searchFrom = new Date(`${isoDate}T23:59:59.999Z`);+ }+ }++ /** First occurrence on or after the dtstart day — the instance date of the origin task. */+ static firstOccurrenceDate(args: ParseRuleArgs): string | null {+ const options = RRule.parseString(args.rrule);+ delete options.count;+ const rule = new RRule({ ...options, dtstart: args.dtstart });+ const occurrence = rule.after(new Date(args.dtstart.getTime() - 1), true);+ return occurrence ? RecurrenceParser.toIsoDate(occurrence) : null;+ }++ /** Today's date in the rule's IANA timezone. */+ static todayInTimezone(timezone: string): string {+ const today = DateTime.now().setZone(timezone);+ return today.isValid ? (today.toISODate() as string) : (DateTime.utc().toISODate() as string);+ }++ /** 'HH:mm:ss' wall-clock time of day of the series, or null when the series carries no time (midnight dtstart). */+ static timeOfDay(dtstart: Date): string | null {+ const hours = dtstart.getUTCHours();+ const minutes = dtstart.getUTCMinutes();+ if (hours === 0 && minutes === 0) return null;+ const pad = (n: number) => String(n).padStart(2, '0');+ return `${pad(hours)}:${pad(minutes)}:00`;+ }++ static isValidTimezone(timezone: string): boolean {+ return DateTime.now().setZone(timezone).isValid;+ }++ /**+ * UTC start/end window of a single occurrence. The series is anchored to+ * wall-clock time in its IANA timezone ("every day at 9:00 in Berlin"),+ * while tasks store UTC instants — so the instant is recomputed for every+ * occurrence date with the offset valid on that day (DST-aware): a summer+ * occurrence lands on 07:00 UTC, a winter one on 08:00 UTC, and the user+ * always sees 9:00 on the wall. Non-existent wall times on spring-forward+ * days are pushed forward by luxon to the nearest valid time.+ */+ static instanceWindowUtc(args: InstanceWindowArgs): InstanceWindow {+ const wallTime = RecurrenceParser.timeOfDay(args.dtstart);++ // Date-only series: calendar dates pass through untouched (no instant semantics).+ if (!wallTime) {+ const days = args.durationMinutes ? Math.floor(args.durationMinutes / (24 * 60)) : 0;+ // An occurrence is due on its own date — a series without an explicit+ // end is not a "no deadline" task, the deadline IS the occurrence date.+ const endDate =+ days > 0+ ? RecurrenceParser.toIsoDate(new Date(new Date(`${args.occurrenceDate}T00:00:00Z`).getTime() + days * 24 * 60 * 60_000))+ : args.occurrenceDate;+ return { startDate: args.occurrenceDate, startTime: null, endDate, endTime: null };+ }++ const [year, month, day] = args.occurrenceDate.split('-').map(Number);+ let start = DateTime.fromObject(+ { year, month, day, hour: args.dtstart.getUTCHours(), minute: args.dtstart.getUTCMinutes() },+ { zone: args.timezone }+ );+ if (!start.isValid) {+ start = DateTime.fromISO(`${args.occurrenceDate}T${wallTime}`, { zone: 'utc' });+ }+ const startUtc = start.toUTC();+ const window: InstanceWindow = {+ startDate: startUtc.toISODate() as string,+ startTime: startUtc.toFormat('HH:mm:ss'),+ // No explicit duration → due at the occurrence moment itself.+ endDate: startUtc.toISODate() as string,+ endTime: startUtc.toFormat('HH:mm:ss'),+ };+ if (args.durationMinutes !== null && args.durationMinutes > 0) {+ const endUtc = startUtc.plus({ minutes: args.durationMinutes });+ window.endDate = endUtc.toISODate() as string;+ window.endTime = endUtc.toFormat('HH:mm:ss');+ }+ return window;+ }++ /** Floating wall-clock 'YYYY-MM-DDTHH:mm:ss' string → Date with the same UTC components. */+ static parseDtstart(dtstart: string): Date {+ const date = new Date(`${dtstart}Z`);+ if (Number.isNaN(date.getTime())) throw new Error('Invalid dtstart');+ return date;+ }++ static toIsoDate(date: Date): string {+ return date.toISOString().slice(0, 10);+ }+}diff --git a/api/src/tv-modules/recurrence/RecurrenceRepository.ts b/api/src/tv-modules/recurrence/RecurrenceRepository.tsnew file mode 100644index 0000000..dcff68a--- /dev/null+++ b/api/src/tv-modules/recurrence/RecurrenceRepository.ts@@ -0,0 +1,244 @@+import { and, eq, inArray, isNotNull, ne, notExists, sql } from 'drizzle-orm';+import {+ RecurrenceRulesSchema,+ type RecurrenceRulesSchemaTypeForInsert,+ type RecurrenceRulesSchemaTypeForSelect,+ RecurrenceSkipDatesSchema,+ RecurrenceTemplateAssigneesSchema,+ RecurrenceTemplateTagsSchema,+ TasksAssigneeSchema,+ TasksSchema,+ type TasksSchemaTypeForSelect,+ TasksToTagsSchema,+} from 'taskview-db-schemas';+import { Database } from '../../modules/db';+import { callWithCatch } from '../../utils/helpers';+import type {+ AddSkipDateArgs,+ ApplyInstanceWindowArgs,+ AttachTaskToRuleArgs,+ RecurrenceRulePatchArgs,+ RemoveTemplateAssigneeFromGoalArgs,+ SetTemplateAssigneesArgs,+ SetTemplateTagsArgs,+} from './types';++export class RecurrenceRepository {+ private readonly db: Database;++ constructor() {+ this.db = Database.getInstance();+ }++ async create(data: RecurrenceRulesSchemaTypeForInsert): Promise<RecurrenceRulesSchemaTypeForSelect | null> {+ const result = await callWithCatch(() => this.db.dbDrizzle.insert(RecurrenceRulesSchema).values(data).returning());+ return result?.[0] ?? null;+ }++ async getById(ruleId: number): Promise<RecurrenceRulesSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.select().from(RecurrenceRulesSchema).where(eq(RecurrenceRulesSchema.id, ruleId)).limit(1)+ );+ return result?.[0] ?? null;+ }++ async getByTaskId(taskId: number): Promise<RecurrenceRulesSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({ rule: RecurrenceRulesSchema })+ .from(TasksSchema)+ .innerJoin(RecurrenceRulesSchema, eq(TasksSchema.recurrenceRuleId, RecurrenceRulesSchema.id))+ .where(eq(TasksSchema.id, taskId))+ .limit(1)+ );+ return result?.[0]?.rule ?? null;+ }++ async patch(args: RecurrenceRulePatchArgs): Promise<RecurrenceRulesSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .update(RecurrenceRulesSchema)+ .set({ ...args.patch, editedAt: new Date() })+ .where(eq(RecurrenceRulesSchema.id, args.ruleId))+ .returning()+ );+ return result?.[0] ?? null;+ }++ async deleteById(ruleId: number): Promise<boolean> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.delete(RecurrenceRulesSchema).where(eq(RecurrenceRulesSchema.id, ruleId))+ );+ return !!result?.rowCount;+ }++ async getSkipDates(ruleId: number): Promise<string[]> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({ skipDate: RecurrenceSkipDatesSchema.skipDate })+ .from(RecurrenceSkipDatesSchema)+ .where(eq(RecurrenceSkipDatesSchema.ruleId, ruleId))+ );+ return result?.map((r) => r.skipDate) ?? [];+ }++ async addSkipDate(args: AddSkipDateArgs): Promise<void> {+ await callWithCatch(() =>+ this.db.dbDrizzle+ .insert(RecurrenceSkipDatesSchema)+ .values({ ruleId: args.ruleId, skipDate: args.skipDate })+ .onConflictDoNothing()+ );+ }++ async getTemplateAssignees(ruleId: number): Promise<number[]> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({ collabUserId: RecurrenceTemplateAssigneesSchema.collabUserId })+ .from(RecurrenceTemplateAssigneesSchema)+ .where(eq(RecurrenceTemplateAssigneesSchema.ruleId, ruleId))+ );+ return result?.map((r) => r.collabUserId) ?? [];+ }++ async getTemplateTags(ruleId: number): Promise<number[]> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({ tagId: RecurrenceTemplateTagsSchema.tagId })+ .from(RecurrenceTemplateTagsSchema)+ .where(eq(RecurrenceTemplateTagsSchema.ruleId, ruleId))+ );+ return result?.map((r) => r.tagId) ?? [];+ }++ async setTemplateAssignees(args: SetTemplateAssigneesArgs): Promise<void> {+ await callWithCatch(() =>+ this.db.dbDrizzle.transaction(async (tx) => {+ await tx.delete(RecurrenceTemplateAssigneesSchema).where(eq(RecurrenceTemplateAssigneesSchema.ruleId, args.ruleId));+ if (args.collabUserIds.length > 0) {+ await tx+ .insert(RecurrenceTemplateAssigneesSchema)+ .values(args.collabUserIds.map((collabUserId) => ({ ruleId: args.ruleId, collabUserId })))+ .onConflictDoNothing();+ }+ })+ );+ }++ async setTemplateTags(args: SetTemplateTagsArgs): Promise<void> {+ await callWithCatch(() =>+ this.db.dbDrizzle.transaction(async (tx) => {+ await tx.delete(RecurrenceTemplateTagsSchema).where(eq(RecurrenceTemplateTagsSchema.ruleId, args.ruleId));+ if (args.tagIds.length > 0) {+ await tx+ .insert(RecurrenceTemplateTagsSchema)+ .values(args.tagIds.map((tagId) => ({ ruleId: args.ruleId, tagId })))+ .onConflictDoNothing();+ }+ })+ );+ }++ /** Drops an ex-collaborator from the assignee snapshot of every rule in the goal. */+ async removeTemplateAssigneeFromGoal(args: RemoveTemplateAssigneeFromGoalArgs): Promise<void> {+ const goalRules = this.db.dbDrizzle+ .select({ id: RecurrenceRulesSchema.id })+ .from(RecurrenceRulesSchema)+ .where(eq(RecurrenceRulesSchema.goalId, args.goalId));+ await callWithCatch(() =>+ this.db.dbDrizzle+ .delete(RecurrenceTemplateAssigneesSchema)+ .where(+ and(+ eq(RecurrenceTemplateAssigneesSchema.collabUserId, args.collabUserId),+ inArray(RecurrenceTemplateAssigneesSchema.ruleId, goalRules)+ )+ )+ );+ }++ async getTaskAssignees(taskId: number): Promise<number[]> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({ collabUserId: TasksAssigneeSchema.collabUserId })+ .from(TasksAssigneeSchema)+ .where(eq(TasksAssigneeSchema.taskId, taskId))+ );+ return result?.map((r) => r.collabUserId) ?? [];+ }++ async getTaskTags(taskId: number): Promise<number[]> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select({ tagId: TasksToTagsSchema.tagId })+ .from(TasksToTagsSchema)+ .where(eq(TasksToTagsSchema.taskId, taskId))+ );+ return result?.map((r) => r.tagId) ?? [];+ }++ async getTaskById(taskId: number): Promise<TasksSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle.select().from(TasksSchema).where(eq(TasksSchema.id, taskId)).limit(1)+ );+ return result?.[0] ?? null;+ }++ async attachTaskToRule(args: AttachTaskToRuleArgs): Promise<boolean> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .update(TasksSchema)+ .set({ recurrenceRuleId: args.ruleId, recurrenceInstanceDate: args.instanceDate })+ .where(eq(TasksSchema.id, args.taskId))+ );+ return !!result?.rowCount;+ }++ /** Aligns a task's start/end window with the series frame (used to normalize the origin instance). */+ async applyInstanceWindow(args: ApplyInstanceWindowArgs): Promise<void> {+ await callWithCatch(() =>+ this.db.dbDrizzle+ .update(TasksSchema)+ .set({+ startDate: args.window.startDate,+ startTime: args.window.startTime,+ endDate: args.window.endDate,+ endTime: args.window.endTime,+ })+ .where(eq(TasksSchema.id, args.taskId))+ );+ }++ /** The single not-completed instance of the rule (the lazy model keeps at most one). */+ async findOpenInstance(ruleId: number): Promise<TasksSchemaTypeForSelect | null> {+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(TasksSchema)+ .where(and(eq(TasksSchema.recurrenceRuleId, ruleId), ne(sql`COALESCE(${TasksSchema.complete}, false)`, sql`true`)))+ .limit(1)+ );+ return result?.[0] ?? null;+ }++ /** Active rules with no open instance — the reconcile sweep input. Empty in normal operation. */+ async findStalledActiveRules(): Promise<RecurrenceRulesSchemaTypeForSelect[]> {+ const openInstance = this.db.dbDrizzle+ .select({ one: sql`1` })+ .from(TasksSchema)+ .where(+ and(+ eq(TasksSchema.recurrenceRuleId, RecurrenceRulesSchema.id),+ isNotNull(TasksSchema.recurrenceRuleId),+ ne(sql`COALESCE(${TasksSchema.complete}, false)`, sql`true`)+ )+ );+ const result = await callWithCatch(() =>+ this.db.dbDrizzle+ .select()+ .from(RecurrenceRulesSchema)+ .where(and(eq(RecurrenceRulesSchema.state, 'active'), notExists(openInstance)))+ );+ return result ?? [];+ }+}diff --git a/api/src/tv-modules/recurrence/RecurrenceRoutes.ts b/api/src/tv-modules/recurrence/RecurrenceRoutes.tsnew file mode 100644index 0000000..0b4792d--- /dev/null+++ b/api/src/tv-modules/recurrence/RecurrenceRoutes.ts@@ -0,0 +1,41 @@+import { Router } from 'express';+import { GoalPermissions } from '../../types/auth.types';+import type { Routable } from '../../types/routable.type';+import { IsLoggedIn } from '../auth/middlewares/is-logged-in';+import RecurrenceController from './RecurrenceController';+import {+ goalIdFromRuleParam,+ goalIdFromTaskBody,+ goalIdFromTaskParam,+ requireRecurrencePermission,+} from './middlewares/require-recurrence-permission';++export default class RecurrenceRoutes implements Routable {+ private readonly router: ReturnType<typeof Router>;+ private readonly controller: RecurrenceController;++ constructor() {+ this.router = Router();+ this.controller = new RecurrenceController();+ this.initRoutes();+ }++ getRouter() {+ return this.router;+ }++ initRoutes() {+ // Recurrence is a schedule attribute of a task, so editing reuses the existing deadline permission.+ this.router.post('', [IsLoggedIn, requireRecurrencePermission(GoalPermissions.TASKS_CAN_EDIT_DEADLINE, goalIdFromTaskBody)], this.controller.create);++ // Read access mirrors reading the task itself.+ this.router.get('/task/:taskId', [IsLoggedIn, requireRecurrencePermission(GoalPermissions.COMPONENT_CAN_WATCH_CONTENT, goalIdFromTaskParam)], this.controller.getForTask);+ this.router.get('/:ruleId', [IsLoggedIn, requireRecurrencePermission(GoalPermissions.COMPONENT_CAN_WATCH_CONTENT, goalIdFromRuleParam)], this.controller.getOne);++ this.router.patch('/:ruleId', [IsLoggedIn, requireRecurrencePermission(GoalPermissions.TASKS_CAN_EDIT_DEADLINE, goalIdFromRuleParam)], this.controller.update);+ this.router.post('/:ruleId/pause', [IsLoggedIn, requireRecurrencePermission(GoalPermissions.TASKS_CAN_EDIT_DEADLINE, goalIdFromRuleParam)], this.controller.pause);+ this.router.post('/:ruleId/resume', [IsLoggedIn, requireRecurrencePermission(GoalPermissions.TASKS_CAN_EDIT_DEADLINE, goalIdFromRuleParam)], this.controller.resume);+ this.router.post('/:ruleId/skip', [IsLoggedIn, requireRecurrencePermission(GoalPermissions.TASKS_CAN_EDIT_DEADLINE, goalIdFromRuleParam)], this.controller.skip);+ this.router.delete('/:ruleId', [IsLoggedIn, requireRecurrencePermission(GoalPermissions.TASKS_CAN_EDIT_DEADLINE, goalIdFromRuleParam)], this.controller.remove);+ }+}diff --git a/api/src/tv-modules/recurrence/middlewares/require-recurrence-permission.ts b/api/src/tv-modules/recurrence/middlewares/require-recurrence-permission.tsnew file mode 100644index 0000000..62b9fe4--- /dev/null+++ b/api/src/tv-modules/recurrence/middlewares/require-recurrence-permission.ts@@ -0,0 +1,51 @@+import type { NextFunction, Request, Response } from 'express';+import { GoalPermissionsFetcher } from '../../../core/GoalPermissionsFetcher';+import { $logger } from '../../../modules/logget';+import type { GoalPermissionType } from '../../../types/auth.types';+import { logError } from '../../../utils/api';+import { RecurrenceRepository } from '../RecurrenceRepository';++type GoalIdResolver = (req: Request) => Promise<number | null> | number | null;++/** goalId for POST /module/recurrence — resolved through the task being made recurring. */+export const goalIdFromTaskBody: GoalIdResolver = async (req) => {+ const taskId = Number(req.body?.taskId);+ if (!taskId) return null;+ const task = await new RecurrenceRepository().getTaskById(taskId);+ return task?.goalId ?? null;+};++/** goalId for /module/recurrence/:ruleId routes — resolved through the rule. */+export const goalIdFromRuleParam: GoalIdResolver = async (req) => {+ const ruleId = Number(req.params?.ruleId);+ if (!ruleId) return null;+ const rule = await new RecurrenceRepository().getById(ruleId);+ return rule?.goalId ?? null;+};++/** goalId for GET /module/recurrence/task/:taskId. */+export const goalIdFromTaskParam: GoalIdResolver = async (req) => {+ const taskId = Number(req.params?.taskId);+ if (!taskId) return null;+ const task = await new RecurrenceRepository().getTaskById(taskId);+ return task?.goalId ?? null;+};++export function requireRecurrencePermission(permission: GoalPermissionType, resolveGoalId: GoalIdResolver) {+ 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 recurrence permissions');+ return res.status(500).end();+ }++ if (permissions.hasPermissions(permission)) return next();+ return res.status(403).end();+ };+}diff --git a/api/src/tv-modules/recurrence/types.ts b/api/src/tv-modules/recurrence/types.tsnew file mode 100644index 0000000..a6e2a5d--- /dev/null+++ b/api/src/tv-modules/recurrence/types.ts@@ -0,0 +1,114 @@+import { type } from 'arktype';+import type { RecurrenceRulesSchemaTypeForSelect, TasksSchemaTypeForSelect } from 'taskview-db-schemas';++/** Request validators (ArkType) */++export const RecurrenceArkTypeCreate = type({+ taskId: 'number',+ rrule: 'string > 0',+ dtstart: 'string', // 'YYYY-MM-DDTHH:mm:ss' floating wall-clock, no TZ suffix+ timezone: 'string > 0', // IANA name, e.g. 'Europe/Moscow'+ 'notifyOnOccurrence?': 'boolean',+});++export const RecurrenceArkTypeUpdate = type({+ ruleId: 'number',+ 'rrule?': 'string > 0',+ 'dtstart?': 'string',+ 'timezone?': 'string > 0',+ 'notifyOnOccurrence?': 'boolean',+ 'templateOverrides?': type({+ 'description?': 'string',+ 'note?': 'string | null',+ 'priorityId?': '1 | 2 | 3 | null',+ 'statusId?': 'number | null',+ 'goalListId?': 'number | null',+ 'durationMinutes?': 'number | null',+ }),+});++export const RecurrenceArkTypeRuleIdParam = type({+ ruleId: type('string | number').pipe((v) => Number(v)),+});++export const RecurrenceArkTypeTaskIdParam = type({+ taskId: type('string | number').pipe((v) => Number(v)),+});++/** Inferred argument types (args-as-object) */++export type RecurrenceCreateArgs = typeof RecurrenceArkTypeCreate.infer;+export type RecurrenceUpdateArgs = typeof RecurrenceArkTypeUpdate.infer;+export type RecurrenceTemplateOverrides = NonNullable<RecurrenceUpdateArgs['templateOverrides']>;++/** Generator args */++export type MaterializeNextArgs = {+ ruleId: number;+ /** Who triggered materialization (instance completer, resume initiator or rule creator for the reconcile job). */+ initiatorId: number;+};++/** Parser args */++export type ParseRuleArgs = { rrule: string; dtstart: Date };+export type NextOccurrenceArgs = {+ rrule: string;+ dtstart: Date;+ /** 'YYYY-MM-DD' — next occurrence is searched strictly after this day. */+ afterDate: string;+ skipDates: Set<string>;+};+export type InstanceWindowArgs = {+ /** 'YYYY-MM-DD' wall-clock occurrence date in the rule's timezone. */+ occurrenceDate: string;+ dtstart: Date;+ timezone: string;+ durationMinutes: number | null;+};+export type InstanceWindow = {+ startDate: string;+ startTime: string | null;+ endDate: string | null;+ endTime: string | null;+};++/** Repository args */++export type RecurrenceRulePatchArgs = {+ ruleId: number;+ patch: Partial<{+ rrule: string;+ dtstart: Date;+ timezone: string;+ state: 'active' | 'paused' | 'ended';+ lastInstanceDate: string;+ instancesCreated: number;+ notifyOnOccurrence: boolean;+ templateDescription: string;+ templateNote: string | null;+ templatePriorityId: 1 | 2 | 3 | null;+ templateStatusId: number | null;+ templateGoalListId: number | null;+ templateDurationMinutes: number | null;+ templateTaskId: number | null;+ }>;+};++export type AttachTaskToRuleArgs = { taskId: number; ruleId: number; instanceDate: string };+export type AddSkipDateArgs = { ruleId: number; skipDate: string };+export type SetTemplateAssigneesArgs = { ruleId: number; collabUserIds: number[] };+export type SetTemplateTagsArgs = { ruleId: number; tagIds: number[] };+export type RemoveTemplateAssigneeFromGoalArgs = { goalId: number; collabUserId: number };+export type ApplyInstanceWindowArgs = { taskId: number; window: InstanceWindow };++/** Detail shape returned by GET endpoints */++export type RecurrenceRuleDetails = {+ rule: RecurrenceRulesSchemaTypeForSelect;+ skipDates: string[];+ openInstance: TasksSchemaTypeForSelect | null;+};++export type RecurrenceErrorCode = 'not_found' | 'conflict' | 'invalid_state' | 'invalid_rule';+export type RecurrenceResult<T> = { ok: true; data: T } | { ok: false; code: RecurrenceErrorCode; message?: string };diff --git a/package.json b/package.jsonindex 64809cb..81b2ad0 100644--- a/package.json+++ b/package.json@@ -27,7 +27,7 @@},"pnpm": {"overrides": {- "pg": "^8.20.0"+ "pg": "8.20.0"}},"engines": {diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 330b194..4ad8432 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -5,7 +5,7 @@ settings:excludeLinksFromLockfile: falseoverrides:- pg: ^8.20.0+ pg: 8.20.0importers:@@ -108,6 +108,9 @@ importers:jsonwebtoken:specifier: ^9.0.2version: 9.0.3+ luxon:+ specifier: ^3.7.2+ version: 3.7.2openid-client:specifier: ^6.8.2version: 6.8.2@@ -124,7 +127,7 @@ importers:specifier: ^2.0.0version: 2.0.0pg:- specifier: ^8.20.0+ specifier: 8.20.0version: 8.20.0pg-boss:specifier: ^12.14.0@@ -135,6 +138,9 @@ importers:rotating-file-stream:specifier: ^3.2.5version: 3.2.7+ rrule:+ specifier: ^2.8.1+ version: 2.8.1semver:specifier: ^7.6.3version: 7.7.3@@ -181,6 +187,9 @@ importers:'@types/jsonwebtoken':specifier: ^9.0.7version: 9.0.10+ '@types/luxon':+ specifier: ^3.7.1+ version: 3.7.1'@types/node':specifier: ^22.10.3version: 22.19.7@@ -234,7 +243,7 @@ importers:specifier: ^1.3.0version: 1.3.6pg:- specifier: ^8.20.0+ specifier: 8.20.0version: 8.20.0testcontainers:specifier: ^11.7.1@@ -436,6 +445,9 @@ importers:qs:specifier: ^6.14.1version: 6.14.1+ rrule:+ specifier: ^2.8.1+ version: 2.8.1scule:specifier: ^1.3.0version: 1.3.0@@ -3302,6 +3314,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-MqTGEo5bj5t157U6fA/BiDynNkn0YknVdh48CMPkTSpFTVmvao5UQmm7uEF6xBEo7qIMAlY/JSleYaE6VOdpaA==}+ '@types/[email protected]':+ resolution: {integrity: sha512-H3iskjFIAn5SlJU7OuxUmTEpebK6TKB8rxZShDslBMZJ5u9S//KM1sbdAisiSrqwLQncVjnpi2OK2J51h+4lsg==}+'@types/[email protected]':resolution: {integrity: sha512-mUWlSxAmYLfwnRBmgYV86tgYmMIICX4kza8YnE/eIlywGe2XoOxlpVnXWwir92xRLjwyarqwpu2EJKD2pk0IUA==}@@ -4947,7 +4962,7 @@ packages:knex: '*'kysely: '*'mysql2: '>=2'- pg: ^8.20.0+ pg: 8.20.0postgres: '>=3'prisma: '*'sql.js: '>=1'@@ -6933,7 +6948,7 @@ packages:resolution: {integrity: sha512-gB+R+Xud1gLFuRD/QgOIgGOBE2KCQPaPwkzBBGC9oG69pHTkhQeIuejVIk3/cnDyX39av2AxomQiyPT13WKHQA==}peerDependencies:- pg: ^8.20.0+ pg: 8.20.0resolution: {integrity: sha512-pfsxk2M9M3BuGgDOfuy37VNRRX3jmKgMjcvAcWqNDpZSf4cUmv8HSOl5ViRQFsfARFn0KuUQTgLxVMbNq5NW3g==}@@ -7426,6 +7441,9 @@ packages:resolution: {integrity: sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==}engines: {node: '>= 18'}+ resolution: {integrity: sha512-hM3dHSBMeaJ0Ktp7W38BJZ7O1zOgaFEsn41PDk+yHoEtfLV+PoJt9E9xAlZiWgf/iqEqionN0ebHFZIDAp+iGw==}+resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}@@ -9592,7 +9610,7 @@ snapshots:rimraf: 4.4.1semver: 7.7.3tar: 6.2.1- tslib: 2.6.2+ tslib: 2.8.1xml2js: 0.5.0transitivePeerDependencies:- supports-color@@ -10541,7 +10559,7 @@ snapshots:'@ionic/[email protected]':dependencies:debug: 4.4.3- tslib: 2.6.2+ tslib: 2.8.1transitivePeerDependencies:- supports-color@@ -10550,7 +10568,7 @@ snapshots:'@types/fs-extra': 8.1.5debug: 4.4.3fs-extra: 9.1.0- tslib: 2.6.2+ tslib: 2.8.1transitivePeerDependencies:- supports-color@@ -12054,6 +12072,8 @@ snapshots:'@types/[email protected]':optional: true+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]':@@ -12648,7 +12668,7 @@ snapshots:'@vue/shared': 3.5.27estree-walker: 2.0.2magic-string: 0.30.21- postcss: 8.5.6+ postcss: 8.5.8source-map-js: 1.2.1'@vue/[email protected]':@@ -16717,6 +16737,10 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ tslib: 2.8.1+dependencies:queue-microtask: 1.2.3diff --git a/taskview-packages/taskview-api/src/api/__tests__/init-api.ts b/taskview-packages/taskview-api/src/api/__tests__/init-api.tsindex cb38a0b..895662e 100644--- a/taskview-packages/taskview-api/src/api/__tests__/init-api.ts+++ b/taskview-packages/taskview-api/src/api/__tests__/init-api.ts@@ -1,4 +1,4 @@-export const API_URL = 'http://localhost:11401';+export const API_URL = process.env.TASKVIEW_TEST_URL || 'http://localhost:11401';export const DEFAULT_USER = 'user';export const DEFAULT_USER_2 = 'user2';export const DEFAULT_PASSWORD = 'user1!#Q';diff --git a/taskview-packages/taskview-api/src/api/__tests__/recurrence.test.ts b/taskview-packages/taskview-api/src/api/__tests__/recurrence.test.tsnew file mode 100644index 0000000..a3fdb0d--- /dev/null+++ b/taskview-packages/taskview-api/src/api/__tests__/recurrence.test.ts@@ -0,0 +1,527 @@+import { TvApi } from '@/tv'+import {+ describe,+ it,+ expect,+ beforeAll,+ afterAll,+} from 'vitest'+import axios, { type AxiosInstance } from 'axios'+import { initApi, API_URL, DEFAULT_USER, DEFAULT_USER_2, DEFAULT_PASSWORD } from './init-api'+import { ymd } from './test-helpers'+import type { RecurrenceRuleDetails } from '@/api/recurrence.types'++/**+ * Integration tests for recurring tasks (lazy materialization).+ *+ * The model keeps exactly ONE open instance per series: completing it+ * materializes the next occurrence through an async event handler, so+ * assertions about "the next card" poll via waitFor().+ *+ * All rules use Europe/Moscow (fixed UTC+3, no DST) with a 10:45 wall-clock+ * time, so UTC expectations are deterministic: stored start_time is 07:45:00.+ */+describe('Recurrence', () => {+ let $api: TvApi+ let raw: AxiosInstance+ let goalId: number++ const MSK_TIME = 'T10:45:00'+ const UTC_TIME = '07:45:00'++ beforeAll(async () => {+ const { $tvApi } = await initApi()+ $api = $tvApi++ // Raw axios with validateStatus:true to assert error statuses directly.+ const auth = await axios.post(`${API_URL}/module/auth/login`, {+ login: DEFAULT_USER,+ password: DEFAULT_PASSWORD,+ })+ raw = axios.create({+ baseURL: API_URL,+ headers: { Authorization: `Bearer ${auth.data.access}` },+ validateStatus: () => true,+ })++ const goal = await $api.goals.createGoal({ name: `Recurrence test project-${Date.now()}` })+ if (!goal) throw new Error('Failed to create goal')+ goalId = goal.id!+ })++ afterAll(async () => {+ await $api.goals.deleteGoal(goalId).catch(() => {})+ })++ async function createTask(description: string, startDate = ymd(3)) {+ const task = await $api.tasks.createTask({+ goalId,+ description,+ startDate,+ startTime: UTC_TIME, // stored frame is UTC; wall-clock 10:45 MSK+ endDate: startDate,+ endTime: '08:45:00',+ })+ if (!task) throw new Error('Failed to create task')+ return task+ }++ async function createRule(taskId: number, rrule: string, startDate = ymd(3)) {+ return await $api.recurrence.create({+ taskId,+ rrule,+ dtstart: `${startDate}${MSK_TIME}`,+ timezone: 'Europe/Moscow',+ })+ }++ /** Last day of the month `monthsAhead` months from now ('YYYY-MM-DD', UTC). */+ function lastDayOfMonth(monthsAhead: number): string {+ const now = new Date()+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + monthsAhead + 1, 0)).toISOString().slice(0, 10)+ }++ /** Polls the rule details until the predicate holds (materialization is async). */+ async function waitFor(+ ruleId: number,+ predicate: (details: RecurrenceRuleDetails) => boolean,+ timeoutMs = 8000,+ ): Promise<RecurrenceRuleDetails> {+ const startedAt = Date.now()+ for (;;) {+ const details = await $api.recurrence.getById(ruleId).catch(() => null)+ if (details && predicate(details)) return details+ if (Date.now() - startedAt > timeoutMs) {+ throw new Error(`waitFor timed out for rule ${ruleId}: ${JSON.stringify(details)?.slice(0, 300)}`)+ }+ await new Promise((r) => setTimeout(r, 300))+ }+ }++ describe('validation', () => {+ let taskId: number++ beforeAll(async () => {+ taskId = (await createTask('Validation target')).id+ })++ const base = { dtstart: `${ymd(3)}${MSK_TIME}`, timezone: 'Europe/Moscow' }++ it('rejects sub-daily frequencies', async () => {+ const res = await raw.post('/module/recurrence', { taskId, rrule: 'FREQ=HOURLY', ...base })+ expect(res.status).toBe(422)+ })++ it('rejects an invalid IANA timezone', async () => {+ const res = await raw.post('/module/recurrence', { taskId, rrule: 'FREQ=DAILY', ...base, timezone: 'Mars/Olympus' })+ expect(res.status).toBe(422)+ })++ it('rejects a malformed rrule string', async () => {+ const res = await raw.post('/module/recurrence', { taskId, rrule: 'garbage', ...base })+ expect(res.status).toBe(422)+ })++ it('rejects COUNT and UNTIL together (RFC 5545)', async () => {+ const res = await raw.post('/module/recurrence', { taskId, rrule: 'FREQ=DAILY;COUNT=5;UNTIL=20270101T000000Z', ...base })+ expect(res.status).toBe(422)+ })++ it('rejects an oversized COUNT', async () => {+ const res = await raw.post('/module/recurrence', { taskId, rrule: 'FREQ=DAILY;COUNT=100000', ...base })+ expect(res.status).toBe(422)+ })++ it('returns 404 for a missing task', async () => {+ const res = await raw.post('/module/recurrence', { taskId: 99999999, rrule: 'FREQ=DAILY', ...base })+ expect(res.status).toBe(404)+ })++ it('rejects a completed task as series origin', async () => {+ const done = await createTask('Already done')+ await $api.tasks.updateTask({ id: done.id, complete: true })+ const res = await raw.post('/module/recurrence', { taskId: done.id, rrule: 'FREQ=DAILY', ...base })+ expect(res.status).toBe(400)+ })++ it('rejects a subtask as series origin', async () => {+ const parent = await createTask('Parent')+ const sub = await $api.tasks.createTask({ goalId, parentId: parent.id, description: 'Subtask' })+ const res = await raw.post('/module/recurrence', { taskId: sub!.id, rrule: 'FREQ=DAILY', ...base })+ expect(res.status).toBe(400)+ })++ it('rejects a second rule on the same task', async () => {+ await createRule(taskId, 'FREQ=DAILY')+ const res = await raw.post('/module/recurrence', { taskId, rrule: 'FREQ=WEEKLY', ...base })+ expect(res.status).toBe(409)+ })+ })++ describe('lifecycle', () => {+ it('origin task becomes the open instance with a UTC-normalized window', async () => {+ const task = await createTask('Daily standup')+ const rule = await createRule(task.id, 'FREQ=DAILY')++ expect(rule.state).toBe('active')+ expect(rule.instancesCreated).toBe(1)+ expect(rule.timezone).toBe('Europe/Moscow')++ const details = await $api.recurrence.getForTask(task.id)+ expect(details?.rule.id).toBe(rule.id)+ expect(details?.openInstance?.id).toBe(task.id)+ expect(details?.openInstance?.recurrenceInstanceDate).toBe(ymd(3))+ // 10:45 wall-clock Moscow stored as the 07:45 UTC instant+ expect(details?.openInstance?.startTime).toBe(UTC_TIME)+ })++ it('completing the open instance materializes exactly one next occurrence', async () => {+ const task = await createTask('Daily report')+ const rule = await createRule(task.id, 'FREQ=DAILY')++ await $api.tasks.updateTask({ id: task.id, complete: true })++ const details = await waitFor(rule.id, (d) => !!d.openInstance && d.openInstance.id !== task.id)+ expect(details.openInstance?.recurrenceInstanceDate).toBe(ymd(4))+ expect(details.openInstance?.startTime).toBe(UTC_TIME)+ expect(details.openInstance?.complete).toBe(false)+ expect(details.openInstance?.description).toBe('Daily report')+ expect(details.rule.instancesCreated).toBe(2)++ // A repeated complete=true PATCH must not spawn another instance.+ await $api.tasks.updateTask({ id: task.id, complete: true })+ await new Promise((r) => setTimeout(r, 1500))+ const after = await $api.recurrence.getById(rule.id)+ expect(after?.rule.instancesCreated).toBe(2)+ })++ it('weekly rule materializes on the next scheduled weekday', async () => {+ // First Monday at least 3 days out, so "today in MSK" never overtakes it.+ let offset = 3+ while (new Date(`${ymd(offset)}T00:00:00Z`).getUTCDay() !== 1) offset++++ const task = await createTask('Weekly sync', ymd(offset))+ const rule = await createRule(task.id, 'FREQ=WEEKLY;BYDAY=MO', ymd(offset))++ const details = await $api.recurrence.getForTask(task.id)+ expect(details?.openInstance?.recurrenceInstanceDate).toBe(ymd(offset))++ await $api.tasks.updateTask({ id: task.id, complete: true })+ const next = await waitFor(rule.id, (d) => !!d.openInstance && d.openInstance.id !== task.id)+ expect(next.openInstance?.recurrenceInstanceDate).toBe(ymd(offset + 7))+ })++ it('skip jumps the card to the next date and records the skipped occurrence', async () => {+ const task = await createTask('Skippable daily')+ const rule = await createRule(task.id, 'FREQ=DAILY')++ const details = await $api.recurrence.skip(rule.id)+ expect(details.skipDates).toContain(ymd(3))+ expect(details.openInstance?.recurrenceInstanceDate).toBe(ymd(4))+ // the skipped origin task is deleted, so its rule lookup is gone too+ const forTask = await raw.get(`/module/recurrence/task/${task.id}`)+ expect(forTask.status).toBe(404)+ })++ it('a COUNT-limited series ends after the last materialized instance is completed', async () => {+ const task = await createTask('Twice and done')+ const rule = await createRule(task.id, 'FREQ=DAILY;COUNT=2')++ await $api.tasks.updateTask({ id: task.id, complete: true })+ const second = await waitFor(rule.id, (d) => d.rule.instancesCreated === 2)+ expect(second.openInstance).toBeTruthy()++ await $api.tasks.updateTask({ id: second.openInstance!.id, complete: true })+ const ended = await waitFor(rule.id, (d) => d.rule.state === 'ended')+ expect(ended.openInstance).toBeNull()+ expect(ended.rule.instancesCreated).toBe(2)+ })++ it('pause blocks materialization; resume restores the open instance', async () => {+ const task = await createTask('Pausable daily')+ const rule = await createRule(task.id, 'FREQ=DAILY')++ const paused = await $api.recurrence.pause(rule.id)+ expect(paused.state).toBe('paused')++ await $api.tasks.updateTask({ id: task.id, complete: true })+ await new Promise((r) => setTimeout(r, 1500))+ const whilePaused = await $api.recurrence.getById(rule.id)+ expect(whilePaused?.openInstance).toBeNull()+ expect(whilePaused?.rule.instancesCreated).toBe(1)++ const resumed = await $api.recurrence.resume(rule.id)+ expect(resumed.state).toBe('active')+ const restored = await waitFor(rule.id, (d) => !!d.openInstance)+ expect(restored.openInstance?.recurrenceInstanceDate).toBe(ymd(4))+ })++ it('renaming the open instance renames future occurrences (template auto-sync)', async () => {+ const task = await createTask('Original name')+ const rule = await createRule(task.id, 'FREQ=DAILY')++ // user edits the visible card: description, note, priority+ await $api.tasks.updateTask({ id: task.id, description: 'Renamed card', note: 'fresh note', priorityId: 2 })+ await new Promise((r) => setTimeout(r, 800)) // template sync is event-driven++ const synced = await $api.recurrence.getById(rule.id)+ expect(synced?.rule.templateDescription).toBe('Renamed card')+ expect(synced?.rule.templateNote).toBe('fresh note')+ expect(synced?.rule.templatePriorityId).toBe(2)++ await $api.tasks.updateTask({ id: task.id, complete: true })+ const details = await waitFor(rule.id, (d) => !!d.openInstance && d.openInstance.id !== task.id)+ expect(details.openInstance?.description).toBe('Renamed card')+ expect(details.openInstance?.note).toBe('fresh note')+ expect(details.openInstance?.priorityId).toBe(2)++ // editing a COMPLETED (historical) instance must NOT touch the template+ await $api.tasks.updateTask({ id: task.id, description: 'History edit' })+ await new Promise((r) => setTimeout(r, 800))+ const after = await $api.recurrence.getById(rule.id)+ expect(after?.rule.templateDescription).toBe('Renamed card')+ })++ it('template overrides apply to the next materialized instance', async () => {+ const task = await createTask('Old name')+ const rule = await createRule(task.id, 'FREQ=DAILY')++ const updated = await $api.recurrence.update({+ ruleId: rule.id,+ templateOverrides: { description: 'New name', priorityId: 3 },+ })+ expect(updated.templateDescription).toBe('New name')++ await $api.tasks.updateTask({ id: task.id, complete: true })+ const details = await waitFor(rule.id, (d) => !!d.openInstance && d.openInstance.id !== task.id)+ expect(details.openInstance?.description).toBe('New name')+ expect(details.openInstance?.priorityId).toBe(3)+ })++ it('updating rrule and timezone re-anchors the series', async () => {+ const task = await createTask('Movable')+ const rule = await createRule(task.id, 'FREQ=DAILY')++ const updated = await $api.recurrence.update({+ ruleId: rule.id,+ rrule: 'FREQ=WEEKLY;BYDAY=TH',+ timezone: 'Asia/Vladivostok',+ notifyOnOccurrence: true,+ })+ expect(updated.rrule).toContain('BYDAY=TH')+ expect(updated.timezone).toBe('Asia/Vladivostok')+ expect(updated.notifyOnOccurrence).toBe(true)+ })++ it('deleting the series keeps existing instances as ordinary tasks', async () => {+ const task = await createTask('Survivor')+ const rule = await createRule(task.id, 'FREQ=DAILY')++ const removed = await $api.recurrence.remove(rule.id)+ expect(removed.deleted).toBe(true)++ const ruleGone = await raw.get(`/module/recurrence/${rule.id}`)+ expect(ruleGone.status).toBe(404)++ const survivor = await $api.tasks.fetchTaskById(task.id)+ expect(survivor).toBeTruthy()+ expect(survivor!.recurrenceRuleId).toBeNull()+ })+ })++ describe('advanced schedules & series content', () => {+ it('a skipped occurrence counts toward COUNT (RFC 5545)', async () => {+ const task = await createTask('Skip eats count')+ const rule = await createRule(task.id, 'FREQ=DAILY;COUNT=2')++ // skip removes the origin and materializes occurrence #2 of 2+ const details = await $api.recurrence.skip(rule.id)+ expect(details.rule.instancesCreated).toBe(2)+ expect(details.skipDates).toContain(ymd(3))+ expect(details.openInstance?.recurrenceInstanceDate).toBe(ymd(4))++ // completing the last allowed occurrence ends the series+ await $api.tasks.updateTask({ id: details.openInstance!.id, complete: true })+ const ended = await waitFor(rule.id, (d) => d.rule.state === 'ended')+ expect(ended.openInstance).toBeNull()+ })++ it('an UNTIL-bounded series ends once the boundary is passed', async () => {+ const task = await createTask('Until series')+ const until = `${ymd(4).replace(/-/g, '')}T235959Z` // floating wall-clock boundary+ const rule = await createRule(task.id, `FREQ=DAILY;UNTIL=${until}`)++ await $api.tasks.updateTask({ id: task.id, complete: true })+ const second = await waitFor(rule.id, (d) => !!d.openInstance && d.openInstance.id !== task.id)+ expect(second.openInstance?.recurrenceInstanceDate).toBe(ymd(4))++ await $api.tasks.updateTask({ id: second.openInstance!.id, complete: true })+ const ended = await waitFor(rule.id, (d) => d.rule.state === 'ended')+ expect(ended.openInstance).toBeNull()+ })++ it('last-day-of-month rule lands on actual month ends', async () => {+ const firstEnd = lastDayOfMonth(1)+ const secondEnd = lastDayOfMonth(2)++ const task = await createTask('Close the books', firstEnd)+ const rule = await createRule(task.id, 'FREQ=MONTHLY;BYMONTHDAY=-1', firstEnd)++ const details = await $api.recurrence.getForTask(task.id)+ expect(details?.openInstance?.recurrenceInstanceDate).toBe(firstEnd)++ await $api.tasks.updateTask({ id: task.id, complete: true })+ const next = await waitFor(rule.id, (d) => !!d.openInstance && d.openInstance.id !== task.id)+ expect(next.openInstance?.recurrenceInstanceDate).toBe(secondEnd)+ })++ it('a date-only series gets deadline = occurrence date (shows up in Today/Upcoming)', async () => {+ const task = await $api.tasks.createTask({ goalId, description: 'No-end daily', startDate: ymd(3) })+ const rule = await $api.recurrence.create({+ taskId: task!.id,+ rrule: 'FREQ=DAILY',+ dtstart: `${ymd(3)}T00:00:00`,+ timezone: 'Europe/Moscow',+ })++ // the origin window is normalized the same way+ const origin = await $api.tasks.fetchTaskById(task!.id)+ expect(origin?.endDate).toBe(ymd(3))+ expect(origin?.endTime).toBeNull()++ await $api.tasks.updateTask({ id: task!.id, complete: true })+ const details = await waitFor(rule.id, (d) => !!d.openInstance && d.openInstance.id !== task!.id)+ expect(details.openInstance?.startDate).toBe(ymd(4))+ expect(details.openInstance?.endDate).toBe(ymd(4))+ expect(details.openInstance?.startTime).toBeNull()+ expect(details.openInstance?.endTime).toBeNull()+ })++ it('a timed series without duration is due at the occurrence moment', async () => {+ const task = await $api.tasks.createTask({+ goalId,+ description: 'Timed no-end',+ startDate: ymd(3),+ startTime: UTC_TIME,+ })+ const rule = await createRule(task!.id, 'FREQ=DAILY')++ await $api.tasks.updateTask({ id: task!.id, complete: true })+ const details = await waitFor(rule.id, (d) => !!d.openInstance && d.openInstance.id !== task!.id)+ expect(details.openInstance?.endDate).toBe(ymd(4))+ expect(details.openInstance?.endTime).toBe(UTC_TIME) // due exactly at 10:45 MSK+ })++ it('materialized instances inherit assignees and tags from the snapshot', async () => {+ const task = await createTask('Assigned standup')++ // collaborator + tag must exist on the origin BEFORE the rule snapshots them+ await $api.collaboration.inviteUserToGoal({ goalId, email: '[email protected]' })+ const users = await $api.collaboration.fetchUsersForGoal(goalId)+ const collabId = users?.find((u) => u.email === '[email protected]')?.id+ expect(collabId).toBeTruthy()+ await $api.tasks.toggleTasksAssignee({ taskId: task.id, userIds: [collabId!] })++ const tag = await $api.tags.createTag({ goalId, name: `recur-tag-${Date.now()}`, color: '#00ff00' })+ expect(tag?.id).toBeTruthy()+ await $api.tags.toggleTag({ tagId: tag!.id, taskId: task.id })++ const rule = await createRule(task.id, 'FREQ=DAILY')++ await $api.tasks.updateTask({ id: task.id, complete: true })+ const details = await waitFor(rule.id, (d) => !!d.openInstance && d.openInstance.id !== task.id)++ const instance = await $api.tasks.fetchTaskById(details.openInstance!.id)+ expect(instance?.assignedUsers).toContain(collabId)+ expect(instance?.tags).toContain(tag!.id)+ })++ it('a collaborator removed from the project stops being auto-assigned', async () => {+ const task = await createTask('Ex-employee standup')++ await $api.collaboration.inviteUserToGoal({ goalId, email: '[email protected]' })+ const users = await $api.collaboration.fetchUsersForGoal(goalId)+ const collabId = users?.find((u) => u.email === '[email protected]')?.id+ expect(collabId).toBeTruthy()+ await $api.tasks.toggleTasksAssignee({ taskId: task.id, userIds: [collabId!] })++ const rule = await createRule(task.id, 'FREQ=DAILY')++ // remove the collaborator — the assignee snapshot must be cleaned up+ await $api.collaboration.deleteUserFromGoal({ goalId, id: collabId! })+ await new Promise((r) => setTimeout(r, 1000)) // cleanup is event-driven++ await $api.tasks.updateTask({ id: task.id, complete: true })+ const details = await waitFor(rule.id, (d) => !!d.openInstance && d.openInstance.id !== task.id)++ const instance = await $api.tasks.fetchTaskById(details.openInstance!.id)+ expect(instance?.assignedUsers ?? []).not.toContain(collabId)+ })+ })++ describe('cross-tenant access (IDOR)', () => {+ let attackerRaw: AxiosInstance+ let victimTaskId: number+ let victimRuleId: number++ beforeAll(async () => {+ const auth = await axios.post(`${API_URL}/module/auth/login`, {+ login: DEFAULT_USER_2,+ password: DEFAULT_PASSWORD,+ })+ attackerRaw = axios.create({+ baseURL: API_URL,+ headers: { Authorization: `Bearer ${auth.data.access}` },+ validateStatus: () => true,+ })++ const task = await createTask('Victim recurring')+ victimTaskId = task.id+ const rule = await createRule(task.id, 'FREQ=DAILY')+ victimRuleId = rule.id+ })++ it('denies reading a foreign rule', async () => {+ const res = await attackerRaw.get(`/module/recurrence/${victimRuleId}`)+ expect(res.status).toBe(403)+ })++ it('denies reading a foreign rule through the task route', async () => {+ const res = await attackerRaw.get(`/module/recurrence/task/${victimTaskId}`)+ expect(res.status).toBe(403)+ })++ it('denies creating a rule on a foreign task', async () => {+ const res = await attackerRaw.post('/module/recurrence', {+ taskId: victimTaskId,+ rrule: 'FREQ=DAILY',+ dtstart: `${ymd(3)}${MSK_TIME}`,+ timezone: 'Europe/Moscow',+ })+ expect(res.status).toBe(403)+ })++ it('denies updating a foreign rule (including body.ruleId injection)', async () => {+ const res = await attackerRaw.patch(`/module/recurrence/${victimRuleId}`, {+ ruleId: victimRuleId, // injected — params must win anyway+ rrule: 'FREQ=YEARLY',+ })+ expect(res.status).toBe(403)++ const intact = await $api.recurrence.getById(victimRuleId)+ expect(intact?.rule.rrule).toContain('DAILY')+ })++ it('denies skip / pause / delete on a foreign rule', async () => {+ const skip = await attackerRaw.post(`/module/recurrence/${victimRuleId}/skip`, {})+ expect(skip.status).toBe(403)+ const pause = await attackerRaw.post(`/module/recurrence/${victimRuleId}/pause`, {})+ expect(pause.status).toBe(403)+ const del = await attackerRaw.delete(`/module/recurrence/${victimRuleId}`)+ expect(del.status).toBe(403)++ const intact = await $api.recurrence.getById(victimRuleId)+ expect(intact?.rule.state).toBe('active')+ })+ })+})diff --git a/taskview-packages/taskview-api/src/api/recurrence.ts b/taskview-packages/taskview-api/src/api/recurrence.tsnew file mode 100644index 0000000..7d6a4ef--- /dev/null+++ b/taskview-packages/taskview-api/src/api/recurrence.ts@@ -0,0 +1,49 @@+import TvApiBase from './base';+import type { AppResponse } from './base.types';+import type {+ RecurrenceCreateArgs,+ RecurrenceRule,+ RecurrenceRuleDetails,+ RecurrenceUpdateArgs,+} from './recurrence.types';++export default class TvRecurrenceApi extends TvApiBase {+ protected moduleUrl = '/module/recurrence';++ public async create(args: RecurrenceCreateArgs) {+ return this.request(this.$axios.post<AppResponse<RecurrenceRule>>(`${this.moduleUrl}`, args));+ }++ public async getById(ruleId: number) {+ return this.request(this.$axios.get<AppResponse<RecurrenceRuleDetails | null>>(`${this.moduleUrl}/${ruleId}`));+ }++ public async getForTask(taskId: number) {+ return this.request(+ this.$axios.get<AppResponse<RecurrenceRuleDetails | null>>(`${this.moduleUrl}/task/${taskId}`)+ );+ }++ public async update(args: RecurrenceUpdateArgs) {+ const { ruleId, ...body } = args;+ return this.request(this.$axios.patch<AppResponse<RecurrenceRule>>(`${this.moduleUrl}/${ruleId}`, body));+ }++ public async pause(ruleId: number) {+ return this.request(this.$axios.post<AppResponse<RecurrenceRule>>(`${this.moduleUrl}/${ruleId}/pause`, {}));+ }++ public async resume(ruleId: number) {+ return this.request(this.$axios.post<AppResponse<RecurrenceRule>>(`${this.moduleUrl}/${ruleId}/resume`, {}));+ }++ public async skip(ruleId: number) {+ return this.request(+ this.$axios.post<AppResponse<RecurrenceRuleDetails>>(`${this.moduleUrl}/${ruleId}/skip`, {})+ );+ }++ public async remove(ruleId: number) {+ return this.request(this.$axios.delete<AppResponse<{ deleted: true }>>(`${this.moduleUrl}/${ruleId}`));+ }+}diff --git a/taskview-packages/taskview-api/src/api/recurrence.types.ts b/taskview-packages/taskview-api/src/api/recurrence.types.tsnew file mode 100644index 0000000..10f8cd4--- /dev/null+++ b/taskview-packages/taskview-api/src/api/recurrence.types.ts@@ -0,0 +1,60 @@+import type { Task } from './tasks.api.types';++export type RecurrenceState = 'active' | 'paused' | 'ended';++export type RecurrenceRule = {+ id: number;+ goalId: number;+ templateTaskId: number | null;+ templateDescription: string | null;+ templateNote: string | null;+ templatePriorityId: 1 | 2 | 3 | null;+ templateStatusId: number | null;+ templateGoalListId: number | null;+ templateDurationMinutes: number | null;+ /** RFC 5545 RRULE string; COUNT/UNTIL live inside it. */+ rrule: string;+ /** Floating wall-clock 'YYYY-MM-DDTHH:mm:ss' anchor of the series. */+ dtstart: string;+ /** IANA timezone name, e.g. 'Europe/Moscow'. */+ timezone: string;+ state: RecurrenceState;+ lastInstanceDate: string;+ instancesCreated: number;+ notifyOnOccurrence: boolean;+ creatorId: number;+ createdAt: string;+ editedAt: string;+};++export type RecurrenceRuleDetails = {+ rule: RecurrenceRule;+ skipDates: string[];+ openInstance: Task | null;+};++export type RecurrenceCreateArgs = {+ taskId: number;+ rrule: string;+ dtstart: string;+ timezone: string;+ notifyOnOccurrence?: boolean;+};++export type RecurrenceTemplateOverrides = Partial<{+ description: string;+ note: string | null;+ priorityId: 1 | 2 | 3 | null;+ statusId: number | null;+ goalListId: number | null;+ durationMinutes: number | null;+}>;++export type RecurrenceUpdateArgs = {+ ruleId: number;+ rrule?: string;+ dtstart?: string;+ timezone?: string;+ notifyOnOccurrence?: boolean;+ templateOverrides?: RecurrenceTemplateOverrides;+};diff --git a/taskview-packages/taskview-api/src/api/tasks.api.types.ts b/taskview-packages/taskview-api/src/api/tasks.api.types.tsindex 265b733..2c336b7 100644--- a/taskview-packages/taskview-api/src/api/tasks.api.types.ts+++ b/taskview-packages/taskview-api/src/api/tasks.api.types.ts@@ -34,6 +34,9 @@ export interface TaskBase {sprintId: number | null;estimateValue: number | string | null;++ recurrenceRuleId: number | null;+ recurrenceInstanceDate: string | null;}export interface Task extends TaskBase {@@ -44,7 +47,8 @@ export interface Task extends TaskBase {// we can not update defined fields// sprintId is managed via the sprints module; dateComplete is trigger-maintained.-type NotAllowedToUpdate = 'id' | 'goalId' | 'owner' | 'dateCreation' | 'dateComplete' | 'historyId' | 'sprintId';+// recurrence fields are managed via the recurrence module.+type NotAllowedToUpdate = 'id' | 'goalId' | 'owner' | 'dateCreation' | 'dateComplete' | 'historyId' | 'sprintId' | 'recurrenceRuleId' | 'recurrenceInstanceDate';export type TaskArgUpdate = Pick<Task, 'id'> & Partial<Omit<Task, NotAllowedToUpdate>>;export type TaskResponseUpdate = (Task & { syncFailed?: boolean }) | null;diff --git a/taskview-packages/taskview-api/src/index.ts b/taskview-packages/taskview-api/src/index.tsindex 37f9d6c..4d46e2e 100644--- a/taskview-packages/taskview-api/src/index.ts+++ b/taskview-packages/taskview-api/src/index.ts@@ -19,4 +19,5 @@ export * from '@/api/sso.types';export * from '@/api/analytics.types';export * from '@/api/time-tracking.types';export * from '@/api/ui-preferences.types';-export * from '@/api/sprints.types';\ No newline at end of file+export * from '@/api/sprints.types';+export * from '@/api/recurrence.types';\ No newline at end of filediff --git a/taskview-packages/taskview-api/src/tv.ts b/taskview-packages/taskview-api/src/tv.tsindex cbd8eca..6e41063 100644--- a/taskview-packages/taskview-api/src/tv.ts+++ b/taskview-packages/taskview-api/src/tv.ts@@ -17,6 +17,7 @@ import TvAnalyticsApi from "./api/analytics";import TvTimeTrackingApi from "./api/time-tracking";import TvUiPreferencesApi from "./api/ui-preferences";import TvSprintApi from "./api/sprints";+import TvRecurrenceApi from "./api/recurrence";export class TvApi {@@ -58,6 +59,8 @@ export class TvApi {public sprints: TvSprintApi;+ public recurrence: TvRecurrenceApi;+constructor($axios: AxiosInstance) {this.$axios = $axios;@@ -96,6 +99,8 @@ export class TvApi {this.uiPreferences = new TvUiPreferencesApi(this.$axios);this.sprints = new TvSprintApi(this.$axios);++ this.recurrence = new TvRecurrenceApi(this.$axios);}public setBaseUrl(baseUrl: string) {diff --git a/taskview-packages/taskview-db-schemas/src/index.ts b/taskview-packages/taskview-db-schemas/src/index.tsindex 614e105..d92d79d 100644--- a/taskview-packages/taskview-db-schemas/src/index.ts+++ b/taskview-packages/taskview-db-schemas/src/index.ts@@ -25,3 +25,7 @@ export * from './schemas/sprint-task-outcomes.schema';export * from './schemas/sprint-user-capacity.schema';export * from './schemas/sprint-retros.schema';export * from './schemas/sprint-cadence.schema';+export * from './schemas/recurrence-rules.schema';+export * from './schemas/recurrence-skip-dates.schema';+export * from './schemas/recurrence-template-assignees.schema';+export * from './schemas/recurrence-template-tags.schema';diff --git a/taskview-packages/taskview-db-schemas/src/schemas/recurrence-rules.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/recurrence-rules.schema.tsnew file mode 100644index 0000000..da22f6a--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/recurrence-rules.schema.ts@@ -0,0 +1,31 @@+import { boolean, date, integer, pgSchema, text, timestamp, varchar } from "drizzle-orm/pg-core";+import { GoalsSchema } from "./goals.schema";+import { TasksSchema } from "./tasks.schema";+import { UsersSchema } from "./users.schema";++export type RecurrenceState = 'active' | 'paused' | 'ended';++export const RecurrenceRulesSchema = pgSchema('tasks').table('recurrence_rules', {+ id: integer().primaryKey().generatedAlwaysAsIdentity(),+ goalId: integer('goal_id').notNull().references(() => GoalsSchema.id, { onDelete: 'cascade' }),+ templateTaskId: integer('template_task_id').references(() => TasksSchema.id, { onDelete: 'set null' }),+ templateDescription: varchar('template_description', { length: 2000 }),+ templateNote: varchar('template_note', { length: 2000 }),+ templatePriorityId: integer('template_priority_id').$type<1 | 2 | 3 | null>(),+ templateStatusId: integer('template_status_id'),+ templateGoalListId: integer('template_goal_list_id'),+ templateDurationMinutes: integer('template_duration_minutes'),+ rrule: text().notNull(),+ dtstart: timestamp().notNull(),+ timezone: varchar({ length: 50 }).notNull(),+ state: varchar({ length: 20 }).$type<RecurrenceState>().notNull().default('active'),+ lastInstanceDate: date('last_instance_date').notNull(),+ instancesCreated: integer('instances_created').notNull().default(1),+ notifyOnOccurrence: boolean('notify_on_occurrence').notNull().default(false),+ creatorId: integer('creator_id').notNull().references(() => UsersSchema.id, { onDelete: 'cascade' }),+ createdAt: timestamp('created_at').notNull().defaultNow(),+ editedAt: timestamp('edited_at').notNull().defaultNow(),+});++export type RecurrenceRulesSchemaTypeForSelect = typeof RecurrenceRulesSchema.$inferSelect;+export type RecurrenceRulesSchemaTypeForInsert = typeof RecurrenceRulesSchema.$inferInsert;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/recurrence-skip-dates.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/recurrence-skip-dates.schema.tsnew file mode 100644index 0000000..81ab363--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/recurrence-skip-dates.schema.ts@@ -0,0 +1,13 @@+import { date, integer, pgSchema, primaryKey, timestamp } from "drizzle-orm/pg-core";+import { RecurrenceRulesSchema } from "./recurrence-rules.schema";++export const RecurrenceSkipDatesSchema = pgSchema('tasks').table('recurrence_skip_dates', {+ ruleId: integer('rule_id').notNull().references(() => RecurrenceRulesSchema.id, { onDelete: 'cascade' }),+ skipDate: date('skip_date').notNull(),+ createdAt: timestamp('created_at').notNull().defaultNow(),+}, (table) => [+ primaryKey({ columns: [table.ruleId, table.skipDate] }),+]);++export type RecurrenceSkipDatesSchemaTypeForSelect = typeof RecurrenceSkipDatesSchema.$inferSelect;+export type RecurrenceSkipDatesSchemaTypeForInsert = typeof RecurrenceSkipDatesSchema.$inferInsert;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/recurrence-template-assignees.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/recurrence-template-assignees.schema.tsnew file mode 100644index 0000000..ed57060--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/recurrence-template-assignees.schema.ts@@ -0,0 +1,13 @@+import { integer, pgSchema, primaryKey } from "drizzle-orm/pg-core";+import { CollaborationUsersSchema } from "./collaboration-users.schema";+import { RecurrenceRulesSchema } from "./recurrence-rules.schema";++export const RecurrenceTemplateAssigneesSchema = pgSchema('tasks').table('recurrence_template_assignees', {+ ruleId: integer('rule_id').notNull().references(() => RecurrenceRulesSchema.id, { onDelete: 'cascade' }),+ collabUserId: integer('collab_user_id').notNull().references(() => CollaborationUsersSchema.id, { onDelete: 'cascade' }),+}, (table) => [+ primaryKey({ columns: [table.ruleId, table.collabUserId] }),+]);++export type RecurrenceTemplateAssigneesSchemaTypeForSelect = typeof RecurrenceTemplateAssigneesSchema.$inferSelect;+export type RecurrenceTemplateAssigneesSchemaTypeForInsert = typeof RecurrenceTemplateAssigneesSchema.$inferInsert;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/recurrence-template-tags.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/recurrence-template-tags.schema.tsnew file mode 100644index 0000000..04aaa5a--- /dev/null+++ b/taskview-packages/taskview-db-schemas/src/schemas/recurrence-template-tags.schema.ts@@ -0,0 +1,13 @@+import { integer, pgSchema, primaryKey } from "drizzle-orm/pg-core";+import { RecurrenceRulesSchema } from "./recurrence-rules.schema";+import { TagsSchema } from "./tags.schema";++export const RecurrenceTemplateTagsSchema = pgSchema('tasks').table('recurrence_template_tags', {+ ruleId: integer('rule_id').notNull().references(() => RecurrenceRulesSchema.id, { onDelete: 'cascade' }),+ tagId: integer('tag_id').notNull().references(() => TagsSchema.id, { onDelete: 'cascade' }),+}, (table) => [+ primaryKey({ columns: [table.ruleId, table.tagId] }),+]);++export type RecurrenceTemplateTagsSchemaTypeForSelect = typeof RecurrenceTemplateTagsSchema.$inferSelect;+export type RecurrenceTemplateTagsSchemaTypeForInsert = typeof RecurrenceTemplateTagsSchema.$inferInsert;diff --git a/taskview-packages/taskview-db-schemas/src/schemas/tasks.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/tasks.schema.tsindex d1ae6e8..62fe4a8 100644--- a/taskview-packages/taskview-db-schemas/src/schemas/tasks.schema.ts+++ b/taskview-packages/taskview-db-schemas/src/schemas/tasks.schema.ts@@ -27,6 +27,8 @@ export const TasksSchema = pgSchema('tasks').table('tasks', {sprintId: integer('sprint_id'),estimateValue: numeric('estimate_value', { precision: 10, scale: 2 }),dateComplete: timestamp('date_complete'),+ recurrenceRuleId: integer('recurrence_rule_id'),+ recurrenceInstanceDate: date('recurrence_instance_date'),});export type TasksSchemaTypeForSelect = typeof TasksSchema.$inferSelect;diff --git a/web/package.json b/web/package.jsonindex 2cc6a5f..fc54d85 100644--- a/web/package.json+++ b/web/package.json@@ -65,6 +65,7 @@"firebase": "^12.10.0","pinia": "^2.3.1","qs": "^6.14.1",+ "rrule": "^2.8.1","scule": "^1.3.0","tailwindcss": "^4.1.18","taskview-api": "workspace:^",diff --git a/web/src/components/features/tasks/parts/TaskDeadline.vue b/web/src/components/features/tasks/parts/TaskDeadline.vueindex 1008d9e..f13d639 100644--- a/web/src/components/features/tasks/parts/TaskDeadline.vue+++ b/web/src/components/features/tasks/parts/TaskDeadline.vue@@ -158,6 +158,9 @@@click="clearAllDates"/></div>++ <!-- Third row: recurrence -->+ <TaskRecurrence :task="task" /></div></template>@@ -167,6 +170,7 @@ import { useDateFormat } from '@vueuse/core'import { useI18n } from 'vue-i18n'import type { Task } from 'taskview-api'import { CalendarDate, Time } from '@internationalized/date'+import TaskRecurrence from './TaskRecurrence.vue'import { useTasksStore } from '@/stores/tasks.store'import { useColor } from '@/composables/useColotMode'import { useGoalPermissions } from '@/composables/useGoalPermissions'diff --git a/web/src/components/features/tasks/parts/TaskItem.vue b/web/src/components/features/tasks/parts/TaskItem.vueindex 03f70bf..1c1ab26 100644--- a/web/src/components/features/tasks/parts/TaskItem.vue+++ b/web/src/components/features/tasks/parts/TaskItem.vue@@ -44,6 +44,17 @@variant="subtle"size="md"/>++ <!-- Recurring series -->+ <UBadge+ v-if="task.recurrenceRuleId"+ icon="i-lucide-repeat"+ color="neutral"+ class="bg-elevated text-muted"+ :ui="{ leadingIcon: 'size-3' }"+ variant="subtle"+ size="md"+ /><!-- Project --><UBadge@@ -252,6 +263,7 @@ const hasAdditionalInfo = computed(() => {listName.value ||props.task.endDate ||props.task.amount ||+ props.task.recurrenceRuleId ||assigneeEmails.value.length > 0 ||taskTags.value.length > 0})diff --git a/web/src/components/features/tasks/parts/TaskRecurrence.vue b/web/src/components/features/tasks/parts/TaskRecurrence.vuenew file mode 100644index 0000000..a7b9cd6--- /dev/null+++ b/web/src/components/features/tasks/parts/TaskRecurrence.vue@@ -0,0 +1,93 @@+<template>+ <div class="flex items-center gap-2">+ <UButton+ :disabled="!canEditTaskDeadline"+ icon="i-lucide-repeat"+ :label="summary"+ color="neutral"+ :variant="isDark ? 'subtle' : 'outline'"+ class="flex-1 justify-start"+ size="xl"+ @click="dialogOpen = true"+ />+ <UBadge+ v-if="details?.rule.state === 'paused'"+ :label="t('recurrence.paused')"+ color="warning"+ variant="subtle"+ size="md"+ />+ <UBadge+ v-else-if="details?.rule.state === 'ended'"+ :label="t('recurrence.ended')"+ color="neutral"+ variant="subtle"+ size="md"+ />++ <TaskRecurrenceDialog+ v-model:open="dialogOpen"+ :task="task"+ :rule="details?.rule ?? null"+ @changed="reload"+ />+ </div>+</template>++<script setup lang="ts">+import { computed, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import type { RecurrenceRuleDetails, Task } from 'taskview-api'+import TaskRecurrenceDialog from './TaskRecurrenceDialog.vue'+import { parseRruleToForm } from '@/helpers/recurrence'+import { useColor } from '@/composables/useColotMode'+import { useGoalPermissions } from '@/composables/useGoalPermissions'+import { useTasksStore } from '@/stores/tasks.store'++const props = defineProps<{+ task: Task+}>()++const { t } = useI18n()+const { isDark } = useColor()+const { canEditTaskDeadline } = useGoalPermissions()+const tasksStore = useTasksStore()++const dialogOpen = ref(false)+const details = ref<RecurrenceRuleDetails | null>(null)++watch(+ () => props.task.recurrenceRuleId,+ () => reload(),+ { immediate: true },+)++async function reload() {+ details.value = props.task.recurrenceRuleId+ ? await tasksStore.fetchRecurrenceForTask(props.task.id)+ : null+}++const summary = computed(() => {+ if (!details.value) return t('recurrence.noRepeat')++ const rule = details.value.rule+ const form = parseRruleToForm({+ rrule: rule.rrule,+ dtstart: new Date(`${rule.dtstart.replace(' ', 'T')}Z`),+ notifyOnOccurrence: rule.notifyOnOccurrence,+ })++ const unit = t(`recurrence.units.${form.frequency}`)+ const base = form.interval > 1+ ? t('recurrence.summary.everyN', { n: form.interval, unit })+ : t(`recurrence.summary.${form.frequency}`)++ if (form.frequency === 'weekly' && form.weekdays.length > 0) {+ const dayKeys = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']+ const days = form.weekdays.map((d) => t(`recurrence.weekdays.${dayKeys[d]}`)).join(', ')+ return `${base} · ${days}`+ }+ return base+})+</script>diff --git a/web/src/components/features/tasks/parts/TaskRecurrenceDialog.vue b/web/src/components/features/tasks/parts/TaskRecurrenceDialog.vuenew file mode 100644index 0000000..1159b35--- /dev/null+++ b/web/src/components/features/tasks/parts/TaskRecurrenceDialog.vue@@ -0,0 +1,189 @@+<template>+ <UModal+ v-model:open="open"+ :fullscreen="isMobile"+ >+ <template #content>+ <UCard>+ <template #header>+ <div class="flex items-center justify-between">+ <h3 class="font-semibold">+ {{ t('recurrence.title') }}+ </h3>+ <UButton+ icon="i-lucide-x"+ variant="ghost"+ color="neutral"+ @click="open = false"+ />+ </div>+ </template>++ <TaskRecurrenceForm+ v-model="form"+ :dtstart="dtstart.date"+ />++ <template #footer>+ <div class="flex flex-wrap items-center gap-2">+ <template v-if="rule">+ <UButton+ :label="t('recurrence.skip')"+ icon="i-lucide-skip-forward"+ color="neutral"+ variant="outline"+ :loading="actionLoading === 'skip'"+ :disabled="rule.state !== 'active'"+ @click="skip"+ />+ <UButton+ :label="rule.state === 'paused' ? t('recurrence.resume') : t('recurrence.pause')"+ :icon="rule.state === 'paused' ? 'i-lucide-play' : 'i-lucide-pause'"+ color="neutral"+ variant="outline"+ :loading="actionLoading === 'pause'"+ @click="togglePause"+ />+ <UButton+ :label="t('recurrence.deleteSeries')"+ icon="i-lucide-trash-2"+ color="error"+ variant="outline"+ :loading="actionLoading === 'delete'"+ @click="removeSeries"+ />+ </template>+ <UButton+ :label="t('common.save')"+ class="ml-auto"+ :loading="actionLoading === 'save'"+ @click="save"+ />+ </div>+ </template>+ </UCard>+ </template>+ </UModal>+</template>++<script setup lang="ts">+import { computed, ref, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import type { RecurrenceRule, Task } from 'taskview-api'+import TaskRecurrenceForm from './TaskRecurrenceForm.vue'+import { buildRruleString, defaultRecurrenceForm, dtstartForTask, parseRruleToForm } from '@/helpers/recurrence'+import { useTaskView } from '@/composables/useTaskView'+import { useTasksStore } from '@/stores/tasks.store'+import type { RecurrenceFormValue } from '@/types/recurrence.types'++type DialogAction = 'save' | 'skip' | 'pause' | 'delete' | null++const open = defineModel<boolean>('open', { default: false })++const props = defineProps<{+ task: Task+ rule: RecurrenceRule | null+}>()++const emit = defineEmits<{+ changed: []+}>()++const { t } = useI18n()+const toast = useToast()+const { isMobile } = useTaskView()+const tasksStore = useTasksStore()++const actionLoading = ref<DialogAction>(null)++const dtstart = computed(() => {+ if (props.rule) {+ return { date: new Date(`${props.rule.dtstart.replace(' ', 'T')}Z`), iso: props.rule.dtstart }+ }+ return dtstartForTask({ startDate: props.task.startDate, startTime: props.task.startTime })+})++function initialForm(): RecurrenceFormValue {+ if (props.rule) {+ return parseRruleToForm({+ rrule: props.rule.rrule,+ dtstart: dtstart.value.date,+ notifyOnOccurrence: props.rule.notifyOnOccurrence,+ })+ }+ return defaultRecurrenceForm(dtstart.value.date)+}++const form = ref<RecurrenceFormValue>(initialForm())++watch(open, (value) => {+ if (value) form.value = initialForm()+})++async function save() {+ actionLoading.value = 'save'+ try {+ const rrule = buildRruleString({ form: form.value, dtstart: dtstart.value.date })+ // Always send the current browser timezone: the series is anchored to the+ // user's wall clock, so editing a rule after relocation re-anchors it+ // ("9:00" stays 9:00 wherever the user lives now).+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC'+ const result = props.rule+ ? await tasksStore.updateRecurrence({+ ruleId: props.rule.id,+ rrule,+ timezone,+ notifyOnOccurrence: form.value.notifyOnOccurrence,+ })+ : await tasksStore.createRecurrence({+ taskId: props.task.id,+ rrule,+ dtstart: dtstart.value.iso,+ timezone,+ notifyOnOccurrence: form.value.notifyOnOccurrence,+ })++ if (result) {+ toast.add({ title: t('recurrence.toasts.saved'), color: 'success' })+ emit('changed')+ open.value = false+ }+ } finally {+ actionLoading.value = null+ }+}++async function skip() {+ if (!props.rule) return+ actionLoading.value = 'skip'+ const details = await tasksStore.skipRecurrence({ ruleId: props.rule.id, taskId: props.task.id })+ actionLoading.value = null+ if (details) {+ toast.add({ title: t('recurrence.toasts.skipped'), color: 'success' })+ emit('changed')+ open.value = false+ }+}++async function togglePause() {+ if (!props.rule) return+ actionLoading.value = 'pause'+ const result = props.rule.state === 'paused'+ ? await tasksStore.resumeRecurrence(props.rule.id)+ : await tasksStore.pauseRecurrence(props.rule.id)+ actionLoading.value = null+ if (result) emit('changed')+}++async function removeSeries() {+ if (!props.rule) return+ actionLoading.value = 'delete'+ const deleted = await tasksStore.deleteRecurrence({ ruleId: props.rule.id, taskId: props.task.id })+ actionLoading.value = null+ if (deleted) {+ toast.add({ title: t('recurrence.toasts.deleted'), color: 'success' })+ emit('changed')+ open.value = false+ }+}+</script>diff --git a/web/src/components/features/tasks/parts/TaskRecurrenceForm.vue b/web/src/components/features/tasks/parts/TaskRecurrenceForm.vuenew file mode 100644index 0000000..7d8e196--- /dev/null+++ b/web/src/components/features/tasks/parts/TaskRecurrenceForm.vue@@ -0,0 +1,173 @@+<template>+ <div class="flex flex-col gap-4">+ <div class="flex gap-2">+ <USelect+ v-model="form.frequency"+ :items="frequencyItems"+ class="flex-1"+ size="lg"+ />+ <UInputNumber+ v-model="form.interval"+ :min="1"+ :max="99"+ class="w-28"+ size="lg"+ />+ </div>++ <div+ v-if="form.frequency === 'weekly'"+ class="flex flex-wrap gap-1.5"+ >+ <UButton+ v-for="(day, index) in weekdayLabels"+ :key="day"+ :label="day"+ :color="form.weekdays.includes(index) ? 'primary' : 'neutral'"+ :variant="form.weekdays.includes(index) ? 'solid' : 'outline'"+ size="sm"+ @click="toggleWeekday(index)"+ />+ </div>++ <USelect+ v-if="form.frequency === 'monthly'"+ v-model="form.monthlyMode"+ :items="monthlyModeItems"+ size="lg"+ />++ <div class="flex flex-col gap-2">+ <span class="text-sm font-medium">{{ t('recurrence.ends.title') }}</span>+ <URadioGroup+ v-model="form.ends"+ :items="endsItems"+ />+ <UInputNumber+ v-if="form.ends === 'after'"+ v-model="form.count"+ :min="1"+ :max="10000"+ class="w-40"+ size="md"+ />+ <UPopover v-if="form.ends === 'onDate'">+ <UButton+ icon="i-lucide-calendar"+ :label="form.untilDate ?? t('recurrence.ends.pickDate')"+ color="neutral"+ variant="outline"+ class="self-start"+ size="md"+ />+ <template #content>+ <UCalendar+ v-model="untilDateModel"+ class="p-2"+ :week-starts-on="weekStart"+ />+ </template>+ </UPopover>+ </div>++ <UCheckbox+ v-model="form.notifyOnOccurrence"+ :label="t('recurrence.notifyOnOccurrence')"+ :ui="{ root: 'items-center' }"+ />++ <div+ v-if="preview.length"+ class="flex flex-col gap-1 rounded-lg p-3 bg-elevated"+ >+ <span class="text-sm font-medium">{{ t('recurrence.preview') }}</span>+ <span+ v-for="date in preview"+ :key="date"+ class="text-sm text-muted"+ >+ {{ formatPreviewDate(date) }}+ </span>+ </div>+ </div>+</template>++<script setup lang="ts">+import { computed, shallowRef, watch } from 'vue'+import { useI18n } from 'vue-i18n'+import { useDateFormat } from '@vueuse/core'+import { CalendarDate } from '@internationalized/date'+import { buildRruleString, previewOccurrences } from '@/helpers/recurrence'+import { useWeekStart } from '@/composables/useWeekStart'+import type { RecurrenceFormValue } from '@/types/recurrence.types'++const PREVIEW_LIMIT = 5++const form = defineModel<RecurrenceFormValue>({ required: true })++const props = defineProps<{+ dtstart: Date+}>()++const { t } = useI18n()+const weekStart = useWeekStart()++const frequencyItems = computed(() => [+ { label: t('recurrence.frequency.daily'), value: 'daily' },+ { label: t('recurrence.frequency.weekly'), value: 'weekly' },+ { label: t('recurrence.frequency.monthly'), value: 'monthly' },+ { label: t('recurrence.frequency.yearly'), value: 'yearly' },+])++const monthlyModeItems = computed(() => [+ { label: t('recurrence.monthly.dayOfMonth', { day: props.dtstart.getUTCDate() }), value: 'dayOfMonth' },+ { label: t('recurrence.monthly.lastDay'), value: 'lastDay' },+])++const endsItems = computed(() => [+ { label: t('recurrence.ends.never'), value: 'never' },+ { label: t('recurrence.ends.after'), value: 'after' },+ { label: t('recurrence.ends.onDate'), value: 'onDate' },+])++const weekdayLabels = computed(() => [+ t('recurrence.weekdays.mon'),+ t('recurrence.weekdays.tue'),+ t('recurrence.weekdays.wed'),+ t('recurrence.weekdays.thu'),+ t('recurrence.weekdays.fri'),+ t('recurrence.weekdays.sat'),+ t('recurrence.weekdays.sun'),+])++function toggleWeekday(index: number) {+ const selected = form.value.weekdays.includes(index)+ if (selected && form.value.weekdays.length === 1) return+ form.value.weekdays = selected+ ? form.value.weekdays.filter((d) => d !== index)+ : [...form.value.weekdays, index].sort((a, b) => a - b)+}++const untilDateModel = shallowRef<CalendarDate | undefined>(+ form.value.untilDate ? parseCalendarDate(form.value.untilDate) : undefined,+)++watch(untilDateModel, (value) => {+ form.value.untilDate = value ? value.toString() : null+})++function parseCalendarDate(date: string): CalendarDate {+ const [year, month, day] = date.split('-').map(Number)+ return new CalendarDate(year, month, day)+}++const preview = computed(() => {+ const rrule = buildRruleString({ form: form.value, dtstart: props.dtstart })+ return previewOccurrences({ rrule, dtstart: props.dtstart, limit: PREVIEW_LIMIT })+})++function formatPreviewDate(date: string): string {+ return useDateFormat(new Date(`${date}T00:00:00`), 'ddd, DD MMM YYYY').value+}+</script>diff --git a/web/src/composables/useCentrifugo/handlers/index.ts b/web/src/composables/useCentrifugo/handlers/index.tsindex 49eb282..e0d93e1 100644--- a/web/src/composables/useCentrifugo/handlers/index.ts+++ b/web/src/composables/useCentrifugo/handlers/index.ts@@ -1,6 +1,7 @@import type { RealtimeEventMap, RealtimeHandler } from '../types'import { handleNotification } from './notification'import { handleGoalsChanged } from './goals-changed'+import { handleRecurrenceInstanceCreated } from './recurrence'import {handleTimeEntryCreated,handleTimeEntryDeleted,@@ -17,4 +18,5 @@ export const eventHandlers: { [K in keyof RealtimeEventMap]: RealtimeHandler<K>'time-entry.created': handleTimeEntryCreated,'time-entry.updated': handleTimeEntryUpdated,'time-entry.deleted': handleTimeEntryDeleted,+ 'recurrence.instanceCreated': handleRecurrenceInstanceCreated,}diff --git a/web/src/composables/useCentrifugo/handlers/recurrence.ts b/web/src/composables/useCentrifugo/handlers/recurrence.tsnew file mode 100644index 0000000..38fb2f1--- /dev/null+++ b/web/src/composables/useCentrifugo/handlers/recurrence.ts@@ -0,0 +1,6 @@+import { useTasksStore } from '@/stores/tasks.store'+import type { RealtimeEventMap } from '../types'++export function handleRecurrenceInstanceCreated(data: RealtimeEventMap['recurrence.instanceCreated']) {+ useTasksStore().handleRecurrenceInstanceCreated(data.task)+}diff --git a/web/src/composables/useCentrifugo/types.ts b/web/src/composables/useCentrifugo/types.tsindex aa26e1e..e26fc19 100644--- a/web/src/composables/useCentrifugo/types.ts+++ b/web/src/composables/useCentrifugo/types.ts@@ -1,4 +1,4 @@-import type { Notification, TimeEntryItem } from 'taskview-api'+import type { Notification, Task, TimeEntryItem } from 'taskview-api'export type RealtimeEventMap = {'notification': {@@ -34,6 +34,12 @@ export type RealtimeEventMap = {entryId: numbertaskId: number}+ 'recurrence.instanceCreated': {+ event: 'recurrence.instanceCreated'+ goalId: number+ ruleId: number+ task: Task+ }}export type RealtimeEvent = RealtimeEventMap[keyof RealtimeEventMap]diff --git a/web/src/helpers/recurrence.ts b/web/src/helpers/recurrence.tsnew file mode 100644index 0000000..dfe8c13--- /dev/null+++ b/web/src/helpers/recurrence.ts@@ -0,0 +1,124 @@+import { RRule, Weekday } from 'rrule'+import type { RecurrenceFormValue } from '@/types/recurrence.types'++const FREQ_TO_RRULE = {+ daily: RRule.DAILY,+ weekly: RRule.WEEKLY,+ monthly: RRule.MONTHLY,+ yearly: RRule.YEARLY,+} as const++const RRULE_TO_FREQ: Record<number, RecurrenceFormValue['frequency']> = {+ [RRule.DAILY]: 'daily',+ [RRule.WEEKLY]: 'weekly',+ [RRule.MONTHLY]: 'monthly',+ [RRule.YEARLY]: 'yearly',+}++/** JS Date.getDay() (0=Sun) → rrule weekday (0=Mon). */+export function jsDayToRruleWeekday(jsDay: number): number {+ return (jsDay + 6) % 7+}++export function defaultRecurrenceForm(dtstart: Date): RecurrenceFormValue {+ return {+ frequency: 'weekly',+ interval: 1,+ weekdays: [jsDayToRruleWeekday(dtstart.getUTCDay())],+ monthlyMode: 'dayOfMonth',+ ends: 'never',+ count: 10,+ untilDate: null,+ notifyOnOccurrence: false,+ }+}++export function buildRruleString(args: { form: RecurrenceFormValue; dtstart: Date }): string {+ const { form, dtstart } = args+ const options: ConstructorParameters<typeof RRule>[0] = {+ freq: FREQ_TO_RRULE[form.frequency],+ interval: form.interval > 1 ? form.interval : undefined,+ }+ if (form.frequency === 'weekly' && form.weekdays.length > 0) {+ options.byweekday = [...form.weekdays].sort((a, b) => a - b)+ }+ if (form.frequency === 'monthly') {+ options.bymonthday = form.monthlyMode === 'lastDay' ? -1 : dtstart.getUTCDate()+ }+ if (form.ends === 'after') {+ options.count = form.count+ } else if (form.ends === 'onDate' && form.untilDate) {+ // Floating wall-clock UNTIL: components are local, the Z suffix is technical (see backend RecurrenceParser).+ options.until = new Date(`${form.untilDate}T23:59:59Z`)+ }+ return RRule.optionsToString({ ...new RRule(options).origOptions }).replace(/^RRULE:/, '')+}++export function parseRruleToForm(args: { rrule: string; dtstart: Date; notifyOnOccurrence: boolean }): RecurrenceFormValue {+ const form = defaultRecurrenceForm(args.dtstart)+ form.notifyOnOccurrence = args.notifyOnOccurrence+ const options = RRule.parseString(args.rrule)+ if (options.freq !== undefined && RRULE_TO_FREQ[options.freq]) {+ form.frequency = RRULE_TO_FREQ[options.freq]+ }+ form.interval = options.interval ?? 1+ if (options.byweekday) {+ const days = Array.isArray(options.byweekday) ? options.byweekday : [options.byweekday]+ form.weekdays = days+ .map((d) => {+ if (typeof d === 'number') return d+ if (typeof d === 'string') return Weekday.fromStr(d).weekday+ return d.weekday+ })+ .sort((a, b) => a - b)+ }+ const monthday = Array.isArray(options.bymonthday) ? options.bymonthday[0] : options.bymonthday+ if (monthday === -1) form.monthlyMode = 'lastDay'+ if (options.count) {+ form.ends = 'after'+ form.count = options.count+ } else if (options.until) {+ form.ends = 'onDate'+ form.untilDate = options.until.toISOString().slice(0, 10)+ }+ return form+}++/** Next N occurrence dates ('YYYY-MM-DD') for the live preview. */+export function previewOccurrences(args: { rrule: string; dtstart: Date; limit: number }): string[] {+ try {+ const rule = new RRule({ ...RRule.parseString(args.rrule), dtstart: args.dtstart })+ return rule.all((_, index) => index < args.limit).map((d) => d.toISOString().slice(0, 10))+ } catch {+ return []+ }+}++/**+ * Wall-clock dtstart for a task: its start date+time, or today when unset.+ * Timed values are stored in UTC, while the series is anchored to the user's+ * wall clock (the browser timezone is what gets sent as the rule timezone) —+ * so the stored instant is converted to local components first.+ */+export function dtstartForTask(args: { startDate: string | null; startTime: string | null }): { date: Date; iso: string } {+ let iso: string+ if (args.startDate && args.startTime?.match(/^\d{2}:\d{2}/)) {+ const instant = new Date(`${args.startDate}T${args.startTime.slice(0, 5)}:00Z`)+ iso = `${formatLocalDate(instant)}T${formatLocalTime(instant)}`+ } else if (args.startDate) {+ iso = `${args.startDate}T00:00:00`+ } else {+ iso = `${formatLocalDate(new Date())}T00:00:00`+ }+ return { date: new Date(`${iso}Z`), iso }+}++function formatLocalDate(date: Date): string {+ const pad = (n: number) => String(n).padStart(2, '0')+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`+}++function formatLocalTime(date: Date): string {+ const pad = (n: number) => String(n).padStart(2, '0')+ return `${pad(date.getHours())}:${pad(date.getMinutes())}:00`+}diff --git a/web/src/locales/en.ts b/web/src/locales/en.tsindex 09e82ae..2e5b0d8 100644--- a/web/src/locales/en.ts+++ b/web/src/locales/en.ts@@ -204,6 +204,62 @@ export default {thisWeek: 'This week',thisMonth: 'This month',},+ recurrence: {+ title: 'Repeat',+ noRepeat: 'No repeat',+ paused: 'Paused',+ ended: 'Ended',+ skip: 'Skip occurrence',+ pause: 'Pause',+ resume: 'Resume',+ deleteSeries: 'Delete series',+ notifyOnOccurrence: 'Remind about each occurrence',+ preview: 'Next occurrences',+ frequency: {+ daily: 'Daily',+ weekly: 'Weekly',+ monthly: 'Monthly',+ yearly: 'Yearly',+ },+ units: {+ daily: 'days',+ weekly: 'weeks',+ monthly: 'months',+ yearly: 'years',+ },+ summary: {+ daily: 'Daily',+ weekly: 'Weekly',+ monthly: 'Monthly',+ yearly: 'Yearly',+ everyN: 'Every {n} {unit}',+ },+ weekdays: {+ mon: 'Mon',+ tue: 'Tue',+ wed: 'Wed',+ thu: 'Thu',+ fri: 'Fri',+ sat: 'Sat',+ sun: 'Sun',+ },+ monthly: {+ dayOfMonth: 'On day {day}',+ lastDay: 'On the last day of the month',+ },+ ends: {+ title: 'Ends',+ never: 'Never',+ after: 'After N occurrences',+ onDate: 'On date',+ pickDate: 'Pick a date',+ },+ toasts: {+ saved: 'Recurrence saved',+ skipped: 'Occurrence skipped',+ deleted: 'Series deleted',+ },+ },graph: {title: 'Graph',description: 'Graph view coming soon',diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.tsindex 592cfa1..56c6bbb 100644--- a/web/src/locales/ru.ts+++ b/web/src/locales/ru.ts@@ -204,6 +204,62 @@ export default {thisWeek: 'Эта неделя',thisMonth: 'Этот месяц',},+ recurrence: {+ title: 'Повторение',+ noRepeat: 'Не повторяется',+ paused: 'На паузе',+ ended: 'Завершена',+ skip: 'Пропустить повторение',+ pause: 'Пауза',+ resume: 'Продолжить',+ deleteSeries: 'Удалить серию',+ notifyOnOccurrence: 'Напоминать о каждом повторении',+ preview: 'Ближайшие повторения',+ frequency: {+ daily: 'Ежедневно',+ weekly: 'Еженедельно',+ monthly: 'Ежемесячно',+ yearly: 'Ежегодно',+ },+ units: {+ daily: 'дн.',+ weekly: 'нед.',+ monthly: 'мес.',+ yearly: 'г.',+ },+ summary: {+ daily: 'Ежедневно',+ weekly: 'Еженедельно',+ monthly: 'Ежемесячно',+ yearly: 'Ежегодно',+ everyN: 'Каждые {n} {unit}',+ },+ weekdays: {+ mon: 'Пн',+ tue: 'Вт',+ wed: 'Ср',+ thu: 'Чт',+ fri: 'Пт',+ sat: 'Сб',+ sun: 'Вс',+ },+ monthly: {+ dayOfMonth: '{day}-го числа',+ lastDay: 'В последний день месяца',+ },+ ends: {+ title: 'Окончание',+ never: 'Никогда',+ after: 'После N повторений',+ onDate: 'В дату',+ pickDate: 'Выбрать дату',+ },+ toasts: {+ saved: 'Повторение сохранено',+ skipped: 'Повторение пропущено',+ deleted: 'Серия удалена',+ },+ },graph: {title: 'Граф',description: 'Вид графа скоро будет доступен',diff --git a/web/src/stores/tasks.store.ts b/web/src/stores/tasks.store.tsindex 902d699..ffebfc2 100644--- a/web/src/stores/tasks.store.ts+++ b/web/src/stores/tasks.store.ts@@ -1,6 +1,10 @@import { defineStore } from 'pinia'import {ALL_TASKS_LIST_ID,+ type RecurrenceCreateArgs,+ type RecurrenceRule,+ type RecurrenceRuleDetails,+ type RecurrenceUpdateArgs,type TagItemArgToggle,type Task,type TaskArgAdd,@@ -570,5 +574,74 @@ export const useTasksStore = defineStore('tasks', {Object.assign(this.selectedTask, task)}},++ setLocalTaskRecurrence(data: { taskId: number; ruleId: number | null }) {+ const localTask = this.tasks.find(({ id }) => id === data.taskId)+ if (localTask) localTask.recurrenceRuleId = data.ruleId+ if (this.selectedTask?.id === data.taskId) {+ this.selectedTask.recurrenceRuleId = data.ruleId+ }+ },++ async fetchRecurrenceForTask(taskId: number): Promise<RecurrenceRuleDetails | null> {+ return await $tvApi.recurrence.getForTask(taskId).catch(() => null) ?? null+ },++ async createRecurrence(args: RecurrenceCreateArgs): Promise<RecurrenceRule | null> {+ const rule = await $tvApi.recurrence.create(args).catch(logError)+ if (!rule) return null+ this.setLocalTaskRecurrence({ taskId: args.taskId, ruleId: rule.id })+ return rule+ },++ async updateRecurrence(args: RecurrenceUpdateArgs): Promise<RecurrenceRule | null> {+ return await $tvApi.recurrence.update(args).catch(logError) || null+ },++ async pauseRecurrence(ruleId: number): Promise<RecurrenceRule | null> {+ return await $tvApi.recurrence.pause(ruleId).catch(logError) || null+ },++ async resumeRecurrence(ruleId: number): Promise<RecurrenceRule | null> {+ return await $tvApi.recurrence.resume(ruleId).catch(logError) || null+ },++ /** The current occurrence is removed and the card jumps to the next date. */+ async skipRecurrence(args: { ruleId: number; taskId: number }): Promise<RecurrenceRuleDetails | null> {+ const details = await $tvApi.recurrence.skip(args.ruleId).catch(logError)+ if (!details) return null++ this.tasks = this.tasks.filter(({ id }) => id !== args.taskId)+ if (details.openInstance) {+ this.handleRecurrenceInstanceCreated(details.openInstance)+ if (this.selectedTask?.id === args.taskId) {+ this.selectedTask = details.openInstance+ }+ } else if (this.selectedTask?.id === args.taskId) {+ this.selectedTask = null+ }+ return details+ },++ async deleteRecurrence(args: { ruleId: number; taskId: number }): Promise<boolean> {+ const result = await $tvApi.recurrence.remove(args.ruleId).catch(logError)+ if (!result) return false+ this.setLocalTaskRecurrence({ taskId: args.taskId, ruleId: null })+ return true+ },++ /** Realtime: the next instance of a series was materialized on the server. */+ handleRecurrenceInstanceCreated(task: Task) {+ if (this.tasks.some(({ id }) => id === task.id)) return+ if (Number(this.fetchRules.goalId) !== task.goalId) return+ // Raw realtime payload may carry no relations — normalize to the client Task shape.+ this.tasks.unshift({+ ...task,+ tags: task.tags ?? [],+ assignedUsers: task.assignedUsers ?? [],+ subtasks: task.subtasks ?? [],+ historyId: task.historyId ?? null,+ })+ },},})diff --git a/web/src/types/recurrence.types.ts b/web/src/types/recurrence.types.tsnew file mode 100644index 0000000..50ce8aa--- /dev/null+++ b/web/src/types/recurrence.types.ts@@ -0,0 +1,16 @@+export type RecurrenceFrequency = 'daily' | 'weekly' | 'monthly' | 'yearly'+export type RecurrenceEndsMode = 'never' | 'after' | 'onDate'+export type RecurrenceMonthlyMode = 'dayOfMonth' | 'lastDay'++export type RecurrenceFormValue = {+ frequency: RecurrenceFrequency+ interval: number+ /** rrule weekday numbers: 0=Mon … 6=Sun. Used when frequency is 'weekly'. */+ weekdays: number[]+ monthlyMode: RecurrenceMonthlyMode+ ends: RecurrenceEndsMode+ count: number+ /** 'YYYY-MM-DD', used when ends is 'onDate'. */+ untilDate: string | null+ notifyOnOccurrence: boolean+}