Skip to content

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.

wip: files quota & fixes & task move & #125

Nikolai Giman97323466d730
diff --git a/LICENSE.md b/LICENSE.md
index 3b640cd..ab73b9e 100644
--- a/LICENSE.md
+++ b/LICENSE.md
@@ -1,6 +1,6 @@
# TaskView Source-Available License
-Version 1.0
+Version 1.1
---
@@ -30,6 +30,10 @@ This license makes the TaskView source code available while:
**“Organization”** means the legal entity You represent (if any).
+**“Affiliate”** means any legal entity that controls, is controlled by, or is under common control with Your Organization (for example, a parent company, subsidiary, or sister company in the same corporate group), where “control” means ownership of more than 50% of the voting interests or the power to direct the entity's management.
+
+For avoidance of doubt, an Affiliate is a separate legal entity and is a third party under this License. Employees and contractors of an Affiliate are not Your Permitted Users unless they are also Your own employees or contractors acting on Your behalf. Each Affiliate may use the Software for its own Internal Use under its own copy of this License, on its own infrastructure.
+
**“Internal Use”** means use of the Software solely by Permitted Users for Your own personal or organizational purposes.
**“Managed Service”** means providing the Software (or a material portion of it) to third parties as a hosted service, SaaS, subscription access, or “service bureau” offering, whether paid or free.
@@ -37,6 +41,7 @@ This license makes the TaskView source code available while:
For avoidance of doubt, Managed Service includes:
- “hosting or operating the Software for the benefit of a third party (e.g., a client), even if provided as part of consulting or IT services;”
- “providing third parties access to Your instance of the Software (accounts, workspaces, or shared projects), whether paid or free.”
+- “hosting or operating a single instance of the Software for several Affiliates, or for a corporate group as a whole (for example, shared group IT services), even when no fee is charged between the entities.”
**“Competing Product”** means any software or service whose primary purpose is project/task management or work tracking, that is offered to third parties (commercially or as a service), and that is reasonably substitutable for TaskView, including products targeting a specific vertical market (e.g., medical, legal, or industrial).
@@ -91,6 +96,7 @@ If You want to:
* offer TaskView as a hosted or managed service
* provide access to TaskView to third parties outside Permitted Users
+* run a single TaskView instance shared by several entities of a corporate group (Affiliates)
* build or sell a competing product based on TaskView
You must obtain a separate commercial license from the copyright holder.
diff --git a/api/.env.example b/api/.env.example
index e9ee1f1..4c991e2 100644
--- a/api/.env.example
+++ b/api/.env.example
@@ -1,5 +1,7 @@
# Node Environment
NODE_ENV=development
+# Log level: fatal, error, warn, info, debug, trace or silent (default: info in production, debug otherwise)
+# LOG_LEVEL=info
# Database Configuration
DB_HOST=localhost
@@ -103,7 +105,7 @@ GITEA_INTEGRATION_CALLBACK_URL=http://localhost:1401/module/integrations/oauth/g
# local needs FILE_STORAGE_LOCAL_DIR (mount it as a volume in Docker), s3 needs the FILE_STORAGE_S3_* variables below.
# Both providers may be configured at once; FILE_STORAGE_PROVIDER is the one new uploads go to.
# FILE_STORAGE_PROVIDER=local
-# FILE_MAX_SIZE_MB=50
+# FILE_MAX_SIZE_MB=10
# FILE_STORAGE_LOCAL_DIR=./data/files
# FILE_STORAGE_S3_BUCKET=taskview
# FILE_STORAGE_S3_REGION=us-east-1
@@ -111,3 +113,10 @@ GITEA_INTEGRATION_CALLBACK_URL=http://localhost:1401/module/integrations/oauth/g
# FILE_STORAGE_S3_ACCESS_KEY=
# FILE_STORAGE_S3_SECRET_KEY=
# FILE_STORAGE_S3_FORCE_PATH_STYLE=true
+# Storage quotas: enforce (default, reject uploads over the quota) or off.
+# Every organization gets FILE_QUOTA_ORGANIZATION_MB unless tv_auth.organizations.file_quota_mb sets its own value.
+# FILE_QUOTA_MODE=enforce
+# FILE_QUOTA_ORGANIZATION_MB=100
+
+# SSO: allow the server to fetch IdP metadata from private addresses (self-hosted IdP on the internal network)
+# SSO_ALLOW_PRIVATE_URLS=false
diff --git a/api/src/App.ts b/api/src/App.ts
index 45b6f3a..2cbcabe 100644
--- a/api/src/App.ts
+++ b/api/src/App.ts
@@ -9,6 +9,7 @@ import { LoginMethods } from './tv-modules/auth/LoginMethods';
import { InviteEmailDispatcher } from './tv-modules/collaboration/InviteEmailDispatcher';
import { PublicApiUrl } from './modules/public-url';
import { validateWebhooksEnvOnStartup } from './tv-modules/webhooks/webhooks.utils';
+import { validateSsoEnvOnStartup } from './tv-modules/sso/sso.utils';
import { FileStorageFactory } from './tv-modules/files/storage/FileStorageFactory';
import cookieParser from 'cookie-parser';
import { registerAllEventHandlers, startAllWorkers } from './core/all-events';
@@ -22,6 +23,7 @@ export default class App {
PublicApiUrl.validateOnStartup();
InviteEmailDispatcher.validateOnStartup();
validateWebhooksEnvOnStartup();
+ validateSsoEnvOnStartup();
FileStorageFactory.validateOnStartup();
this.app = express();
diff --git a/api/src/core/EventBus.ts b/api/src/core/EventBus.ts
index a7885d0..69c56ae 100644
--- a/api/src/core/EventBus.ts
+++ b/api/src/core/EventBus.ts
@@ -1,4 +1,5 @@
import { EventEmitter } from 'node:events';
+import { FileEvents, type FileEventPayload } from '../tv-modules/files/types';
import type { RecurrenceRulesSchemaTypeForSelect, SprintsSchemaTypeForSelect, TasksSchemaTypeForSelect } from 'taskview-db-schemas';
import type { TimeEntryWithUser } from '../tv-modules/time-tracking/types';
import type { InviteEmailLocale } from '../tv-modules/collaboration/collaboration.server.types';
@@ -9,6 +10,8 @@ export interface AppEvents {
'task.updated': { task: TasksSchemaTypeForSelect; changes: Record<string, unknown>; initiatorId: number };
'task.assigneesChanged': { taskId: number; userIds: number[]; initiatorId: number };
'task.deleted': { taskId: number; goalId: number; initiatorId: number };
+ // A task (with the subtasks in taskIds) moved to another project; the copy mode emits task.created instead
+ 'task.moved': { task: TasksSchemaTypeForSelect; taskIds: number[]; fromGoalId: number; toGoalId: number; initiatorId: number };
'collaboration.userAdded': { goalId: number; email: string; initiatorId: number; locale: InviteEmailLocale };
'collaboration.userRemoved': { goalId: number; collaborationUserId: number; initiatorId: number };
'collaboration.rolesChanged': { goalId: number; collaborationUserId: number; initiatorId: number };
@@ -40,6 +43,11 @@ export interface AppEvents {
'recurrence.deleted': { ruleId: number; goalId: number; initiatorId: number };
'recurrence.instanceSkipped': { ruleId: number; goalId: number; date: string; initiatorId: number };
'files.changed': { goalId: number; taskIds: number[]; initiatorId: number };
+ [FileEvents.Uploaded]: FileEventPayload;
+ [FileEvents.Renamed]: FileEventPayload;
+ [FileEvents.Deleted]: FileEventPayload;
+ [FileEvents.Attached]: FileEventPayload;
+ [FileEvents.Detached]: FileEventPayload;
}
type EventName = keyof AppEvents;
diff --git a/api/src/migrations/taskview/migrate.json b/api/src/migrations/taskview/migrate.json
index acff472..c7ad81f 100644
--- a/api/src/migrations/taskview/migrate.json
+++ b/api/src/migrations/taskview/migrate.json
@@ -816,5 +816,17 @@
"Storage provider per file (local or s3) so an instance can be migrated between providers without downtime.",
"New permission group 7 'files' with file_can_view (list, open, download) and file_can_manage (upload, rename, link, unlink, delete). New projects grant them to editor (both) and executor (view) through the updated add_roles_and_permissions() trigger. Existing projects are not backfilled: owners grant the permissions to their roles in the role editor."
]
+ },
+ "63": {
+ "version": "1.68.0",
+ "name": "Files: storage quotas",
+ "releaseDate": "20261005",
+ "scripts": [
+ "/1.68.0/0.alter-organizations-file-quota.sql"
+ ],
+ "description": [
+ "New column tv_auth.organizations.file_quota_mb (megabytes, NULL by default). Every organization has its own file storage quota: this column when set, otherwise the instance default FILE_QUOTA_ORGANIZATION_MB.",
+ "Quotas are enforced by default (100 MB per organization, FILE_QUOTA_ORGANIZATION_MB); FILE_QUOTA_MODE=off disables them."
+ ]
}
}
diff --git a/api/src/migrations/taskview/sql/1.68.0/0.alter-organizations-file-quota.sql b/api/src/migrations/taskview/sql/1.68.0/0.alter-organizations-file-quota.sql
new file mode 100644
index 0000000..76b3269
--- /dev/null
+++ b/api/src/migrations/taskview/sql/1.68.0/0.alter-organizations-file-quota.sql
@@ -0,0 +1,3 @@
+-- File storage quota of an organization in megabytes. NULL (the default) means the instance-wide default
+-- (FILE_QUOTA_ORGANIZATION_MB) applies. Set by billing or an administrator, never by the API.
+ALTER TABLE tv_auth.organizations ADD COLUMN IF NOT EXISTS file_quota_mb INTEGER CHECK (file_quota_mb IS NULL OR file_quota_mb >= 0);
diff --git a/api/src/modules/__tests__/log-level.spec.ts b/api/src/modules/__tests__/log-level.spec.ts
new file mode 100644
index 0000000..6558093
--- /dev/null
+++ b/api/src/modules/__tests__/log-level.spec.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+import { resolveLogLevel } from '../log-level';
+
+describe('resolveLogLevel', () => {
+ it('keeps the old defaults when LOG_LEVEL is not set', () => {
+ expect(resolveLogLevel({ NODE_ENV: 'production' })).toEqual({ level: 'info', invalidValue: null });
+ expect(resolveLogLevel({ NODE_ENV: 'development' })).toEqual({ level: 'debug', invalidValue: null });
+ expect(resolveLogLevel({ NODE_ENV: 'production', LOG_LEVEL: ' ' })).toEqual({ level: 'info', invalidValue: null });
+ });
+
+ it('takes any pino level from LOG_LEVEL, case and spaces aside', () => {
+ expect(resolveLogLevel({ NODE_ENV: 'production', LOG_LEVEL: 'debug' }).level).toBe('debug');
+ expect(resolveLogLevel({ NODE_ENV: 'development', LOG_LEVEL: ' WARN ' }).level).toBe('warn');
+ expect(resolveLogLevel({ LOG_LEVEL: 'silent' }).level).toBe('silent');
+ expect(resolveLogLevel({ LOG_LEVEL: 'trace' }).level).toBe('trace');
+ });
+
+ it('falls back to the default and reports an unknown value', () => {
+ expect(resolveLogLevel({ NODE_ENV: 'production', LOG_LEVEL: 'verbose' })).toEqual({ level: 'info', invalidValue: 'verbose' });
+ expect(resolveLogLevel({ NODE_ENV: 'development', LOG_LEVEL: 'loud' })).toEqual({ level: 'debug', invalidValue: 'loud' });
+ });
+});
diff --git a/api/src/modules/log-level.ts b/api/src/modules/log-level.ts
new file mode 100644
index 0000000..a352ad6
--- /dev/null
+++ b/api/src/modules/log-level.ts
@@ -0,0 +1,16 @@
+import type { LevelWithSilent } from 'pino';
+
+export const LOG_LEVELS: readonly LevelWithSilent[] = ['fatal', 'error', 'warn', 'info', 'debug', 'trace', 'silent'];
+
+export type LogLevelResolution = {
+ level: LevelWithSilent;
+ invalidValue: string | null;
+};
+
+export function resolveLogLevel(env: NodeJS.ProcessEnv): LogLevelResolution {
+ const fallback: LevelWithSilent = env.NODE_ENV === 'production' ? 'info' : 'debug';
+ const raw = env.LOG_LEVEL?.trim().toLowerCase();
+ if (!raw) return { level: fallback, invalidValue: null };
+ const known = LOG_LEVELS.find((level) => level === raw);
+ return known ? { level: known, invalidValue: null } : { level: fallback, invalidValue: env.LOG_LEVEL as string };
+}
diff --git a/api/src/modules/logget.ts b/api/src/modules/logget.ts
index fbd3105..abf9dd6 100644
--- a/api/src/modules/logget.ts
+++ b/api/src/modules/logget.ts
@@ -1,6 +1,7 @@
import path from 'path';
import pino from 'pino';
import { createStream } from 'rotating-file-stream';
+import { LOG_LEVELS, resolveLogLevel } from './log-level';
const generator = () => {
const date = new Date();
@@ -15,10 +16,12 @@ const logStream = createStream(generator, {
path: path.join('./logs'),
});
+const { level, invalidValue } = resolveLogLevel(process.env);
-export const $logger = pino(
- {
- level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
- },
- logStream
-);
+export const $logger = pino({ level }, logStream);
+
+if (invalidValue !== null) {
+ const message = `[logger] LOG_LEVEL="${invalidValue}" is not supported (${LOG_LEVELS.join(', ')}) - using ${level}`;
+ console.warn(message);
+ $logger.warn(message);
+}
diff --git a/api/src/tv-modules/files/FileQuotaResolver.ts b/api/src/tv-modules/files/FileQuotaResolver.ts
new file mode 100644
index 0000000..b48463c
--- /dev/null
+++ b/api/src/tv-modules/files/FileQuotaResolver.ts
@@ -0,0 +1,30 @@
+import type { FilesRepository } from './FilesRepository';
+import type { FileQuotaMode, FileQuotaResolverArgs, FileQuotaState } from './types';
+
+const BYTES_PER_MB = 1024 * 1024;
+
+export class FileQuotaResolver {
+ private readonly repository: FilesRepository;
+ private readonly mode: FileQuotaMode;
+ private readonly defaultOrganizationQuotaBytes: number;
+
+ constructor(args: FileQuotaResolverArgs) {
+ this.repository = args.repository;
+ this.mode = args.mode;
+ this.defaultOrganizationQuotaBytes = args.defaultOrganizationQuotaBytes;
+ }
+
+ async forGoal(goalId: number): Promise<FileQuotaState> {
+ if (this.mode === 'off') return { mode: 'off', quotaBytes: null, usedBytes: null, organizationId: null };
+
+ const organization = await this.repository.quotaOrganizationForGoal(goalId);
+ if (!organization) return { mode: this.mode, quotaBytes: null, usedBytes: null, organizationId: null };
+
+ return {
+ mode: this.mode,
+ organizationId: organization.organizationId,
+ quotaBytes: organization.quotaMb !== null ? organization.quotaMb * BYTES_PER_MB : this.defaultOrganizationQuotaBytes,
+ usedBytes: await this.repository.usedBytesInOrganization(organization.organizationId),
+ };
+ }
+}
diff --git a/api/src/tv-modules/files/FilesController.ts b/api/src/tv-modules/files/FilesController.ts
index aa3b13c..3477d39 100644
--- a/api/src/tv-modules/files/FilesController.ts
+++ b/api/src/tv-modules/files/FilesController.ts
@@ -28,6 +28,7 @@ const codeToStatus: Record<FileErrorCode, number> = {
invalid: 400,
storage_error: 500,
storage_not_configured: 503,
+ quota_exceeded: 507,
};
type IncomingFile = { stream: Readable; filename: string; mimeType: string };
@@ -42,6 +43,12 @@ export default class FilesController {
return res.tvJson(req.appUser.filesManager.status());
};
+ quota = async (req: Request, res: Response) => {
+ const params = FileArkTypeGoalIdParam(req.params);
+ if (params instanceof type.errors) return res.status(400).send(params.summary);
+ return res.tvJson(await req.appUser.filesManager.quotaForGoal(params.goalId));
+ };
+
upload = async (req: Request, res: Response) => {
const params = FileArkTypeGoalIdParam(req.params);
if (params instanceof type.errors) return res.status(400).send(params.summary);
diff --git a/api/src/tv-modules/files/FilesManager.ts b/api/src/tv-modules/files/FilesManager.ts
index 421e638..e3bc6c1 100644
--- a/api/src/tv-modules/files/FilesManager.ts
+++ b/api/src/tv-modules/files/FilesManager.ts
@@ -5,21 +5,27 @@ import { eventBus } from '../../core/EventBus';
import { $logger } from '../../modules/logget';
import { TasksRepository } from '../tasks/TasksRepository';
import { FileDownloadTokens } from './FileDownloadTokens';
+import { FileQuotaResolver } from './FileQuotaResolver';
import { FilesRepository } from './FilesRepository';
import { FileStorageFactory } from './storage/FileStorageFactory';
import { FileTooLargeError, HashingStream } from './storage/HashingStream';
import {
FILE_DOWNLOAD_TOKEN_TTL_SECONDS,
FILE_NAME_MAX_LENGTH,
+ FILE_QUOTA_EXCEEDED_MESSAGE,
FILE_STORAGE_NOT_CONFIGURED_MESSAGE,
+ FileEvents,
type FileContent,
type FileDownloadUrl,
type FileDto,
+ type FileEmitEventArgs,
type FileErrorCode,
+ type FileInsertArgs,
type FileIssueDownloadUrlArgs,
type FileLinkArgs,
type FileListArgs,
type FileListPage,
+ type FileQuotaDto,
type FileRenameArgs,
type FileResult,
type FileStorageStatusDto,
@@ -57,6 +63,16 @@ export class FilesManager {
return this.storages.status();
}
+ private get quotas(): FileQuotaResolver {
+ const { mode, defaultOrganizationQuotaBytes } = this.storages.quota;
+ return new FileQuotaResolver({ repository: this.repository, mode, defaultOrganizationQuotaBytes });
+ }
+
+ async quotaForGoal(goalId: number): Promise<FileQuotaDto> {
+ const { organizationId: _organizationId, ...quota } = await this.quotas.forGoal(goalId);
+ return quota;
+ }
+
async upload(args: FileUploadArgs): Promise<FileResult<FileDto>> {
if (!this.storages.isConfigured) return fail('storage_not_configured', FILE_STORAGE_NOT_CONFIGURED_MESSAGE);
if (args.taskId !== null) {
@@ -65,10 +81,22 @@ export class FilesManager {
if (task.goalId !== args.goalId) return fail('forbidden', 'task belongs to another project');
}
+ const quota = await this.quotas.forGoal(args.goalId);
+ const remainingBytes =
+ quota.mode === 'enforce' && quota.quotaBytes !== null && quota.usedBytes !== null
+ ? Math.max(0, quota.quotaBytes - quota.usedBytes)
+ : null;
+ if (remainingBytes === 0) {
+ args.stream.resume();
+ return fail('quota_exceeded', FILE_QUOTA_EXCEEDED_MESSAGE);
+ }
+
+ const limitBytes = remainingBytes === null ? this.maxFileSizeBytes : Math.min(this.maxFileSizeBytes, remainingBytes);
+
const storage = this.storages.active();
const fileId = randomUUID();
const storageKey = `${args.goalId}/${fileId}`;
- const hashing = new HashingStream(this.maxFileSizeBytes);
+ const hashing = new HashingStream(limitBytes);
args.stream.on('error', (err) => hashing.destroy(err));
let sizeBytes: number;
@@ -78,31 +106,43 @@ export class FilesManager {
} catch (err) {
args.stream.resume();
await storage.delete(storageKey).catch(() => undefined);
- if (err instanceof FileTooLargeError) return fail('too_large', err.message);
+ if (err instanceof FileTooLargeError) {
+ if (limitBytes < this.maxFileSizeBytes) return fail('quota_exceeded', FILE_QUOTA_EXCEEDED_MESSAGE);
+ return fail('too_large', err.message);
+ }
$logger.error(err, '[FilesManager] storage put failed');
return fail('storage_error');
}
- let row: FilesSchemaTypeForSelect;
+ const fileRow: FileInsertArgs = {
+ id: fileId,
+ goalId: args.goalId,
+ uploaderId: args.uploaderId,
+ uploaderEmail: args.uploaderEmail,
+ name: this.normalizeName(args.originalName),
+ originalName: this.normalizeName(args.originalName),
+ mimeType: args.mimeType,
+ sizeBytes,
+ checksumSha256: hashing.digestHex(),
+ storageProvider: storage.provider,
+ storageKey,
+ };
+
+ let row: FilesSchemaTypeForSelect | null;
try {
- row = await this.repository.insert({
- id: fileId,
- goalId: args.goalId,
- uploaderId: args.uploaderId,
- uploaderEmail: args.uploaderEmail,
- name: this.normalizeName(args.originalName),
- originalName: this.normalizeName(args.originalName),
- mimeType: args.mimeType,
- sizeBytes,
- checksumSha256: hashing.digestHex(),
- storageProvider: storage.provider,
- storageKey,
- });
+ row =
+ quota.mode === 'enforce' && quota.organizationId !== null && quota.quotaBytes !== null
+ ? await this.repository.insertWithinQuota({ row: fileRow, organizationId: quota.organizationId, quotaBytes: quota.quotaBytes })
+ : await this.repository.insert(fileRow);
} catch (err) {
await storage.delete(storageKey).catch(() => undefined);
$logger.error(err, '[FilesManager] insert failed');
return fail('storage_error');
}
+ if (!row) {
+ await storage.delete(storageKey).catch(() => undefined);
+ return fail('quota_exceeded', FILE_QUOTA_EXCEEDED_MESSAGE);
+ }
const linkedTaskIds: number[] = [];
if (args.taskId !== null) {
@@ -115,8 +155,10 @@ export class FilesManager {
linkedTaskIds.push(args.taskId);
}
+ const dto = this.toDto(row, linkedTaskIds);
this.emitChanged(args.goalId, linkedTaskIds);
- return ok(this.toDto(row, linkedTaskIds));
+ this.emitFileEvent({ event: FileEvents.Uploaded, file: dto, taskIds: linkedTaskIds });
+ return ok(dto);
}
async listForGoal(args: FileListArgs): Promise<FileListPage> {
@@ -147,8 +189,10 @@ export class FilesManager {
if (files.some((f) => f.goalId !== task.goalId)) return fail('forbidden', 'file belongs to another project');
await this.repository.link(args);
+ const dtos = await this.toDtos(files);
this.emitChanged(task.goalId, [args.taskId]);
- return ok(await this.toDtos(files));
+ for (const dto of dtos) this.emitFileEvent({ event: FileEvents.Attached, file: dto, taskIds: [args.taskId] });
+ return ok(dtos);
}
async unlink(args: FileUnlinkArgs): Promise<FileResult<null>> {
@@ -156,7 +200,9 @@ export class FilesManager {
if (!file) return fail('not_found');
const removed = await this.repository.unlink(args);
if (!removed) return fail('not_found', 'file is not linked to this task');
+ const [dto] = await this.toDtos([file]);
this.emitChanged(file.goalId, [args.taskId]);
+ this.emitFileEvent({ event: FileEvents.Detached, file: dto, taskIds: [args.taskId] });
return ok(null);
}
@@ -166,15 +212,19 @@ export class FilesManager {
const name = this.keepExtension(this.normalizeName(args.name), current.originalName);
const row = await this.repository.rename({ fileId: args.fileId, name });
if (!row) return fail('not_found');
- const linked = await this.repository.linkedTaskIdsFor([row.id]);
- this.emitChanged(row.goalId, linked.get(row.id) ?? []);
- return ok(this.toDto(row, linked.get(row.id) ?? []));
+ const taskIds = (await this.repository.linkedTaskIdsFor([row.id])).get(row.id) ?? [];
+ const dto = this.toDto(row, taskIds);
+ this.emitChanged(row.goalId, taskIds);
+ this.emitFileEvent({ event: FileEvents.Renamed, file: dto, taskIds });
+ return ok(dto);
}
async deleteForever(fileId: string): Promise<FileResult<null>> {
const file = await this.repository.getById(fileId);
if (!file) return fail('not_found');
const linked = (await this.repository.linkedTaskIdsFor([fileId])).get(fileId) ?? [];
+ // Snapshot before the row is gone: the event describes the file that was deleted
+ const dto = this.toDto(file, linked);
await this.repository.delete(fileId);
try {
@@ -184,6 +234,7 @@ export class FilesManager {
}
this.emitChanged(file.goalId, linked);
+ this.emitFileEvent({ event: FileEvents.Deleted, file: dto, taskIds: linked });
return ok(null);
}
@@ -215,6 +266,15 @@ export class FilesManager {
eventBus.emit('files.changed', { goalId, taskIds, initiatorId: this.initiatorId });
}
+ private emitFileEvent(args: FileEmitEventArgs) {
+ eventBus.emit(args.event, {
+ goalId: args.file.goalId,
+ file: args.file,
+ taskIds: args.taskIds,
+ initiatorId: this.initiatorId,
+ });
+ }
+
private async toDtos(rows: FilesSchemaTypeForSelect[]): Promise<FileDto[]> {
const linked = await this.repository.linkedTaskIdsFor(rows.map((r) => r.id));
return rows.map((r) => this.toDto(r, linked.get(r.id) ?? []));
diff --git a/api/src/tv-modules/files/FilesRepository.ts b/api/src/tv-modules/files/FilesRepository.ts
index 244a382..82036b8 100644
--- a/api/src/tv-modules/files/FilesRepository.ts
+++ b/api/src/tv-modules/files/FilesRepository.ts
@@ -1,17 +1,21 @@
-import { and, desc, eq, ilike, inArray, like, lt, not, notInArray, or, sql, type SQL } from 'drizzle-orm';
+import { and, desc, eq, ilike, inArray, like, lt, not, notInArray, or, sql, sum, type SQL } from 'drizzle-orm';
import { alias } from 'drizzle-orm/pg-core';
import {
FileToTaskSchema,
FilesSchema,
type FilesSchemaTypeForSelect,
+ GoalsSchema,
+ OrganizationsSchema,
} from 'taskview-db-schemas';
import { Database } from '../../modules/db';
import type {
FileInsertArgs,
+ FileInsertWithinQuotaArgs,
FileLinkRowsArgs,
FileListArgs,
FileListByProviderArgs,
FileListCursor,
+ FileQuotaOrganization,
FileRenameArgs,
FileUnlinkArgs,
FileUpdateStorageProviderArgs,
@@ -29,6 +33,43 @@ export class FilesRepository {
return row;
}
+ async quotaOrganizationForGoal(goalId: number): Promise<FileQuotaOrganization | null> {
+ const [row] = await this.db.dbDrizzle
+ .select({ organizationId: OrganizationsSchema.id, quotaMb: OrganizationsSchema.fileQuotaMb })
+ .from(GoalsSchema)
+ .innerJoin(OrganizationsSchema, eq(OrganizationsSchema.id, GoalsSchema.organizationId))
+ .where(eq(GoalsSchema.id, goalId))
+ .limit(1);
+ return row ?? null;
+ }
+
+ async usedBytesInOrganization(organizationId: number): Promise<number> {
+ const [row] = await this.db.dbDrizzle
+ .select({ total: sum(FilesSchema.sizeBytes) })
+ .from(FilesSchema)
+ .innerJoin(GoalsSchema, eq(GoalsSchema.id, FilesSchema.goalId))
+ .where(eq(GoalsSchema.organizationId, organizationId));
+ return Number(row?.total ?? 0);
+ }
+
+ async insertWithinQuota(args: FileInsertWithinQuotaArgs): Promise<FilesSchemaTypeForSelect | null> {
+ return this.db.dbDrizzle.transaction(async (tx) => {
+ await tx
+ .select({ id: OrganizationsSchema.id })
+ .from(OrganizationsSchema)
+ .where(eq(OrganizationsSchema.id, args.organizationId))
+ .for('update');
+ const [usage] = await tx
+ .select({ total: sum(FilesSchema.sizeBytes) })
+ .from(FilesSchema)
+ .innerJoin(GoalsSchema, eq(GoalsSchema.id, FilesSchema.goalId))
+ .where(eq(GoalsSchema.organizationId, args.organizationId));
+ if (Number(usage?.total ?? 0) + args.row.sizeBytes > args.quotaBytes) return null;
+ const [row] = await tx.insert(FilesSchema).values(args.row).returning();
+ return row;
+ });
+ }
+
async getById(fileId: string): Promise<FilesSchemaTypeForSelect | null> {
const [row] = await this.db.dbDrizzle.select().from(FilesSchema).where(eq(FilesSchema.id, fileId)).limit(1);
return row ?? null;
diff --git a/api/src/tv-modules/files/FilesRoutes.ts b/api/src/tv-modules/files/FilesRoutes.ts
index 0197297..34f0095 100644
--- a/api/src/tv-modules/files/FilesRoutes.ts
+++ b/api/src/tv-modules/files/FilesRoutes.ts
@@ -27,6 +27,8 @@ export default class FilesRoutes implements Routable {
// Project scope: upload (multipart, optional ?taskId= to link right away) and paginated listing.
this.router.post('/goal/:goalId', [IsLoggedIn, requireFilePermission(GoalPermissions.FILE_CAN_MANAGE, goalIdFromParam)], this.controller.upload);
this.router.get('/goal/:goalId', [IsLoggedIn, requireFilePermission(GoalPermissions.FILE_CAN_VIEW, goalIdFromParam)], this.controller.listForGoal);
+ // Storage quota of the pool the project's files count against (its organization's own quota or the owner's pool).
+ this.router.get('/goal/:goalId/quota', [IsLoggedIn, requireFilePermission(GoalPermissions.FILE_CAN_VIEW, goalIdFromParam)], this.controller.quota);
// Task scope: files of a task, link existing project files, unlink (the file itself stays).
this.router.get('/task/:taskId', [IsLoggedIn, requireFilePermission(GoalPermissions.FILE_CAN_VIEW, goalIdFromTask)], this.controller.listForTask);
diff --git a/api/src/tv-modules/files/__tests__/FileStorageConfigReader.spec.ts b/api/src/tv-modules/files/__tests__/FileStorageConfigReader.spec.ts
index 5e0903f..8a51493 100644
--- a/api/src/tv-modules/files/__tests__/FileStorageConfigReader.spec.ts
+++ b/api/src/tv-modules/files/__tests__/FileStorageConfigReader.spec.ts
@@ -13,7 +13,7 @@ describe('FileStorageConfigReader', () => {
const empty = FileStorageConfigReader.fromEnv({});
expect(empty.active).toBeNull();
expect(empty.inactiveReason).toContain('FILE_STORAGE_PROVIDER is not set');
- expect(empty.maxFileSizeBytes).toBe(50 * 1024 * 1024);
+ expect(empty.maxFileSizeBytes).toBe(10 * 1024 * 1024);
expect(empty.providers).toEqual({});
const described = FileStorageConfigReader.fromEnv({ FILE_STORAGE_LOCAL_DIR: '/var/files', ...s3Env });
@@ -66,4 +66,16 @@ describe('FileStorageConfigReader', () => {
expect(config.active).toBeNull();
expect(config.inactiveReason).toContain('"ftp" is not supported');
});
+ it('reads quota settings: enforced with 100 MB per organization by default, explicit off, and invalid values', () => {
+ expect(FileStorageConfigReader.fromEnv({}).quota).toEqual({ mode: 'enforce', defaultOrganizationQuotaBytes: 100 * 1024 * 1024, invalidModeValue: null });
+ expect(FileStorageConfigReader.fromEnv({ FILE_QUOTA_MODE: 'off' }).quota.mode).toBe('off');
+
+ const enforce = FileStorageConfigReader.fromEnv({ FILE_QUOTA_MODE: 'Enforce', FILE_QUOTA_ORGANIZATION_MB: '500' });
+ expect(enforce.quota).toEqual({ mode: 'enforce', defaultOrganizationQuotaBytes: 500 * 1024 * 1024, invalidModeValue: null });
+
+ expect(FileStorageConfigReader.fromEnv({ FILE_QUOTA_MODE: 'observe' }).quota).toMatchObject({ mode: 'off', invalidModeValue: 'observe' });
+
+ const invalid = FileStorageConfigReader.fromEnv({ FILE_QUOTA_MODE: 'strict', FILE_QUOTA_ORGANIZATION_MB: 'lots' });
+ expect(invalid.quota).toEqual({ mode: 'off', defaultOrganizationQuotaBytes: 100 * 1024 * 1024, invalidModeValue: 'strict' });
+ });
});
diff --git a/api/src/tv-modules/files/__tests__/FileStorageFactory.spec.ts b/api/src/tv-modules/files/__tests__/FileStorageFactory.spec.ts
index d3cb8c8..4b81dd4 100644
--- a/api/src/tv-modules/files/__tests__/FileStorageFactory.spec.ts
+++ b/api/src/tv-modules/files/__tests__/FileStorageFactory.spec.ts
@@ -4,7 +4,7 @@ import { FILE_STORAGE_DOCS_URL } from '../storage/FileStorageConfigReader';
import { FileStorageFactory } from '../storage/FileStorageFactory';
import { FileStorageNotConfiguredError } from '../storage/FileStorageNotConfiguredError';
-const STORAGE_VARS = ['FILE_STORAGE_PROVIDER', 'FILE_STORAGE_LOCAL_DIR', 'FILE_STORAGE_S3_BUCKET'] as const;
+const STORAGE_VARS = ['FILE_STORAGE_PROVIDER', 'FILE_STORAGE_LOCAL_DIR', 'FILE_STORAGE_S3_BUCKET', 'FILE_QUOTA_MODE'] as const;
describe('FileStorageFactory startup', () => {
const saved: Partial<Record<(typeof STORAGE_VARS)[number], string | undefined>> = {};
@@ -67,4 +67,14 @@ describe('FileStorageFactory startup', () => {
expect(factory.status()).toEqual({ enabled: true, maxFileSizeBytes: factory.maxFileSizeBytes });
expect(factory.active().provider).toBe('local');
});
+ it('warns about an unsupported quota mode and keeps quotas off', () => {
+ process.env.FILE_STORAGE_PROVIDER = 'local';
+ process.env.FILE_STORAGE_LOCAL_DIR = './.test-data/files';
+ process.env.FILE_QUOTA_MODE = 'strict';
+
+ FileStorageFactory.validateOnStartup();
+
+ expect($logger.warn).toHaveBeenCalledWith(expect.stringContaining('FILE_QUOTA_MODE="strict" is not supported'));
+ expect(FileStorageFactory.getInstance().quota.mode).toBe('off');
+ });
});
diff --git a/api/src/tv-modules/files/__tests__/Files.integration.spec.ts b/api/src/tv-modules/files/__tests__/Files.integration.spec.ts
index fb93050..f40bf35 100644
--- a/api/src/tv-modules/files/__tests__/Files.integration.spec.ts
+++ b/api/src/tv-modules/files/__tests__/Files.integration.spec.ts
@@ -75,10 +75,16 @@ describe('Files module', () => {
beforeAll(async () => {
const db = Database.getInstance();
const client = await db.getClient();
- for (const file of (await fs.readdir(MIGRATION_DIR)).sort()) {
- await client.query(await fs.readFile(join(MIGRATION_DIR, file), 'utf-8'));
+ // Integration specs run in parallel and re-apply migration SQL; an advisory lock keeps the DDL from racing.
+ await client.query('SELECT pg_advisory_lock(1401067)');
+ try {
+ for (const file of (await fs.readdir(MIGRATION_DIR)).sort()) {
+ await client.query(await fs.readFile(join(MIGRATION_DIR, file), 'utf-8'));
+ }
+ } finally {
+ await client.query('SELECT pg_advisory_unlock(1401067)');
+ client.release();
}
- client.release();
server = new App(port).listen();
diff --git a/api/src/tv-modules/files/__tests__/FilesQuota.integration.spec.ts b/api/src/tv-modules/files/__tests__/FilesQuota.integration.spec.ts
new file mode 100644
index 0000000..8d3e4b5
--- /dev/null
+++ b/api/src/tv-modules/files/__tests__/FilesQuota.integration.spec.ts
@@ -0,0 +1,246 @@
+import axios, { type AxiosInstance } from 'axios';
+import { eq } from 'drizzle-orm';
+import fs from 'fs/promises';
+import http from 'http';
+import { join } from 'path';
+import { OrganizationsSchema } from 'taskview-db-schemas';
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import App from '../../../App';
+import { Database } from '../../../modules/db';
+import { FilesRepository } from '../FilesRepository';
+import { FileStorageFactory } from '../storage/FileStorageFactory';
+import type { FileDto, FileInsertArgs, FileListPage, FileQuotaDto, FileQuotaMode } from '../types';
+
+vi.mock('emailjs', () => ({
+ SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),
+}));
+
+const port = 1824;
+const MIGRATION_DIRS = ['1.67.0', '1.68.0'].map((v) => join(__dirname, `../../../migrations/taskview/sql/${v}`));
+const MB = 1024 * 1024;
+
+const api: AxiosInstance = axios.create({
+ baseURL: `http://localhost:${port}`,
+ validateStatus: () => true,
+ httpAgent: new http.Agent({ keepAlive: false }),
+});
+
+let server: http.Server;
+let jwt = '';
+// [owner jwt, goal ids, organization ids] - cleanup has to run as the user who owns the rows.
+const cleanup: [string, number[], number[]][] = [];
+function track(kind: 'goal' | 'org', id: number) {
+ let entry = cleanup.find(([owner]) => owner === jwt);
+ if (!entry) {
+ entry = [jwt, [], []];
+ cleanup.push(entry);
+ }
+ (kind === 'goal' ? entry[1] : entry[2]).push(id);
+}
+const auth = () => ({ headers: { Authorization: `Bearer ${jwt}` } });
+
+type QuotaSettings = { mode: FileQuotaMode; organizationMb?: number };
+type UploadArgs = { goalId: number; bytes: number };
+type OrgQuotaArgs = { organizationId: number; quotaMb: number | null };
+
+const savedEnv = { mode: process.env.FILE_QUOTA_MODE, organizationMb: process.env.FILE_QUOTA_ORGANIZATION_MB };
+
+function useQuota(settings: QuotaSettings) {
+ process.env.FILE_QUOTA_MODE = settings.mode;
+ if (settings.organizationMb === undefined) delete process.env.FILE_QUOTA_ORGANIZATION_MB;
+ else process.env.FILE_QUOTA_ORGANIZATION_MB = String(settings.organizationMb);
+ FileStorageFactory.resetInstance();
+}
+
+async function createOrg(name: string): Promise<number> {
+ const response = await api.post('/module/organizations', { name: `${name}-${Date.now()}` }, auth());
+ expect(response.status).toBe(200);
+ track('org', response.data.response.id);
+ return response.data.response.id;
+}
+
+async function createGoal(organizationId: number): Promise<number> {
+ const response = await api.post('/module/goals', { name: `quota-${Date.now()}`, organizationId }, auth());
+ expect(response.status).toBe(200);
+ track('goal', response.data.response.id);
+ return response.data.response.id;
+}
+
+async function setOrgQuota(args: OrgQuotaArgs) {
+ await Database.getInstance()
+ .dbDrizzle.update(OrganizationsSchema)
+ .set({ fileQuotaMb: args.quotaMb })
+ .where(eq(OrganizationsSchema.id, args.organizationId));
+}
+
+async function upload(args: UploadArgs) {
+ const form = new FormData();
+ form.append('file', new Blob([new Uint8Array(args.bytes)], { type: 'application/octet-stream' }), `q-${Date.now()}.bin`);
+ return api.post<{ response: FileDto }>(`/module/files/goal/${args.goalId}`, form, auth());
+}
+
+async function quota(goalId: number): Promise<FileQuotaDto> {
+ const response = await api.get(`/module/files/goal/${goalId}/quota`, auth());
+ expect(response.status).toBe(200);
+ return response.data.response;
+}
+
+async function fileIds(goalId: number): Promise<string[]> {
+ const page = await api.get<{ response: FileListPage }>(`/module/files/goal/${goalId}?limit=200`, auth());
+ return (page.data.response?.items ?? []).map((f) => f.id);
+}
+
+describe('Files storage quotas', () => {
+ beforeAll(async () => {
+ const client = await Database.getInstance().getClient();
+ // Integration specs run in parallel and re-apply migration SQL; an advisory lock keeps the DDL from racing.
+ await client.query('SELECT pg_advisory_lock(1401067)');
+ try {
+ for (const dir of MIGRATION_DIRS) {
+ for (const file of (await fs.readdir(dir)).sort()) {
+ await client.query(await fs.readFile(join(dir, file), 'utf-8'));
+ }
+ }
+ } finally {
+ await client.query('SELECT pg_advisory_unlock(1401067)');
+ client.release();
+ }
+
+ server = new App(port).listen();
+ const login = await api.post('/module/auth/login', { login: '[email protected]', password: 'user1!#Q' });
+ expect(login.status).toBe(200);
+ jwt = login.data.access;
+ });
+
+ afterEach(() => useQuota({ mode: 'off' }));
+
+ afterAll(async () => {
+ for (const [owner, goals, orgs] of cleanup) {
+ jwt = owner;
+ for (const goalId of goals) {
+ for (const id of await fileIds(goalId)) await api.delete(`/module/files/file/${id}`, auth());
+ }
+ for (const orgId of orgs) await api.delete(`/module/organizations/${orgId}`, auth());
+ }
+ process.env.FILE_QUOTA_MODE = savedEnv.mode;
+ process.env.FILE_QUOTA_ORGANIZATION_MB = savedEnv.organizationMb;
+ if (savedEnv.mode === undefined) delete process.env.FILE_QUOTA_MODE;
+ if (savedEnv.organizationMb === undefined) delete process.env.FILE_QUOTA_ORGANIZATION_MB;
+ FileStorageFactory.resetInstance();
+ if (server) await new Promise<void>((resolve) => server.close(() => resolve()));
+ }, 30_000);
+
+ it('reports no quota and never blocks when quotas are off', async () => {
+ useQuota({ mode: 'off' });
+ const org = await createOrg('quota-off');
+ await setOrgQuota({ organizationId: org, quotaMb: 0 });
+ const goalId = await createGoal(org);
+
+ expect(await quota(goalId)).toEqual({ mode: 'off', quotaBytes: null, usedBytes: null });
+ expect((await upload({ goalId, bytes: 1000 })).status).toBe(200);
+ });
+
+ it('enforces an organization quota mid-stream, stores nothing over it, and frees space on delete', async () => {
+ useQuota({ mode: 'enforce' });
+ const org = await createOrg('quota-org');
+ await setOrgQuota({ organizationId: org, quotaMb: 1 });
+ const goalId = await createGoal(org);
+
+ const first = await upload({ goalId, bytes: 600_000 });
+ expect(first.status).toBe(200);
+ expect(await quota(goalId)).toEqual({ mode: 'enforce', quotaBytes: MB, usedBytes: 600_000 });
+
+ const second = await upload({ goalId, bytes: 600_000 });
+ expect(second.status).toBe(507);
+ expect(second.data).toContain('quota exceeded');
+ expect(await fileIds(goalId)).toEqual([first.data.response.id]);
+ expect((await quota(goalId)).usedBytes).toBe(600_000);
+
+ expect((await api.delete(`/module/files/file/${first.data.response.id}`, auth())).status).toBe(200);
+ expect((await quota(goalId)).usedBytes).toBe(0);
+ expect((await upload({ goalId, bytes: 600_000 })).status).toBe(200);
+ });
+
+ it('rejects right away when nothing is left of the quota', async () => {
+ useQuota({ mode: 'enforce' });
+ const org = await createOrg('quota-zero');
+ await setOrgQuota({ organizationId: org, quotaMb: 0 });
+ const goalId = await createGoal(org);
+
+ const response = await upload({ goalId, bytes: 1000 });
+ expect(response.status).toBe(507);
+ expect(await fileIds(goalId)).toEqual([]);
+ });
+
+ it('gives every organization the default quota of its own, independent of other organizations', async () => {
+ useQuota({ mode: 'enforce', organizationMb: 1 });
+ const goalA = await createGoal(await createOrg('default-a'));
+ const goalB = await createGoal(await createOrg('default-b'));
+
+ expect(await quota(goalA)).toEqual({ mode: 'enforce', quotaBytes: MB, usedBytes: 0 });
+
+ expect((await upload({ goalId: goalA, bytes: 600_000 })).status).toBe(200);
+ expect((await upload({ goalId: goalB, bytes: 600_000 })).status).toBe(200);
+ expect((await quota(goalA)).usedBytes).toBe(600_000);
+ expect((await quota(goalB)).usedBytes).toBe(600_000);
+
+ expect((await upload({ goalId: goalA, bytes: 600_000 })).status).toBe(507);
+ });
+
+ it('uses the organization column instead of the default when it is set', async () => {
+ useQuota({ mode: 'enforce', organizationMb: 1 });
+ const org = await createOrg('custom');
+ await setOrgQuota({ organizationId: org, quotaMb: 3 });
+ const goalId = await createGoal(org);
+
+ expect((await quota(goalId)).quotaBytes).toBe(3 * MB);
+ expect((await upload({ goalId, bytes: 600_000 })).status).toBe(200);
+ expect((await upload({ goalId, bytes: 600_000 })).status).toBe(200);
+ });
+
+ it('never exceeds the quota when uploads into one organization run in parallel', async () => {
+ useQuota({ mode: 'enforce' });
+ const org = await createOrg('quota-parallel');
+ await setOrgQuota({ organizationId: org, quotaMb: 1 });
+ const goalId = await createGoal(org);
+
+ // Whichever way the race goes (cut while streaming or refused at the locked final check), one upload must lose.
+ const results = await Promise.all([upload({ goalId, bytes: 600_000 }), upload({ goalId, bytes: 600_000 })]);
+
+ expect(results.map((r) => r.status).sort()).toEqual([200, 507]);
+ expect(await fileIds(goalId)).toHaveLength(1);
+ expect((await quota(goalId)).usedBytes).toBe(600_000);
+ });
+ it('lets only one of two concurrent records into an organization through when both would not fit', async () => {
+ const org = await createOrg('quota-lock');
+ const goalId = await createGoal(org);
+ const repository = new FilesRepository();
+ const row = (): FileInsertArgs => {
+ const id = crypto.randomUUID();
+ return {
+ id,
+ goalId,
+ uploaderId: null,
+ uploaderEmail: '[email protected]',
+ name: `${id}.bin`,
+ originalName: `${id}.bin`,
+ mimeType: 'application/octet-stream',
+ sizeBytes: 600_000,
+ checksumSha256: '0'.repeat(64),
+ storageProvider: 'local',
+ storageKey: `${goalId}/${id}`,
+ };
+ };
+
+ // Both transactions start before either commits; without the organization row lock both would see 0 used.
+ const results = await Promise.all([
+ repository.insertWithinQuota({ row: row(), organizationId: org, quotaBytes: MB }),
+ repository.insertWithinQuota({ row: row(), organizationId: org, quotaBytes: MB }),
+ ]);
+
+ const inserted = results.filter((r) => r !== null);
+ expect(inserted).toHaveLength(1);
+ expect(results.filter((r) => r === null)).toHaveLength(1);
+ for (const file of inserted) if (file) await repository.delete(file.id);
+ });
+});
diff --git a/api/src/tv-modules/files/storage/FileStorageConfigReader.ts b/api/src/tv-modules/files/storage/FileStorageConfigReader.ts
index 1e75390..d6f3a76 100644
--- a/api/src/tv-modules/files/storage/FileStorageConfigReader.ts
+++ b/api/src/tv-modules/files/storage/FileStorageConfigReader.ts
@@ -1,5 +1,7 @@
import type { FileStorageProvider } from 'taskview-db-schemas';
+import type { FileQuotaMode } from '../types';
import type {
+ FileQuotaConfig,
FileStorageActiveResolution,
FileStorageConfig,
FileStorageProviderConfig,
@@ -7,7 +9,9 @@ import type {
FileStorageS3Reading,
} from './storage.types';
-const DEFAULT_MAX_FILE_SIZE_MB = 50;
+const DEFAULT_MAX_FILE_SIZE_MB = 10;
+const DEFAULT_ORGANIZATION_QUOTA_MB = 100;
+const QUOTA_MODES: readonly FileQuotaMode[] = ['off', 'enforce'];
const S3_REQUIRED_VARS = ['FILE_STORAGE_S3_BUCKET', 'FILE_STORAGE_S3_REGION', 'FILE_STORAGE_S3_ACCESS_KEY', 'FILE_STORAGE_S3_SECRET_KEY'] as const;
export const FILE_STORAGE_DOCS_URL = 'https://taskview.tech/docs/configuration/environment-variables#files-task-attachments';
@@ -31,6 +35,18 @@ export class FileStorageConfigReader {
active,
inactiveReason,
providers,
+ quota: FileStorageConfigReader.readQuota(env),
+ };
+ }
+
+ private static readQuota(env: NodeJS.ProcessEnv): FileQuotaConfig {
+ const raw = env.FILE_QUOTA_MODE?.trim().toLowerCase() || 'enforce';
+ const known = QUOTA_MODES.find((mode) => mode === raw);
+ const organizationMb = Number(env.FILE_QUOTA_ORGANIZATION_MB ?? DEFAULT_ORGANIZATION_QUOTA_MB);
+ return {
+ mode: known ?? 'off',
+ defaultOrganizationQuotaBytes: (Number.isFinite(organizationMb) && organizationMb >= 0 ? organizationMb : DEFAULT_ORGANIZATION_QUOTA_MB) * 1024 * 1024,
+ invalidModeValue: !known ? (env.FILE_QUOTA_MODE as string) : null,
};
}
diff --git a/api/src/tv-modules/files/storage/FileStorageFactory.ts b/api/src/tv-modules/files/storage/FileStorageFactory.ts
index ee41ee3..3a37dd5 100644
--- a/api/src/tv-modules/files/storage/FileStorageFactory.ts
+++ b/api/src/tv-modules/files/storage/FileStorageFactory.ts
@@ -6,7 +6,7 @@ import { FILE_STORAGE_DOCS_URL, FileStorageConfigReader } from './FileStorageCon
import { FileStorageNotConfiguredError } from './FileStorageNotConfiguredError';
import { LocalFileStorage } from './LocalFileStorage';
import { S3FileStorage } from './S3FileStorage';
-import type { FileStorageConfig, FileStorageProviderConfig } from './storage.types';
+import type { FileQuotaConfig, FileStorageConfig, FileStorageProviderConfig } from './storage.types';
export class FileStorageFactory {
private static instance: FileStorageFactory | null = null;
@@ -34,6 +34,7 @@ export class FileStorageFactory {
static validateOnStartup(): void {
const factory = FileStorageFactory.getInstance();
+ factory.logQuotaStatus();
if (factory.isConfigured) {
console.log(`[files] File storage: ${factory.config.active}`);
return;
@@ -59,6 +60,22 @@ export class FileStorageFactory {
return this.config.maxFileSizeBytes;
}
+ get quota(): FileQuotaConfig {
+ return this.config.quota;
+ }
+
+ private logQuotaStatus(): void {
+ const { mode, defaultOrganizationQuotaBytes, invalidModeValue } = this.config.quota;
+ if (invalidModeValue !== null) {
+ const message = `[files] FILE_QUOTA_MODE="${invalidModeValue}" is not supported (off, enforce) - quotas are off`;
+ console.warn(message);
+ $logger.warn(message);
+ return;
+ }
+ if (mode === 'off') return;
+ console.log(`[files] File quotas: ${mode}, ${Math.round(defaultOrganizationQuotaBytes / 1024 / 1024)} MB per organization by default`);
+ }
+
get isConfigured(): boolean {
return this.config.active !== null;
}
diff --git a/api/src/tv-modules/files/storage/storage.types.ts b/api/src/tv-modules/files/storage/storage.types.ts
index 7edf047..1ff28bf 100644
--- a/api/src/tv-modules/files/storage/storage.types.ts
+++ b/api/src/tv-modules/files/storage/storage.types.ts
@@ -2,6 +2,7 @@ import type { Readable } from 'node:stream';
import type { FileStorageProvider } from 'taskview-db-schemas';
import type { FileStorage } from './FileStorage';
import type { FilesRepository } from '../FilesRepository';
+import type { FileQuotaMode } from '../types';
export type LocalFileStorageConfig = {
type: 'local';
@@ -25,6 +26,13 @@ export type FileStorageConfig = {
active: FileStorageProvider | null;
inactiveReason: string | null;
providers: Partial<Record<FileStorageProvider, FileStorageProviderConfig>>;
+ quota: FileQuotaConfig;
+};
+
+export type FileQuotaConfig = {
+ mode: FileQuotaMode;
+ defaultOrganizationQuotaBytes: number;
+ invalidModeValue: string | null;
};
export type FileStorageActiveResolution = {
diff --git a/api/src/tv-modules/files/types.ts b/api/src/tv-modules/files/types.ts
index 36eddea..32cd1e2 100644
--- a/api/src/tv-modules/files/types.ts
+++ b/api/src/tv-modules/files/types.ts
@@ -1,6 +1,7 @@
import { type } from 'arktype';
import type { Readable } from 'node:stream';
import type { FileStorageProvider, FilesSchemaTypeForInsert, FilesSchemaTypeForSelect } from 'taskview-db-schemas';
+import type { FilesRepository } from './FilesRepository';
export const FILE_LIST_DEFAULT_LIMIT = 50;
export const FILE_LIST_MAX_LIMIT = 200;
@@ -106,6 +107,35 @@ export type FileDto = Omit<FilesSchemaTypeForSelect, FileInternalColumns> & {
linkedTaskIds: number[];
};
+export const FileEvents = {
+ Uploaded: 'file.uploaded',
+ Renamed: 'file.renamed',
+ Deleted: 'file.deleted',
+ Attached: 'file.attached',
+ Detached: 'file.detached',
+} as const;
+export type FileEventName = (typeof FileEvents)[keyof typeof FileEvents];
+export const FILE_EVENTS = [
+ FileEvents.Uploaded,
+ FileEvents.Renamed,
+ FileEvents.Deleted,
+ FileEvents.Attached,
+ FileEvents.Detached,
+] as const;
+
+export type FileEventPayload = {
+ goalId: number;
+ file: FileDto;
+ taskIds: number[];
+ initiatorId: number;
+};
+
+export type FileEmitEventArgs = {
+ event: FileEventName;
+ file: FileDto;
+ taskIds: number[];
+};
+
export type FileListPage = {
items: FileDto[];
nextCursor: string | null;
@@ -123,8 +153,45 @@ export type FileContent = {
inline: boolean;
};
-export type FileErrorCode = 'not_found' | 'forbidden' | 'too_large' | 'invalid' | 'storage_error' | 'storage_not_configured';
+export type FileErrorCode =
+ | 'not_found'
+ | 'forbidden'
+ | 'too_large'
+ | 'invalid'
+ | 'storage_error'
+ | 'storage_not_configured'
+ | 'quota_exceeded';
export const FILE_STORAGE_NOT_CONFIGURED_MESSAGE = 'File storage is not configured on this server';
+export const FILE_QUOTA_EXCEEDED_MESSAGE = 'File storage quota exceeded';
+
+export type FileQuotaMode = 'off' | 'enforce';
+
+export type FileQuotaDto = {
+ mode: FileQuotaMode;
+ quotaBytes: number | null;
+ usedBytes: number | null;
+};
+
+export type FileQuotaState = FileQuotaDto & {
+ organizationId: number | null;
+};
+
+export type FileInsertWithinQuotaArgs = {
+ row: FileInsertArgs;
+ organizationId: number;
+ quotaBytes: number;
+};
+
+export type FileQuotaOrganization = {
+ organizationId: number;
+ quotaMb: number | null;
+};
+
+export type FileQuotaResolverArgs = {
+ repository: FilesRepository;
+ mode: FileQuotaMode;
+ defaultOrganizationQuotaBytes: number;
+};
export type FileStorageStatusDto = {
enabled: boolean;
diff --git a/api/src/tv-modules/sso/SsoController.ts b/api/src/tv-modules/sso/SsoController.ts
index 473b799..816be6a 100644
--- a/api/src/tv-modules/sso/SsoController.ts
+++ b/api/src/tv-modules/sso/SsoController.ts
@@ -12,7 +12,7 @@ import { OrganizationRepository } from '../organizations/OrganizationRepository'
import { createSsoProvider } from './providers/provider-factory'
import { SsoRepository } from './SsoRepository'
import { parseSamlMetadata } from './saml-metadata-parser'
-import { generateLoginCode, isSsoDomainVerified, stripSecrets, validateMetadataUrl } from './sso.utils'
+import { checkSsoFetchUrl, generateLoginCode, isSsoDomainVerified, stripSecrets } from './sso.utils'
import {
SsoConfigArkTypeCreate,
SsoConfigArkTypeUpdate,
@@ -326,7 +326,7 @@ export class SsoController {
const metadataUrl = req.query.url as string
if (!metadataUrl) return res.status(400).tvJson({ message: 'url is required' })
- const urlError = validateMetadataUrl(metadataUrl)
+ const urlError = await checkSsoFetchUrl(metadataUrl)
if (urlError) return res.status(400).tvJson({ message: urlError })
try {
diff --git a/api/src/tv-modules/sso/__tests__/SsoMetadataSync.integration.spec.ts b/api/src/tv-modules/sso/__tests__/SsoMetadataSync.integration.spec.ts
new file mode 100644
index 0000000..9fcbe5b
--- /dev/null
+++ b/api/src/tv-modules/sso/__tests__/SsoMetadataSync.integration.spec.ts
@@ -0,0 +1,85 @@
+import axios, { type AxiosInstance } from 'axios'
+import { createServer, type Server } from 'http'
+import http from 'http'
+import type { AddressInfo } from 'net'
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import App from '../../../App'
+
+vi.mock('emailjs', () => ({
+ SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),
+}))
+
+const port = 1827
+const api: AxiosInstance = axios.create({
+ baseURL: `http://localhost:${port}`,
+ validateStatus: () => true,
+ httpAgent: new http.Agent({ keepAlive: false }),
+})
+
+const METADATA = `<?xml version="1.0"?>
+<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" entityID="https://idp.example.com">
+ <md:IDPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol">
+ <md:KeyDescriptor use="signing"><ds:KeyInfo><ds:X509Data><ds:X509Certificate>MIICERT</ds:X509Certificate></ds:X509Data></ds:KeyInfo></md:KeyDescriptor>
+ <md:SingleLogoutService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://idp.example.com/slo"/>
+ <md:SingleSignOnService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect" Location="https://idp.example.com/sso"/>
+ </md:IDPSSODescriptor>
+</md:EntityDescriptor>`
+
+let server: http.Server
+let metadataServer: Server
+let metadataUrl = ''
+let auth: { headers: { Authorization: string } }
+let organizationId = 0
+const savedAllow = process.env.SSO_ALLOW_PRIVATE_URLS
+
+// Issue #125: the SAML form's "Sync" always got an empty 400 because the client never sent the organization
+// the org-admin guard needs. With the organization the request reaches the metadata fetch, which is SSRF-guarded.
+describe('SSO SAML metadata sync', () => {
+ beforeAll(async () => {
+ metadataServer = createServer((_req, res) => {
+ res.writeHead(200, { 'Content-Type': 'application/xml' })
+ res.end(METADATA)
+ })
+ await new Promise<void>((resolve) => metadataServer.listen(0, '127.0.0.1', resolve))
+ metadataUrl = `http://127.0.0.1:${(metadataServer.address() as AddressInfo).port}/metadata`
+
+ server = new App(port).listen()
+ const login = await api.post('/module/auth/login', { login: '[email protected]', password: 'user1!#Q' })
+ expect(login.status).toBe(200)
+ auth = { headers: { Authorization: `Bearer ${login.data.access}` } }
+ const org = await api.post('/module/organizations', { name: `sso-sync-${Date.now()}` }, auth)
+ expect(org.status).toBe(200)
+ organizationId = org.data.response.id
+ })
+
+ afterAll(async () => {
+ if (savedAllow === undefined) delete process.env.SSO_ALLOW_PRIVATE_URLS
+ else process.env.SSO_ALLOW_PRIVATE_URLS = savedAllow
+ if (organizationId) await api.delete(`/module/organizations/${organizationId}`, auth)
+ await new Promise<void>((resolve) => metadataServer.close(() => resolve()))
+ if (server) await new Promise<void>((resolve) => server.close(() => resolve()))
+ })
+
+ it('is refused by the org-admin guard without an organization (what the old client sent)', async () => {
+ const response = await api.get('/module/sso/admin/metadata', { ...auth, params: { url: metadataUrl } })
+ expect(response.status).toBe(400)
+ })
+
+ it('reaches the fetch with the organization and refuses an internal metadata URL', async () => {
+ delete process.env.SSO_ALLOW_PRIVATE_URLS
+ const response = await api.get('/module/sso/admin/metadata', { ...auth, params: { url: metadataUrl, organizationId } })
+ expect(response.status).toBe(400)
+ expect(response.data.response).toMatchObject({ message: 'URL must point to a public address' })
+ })
+
+ it('fetches and parses the metadata when the IdP may be internal (self-hosted opt-out)', async () => {
+ process.env.SSO_ALLOW_PRIVATE_URLS = 'true'
+ const response = await api.get('/module/sso/admin/metadata', { ...auth, params: { url: metadataUrl, organizationId } })
+ expect(response.status).toBe(200)
+ expect(response.data.response).toEqual({
+ samlEntryPoint: 'https://idp.example.com/sso',
+ samlCert: 'MIICERT',
+ samlLogoutUrl: 'https://idp.example.com/slo',
+ })
+ })
+})
diff --git a/api/src/tv-modules/sso/__tests__/sso.fetch-url.test.ts b/api/src/tv-modules/sso/__tests__/sso.fetch-url.test.ts
new file mode 100644
index 0000000..4d7bd28
--- /dev/null
+++ b/api/src/tv-modules/sso/__tests__/sso.fetch-url.test.ts
@@ -0,0 +1,67 @@
+import { promises as dns } from 'dns'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { checkSsoFetchUrl, validateSsoEnvOnStartup } from '../sso.utils'
+
+// The server fetches IdP metadata and the domain-ownership file for SSO. Those URLs must not reach internal
+// addresses, whether written literally or behind a public-looking name that resolves inward.
+describe('checkSsoFetchUrl', () => {
+ const saved = { env: process.env.NODE_ENV, allow: process.env.SSO_ALLOW_PRIVATE_URLS }
+
+ afterEach(() => {
+ process.env.NODE_ENV = saved.env
+ if (saved.allow === undefined) delete process.env.SSO_ALLOW_PRIVATE_URLS
+ else process.env.SSO_ALLOW_PRIVATE_URLS = saved.allow
+ vi.restoreAllMocks()
+ })
+
+ const resolvesTo = (address: string) =>
+ vi.spyOn(dns, 'lookup').mockResolvedValue([{ address, family: address.includes(':') ? 6 : 4 }] as never)
+
+ it.each(['http://127.0.0.1/metadata', 'http://localhost/metadata', 'http://10.0.0.5/metadata', 'http://169.254.169.254/latest', 'http://[::1]/x'])(
+ 'refuses the internal address %s',
+ async (url) => {
+ expect(await checkSsoFetchUrl(url)).toBe('URL must point to a public address')
+ },
+ )
+
+ it('refuses a public-looking host that resolves to a private address', async () => {
+ resolvesTo('10.1.2.3')
+ expect(await checkSsoFetchUrl('https://idp.example.com/metadata')).toBe('URL must point to a public address')
+ })
+
+ it('refuses a host that resolves to the cloud metadata address', async () => {
+ resolvesTo('169.254.169.254')
+ expect(await checkSsoFetchUrl('https://idp.example.com/metadata')).toBe('URL must point to a public address')
+ })
+
+ it('refuses a host that does not resolve', async () => {
+ vi.spyOn(dns, 'lookup').mockRejectedValue(new Error('ENOTFOUND'))
+ expect(await checkSsoFetchUrl('https://nowhere.example.com/metadata')).toBe('URL host could not be resolved')
+ })
+
+ it('accepts a host that resolves to a public address', async () => {
+ resolvesTo('93.184.216.34')
+ expect(await checkSsoFetchUrl('https://idp.example.com/metadata')).toBeNull()
+ })
+
+ it('refuses non-http schemes and plain http in production', async () => {
+ expect(await checkSsoFetchUrl('file:///etc/passwd')).toBe('URL must use http or https')
+ process.env.NODE_ENV = 'production'
+ expect(await checkSsoFetchUrl('http://idp.example.com/metadata')).toBe('Only HTTPS URLs are allowed')
+ })
+
+ it('lets a self-hosted install reach an internal IdP with SSO_ALLOW_PRIVATE_URLS=true', async () => {
+ process.env.SSO_ALLOW_PRIVATE_URLS = 'true'
+ resolvesTo('10.1.2.3')
+ expect(await checkSsoFetchUrl('https://keycloak.internal/metadata')).toBeNull()
+ expect(await checkSsoFetchUrl('http://192.168.1.10/metadata')).toBeNull()
+ expect(await checkSsoFetchUrl('file:///etc/passwd')).toBe('URL must use http or https')
+ })
+
+ it('stops the server on an unrecognized SSO_ALLOW_PRIVATE_URLS value', () => {
+ process.env.SSO_ALLOW_PRIVATE_URLS = 'yes'
+ expect(() => validateSsoEnvOnStartup()).toThrow('SSO_ALLOW_PRIVATE_URLS')
+ process.env.SSO_ALLOW_PRIVATE_URLS = 'false'
+ expect(() => validateSsoEnvOnStartup()).not.toThrow()
+ })
+})
diff --git a/api/src/tv-modules/sso/sso.utils.ts b/api/src/tv-modules/sso/sso.utils.ts
index 203a7a8..64c0527 100644
--- a/api/src/tv-modules/sso/sso.utils.ts
+++ b/api/src/tv-modules/sso/sso.utils.ts
@@ -2,6 +2,8 @@ import { randomBytes } from 'crypto'
import { resolveTxt } from 'node:dns/promises'
import type { SsoConfigsSchemaTypeForSelect } from 'taskview-db-schemas'
import { decryptField } from '../../utils/crypto'
+import { OutboundUrlError } from '../../utils/OutboundUrlError'
+import { resolveOutboundUrl } from '../../utils/outbound-url'
import { generateString } from '../../utils/helpers'
import type { CheckSsoDomainProofArgs, SsoDomainVerificationMethod } from './types'
@@ -100,7 +102,7 @@ export async function checkSsoDomainHttpFile(args: CheckSsoDomainProofArgs): Pro
]
for (const url of urls) {
- const urlError = validateMetadataUrl(url)
+ const urlError = await checkSsoFetchUrl(url)
if (urlError) continue
try {
@@ -139,42 +141,30 @@ export function generateLoginCode(): string {
return `${generateString(12)}:${Date.now()}`.toLowerCase()
}
-const BLOCKED_HOSTNAMES = ['localhost', '127.0.0.1', '0.0.0.0', '[::1]']
-const PRIVATE_IP_RANGES = [
- /^10\./,
- /^172\.(1[6-9]|2\d|3[01])\./,
- /^192\.168\./,
- /^169\.254\./,
- /^fc00:/,
- /^fd/,
- /^fe80:/,
-]
+export function isPrivateSsoUrlsAllowed(): boolean {
+ return process.env.SSO_ALLOW_PRIVATE_URLS?.trim().toLowerCase() === 'true'
+}
-export function validateMetadataUrl(url: string): string | null {
- let parsed: URL
- try {
- parsed = new URL(url)
- } catch {
- return 'Invalid URL format'
+export function validateSsoEnvOnStartup(): void {
+ const raw = process.env.SSO_ALLOW_PRIVATE_URLS
+ if (raw === undefined || raw.trim() === '') return
+ const normalized = raw.trim().toLowerCase()
+ if (normalized !== 'true' && normalized !== 'false') {
+ throw new Error(`SSO_ALLOW_PRIVATE_URLS has unrecognized value "${raw}". Allowed: true, false`)
}
+}
- if (parsed.protocol !== 'https:' && process.env.NODE_ENV === 'production') {
+// URLs the server fetches for SSO (IdP metadata, domain-ownership file) go through the shared SSRF guard,
+// DNS resolution included. Returns a user-facing error, or null when the URL may be fetched.
+export async function checkSsoFetchUrl(url: string): Promise<string | null> {
+ if (process.env.NODE_ENV === 'production' && !url.toLowerCase().startsWith('https://')) {
return 'Only HTTPS URLs are allowed'
}
-
- if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
- return 'Only HTTP(S) URLs are allowed'
- }
-
- if (BLOCKED_HOSTNAMES.includes(parsed.hostname)) {
- return 'Localhost URLs are not allowed'
- }
-
- for (const range of PRIVATE_IP_RANGES) {
- if (range.test(parsed.hostname)) {
- return 'Private IP addresses are not allowed'
- }
+ try {
+ await resolveOutboundUrl({ url, allowPrivate: isPrivateSsoUrlsAllowed() })
+ return null
+ } catch (err) {
+ if (err instanceof OutboundUrlError) return `URL ${err.message}`
+ throw err
}
-
- return null
}
diff --git a/api/src/tv-modules/tasks/TaskMovePlanner.ts b/api/src/tv-modules/tasks/TaskMovePlanner.ts
new file mode 100644
index 0000000..bf95cb3
--- /dev/null
+++ b/api/src/tv-modules/tasks/TaskMovePlanner.ts
@@ -0,0 +1,93 @@
+import { GoalPermissions } from '../../types/auth.types';
+import type { GoalPermissionsChecker } from '../../core/GoalPermissionsChecker';
+import type { TaskMoveRepository } from './TaskMoveRepository';
+import type {
+ TaskArgMove,
+ TaskMoveDecision,
+ TaskMovePlannerArgs,
+ TaskMovePreviewDto,
+ TaskMoveTimeEntryCountArgs,
+} from './task-move.types';
+
+export class TaskMovePlanner {
+ private readonly repository: TaskMoveRepository;
+ private readonly userId: number;
+ private readonly checkerForGoal: (goalId: number) => Promise<GoalPermissionsChecker>;
+
+ constructor(args: TaskMovePlannerArgs) {
+ this.repository = args.repository;
+ this.userId = args.userId;
+ this.checkerForGoal = args.checkerForGoal;
+ }
+
+ async plan(args: TaskArgMove): Promise<TaskMoveDecision> {
+ const context = await this.repository.fetchContext(args);
+ if (!context || !context.target) return { ok: false, reason: 'not_found' };
+ const { task, target } = context;
+
+ // No access to the task itself is reported as "not found", so the task's existence is not revealed
+ const source = await this.checkerForGoal(task.goalId);
+ if (!source.hasPermissions(GoalPermissions.COMPONENT_CAN_WATCH_CONTENT)) return { ok: false, reason: 'not_found' };
+ if (task.parentId !== null) return { ok: false, reason: 'is_subtask' };
+ if (target.id === task.goalId) return { ok: false, reason: 'same_project' };
+ if (context.sourceOrganizationId === null || context.sourceOrganizationId !== target.organizationId) {
+ return { ok: false, reason: 'other_organization' };
+ }
+
+ const destination = await this.checkerForGoal(target.id);
+ if (!destination.hasPermissions(GoalPermissions.COMPONENT_CAN_ADD_TASKS)) return { ok: false, reason: 'no_target_permission' };
+
+ // Without the right to delete tasks in the source project the original stays and a copy is created
+ const mode = source.hasPermissions(GoalPermissions.TASKS_CAN_DELETE) ? 'move' : 'copy';
+
+ const subtaskIds = await this.repository.fetchSubtaskIds(task.id);
+ const withSubtasks = destination.hasPermissions(GoalPermissions.TASKS_CAN_ADD_SUBTASKS);
+ const taskIds = [task.id, ...(withSubtasks ? subtaskIds : [])];
+ const leftBehindSubtaskIds = withSubtasks ? [] : subtaskIds;
+
+ // Logged time is never duplicated: a copy starts without it, a move takes the entries the user may log there
+ const timeEntryUserIds = mode === 'move' ? this.timeEntryUsers(destination) : [];
+ const counted: TaskMoveTimeEntryCountArgs = { taskIds, userIds: timeEntryUserIds };
+ const movedTimeEntries = mode === 'move' ? await this.repository.countTimeEntries(counted) : 0;
+ const allTimeEntries = mode === 'move' ? await this.repository.countTimeEntries({ taskIds, userIds: null }) : 0;
+
+ return {
+ ok: true,
+ plan: {
+ mode,
+ rootTaskId: task.id,
+ sourceGoalId: task.goalId,
+ targetGoalId: target.id,
+ targetGoalOwnerId: target.ownerId,
+ taskIds,
+ leftBehindSubtaskIds,
+ timeEntryUserIds,
+ removals: await this.repository.countRemovals({ taskIds }),
+ leftBehind: { subtasks: leftBehindSubtaskIds.length, timeEntries: allTimeEntries - movedTimeEntries },
+ movedTimeEntries,
+ },
+ };
+ }
+
+ toPreview(decision: TaskMoveDecision): TaskMovePreviewDto {
+ if (!decision.ok) {
+ return { allowed: false, reason: decision.reason, mode: null, tasks: 0, timeEntries: 0, removals: null, leftBehind: null };
+ }
+ const { plan } = decision;
+ return {
+ allowed: true,
+ reason: null,
+ mode: plan.mode,
+ tasks: plan.taskIds.length,
+ timeEntries: plan.movedTimeEntries,
+ removals: plan.removals,
+ leftBehind: plan.leftBehind,
+ };
+ }
+
+ private timeEntryUsers(destination: GoalPermissionsChecker): number[] | null {
+ if (destination.hasPermissions(GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL)) return null;
+ if (destination.hasPermissions(GoalPermissions.TIMETRACKING_CAN_LOG)) return [this.userId];
+ return [];
+ }
+}
diff --git a/api/src/tv-modules/tasks/TaskMoveRepository.ts b/api/src/tv-modules/tasks/TaskMoveRepository.ts
new file mode 100644
index 0000000..61e8412
--- /dev/null
+++ b/api/src/tv-modules/tasks/TaskMoveRepository.ts
@@ -0,0 +1,234 @@
+import { and, count, countDistinct, eq, inArray, isNotNull, isNull, min, not, or, type SQL } from 'drizzle-orm';
+import {
+ FileToTaskSchema,
+ GoalsSchema,
+ GraphRelationsSchema,
+ IntegrationTaskMapSchema,
+ RecurrenceRulesSchema,
+ SprintTaskOutcomesSchema,
+ TasksAssigneeSchema,
+ TasksSchema,
+ type TasksSchemaTypeForSelect,
+ TasksToTagsSchema,
+ TimeEntriesSchema,
+} from 'taskview-db-schemas';
+import { Database } from '../../modules/db';
+import { TasksRepository } from './TasksRepository';
+import type {
+ TaskCopyExecuteArgs,
+ TaskCopyResult,
+ TaskMoveContext,
+ TaskMoveContextArgs,
+ TaskMoveCountArgs,
+ TaskMoveExecuteArgs,
+ TaskMoveRemovals,
+ TaskMoveTimeEntryCountArgs,
+} from './task-move.types';
+
+type Transaction = Parameters<Parameters<Database['dbDrizzle']['transaction']>[0]>[0];
+
+export class TaskMoveRepository {
+ private readonly db: Database;
+
+ constructor() {
+ this.db = Database.getInstance();
+ }
+
+ async fetchContext(args: TaskMoveContextArgs): Promise<TaskMoveContext | null> {
+ const [task] = await this.db.dbDrizzle.select().from(TasksSchema).where(eq(TasksSchema.id, args.taskId)).limit(1);
+ if (!task) return null;
+
+ const goals = await this.db.dbDrizzle
+ .select({ id: GoalsSchema.id, organizationId: GoalsSchema.organizationId, ownerId: GoalsSchema.owner })
+ .from(GoalsSchema)
+ .where(inArray(GoalsSchema.id, [task.goalId, args.targetGoalId]));
+ const source = goals.find((g) => g.id === task.goalId);
+ const target = goals.find((g) => g.id === args.targetGoalId) ?? null;
+
+ return { task, sourceOrganizationId: source?.organizationId ?? null, target };
+ }
+
+ // All descendants of a task, parents before children
+ async fetchSubtaskIds(rootTaskId: number): Promise<number[]> {
+ const result: number[] = [];
+ let level = [rootTaskId];
+ while (level.length > 0) {
+ const children = await this.db.dbDrizzle
+ .select({ id: TasksSchema.id })
+ .from(TasksSchema)
+ .where(inArray(TasksSchema.parentId, level));
+ level = children.map((c) => c.id).filter((id) => !result.includes(id) && id !== rootTaskId);
+ result.push(...level);
+ }
+ return result;
+ }
+
+ async countRemovals(args: TaskMoveCountArgs): Promise<TaskMoveRemovals> {
+ const ids = args.taskIds;
+ const total = async (query: Promise<{ value: number }[]>) => Number((await query)[0]?.value ?? 0);
+ const db = this.db.dbDrizzle;
+
+ const recurrenceTasks = new Set<number>();
+ const instances = await db
+ .select({ id: TasksSchema.id })
+ .from(TasksSchema)
+ .where(and(inArray(TasksSchema.id, ids), isNotNull(TasksSchema.recurrenceRuleId)));
+ const templates = await db
+ .select({ id: RecurrenceRulesSchema.templateTaskId })
+ .from(RecurrenceRulesSchema)
+ .where(inArray(RecurrenceRulesSchema.templateTaskId, ids));
+ for (const row of [...instances, ...templates]) if (row.id !== null) recurrenceTasks.add(row.id);
+
+ return {
+ tags: await total(db.select({ value: count() }).from(TasksToTagsSchema).where(inArray(TasksToTagsSchema.taskId, ids))),
+ assignees: await total(db.select({ value: count() }).from(TasksAssigneeSchema).where(inArray(TasksAssigneeSchema.taskId, ids))),
+ fileLinks: await total(db.select({ value: count() }).from(FileToTaskSchema).where(inArray(FileToTaskSchema.taskId, ids))),
+ dependencies: await total(db.select({ value: count() }).from(GraphRelationsSchema).where(this.crossingEdges(ids))),
+ sprintOutcomes: await total(
+ db.select({ value: count() }).from(SprintTaskOutcomesSchema).where(inArray(SprintTaskOutcomesSchema.taskId, ids))
+ ),
+ integrationLinks: await total(
+ db.select({ value: count() }).from(IntegrationTaskMapSchema).where(inArray(IntegrationTaskMapSchema.taskId, ids))
+ ),
+ recurrence: recurrenceTasks.size,
+ };
+ }
+
+ async countTimeEntries(args: TaskMoveTimeEntryCountArgs): Promise<number> {
+ const conditions: SQL[] = [inArray(TimeEntriesSchema.taskId, args.taskIds)];
+ if (args.userIds !== null) conditions.push(inArray(TimeEntriesSchema.userId, args.userIds.length ? args.userIds : [-1]));
+ const [row] = await this.db.dbDrizzle
+ .select({ value: countDistinct(TimeEntriesSchema.id) })
+ .from(TimeEntriesSchema)
+ .where(and(...conditions));
+ return Number(row?.value ?? 0);
+ }
+
+ async executeMove(args: TaskMoveExecuteArgs): Promise<TasksSchemaTypeForSelect | null> {
+ const { plan } = args;
+ const ids = plan.taskIds;
+
+ return this.db.dbDrizzle.transaction(async (tx) => {
+ const [locked] = await tx.select({ id: TasksSchema.id }).from(TasksSchema).where(eq(TasksSchema.id, plan.rootTaskId)).for('update');
+ if (!locked) return null;
+
+ await tx.delete(TasksToTagsSchema).where(inArray(TasksToTagsSchema.taskId, ids));
+ await tx.delete(TasksAssigneeSchema).where(inArray(TasksAssigneeSchema.taskId, ids));
+ await tx.delete(FileToTaskSchema).where(inArray(FileToTaskSchema.taskId, ids));
+ await tx.delete(SprintTaskOutcomesSchema).where(inArray(SprintTaskOutcomesSchema.taskId, ids));
+ await tx.delete(IntegrationTaskMapSchema).where(inArray(IntegrationTaskMapSchema.taskId, ids));
+ await tx.delete(GraphRelationsSchema).where(this.crossingEdges(ids));
+ await tx.update(RecurrenceRulesSchema).set({ templateTaskId: null }).where(inArray(RecurrenceRulesSchema.templateTaskId, ids));
+
+ if (plan.leftBehindSubtaskIds.length > 0) {
+ await tx
+ .update(TasksSchema)
+ .set({ parentId: null })
+ .where(and(inArray(TasksSchema.id, plan.leftBehindSubtaskIds), inArray(TasksSchema.parentId, ids)));
+ }
+
+ const timeEntryConditions: SQL[] = [inArray(TimeEntriesSchema.taskId, ids)];
+ if (plan.timeEntryUserIds !== null) {
+ timeEntryConditions.push(inArray(TimeEntriesSchema.userId, plan.timeEntryUserIds.length ? plan.timeEntryUserIds : [-1]));
+ }
+ await tx.update(TimeEntriesSchema).set({ goalId: plan.targetGoalId }).where(and(...timeEntryConditions));
+
+ let order = await this.nextBacklogOrder(tx, plan.targetGoalId);
+ for (const id of ids) {
+ await tx
+ .update(TasksSchema)
+ .set({
+ goalId: plan.targetGoalId,
+ owner: plan.targetGoalOwnerId,
+ goalListId: null,
+ statusId: null,
+ sprintId: null,
+ nodeGraphPosition: null,
+ recurrenceRuleId: null,
+ recurrenceInstanceDate: null,
+ kanbanOrder: order,
+ })
+ .where(eq(TasksSchema.id, id));
+ order -= TasksRepository.KANBAN_ORDER_GAP;
+ }
+
+ await tx
+ .update(GraphRelationsSchema)
+ .set({ goalId: plan.targetGoalId })
+ .where(and(inArray(GraphRelationsSchema.fromTaskId, ids), inArray(GraphRelationsSchema.toTaskId, ids)));
+
+ const [root] = await tx.select().from(TasksSchema).where(eq(TasksSchema.id, plan.rootTaskId));
+ return root ?? null;
+ });
+ }
+
+ async executeCopy(args: TaskCopyExecuteArgs): Promise<TaskCopyResult> {
+ const { plan } = args;
+
+ return this.db.dbDrizzle.transaction(async (tx) => {
+ const originals = await tx.select().from(TasksSchema).where(inArray(TasksSchema.id, plan.taskIds));
+ const byId = new Map(originals.map((t) => [t.id, t]));
+ const newIds = new Map<number, number>();
+ const created: TasksSchemaTypeForSelect[] = [];
+
+ let order = await this.nextBacklogOrder(tx, plan.targetGoalId);
+ for (const id of plan.taskIds) {
+ const source = byId.get(id);
+ if (!source) continue;
+ const parentId = id === plan.rootTaskId || source.parentId === null ? null : (newIds.get(source.parentId) ?? null);
+ const [copy] = await tx
+ .insert(TasksSchema)
+ .values({
+ goalId: plan.targetGoalId,
+ parentId,
+ description: source.description,
+ complete: source.complete,
+ note: source.note,
+ priorityId: source.priorityId,
+ startDate: source.startDate,
+ endDate: source.endDate,
+ startTime: source.startTime,
+ endTime: source.endTime,
+ amount: source.amount,
+ transactionType: source.transactionType,
+ estimateValue: source.estimateValue,
+ dateComplete: source.dateComplete,
+ sourceUrl: source.sourceUrl,
+ creatorId: args.creatorId,
+ kanbanOrder: order,
+ })
+ .returning();
+ order -= TasksRepository.KANBAN_ORDER_GAP;
+ newIds.set(id, copy.id);
+ created.push(copy);
+ }
+
+ const edges = await tx
+ .select()
+ .from(GraphRelationsSchema)
+ .where(and(inArray(GraphRelationsSchema.fromTaskId, plan.taskIds), inArray(GraphRelationsSchema.toTaskId, plan.taskIds)));
+ for (const edge of edges) {
+ const fromTaskId = edge.fromTaskId === null ? null : newIds.get(edge.fromTaskId);
+ const toTaskId = edge.toTaskId === null ? null : newIds.get(edge.toTaskId);
+ if (!fromTaskId || !toTaskId) continue;
+ await tx.insert(GraphRelationsSchema).values({ fromTaskId, toTaskId, goalId: plan.targetGoalId, nodeMetadata: edge.nodeMetadata });
+ }
+
+ return { rootTaskId: newIds.get(plan.rootTaskId) as number, tasks: created };
+ });
+ }
+
+ private crossingEdges(ids: number[]): SQL {
+ const fromInside = inArray(GraphRelationsSchema.fromTaskId, ids);
+ const toInside = inArray(GraphRelationsSchema.toTaskId, ids);
+ return or(and(fromInside, not(toInside)), and(toInside, not(fromInside))) as SQL;
+ }
+
+ private async nextBacklogOrder(tx: Transaction, goalId: number): Promise<number> {
+ const [row] = await tx
+ .select({ value: min(TasksSchema.kanbanOrder) })
+ .from(TasksSchema)
+ .where(and(eq(TasksSchema.goalId, goalId), isNull(TasksSchema.statusId)));
+ return (row?.value ?? 0) - TasksRepository.KANBAN_ORDER_GAP;
+ }
+}
diff --git a/api/src/tv-modules/tasks/TasksController.ts b/api/src/tv-modules/tasks/TasksController.ts
index dd1a34f..170ee4f 100644
--- a/api/src/tv-modules/tasks/TasksController.ts
+++ b/api/src/tv-modules/tasks/TasksController.ts
@@ -1,4 +1,5 @@
import { type } from 'arktype';
+import { TaskArkTypeMove, TaskArkTypeMovePreview, type TaskMoveBlockReason } from './task-move.types';
import type { Request, Response } from 'express';
import { $logger } from '../../modules/logget';
import {
@@ -39,6 +40,14 @@ import {
} from './tasks.server.types';
// import { TasksSchemaArkTypeInsert } from "taskview-db-schemas";
+
+const TASK_MOVE_REASON_STATUS: Record<TaskMoveBlockReason, number> = {
+ not_found: 404,
+ same_project: 400,
+ other_organization: 400,
+ is_subtask: 400,
+ no_target_permission: 403,
+};
export class TasksController {
/** @deprecated */
fetchTaskById = async (req: Request, res: Response) => {
@@ -336,6 +345,24 @@ export class TasksController {
// }
};
+ previewMoveToProject = async (req: Request, res: Response) => {
+ const args = TaskArkTypeMovePreview({ taskId: req.params.taskId, targetGoalId: req.query.targetGoalId });
+ if (args instanceof type.errors) return res.status(400).send(args.summary);
+
+ const preview = await req.appUser.tasksManager.previewMoveToProject(args);
+ if (preview.reason === 'not_found') return res.status(404).send(preview.reason);
+ return res.tvJson(preview);
+ };
+
+ moveToProject = async (req: Request, res: Response) => {
+ const args = TaskArkTypeMove(req.body);
+ if (args instanceof type.errors) return res.status(400).send(args.summary);
+
+ const outcome = await req.appUser.tasksManager.moveToProject(args);
+ if (outcome.ok) return res.tvJson(outcome.data);
+ return res.status(TASK_MOVE_REASON_STATUS[outcome.reason]).send(outcome.reason);
+ };
+
updateTask = async (req: Request, res: Response) => {
const args = TaskArkTypeUpdate(req.body);
@@ -344,7 +371,12 @@ export class TasksController {
}
const result = await req.appUser.tasksManager.updateTask(args);
- if (!result) return res.tvJson(null);
+ if (!result.ok) {
+ if (result.reason === 'foreign_reference') {
+ return res.status(400).send('List, kanban column and parent must belong to the task project; use /module/tasks/move to move a task');
+ }
+ return res.tvJson(null);
+ }
return res.tvJson({ ...result.task, syncFailed: result.syncFailed });
};
diff --git a/api/src/tv-modules/tasks/TasksManager.ts b/api/src/tv-modules/tasks/TasksManager.ts
index 8ab957f..94c95de 100644
--- a/api/src/tv-modules/tasks/TasksManager.ts
+++ b/api/src/tv-modules/tasks/TasksManager.ts
@@ -25,7 +25,10 @@ import type {
UpdateTaskNoteArg,
} from '../../types/tasks.types';
import { TaskItemForClient } from './TaskItemForClient';
+import { TaskMovePlanner } from './TaskMovePlanner';
+import { TaskMoveRepository } from './TaskMoveRepository';
import { TasksRepository } from './TasksRepository';
+import type { TaskArgMove, TaskMoveOutcome, TaskMovePreviewDto } from './task-move.types';
import { FilesRepository } from '../files/FilesRepository';
import {
type TaskArgAdd,
@@ -37,6 +40,7 @@ import {
type TaskArgUpdate,
TaskFieldPermissionsForWatching,
type TaskForClientNew,
+ type TaskUpdateResult,
type TasksArgToggleTaskUsers,
} from './tasks.server.types';
import type { KanbanArgFetchTasksForColumn, KanbanArgFilters } from '../kanban/types';
@@ -263,18 +267,25 @@ export class TasksManager {
return await this.repository.updateTransactionType(data);
}
- async updateTask(data: TaskArgUpdate): Promise<{ task: TaskForClientNew; syncFailed?: boolean } | null> {
- if (data.statusId !== undefined) {
- const currentTask = await this.repository.fetchTaskByIdNew(data.id);
- if (currentTask && currentTask.statusId !== data.statusId) {
- data.kanbanOrder = await this.repository.getNextKanbanOrder(currentTask.goalId);
- }
+ async updateTask(data: TaskArgUpdate): Promise<TaskUpdateResult> {
+ const currentTask = await this.repository.fetchTaskByIdNew(data.id);
+ if (!currentTask) return { ok: false, reason: 'not_found' };
+
+ const foreign = await this.repository.referencesOutsideGoal({
+ taskId: data.id,
+ goalId: currentTask.goalId,
+ goalListId: data.goalListId,
+ statusId: data.statusId,
+ parentId: data.parentId,
+ });
+ if (foreign) return { ok: false, reason: 'foreign_reference' };
+
+ if (data.statusId !== undefined && currentTask.statusId !== data.statusId) {
+ data.kanbanOrder = await this.repository.getNextKanbanOrder(currentTask.goalId);
}
const task = await this.repository.updateTask(data);
- if (!task) {
- return null;
- }
+ if (!task) return { ok: false, reason: 'not_found' };
let syncFailed = false;
if (data.complete !== undefined) {
@@ -291,8 +302,8 @@ export class TasksManager {
const tasks = await this.extendTasksWithTagsAndAssignees([task]);
const result = tasks[0] ?? null;
- if (!result) return null;
- return { task: result, syncFailed: syncFailed || undefined };
+ if (!result) return { ok: false, reason: 'not_found' };
+ return { ok: true, task: result, syncFailed: syncFailed || undefined };
}
async fetchTasksNew(data: TaskArgFetchTasksNew) {
@@ -440,6 +451,38 @@ export class TasksManager {
return result;
}
+ async previewMoveToProject(args: TaskArgMove): Promise<TaskMovePreviewDto> {
+ const planner = this.movePlanner();
+ return planner.toPreview(await planner.plan(args));
+ }
+
+ async moveToProject(args: TaskArgMove): Promise<TaskMoveOutcome> {
+ const decision = await this.movePlanner().plan(args);
+ if (!decision.ok) return decision;
+ const { plan } = decision;
+ const initiatorId = this.user.getUserData()?.id as number;
+ const repository = new TaskMoveRepository();
+
+ if (plan.mode === 'copy') {
+ const copy = await repository.executeCopy({ plan, creatorId: initiatorId });
+ for (const task of copy.tasks) eventBus.emit('task.created', { task, initiatorId });
+ return { ok: true, data: { mode: 'copy', taskId: copy.rootTaskId, goalId: plan.targetGoalId } };
+ }
+
+ const task = await repository.executeMove({ plan });
+ if (!task) return { ok: false, reason: 'not_found' };
+ eventBus.emit('task.moved', { task, taskIds: plan.taskIds, fromGoalId: plan.sourceGoalId, toGoalId: plan.targetGoalId, initiatorId });
+ return { ok: true, data: { mode: 'move', taskId: task.id, goalId: plan.targetGoalId } };
+ }
+
+ private movePlanner(): TaskMovePlanner {
+ return new TaskMovePlanner({
+ repository: new TaskMoveRepository(),
+ userId: this.user.getUserData()?.id as number,
+ checkerForGoal: (goalId) => this.user.permissionsFetcher.getCheckerForGoal(goalId),
+ });
+ }
+
async fetchTasksForKanbanColumn(data: KanbanArgFetchTasksForColumn & { filters?: KanbanArgFilters }): Promise<{ tasks: TaskForClientNew[], nextCursor: string | number | null }> {
const tasks = await this.repository.fetchTasksForKanbanColumn(data.goalId, data.columnId, data.cursor, data.filters);
if (!tasks || tasks.length === 0) return { tasks: [], nextCursor: null };
diff --git a/api/src/tv-modules/tasks/TasksRepository.ts b/api/src/tv-modules/tasks/TasksRepository.ts
index 7a23894..f07cc2d 100644
--- a/api/src/tv-modules/tasks/TasksRepository.ts
+++ b/api/src/tv-modules/tasks/TasksRepository.ts
@@ -1,6 +1,6 @@
import { and, asc, desc, eq, exists, gt, ilike, inArray, isNotNull, isNull, sql } from 'drizzle-orm';
import type { TasksSchemaTypeForSelect } from 'taskview-db-schemas';
-import { TasksAssigneeSchema, TasksSchema, TasksToTagsSchema } from 'taskview-db-schemas';
+import { GoalsListSchema, TasksAssigneeSchema, TasksSchema, TasksStatusesSchema, TasksToTagsSchema } from 'taskview-db-schemas';
import { FetchTasksQueryBuilder } from '../../core/FetchTasksQueryBuilder';
import { Database } from '../../modules/db';
import { $logger } from '../../modules/logget';
@@ -28,6 +28,9 @@ import {
type TaskArgDelete,
type TaskArgFetchTasksNew,
type TaskArgUpdate,
+ type TaskHistoryRestoreArgs,
+ type TaskReferenceCheckArgs,
+ TASK_PROJECT_BOUND_COLUMNS,
TASK_UPDATABLE_COLUMNS,
type TasksArgToggleTaskUsers,
} from './tasks.server.types';
@@ -470,14 +473,25 @@ export class TasksRepository {
return [];
}
- async recoveryTaskHistory(historyId: number, _taskId: number): Promise<boolean> {
+ async recoveryTaskHistory(historyId: number, taskId: number): Promise<boolean> {
const history = await this.fetchTaskHistoryById(historyId);
+ const current = await this.fetchTaskByIdNew(taskId);
- if (!history) {
+ if (!history || !current) {
return false;
}
- return await this.updateTaskState(history.task);
+ return await this.updateTaskState(this.restorableState({ snapshot: history.task, currentGoalId: current.goalId }));
+ }
+
+ private restorableState(args: TaskHistoryRestoreArgs): TaskItemInDb {
+ const state: Partial<TaskItemInDb> = { ...args.snapshot };
+ delete state.goal_id;
+ delete state.owner;
+ if (args.snapshot.goal_id !== args.currentGoalId) {
+ for (const column of TASK_PROJECT_BOUND_COLUMNS) delete state[column];
+ }
+ return state as TaskItemInDb;
}
async updateTaskStatusId(data: TasksUpdateStatusId): Promise<boolean> {
@@ -625,11 +639,11 @@ export class TasksRepository {
const order =
data.sortBy === 'priority'
? [
- descending
- ? sql`${TasksSchema.priorityId} DESC NULLS LAST`
- : sql`${TasksSchema.priorityId} ASC NULLS LAST`,
- desc(TasksSchema.id),
- ]
+ descending
+ ? sql`${TasksSchema.priorityId} DESC NULLS LAST`
+ : sql`${TasksSchema.priorityId} ASC NULLS LAST`,
+ desc(TasksSchema.id),
+ ]
: [descending ? desc(TasksSchema.id) : asc(TasksSchema.id)];
const limit = 30;
@@ -722,6 +736,37 @@ export class TasksRepository {
return result?.[0]?.minKanbanOrder ?? null;
}
+ async referencesOutsideGoal(args: TaskReferenceCheckArgs): Promise<boolean> {
+ const db = this.db.dbDrizzle;
+ if (args.goalListId != null) {
+ const [list] = await db.select({ goalId: GoalsListSchema.goalId }).from(GoalsListSchema).where(eq(GoalsListSchema.id, args.goalListId));
+ if (!list || list.goalId !== args.goalId) return true;
+ }
+ if (args.statusId != null) {
+ const [status] = await db
+ .select({ goalId: TasksStatusesSchema.goalId })
+ .from(TasksStatusesSchema)
+ .where(eq(TasksStatusesSchema.id, args.statusId));
+ if (!status || status.goalId !== args.goalId) return true;
+ }
+ if (args.parentId != null) {
+ // Walk up from the new parent: another project, or reaching the task itself (a cycle), is not allowed
+ let current: number | null = args.parentId;
+ const seen = new Set<number>();
+ while (current !== null) {
+ if (current === args.taskId || seen.has(current)) return true;
+ seen.add(current);
+ const [row] = await db
+ .select({ goalId: TasksSchema.goalId, parentId: TasksSchema.parentId })
+ .from(TasksSchema)
+ .where(eq(TasksSchema.id, current));
+ if (!row || row.goalId !== args.goalId) return true;
+ current = row.parentId;
+ }
+ }
+ return false;
+ }
+
static readonly KANBAN_ORDER_GAP = 16384;
async getNextKanbanOrder(goalId: number, columnId?: number | null): Promise<number> {
diff --git a/api/src/tv-modules/tasks/TasksRoutes.ts b/api/src/tv-modules/tasks/TasksRoutes.ts
index 0f3cc3e..ddcd2bd 100644
--- a/api/src/tv-modules/tasks/TasksRoutes.ts
+++ b/api/src/tv-modules/tasks/TasksRoutes.ts
@@ -60,6 +60,13 @@ export default class TasksRoutes implements Routable {
*/
this.router.delete('', [IsLoggedIn, CanDeleteTask], this.tasksController.deleteTaskNew);
+ /**
+ * Move a task (with its subtasks) to another project of the same organization. The planner checks both
+ * projects; without the right to delete in the source project the task is copied instead.
+ */
+ this.router.get('/:taskId/move-preview', [IsLoggedIn], this.tasksController.previewMoveToProject);
+ this.router.post('/move', [IsLoggedIn], this.tasksController.moveToProject);
+
/**
* Fetch task history
*/
diff --git a/api/src/tv-modules/tasks/__tests__/TaskMove.integration.spec.ts b/api/src/tv-modules/tasks/__tests__/TaskMove.integration.spec.ts
new file mode 100644
index 0000000..dd08be4
--- /dev/null
+++ b/api/src/tv-modules/tasks/__tests__/TaskMove.integration.spec.ts
@@ -0,0 +1,341 @@
+import axios, { type AxiosInstance } from 'axios';
+import { randomUUID } from 'node:crypto';
+import { eq, inArray } from 'drizzle-orm';
+import http from 'http';
+import {
+ CollaborationUsersSchema,
+ CollaborationUsersToGoalsSchema,
+ FileToTaskSchema,
+ FilesSchema,
+ GoalsListSchema,
+ GraphRelationsSchema,
+ IntegrationTaskMapSchema,
+ IntegrationsSchema,
+ RecurrenceRulesSchema,
+ SprintTaskOutcomesSchema,
+ SprintsSchema,
+ TagsSchema,
+ TasksAssigneeSchema,
+ TasksSchema,
+ TasksStatusesSchema,
+ TasksToTagsSchema,
+ TimeEntriesSchema,
+ UsersSchema,
+} from 'taskview-db-schemas';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import App from '../../../App';
+import { Database } from '../../../modules/db';
+import { GoalPermissions } from '../../../types/auth.types';
+import { WebhooksRepository } from '../../webhooks/WebhooksRepository';
+import type { TaskMovePreviewDto, TaskMoveResultDto } from '../task-move.types';
+
+vi.mock('emailjs', () => ({
+ SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),
+}));
+
+const port = 1826;
+const api: AxiosInstance = axios.create({
+ baseURL: `http://localhost:${port}`,
+ validateStatus: () => true,
+ httpAgent: new http.Agent({ keepAlive: false }),
+});
+const db = () => Database.getInstance().dbDrizzle;
+
+type Auth = { headers: { Authorization: string } };
+type CreateTaskArgs = { goalId: number; description: string; parentId?: number; auth?: Auth };
+type MoveArgs = { taskId: number; targetGoalId: number; auth?: Auth };
+type SeededTree = { root: number; sub: number; subSub: number; outside: number; listId: number };
+
+let server: http.Server;
+let ownerAuth: Auth;
+let userId = 0;
+let goalA = 0;
+let goalB = 0;
+let otherOrgId = 0;
+let goalOtherOrg = 0;
+const tokenIds: number[] = [];
+
+async function createGoal(name: string, organizationId?: number): Promise<number> {
+ const response = await api.post('/module/goals', { name: `${name}-${Date.now()}`, organizationId }, ownerAuth);
+ expect(response.status).toBe(200);
+ return response.data.response.id;
+}
+
+async function createTask(args: CreateTaskArgs): Promise<number> {
+ const response = await api.post('/module/tasks', { goalId: args.goalId, description: args.description, parentId: args.parentId }, args.auth ?? ownerAuth);
+ expect(response.status).toBe(200);
+ return response.data.response[0]?.id ?? response.data.response.id;
+}
+
+function preview(args: MoveArgs) {
+ return api.get<{ response: TaskMovePreviewDto }>(`/module/tasks/${args.taskId}/move-preview?targetGoalId=${args.targetGoalId}`, args.auth ?? ownerAuth);
+}
+
+function move(args: MoveArgs) {
+ return api.post<{ response: TaskMoveResultDto }>('/module/tasks/move', { taskId: args.taskId, targetGoalId: args.targetGoalId }, args.auth ?? ownerAuth);
+}
+
+async function tokenWithout(excluded: string[]): Promise<Auth> {
+ const allowedPermissions = Object.values(GoalPermissions).filter((p) => !excluded.includes(p));
+ const response = await api.post('/module/api-tokens', { name: `move-${Date.now()}`, allowedPermissions, allowedGoalIds: [] }, ownerAuth);
+ expect(response.status).toBe(200);
+ tokenIds.push(response.data.response.item.id);
+ return { headers: { Authorization: `Bearer ${response.data.response.token}` } };
+}
+
+async function taskRow(id: number) {
+ const [row] = await db().select().from(TasksSchema).where(eq(TasksSchema.id, id));
+ return row;
+}
+
+// Root with a two-level subtask tree, everything a task can be bound to in its project, and a sibling task the
+// root depends on
+async function seedTree(): Promise<SeededTree> {
+ const root = await createTask({ goalId: goalA, description: 'root to move' });
+ const sub = await createTask({ goalId: goalA, description: 'subtask', parentId: root });
+ const subSub = await createTask({ goalId: goalA, description: 'sub-subtask', parentId: sub });
+ const outside = await createTask({ goalId: goalA, description: 'stays in A' });
+
+ const [list] = await db().insert(GoalsListSchema).values({ name: 'List A', goalId: goalA, creatorId: userId }).returning();
+ const [status] = await db().insert(TasksStatusesSchema).values({ name: 'Doing', goalId: goalA }).returning();
+ const [sprint] = await db().insert(SprintsSchema).values({ goalId: goalA, name: 'S1', startDate: '2026-01-01', endDate: '2026-01-14' }).returning();
+ const [rule] = await db()
+ .insert(RecurrenceRulesSchema)
+ .values({ goalId: goalA, rrule: 'FREQ=DAILY', dtstart: new Date(), timezone: 'UTC', lastInstanceDate: '2026-01-01', creatorId: userId, templateTaskId: root })
+ .returning();
+ await db()
+ .update(TasksSchema)
+ .set({ goalListId: list.id, statusId: status.id, sprintId: sprint.id, recurrenceRuleId: rule.id, nodeGraphPosition: { x: 1, y: 2 } })
+ .where(eq(TasksSchema.id, root));
+
+ const [tag] = await db().insert(TagsSchema).values({ name: `tag-${Date.now()}`, color: '#000000', owner: userId, goalId: goalA }).returning();
+ await db().insert(TasksToTagsSchema).values({ taskId: root, tagId: tag.id });
+ const [collaborator] = await db().insert(CollaborationUsersSchema).values({ email: `assignee-${Date.now()}@test.dest` }).returning();
+ await db().insert(CollaborationUsersToGoalsSchema).values({ userId: collaborator.id, goalId: goalA });
+ await db().insert(TasksAssigneeSchema).values({ taskId: root, collabUserId: collaborator.id });
+ const fileId = randomUUID();
+ await db().insert(FilesSchema).values({
+ id: fileId, goalId: goalA, uploaderId: userId, uploaderEmail: '[email protected]', name: 'a.txt', originalName: 'a.txt',
+ mimeType: 'text/plain', sizeBytes: 1, checksumSha256: '0'.repeat(64), storageProvider: 'local', storageKey: `${goalA}/${fileId}`,
+ });
+ await db().insert(FileToTaskSchema).values({ fileId, taskId: root, linkedById: userId, linkedByEmail: '[email protected]' });
+ await db().insert(SprintTaskOutcomesSchema).values({ sprintId: sprint.id, taskId: root, outcome: 'accepted' });
+ const [integration] = await db().insert(IntegrationsSchema).values({ provider: 'github', projectId: goalA }).returning();
+ await db().insert(IntegrationTaskMapSchema).values({ integrationId: integration.id, taskId: root, issueNumber: 1 });
+ await db().insert(GraphRelationsSchema).values([
+ { fromTaskId: root, toTaskId: sub, goalId: goalA },
+ { fromTaskId: root, toTaskId: outside, goalId: goalA },
+ ]);
+ await db().insert(TimeEntriesSchema).values({ taskId: root, goalId: goalA, userId, startedAt: new Date(), endedAt: new Date(), durationSeconds: 60 });
+
+ return { root, sub, subSub, outside, listId: list.id };
+}
+
+describe('Moving a task to another project', () => {
+ beforeAll(async () => {
+ server = new App(port).listen();
+ const login = await api.post('/module/auth/login', { login: '[email protected]', password: 'user1!#Q' });
+ expect(login.status).toBe(200);
+ ownerAuth = { headers: { Authorization: `Bearer ${login.data.access}` } };
+ const [user] = await db().select({ id: UsersSchema.id }).from(UsersSchema).where(eq(UsersSchema.email, '[email protected]'));
+ userId = user.id;
+
+ goalA = await createGoal('move-A');
+ goalB = await createGoal('move-B');
+ const org = await api.post('/module/organizations', { name: `move-org-${Date.now()}` }, ownerAuth);
+ expect(org.status).toBe(200);
+ otherOrgId = org.data.response.id;
+ goalOtherOrg = await createGoal('move-other-org', otherOrgId);
+ });
+
+ afterAll(async () => {
+ for (const id of tokenIds) await api.delete('/module/api-tokens', { ...ownerAuth, data: { id } });
+ for (const goalId of [goalA, goalB, goalOtherOrg]) if (goalId) await api.delete('/module/goals', { ...ownerAuth, data: { goalId } });
+ if (otherOrgId) await api.delete(`/module/organizations/${otherOrgId}`, ownerAuth);
+ if (server) await new Promise<void>((resolve) => server.close(() => resolve()));
+ }, 30_000);
+
+ it('previews and moves the whole tree, detaching everything bound to the old project', async () => {
+ const tree = await seedTree();
+ const ids = [tree.root, tree.sub, tree.subSub];
+
+ const shown = await preview({ taskId: tree.root, targetGoalId: goalB });
+ expect(shown.status).toBe(200);
+ expect(shown.data.response).toEqual({
+ allowed: true,
+ reason: null,
+ mode: 'move',
+ tasks: 3,
+ timeEntries: 1,
+ removals: { tags: 1, assignees: 1, fileLinks: 1, dependencies: 1, sprintOutcomes: 1, integrationLinks: 1, recurrence: 1 },
+ leftBehind: { subtasks: 0, timeEntries: 0 },
+ });
+
+ const moved = await move({ taskId: tree.root, targetGoalId: goalB });
+ expect(moved.status).toBe(200);
+ expect(moved.data.response).toEqual({ mode: 'move', taskId: tree.root, goalId: goalB });
+
+ const rows = await db().select().from(TasksSchema).where(inArray(TasksSchema.id, ids));
+ for (const row of rows) expect(row.goalId).toBe(goalB);
+ const root = await taskRow(tree.root);
+ expect(root).toMatchObject({ goalListId: null, statusId: null, sprintId: null, recurrenceRuleId: null, nodeGraphPosition: null, parentId: null });
+ expect((await taskRow(tree.subSub)).parentId).toBe(tree.sub);
+
+ for (const table of [TasksToTagsSchema, TasksAssigneeSchema, FileToTaskSchema, SprintTaskOutcomesSchema, IntegrationTaskMapSchema]) {
+ expect(await db().select().from(table).where(inArray(table.taskId, ids))).toEqual([]);
+ }
+ const edges = await db().select().from(GraphRelationsSchema).where(eq(GraphRelationsSchema.fromTaskId, tree.root));
+ expect(edges.map((e) => [e.toTaskId, e.goalId])).toEqual([[tree.sub, goalB]]);
+ const [entry] = await db().select().from(TimeEntriesSchema).where(eq(TimeEntriesSchema.taskId, tree.root));
+ expect(entry.goalId).toBe(goalB);
+ const [rule] = await db().select().from(RecurrenceRulesSchema).where(eq(RecurrenceRulesSchema.goalId, goalA));
+ expect(rule.templateTaskId).toBeNull();
+ // Files are not moved: they stay in the old project, only the link is gone
+ expect(await db().select().from(FilesSchema).where(eq(FilesSchema.goalId, goalA))).toHaveLength(1);
+ // The task the root depended on stays where it was
+ expect((await taskRow(tree.outside)).goalId).toBe(goalA);
+ });
+
+ it('refuses an update that points the moved task back at a list of the old project', async () => {
+ const task = await createTask({ goalId: goalA, description: 'list probe' });
+ const [listB] = await db().insert(GoalsListSchema).values({ name: 'List B', goalId: goalB, creatorId: userId }).returning();
+ const response = await api.patch('/module/tasks', { id: task, goalListId: listB.id }, ownerAuth);
+ expect(response.status).toBe(400);
+ expect((await taskRow(task)).goalId).toBe(goalA);
+
+ const [statusB] = await db().insert(TasksStatusesSchema).values({ name: 'B col', goalId: goalB }).returning();
+ expect((await api.patch('/module/tasks', { id: task, statusId: statusB.id }, ownerAuth)).status).toBe(400);
+ const foreignParent = await createTask({ goalId: goalB, description: 'foreign parent' });
+ expect((await api.patch('/module/tasks', { id: task, parentId: foreignParent }, ownerAuth)).status).toBe(400);
+ expect((await api.patch('/module/tasks', { id: task, parentId: task }, ownerAuth)).status).toBe(400);
+ });
+
+ it('does not move the task back when a history version from before the move is restored', async () => {
+ const task = await createTask({ goalId: goalA, description: 'history before' });
+ await api.patch('/module/tasks', { id: task, description: 'history edited in A' }, ownerAuth);
+ expect((await move({ taskId: task, targetGoalId: goalB })).status).toBe(200);
+
+ const history = await api.get(`/module/tasks/${task}/history`, ownerAuth);
+ const versions = history.data.response.history as { historyId: number | null; goalId: number }[];
+ const fromA = versions.find((h) => h.historyId && h.goalId === goalA);
+ expect(fromA).toBeTruthy();
+ const restored = await api.post(`/module/tasks/${task}/restore/${fromA?.historyId}`, {}, ownerAuth);
+ expect(restored.status).toBe(200);
+ expect((await taskRow(task)).goalId).toBe(goalB);
+ });
+
+ it.each([
+ ['a subtask on its own', 'sub', 'is_subtask', 400],
+ ['to the same project', 'same', 'same_project', 400],
+ ['to a project of another organization', 'other-org', 'other_organization', 400],
+ ] as const)('refuses moving %s', async (_label, kind, reason, status) => {
+ const root = await createTask({ goalId: goalA, description: `refuse ${kind}` });
+ const sub = await createTask({ goalId: goalA, description: 'child', parentId: root });
+ const args = {
+ sub: { taskId: sub, targetGoalId: goalB },
+ same: { taskId: root, targetGoalId: goalA },
+ 'other-org': { taskId: root, targetGoalId: goalOtherOrg },
+ }[kind];
+ expect((await preview(args)).data.response).toMatchObject({ allowed: false, reason });
+ const response = await move(args);
+ expect(response.status).toBe(status);
+ expect(response.data).toBe(reason);
+ expect((await taskRow(root)).goalId).toBe(goalA);
+ });
+
+ it('copies the task when the user may not delete tasks in the source project, leaving the original untouched', async () => {
+ const auth = await tokenWithout([GoalPermissions.TASKS_CAN_DELETE]);
+ const tree = await seedTree();
+
+ expect((await preview({ taskId: tree.root, targetGoalId: goalB, auth })).data.response).toMatchObject({ allowed: true, mode: 'copy', tasks: 3, timeEntries: 0 });
+ const copied = await move({ taskId: tree.root, targetGoalId: goalB, auth });
+ expect(copied.status).toBe(200);
+ expect(copied.data.response.mode).toBe('copy');
+ const copyRootId = copied.data.response.taskId;
+ expect(copyRootId).not.toBe(tree.root);
+
+ // The original keeps its project, tags and time
+ expect((await taskRow(tree.root)).goalId).toBe(goalA);
+ expect(await db().select().from(TasksToTagsSchema).where(eq(TasksToTagsSchema.taskId, tree.root))).toHaveLength(1);
+ expect(await db().select().from(TimeEntriesSchema).where(eq(TimeEntriesSchema.taskId, tree.root))).toHaveLength(1);
+
+ // The copy: same content and subtree in B, nothing project-bound, no logged time
+ const copyRoot = await taskRow(copyRootId);
+ expect(copyRoot).toMatchObject({ goalId: goalB, description: 'root to move', goalListId: null, statusId: null, parentId: null });
+ const copySubs = await db().select().from(TasksSchema).where(eq(TasksSchema.parentId, copyRootId));
+ expect(copySubs.map((t) => t.description)).toEqual(['subtask']);
+ const copySubSubs = await db().select().from(TasksSchema).where(eq(TasksSchema.parentId, copySubs[0].id));
+ expect(copySubSubs.map((t) => [t.description, t.goalId])).toEqual([['sub-subtask', goalB]]);
+ expect(await db().select().from(TasksToTagsSchema).where(eq(TasksToTagsSchema.taskId, copyRootId))).toEqual([]);
+ expect(await db().select().from(TimeEntriesSchema).where(eq(TimeEntriesSchema.taskId, copyRootId))).toEqual([]);
+ const copiedEdges = await db().select().from(GraphRelationsSchema).where(eq(GraphRelationsSchema.fromTaskId, copyRootId));
+ expect(copiedEdges.map((e) => [e.toTaskId, e.goalId])).toEqual([[copySubs[0].id, goalB]]);
+ });
+
+ it('leaves the subtasks in the old project as standalone tasks without the subtask permission in the target', async () => {
+ const auth = await tokenWithout([GoalPermissions.TASKS_CAN_ADD_SUBTASKS]);
+ const root = await createTask({ goalId: goalA, description: 'root without subtasks' });
+ const sub = await createTask({ goalId: goalA, description: 'left behind', parentId: root });
+ const subSub = await createTask({ goalId: goalA, description: 'left behind child', parentId: sub });
+
+ expect((await preview({ taskId: root, targetGoalId: goalB, auth })).data.response).toMatchObject({ tasks: 1, leftBehind: { subtasks: 2 } });
+ expect((await move({ taskId: root, targetGoalId: goalB, auth })).status).toBe(200);
+
+ expect((await taskRow(root)).goalId).toBe(goalB);
+ expect(await taskRow(sub)).toMatchObject({ goalId: goalA, parentId: null });
+ expect(await taskRow(subSub)).toMatchObject({ goalId: goalA, parentId: sub });
+ });
+
+ it('moves only the user\'s own logged time with the log permission, other people\'s stays in the old project', async () => {
+ const auth = await tokenWithout([GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL]);
+ const root = await createTask({ goalId: goalA, description: 'time split' });
+ // A dedicated second user: picking an existing row raced with specs that delete their users in parallel
+ const [someoneElse] = await db()
+ .insert(UsersSchema)
+ .values({ login: `move-time-${Date.now()}`, email: `move-time-${Date.now()}@mail.dest`, password: 'not-used', block: 0 })
+ .returning({ id: UsersSchema.id });
+ try {
+ await db().insert(TimeEntriesSchema).values([
+ { taskId: root, goalId: goalA, userId, startedAt: new Date(), endedAt: new Date(), durationSeconds: 30 },
+ { taskId: root, goalId: goalA, userId: someoneElse.id, startedAt: new Date(), endedAt: new Date(), durationSeconds: 30 },
+ ]);
+
+ expect((await move({ taskId: root, targetGoalId: goalB, auth })).status).toBe(200);
+ const entries = await db().select().from(TimeEntriesSchema).where(eq(TimeEntriesSchema.taskId, root));
+ expect(entries.find((e) => e.userId === userId)?.goalId).toBe(goalB);
+ expect(entries.find((e) => e.userId === someoneElse.id)?.goalId).toBe(goalA);
+ } finally {
+ await db().delete(UsersSchema).where(eq(UsersSchema.id, someoneElse.id));
+ }
+ });
+
+ it('notifies the webhooks of both projects about the move', async () => {
+ const savedAllowPrivate = process.env.WEBHOOKS_ALLOW_PRIVATE_URLS;
+ process.env.WEBHOOKS_ALLOW_PRIVATE_URLS = 'true';
+ const webhookIds: number[] = [];
+ try {
+ for (const goalId of [goalA, goalB]) {
+ const created = await api.post('/module/webhooks', { goalId, url: 'http://127.0.0.1:9/hook', events: ['task.moved'] }, ownerAuth);
+ expect(created.status).toBe(200);
+ webhookIds.push(created.data.response.webhook.id);
+ }
+ const task = await createTask({ goalId: goalA, description: 'announced move' });
+ expect((await move({ taskId: task, targetGoalId: goalB })).status).toBe(200);
+
+ const repository = new WebhooksRepository();
+ for (const webhookId of webhookIds) {
+ let deliveries = await repository.fetchDeliveries(webhookId);
+ for (let attempt = 0; attempt < 50 && deliveries.length === 0; attempt++) {
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ deliveries = await repository.fetchDeliveries(webhookId);
+ }
+ expect(deliveries).toHaveLength(1);
+ expect(deliveries[0].payload).toMatchObject({ event: 'task.moved', taskIds: [task], fromGoalId: goalA, toGoalId: goalB });
+ }
+ } finally {
+ for (const id of webhookIds) await api.delete('/module/webhooks', { ...ownerAuth, data: { id } });
+ if (savedAllowPrivate === undefined) delete process.env.WEBHOOKS_ALLOW_PRIVATE_URLS;
+ else process.env.WEBHOOKS_ALLOW_PRIVATE_URLS = savedAllowPrivate;
+ }
+ });
+});
diff --git a/api/src/tv-modules/tasks/__tests__/TaskMovePlanner.spec.ts b/api/src/tv-modules/tasks/__tests__/TaskMovePlanner.spec.ts
new file mode 100644
index 0000000..82c2425
--- /dev/null
+++ b/api/src/tv-modules/tasks/__tests__/TaskMovePlanner.spec.ts
@@ -0,0 +1,144 @@
+import type { TasksSchemaTypeForSelect } from 'taskview-db-schemas';
+import { describe, expect, it } from 'vitest';
+import { GoalPermissionsChecker } from '../../../core/GoalPermissionsChecker';
+import { GoalPermissions, type GoalPermissionType } from '../../../types/auth.types';
+import { TaskMovePlanner } from '../TaskMovePlanner';
+import type { TaskMoveRepository } from '../TaskMoveRepository';
+import type { TaskMoveContext, TaskMoveRemovals, TaskMoveTimeEntryCountArgs } from '../task-move.types';
+
+const USER_ID = 7;
+const SOURCE = 10;
+const TARGET = 20;
+const ROOT = 100;
+const SUBTASKS = [101, 102];
+
+const REMOVALS: TaskMoveRemovals = { tags: 2, assignees: 1, fileLinks: 3, dependencies: 1, sprintOutcomes: 0, integrationLinks: 1, recurrence: 1 };
+
+type FakeSetup = {
+ context?: TaskMoveContext | null;
+ source?: GoalPermissionType[];
+ target?: GoalPermissionType[];
+ // entries per user id, for every task of the plan
+ timeEntries?: Record<number, number>;
+};
+
+const ALL_SOURCE = [GoalPermissions.COMPONENT_CAN_WATCH_CONTENT, GoalPermissions.TASKS_CAN_DELETE];
+const ALL_TARGET = [
+ GoalPermissions.COMPONENT_CAN_ADD_TASKS,
+ GoalPermissions.TASKS_CAN_ADD_SUBTASKS,
+ GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL,
+];
+
+function context(overrides: Partial<TasksSchemaTypeForSelect> = {}, targetOrganizationId = 1): TaskMoveContext {
+ return {
+ task: { id: ROOT, goalId: SOURCE, parentId: null, ...overrides } as TasksSchemaTypeForSelect,
+ sourceOrganizationId: 1,
+ target: { id: TARGET, organizationId: targetOrganizationId, ownerId: 3 },
+ };
+}
+
+function planner(setup: FakeSetup = {}) {
+ const entries = setup.timeEntries ?? { [USER_ID]: 2, 8: 5 };
+ const repository = {
+ fetchContext: async () => (setup.context === undefined ? context() : setup.context),
+ fetchSubtaskIds: async () => SUBTASKS,
+ countRemovals: async () => REMOVALS,
+ countTimeEntries: async (args: TaskMoveTimeEntryCountArgs) =>
+ Object.entries(entries)
+ .filter(([userId]) => args.userIds === null || args.userIds.includes(Number(userId)))
+ .reduce((sum, [, n]) => sum + n, 0),
+ } as unknown as TaskMoveRepository;
+ const checkers: Record<number, GoalPermissionType[]> = { [SOURCE]: setup.source ?? ALL_SOURCE, [TARGET]: setup.target ?? ALL_TARGET };
+ return new TaskMovePlanner({
+ repository,
+ userId: USER_ID,
+ checkerForGoal: async (goalId) =>
+ new GoalPermissionsChecker((checkers[goalId] ?? []).map((permissionName, i) => ({ permissionName, permissionId: i }))),
+ });
+}
+
+const move = { taskId: ROOT, targetGoalId: TARGET };
+
+describe('TaskMovePlanner', () => {
+ it('moves the task with its subtasks and everyone\'s time when all permissions are there', async () => {
+ const decision = await planner().plan(move);
+ expect(decision).toEqual({
+ ok: true,
+ plan: {
+ mode: 'move',
+ rootTaskId: ROOT,
+ sourceGoalId: SOURCE,
+ targetGoalId: TARGET,
+ targetGoalOwnerId: 3,
+ taskIds: [ROOT, ...SUBTASKS],
+ leftBehindSubtaskIds: [],
+ timeEntryUserIds: null,
+ removals: REMOVALS,
+ leftBehind: { subtasks: 0, timeEntries: 0 },
+ movedTimeEntries: 7,
+ },
+ });
+ });
+
+ it('copies instead of moving when the user may not delete tasks in the source project', async () => {
+ const decision = await planner({ source: [GoalPermissions.COMPONENT_CAN_WATCH_CONTENT] }).plan(move);
+ expect(decision.ok && decision.plan.mode).toBe('copy');
+ // A copy never takes logged time: it would be counted twice
+ expect(decision.ok && decision.plan.timeEntryUserIds).toEqual([]);
+ expect(decision.ok && decision.plan.movedTimeEntries).toBe(0);
+ expect(decision.ok && decision.plan.leftBehind.timeEntries).toBe(0);
+ });
+
+ it('leaves the subtasks behind without the subtask permission in the target project', async () => {
+ const decision = await planner({ target: [GoalPermissions.COMPONENT_CAN_ADD_TASKS, GoalPermissions.TIMETRACKING_CAN_MANAGE_ALL] }).plan(move);
+ expect(decision.ok && decision.plan.taskIds).toEqual([ROOT]);
+ expect(decision.ok && decision.plan.leftBehindSubtaskIds).toEqual(SUBTASKS);
+ expect(decision.ok && decision.plan.leftBehind.subtasks).toBe(2);
+ });
+
+ it('moves only the user\'s own time with the log permission, and none without time permissions', async () => {
+ const own = await planner({
+ target: [GoalPermissions.COMPONENT_CAN_ADD_TASKS, GoalPermissions.TASKS_CAN_ADD_SUBTASKS, GoalPermissions.TIMETRACKING_CAN_LOG],
+ }).plan(move);
+ expect(own.ok && own.plan.timeEntryUserIds).toEqual([USER_ID]);
+ expect(own.ok && own.plan.movedTimeEntries).toBe(2);
+ expect(own.ok && own.plan.leftBehind.timeEntries).toBe(5);
+
+ const none = await planner({ target: [GoalPermissions.COMPONENT_CAN_ADD_TASKS, GoalPermissions.TASKS_CAN_ADD_SUBTASKS] }).plan(move);
+ expect(none.ok && none.plan.timeEntryUserIds).toEqual([]);
+ expect(none.ok && none.plan.leftBehind.timeEntries).toBe(7);
+ });
+
+ it.each([
+ ['an unknown task', { context: null }, 'not_found'],
+ ['a task the user cannot see (reported as not found)', { source: [] }, 'not_found'],
+ ['a subtask', { context: context({ parentId: 55 }) }, 'is_subtask'],
+ ['the same project', { context: { ...context(), target: { id: SOURCE, organizationId: 1, ownerId: 3 } } }, 'same_project'],
+ ['a project of another organization', { context: context({}, 2) }, 'other_organization'],
+ ['a target without the right to add tasks', { target: [GoalPermissions.TASKS_CAN_ADD_SUBTASKS] }, 'no_target_permission'],
+ ] as const)('refuses %s', async (_label, setup, reason) => {
+ expect(await planner(setup as FakeSetup).plan(move)).toEqual({ ok: false, reason });
+ });
+
+ it('turns a decision into the preview the client shows', async () => {
+ const p = planner({ target: [GoalPermissions.COMPONENT_CAN_ADD_TASKS, GoalPermissions.TIMETRACKING_CAN_LOG] });
+ expect(p.toPreview(await p.plan(move))).toEqual({
+ allowed: true,
+ reason: null,
+ mode: 'move',
+ tasks: 1,
+ timeEntries: 2,
+ removals: REMOVALS,
+ leftBehind: { subtasks: 2, timeEntries: 5 },
+ });
+ expect(p.toPreview({ ok: false, reason: 'same_project' })).toEqual({
+ allowed: false,
+ reason: 'same_project',
+ mode: null,
+ tasks: 0,
+ timeEntries: 0,
+ removals: null,
+ leftBehind: null,
+ });
+ });
+});
diff --git a/api/src/tv-modules/tasks/task-move.types.ts b/api/src/tv-modules/tasks/task-move.types.ts
new file mode 100644
index 0000000..2f3bb43
--- /dev/null
+++ b/api/src/tv-modules/tasks/task-move.types.ts
@@ -0,0 +1,118 @@
+import { type } from 'arktype';
+import type { TasksSchemaTypeForSelect } from 'taskview-db-schemas';
+import type { GoalPermissionsChecker } from '../../core/GoalPermissionsChecker';
+import type { TaskMoveRepository } from './TaskMoveRepository';
+
+const NumberFromString = type('string | number').pipe((v) => Number(v));
+
+export const TaskArkTypeMove = type({
+ taskId: 'number',
+ targetGoalId: 'number',
+});
+export type TaskArgMove = typeof TaskArkTypeMove.infer;
+
+export const TaskArkTypeMovePreview = type({
+ taskId: NumberFromString,
+ targetGoalId: NumberFromString,
+});
+
+export type TaskMoveMode = 'move' | 'copy';
+
+export type TaskMoveBlockReason =
+ | 'not_found'
+ | 'same_project'
+ | 'other_organization'
+ | 'is_subtask'
+ | 'no_target_permission';
+
+export type TaskMoveRemovals = {
+ tags: number;
+ assignees: number;
+ fileLinks: number;
+ dependencies: number;
+ sprintOutcomes: number;
+ integrationLinks: number;
+ recurrence: number;
+};
+
+export type TaskMoveLeftBehind = {
+ subtasks: number;
+ timeEntries: number;
+};
+
+export type TaskMovePlan = {
+ mode: TaskMoveMode;
+ rootTaskId: number;
+ sourceGoalId: number;
+ targetGoalId: number;
+ targetGoalOwnerId: number;
+ // Root first, then subtasks parent-before-child; only the tasks that go to the target project
+ taskIds: number[];
+ // Subtasks staying in the source project (they become standalone tasks there when the root moves)
+ leftBehindSubtaskIds: number[];
+ // Time entries move only in 'move' mode, and only those of the users listed here (null = everyone's)
+ timeEntryUserIds: number[] | null;
+ removals: TaskMoveRemovals;
+ leftBehind: TaskMoveLeftBehind;
+ movedTimeEntries: number;
+};
+
+export type TaskMoveDecision = { ok: true; plan: TaskMovePlan } | { ok: false; reason: TaskMoveBlockReason };
+
+export type TaskMovePreviewDto = {
+ allowed: boolean;
+ reason: TaskMoveBlockReason | null;
+ mode: TaskMoveMode | null;
+ tasks: number;
+ timeEntries: number;
+ removals: TaskMoveRemovals | null;
+ leftBehind: TaskMoveLeftBehind | null;
+};
+
+export type TaskMoveResultDto = {
+ mode: TaskMoveMode;
+ taskId: number;
+ goalId: number;
+};
+
+export type TaskMoveOutcome = { ok: true; data: TaskMoveResultDto } | { ok: false; reason: TaskMoveBlockReason };
+
+export type TaskMoveContext = {
+ task: TasksSchemaTypeForSelect;
+ sourceOrganizationId: number | null;
+ target: { id: number; organizationId: number | null; ownerId: number } | null;
+};
+
+export type TaskMoveContextArgs = {
+ taskId: number;
+ targetGoalId: number;
+};
+
+export type TaskMoveCountArgs = {
+ taskIds: number[];
+};
+
+export type TaskMoveTimeEntryCountArgs = {
+ taskIds: number[];
+ userIds: number[] | null;
+};
+
+export type TaskMoveExecuteArgs = {
+ plan: TaskMovePlan;
+};
+
+export type TaskCopyExecuteArgs = {
+ plan: TaskMovePlan;
+ creatorId: number;
+};
+
+export type TaskCopyResult = {
+ rootTaskId: number;
+ tasks: TasksSchemaTypeForSelect[];
+};
+
+export type TaskMovePlannerArgs = {
+ repository: TaskMoveRepository;
+ userId: number;
+ checkerForGoal: (goalId: number) => Promise<GoalPermissionsChecker>;
+};
diff --git a/api/src/tv-modules/tasks/tasks.server.types.ts b/api/src/tv-modules/tasks/tasks.server.types.ts
index 64b31b1..fd0b28a 100644
--- a/api/src/tv-modules/tasks/tasks.server.types.ts
+++ b/api/src/tv-modules/tasks/tasks.server.types.ts
@@ -1,4 +1,5 @@
import { type } from 'arktype';
+import type { TaskItemInDb } from '../../types/tasks.types';
import type { TasksSchemaTypeForSelect } from 'taskview-db-schemas';
import { GoalPermissions } from '../../types/auth.types';
@@ -74,6 +75,16 @@ export type TaskArgFetchTasksNew = typeof TaskArkTypeFetchTasksNew.infer;
export type TaskArgUpdate = typeof TaskArkTypeUpdate.infer;
+// A list, kanban column or parent from another project would silently move the task there (a DB trigger derives
+// goal_id from the list), so updates must only reference the task's own project. Moving goes through /tasks/move.
+export type TaskReferenceCheckArgs = {
+ taskId: number;
+ goalId: number;
+ goalListId?: number | null;
+ statusId?: number | null;
+ parentId?: number | null;
+};
+
export const TASK_UPDATABLE_COLUMNS = [
'parentId',
'description',
@@ -203,3 +214,24 @@ export const TaskArkTypeRestoreTaskHistory = type({
});
export type TaskArgRestoreTaskHistory = typeof TaskArkTypeRestoreTaskHistory.infer;
+
+export type TaskUpdateResult =
+ | { ok: true; task: TaskForClientNew; syncFailed?: boolean }
+ | { ok: false; reason: 'not_found' | 'foreign_reference' };
+
+// Columns that point into the task's project; a history snapshot from another project must not restore them
+export const TASK_PROJECT_BOUND_COLUMNS = [
+ 'goal_list_id',
+ 'status_id',
+ 'sprint_id',
+ 'parent_id',
+ 'recurrence_rule_id',
+ 'recurrence_instance_date',
+ 'node_graph_position',
+ 'kanban_order',
+] as const satisfies ReadonlyArray<keyof TaskItemInDb>;
+
+export type TaskHistoryRestoreArgs = {
+ snapshot: TaskItemInDb;
+ currentGoalId: number;
+};
diff --git a/api/src/tv-modules/webhooks/WebhooksDispatcher.ts b/api/src/tv-modules/webhooks/WebhooksDispatcher.ts
index 3fa729c..d56adec 100644
--- a/api/src/tv-modules/webhooks/WebhooksDispatcher.ts
+++ b/api/src/tv-modules/webhooks/WebhooksDispatcher.ts
@@ -9,6 +9,7 @@ import { WebhooksRepository } from './WebhooksRepository';
import { WebhooksManager } from './WebhooksManager';
import type { WebhookDeliverJobData } from './types';
import type { Dispatcher } from '../../core/Dispatcher';
+import { FILE_EVENTS } from '../files/types';
const WEBHOOK_DELIVER_JOB = 'webhook-deliver';
const MAX_ATTEMPTS = 3;
@@ -22,6 +23,11 @@ export class WebhooksDispatcher implements Dispatcher {
eventBus.on('task.created', (data) => this.dispatch('task.created', data.task.goalId, data));
eventBus.on('task.updated', (data) => this.dispatch('task.updated', data.task.goalId, data));
eventBus.on('task.deleted', (data) => this.dispatch('task.deleted', data.goalId, data));
+ // Both projects hear about a move: the task left one and arrived in the other
+ eventBus.on('task.moved', async (data) => {
+ await this.dispatch('task.moved', data.fromGoalId, data);
+ await this.dispatch('task.moved', data.toGoalId, data);
+ });
eventBus.on('task.assigneesChanged', (data) => this.dispatchAssigneesChanged(data));
eventBus.on('time-entry.started', (data) => this.dispatch('time-entry.started', data.goalId, data));
eventBus.on('time-entry.stopped', (data) => this.dispatch('time-entry.stopped', data.goalId, data));
@@ -37,6 +43,9 @@ export class WebhooksDispatcher implements Dispatcher {
eventBus.on('sprint.resumed', (data) => this.dispatchSprintLifecycle('sprint.resumed', data));
eventBus.on('sprint.deleted', (data) => this.dispatch('sprint.deleted', data.goalId, data));
eventBus.on('task.assignedToSprint', (data) => this.dispatch('task.assignedToSprint', data.goalId, data));
+ for (const event of FILE_EVENTS) {
+ eventBus.on(event, (data) => this.dispatch(event, data.goalId, data));
+ }
}
async registerWorkers(): Promise<void> {
diff --git a/api/src/tv-modules/webhooks/__tests__/WebhooksFiles.integration.spec.ts b/api/src/tv-modules/webhooks/__tests__/WebhooksFiles.integration.spec.ts
new file mode 100644
index 0000000..7001581
--- /dev/null
+++ b/api/src/tv-modules/webhooks/__tests__/WebhooksFiles.integration.spec.ts
@@ -0,0 +1,133 @@
+import axios, { type AxiosInstance } from 'axios';
+import fs from 'fs/promises';
+import http from 'http';
+import { join } from 'path';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import App from '../../../App';
+import { Database } from '../../../modules/db';
+import { FILE_EVENTS, FileEvents, type FileDto, type FileEventPayload } from '../../files/types';
+import { WebhooksRepository } from '../WebhooksRepository';
+
+vi.mock('emailjs', () => ({
+ SMTPClient: vi.fn().mockImplementation(() => ({ sendAsync: vi.fn().mockResolvedValue(true) })),
+}));
+
+const port = 1825;
+const FILES_MIGRATION_DIR = join(__dirname, '../../../migrations/taskview/sql/1.67.0');
+
+const api: AxiosInstance = axios.create({
+ baseURL: `http://localhost:${port}`,
+ validateStatus: () => true,
+ httpAgent: new http.Agent({ keepAlive: false }),
+});
+
+type DeliveryPayload = FileEventPayload & { event: string; timestamp: string };
+
+let server: http.Server;
+let jwt = '';
+let goalId = 0;
+let taskId = 0;
+let otherTaskId = 0;
+let webhookId = 0;
+const savedAllowPrivate = process.env.WEBHOOKS_ALLOW_PRIVATE_URLS;
+const auth = () => ({ headers: { Authorization: `Bearer ${jwt}` } });
+
+async function createTask(description: string): Promise<number> {
+ const response = await api.post('/module/tasks', { goalId, description }, auth());
+ expect(response.status).toBe(200);
+ return response.data.response.id;
+}
+
+// Deliveries are written by an async event listener; wait until the expected number shows up
+async function fileDeliveries(expected: number): Promise<DeliveryPayload[]> {
+ const repository = new WebhooksRepository();
+ for (let attempt = 0; attempt < 50; attempt++) {
+ const rows = await repository.fetchDeliveries(webhookId, { limit: 50 });
+ if (rows.length >= expected) {
+ return rows
+ .sort((a, b) => a.id - b.id)
+ .map((row) => row.payload as DeliveryPayload);
+ }
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+ throw new Error(`Expected ${expected} webhook deliveries`);
+}
+
+describe('Webhooks: file events', () => {
+ beforeAll(async () => {
+ const client = await Database.getInstance().getClient();
+ await client.query('SELECT pg_advisory_lock(1401067)');
+ try {
+ for (const file of (await fs.readdir(FILES_MIGRATION_DIR)).sort()) {
+ await client.query(await fs.readFile(join(FILES_MIGRATION_DIR, file), 'utf-8'));
+ }
+ } finally {
+ await client.query('SELECT pg_advisory_unlock(1401067)');
+ client.release();
+ }
+
+ // The receiver URL is never reached in this test; only the recorded deliveries are checked
+ process.env.WEBHOOKS_ALLOW_PRIVATE_URLS = 'true';
+ server = new App(port).listen();
+
+ const login = await api.post('/module/auth/login', { login: '[email protected]', password: 'user1!#Q' });
+ expect(login.status).toBe(200);
+ jwt = login.data.access;
+
+ const goal = await api.post('/module/goals', { name: `webhook-files-${Date.now()}` }, auth());
+ expect(goal.status).toBe(200);
+ goalId = goal.data.response.id;
+ taskId = await createTask('task with a file');
+ otherTaskId = await createTask('another task');
+
+ const webhook = await api.post('/module/webhooks', { goalId, url: 'http://127.0.0.1:9/hook', events: [...FILE_EVENTS] }, auth());
+ expect(webhook.status).toBe(200);
+ webhookId = webhook.data.response.webhook.id;
+ });
+
+ afterAll(async () => {
+ if (webhookId) await api.delete('/module/webhooks', { ...auth(), data: { id: webhookId } });
+ if (goalId) await api.delete('/module/goals', { ...auth(), data: { goalId } });
+ if (savedAllowPrivate === undefined) delete process.env.WEBHOOKS_ALLOW_PRIVATE_URLS;
+ else process.env.WEBHOOKS_ALLOW_PRIVATE_URLS = savedAllowPrivate;
+ if (server) await new Promise<void>((resolve) => server.close(() => resolve()));
+ }, 30_000);
+
+ it('delivers upload, rename, attach, detach and delete with the file metadata and no download link', async () => {
+ const form = new FormData();
+ form.append('file', new Blob(['webhook file'], { type: 'text/plain' }), 'report.txt');
+ const uploaded = await api.post<{ response: FileDto }>(`/module/files/goal/${goalId}?taskId=${taskId}`, form, auth());
+ expect(uploaded.status).toBe(200);
+ const fileId = uploaded.data.response.id;
+
+ expect((await api.patch(`/module/files/file/${fileId}`, { name: 'final' }, auth())).status).toBe(200);
+ expect((await api.post(`/module/files/task/${otherTaskId}/link`, { fileIds: [fileId] }, auth())).status).toBe(200);
+ expect((await api.delete(`/module/files/task/${taskId}/file/${fileId}`, auth())).status).toBe(200);
+ expect((await api.delete(`/module/files/file/${fileId}`, auth())).status).toBe(200);
+
+ const payloads = await fileDeliveries(5);
+ expect(payloads.map((p) => p.event)).toEqual([
+ FileEvents.Uploaded,
+ FileEvents.Renamed,
+ FileEvents.Attached,
+ FileEvents.Detached,
+ FileEvents.Deleted,
+ ]);
+
+ const [upload, rename, attach, detach, remove] = payloads;
+ expect(upload).toMatchObject({ goalId, taskIds: [taskId], file: { id: fileId, name: 'report.txt', mimeType: 'text/plain', linkedTaskIds: [taskId] } });
+ expect(rename).toMatchObject({ taskIds: [taskId], file: { id: fileId, name: 'final.txt' } });
+ expect(attach.taskIds).toEqual([otherTaskId]);
+ expect([...attach.file.linkedTaskIds].sort()).toEqual([taskId, otherTaskId].sort());
+ expect(detach).toMatchObject({ taskIds: [taskId], file: { linkedTaskIds: [otherTaskId] } });
+ expect(remove).toMatchObject({ taskIds: [otherTaskId], file: { id: fileId, name: 'final.txt' } });
+
+ for (const payload of payloads) {
+ expect(typeof payload.initiatorId).toBe('number');
+ expect(payload.timestamp).toBeTruthy();
+ const raw = JSON.stringify(payload);
+ expect(raw).not.toContain('/module/files/content/');
+ expect(raw).not.toContain('storageKey');
+ }
+ });
+});
diff --git a/api/src/tv-modules/webhooks/types.ts b/api/src/tv-modules/webhooks/types.ts
index 262de90..eee796e 100644
--- a/api/src/tv-modules/webhooks/types.ts
+++ b/api/src/tv-modules/webhooks/types.ts
@@ -1,4 +1,6 @@
import { type } from 'arktype';
+import { OUTBOUND_URL_ERROR_CODES } from '../../utils/outbound-url.types';
+import { FILE_EVENTS } from '../files/types';
const NumberFromString = type('string|number').pipe((v) => Number(v));
@@ -51,6 +53,7 @@ export const WEBHOOK_EVENTS = [
'task.created',
'task.updated',
'task.deleted',
+ 'task.moved',
'task.assigneesChanged',
'time-entry.started',
'time-entry.stopped',
@@ -66,11 +69,12 @@ export const WEBHOOK_EVENTS = [
'sprint.resumed',
'sprint.deleted',
'task.assignedToSprint',
+ ...FILE_EVENTS,
] as const;
export type WebhookEvent = typeof WEBHOOK_EVENTS[number];
-export const WEBHOOK_URL_ERROR_CODES = ['invalid', 'scheme', 'private', 'unresolvable'] as const;
+export const WEBHOOK_URL_ERROR_CODES = OUTBOUND_URL_ERROR_CODES;
export type WebhookUrlErrorCode = typeof WEBHOOK_URL_ERROR_CODES[number];
diff --git a/api/src/tv-modules/webhooks/webhooks.utils.ts b/api/src/tv-modules/webhooks/webhooks.utils.ts
index 2d8a5fa..9750436 100644
--- a/api/src/tv-modules/webhooks/webhooks.utils.ts
+++ b/api/src/tv-modules/webhooks/webhooks.utils.ts
@@ -1,41 +1,8 @@
-import { promises as dns } from 'dns';
-import { BlockList, isIP } from 'net';
+import { OutboundUrlError } from '../../utils/OutboundUrlError';
+import { isPublicAddress, parseOutboundUrl, resolveOutboundUrl } from '../../utils/outbound-url';
import { WebhookUrlError } from './WebhookUrlError';
-const ALLOWED_PROTOCOLS = new Set(['http:', 'https:']);
-
-const BLOCKED_IPV4: Array<[string, number]> = [
- ['0.0.0.0', 8],
- ['10.0.0.0', 8],
- ['100.64.0.0', 10],
- ['127.0.0.0', 8],
- ['169.254.0.0', 16],
- ['172.16.0.0', 12],
- ['192.0.0.0', 24],
- ['192.0.2.0', 24],
- ['192.88.99.0', 24],
- ['192.168.0.0', 16],
- ['198.18.0.0', 15],
- ['198.51.100.0', 24],
- ['203.0.113.0', 24],
- ['224.0.0.0', 4],
- ['240.0.0.0', 4],
-];
-
-const BLOCKED_IPV6: Array<[string, number]> = [
- ['::', 128],
- ['::1', 128],
- ['64:ff9b::', 96],
- ['100::', 64],
- ['2001:db8::', 32],
- ['fc00::', 7],
- ['fe80::', 10],
- ['ff00::', 8],
-];
-
-const blockList = new BlockList();
-for (const [address, prefix] of BLOCKED_IPV4) blockList.addSubnet(address, prefix, 'ipv4');
-for (const [address, prefix] of BLOCKED_IPV6) blockList.addSubnet(address, prefix, 'ipv6');
+export { isPublicAddress };
export function isPrivateWebhookUrlsAllowed(): boolean {
return process.env.WEBHOOKS_ALLOW_PRIVATE_URLS?.trim().toLowerCase() === 'true';
@@ -50,68 +17,23 @@ export function validateWebhooksEnvOnStartup(): void {
}
}
-export function isPublicAddress(address: string): boolean {
- const family = isIP(address);
- if (family === 0) return false;
- return !blockList.check(address, family === 6 ? 'ipv6' : 'ipv4');
-}
-
-function stripBrackets(hostname: string): string {
- return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;
-}
-
-function isLocalHostname(hostname: string): boolean {
- const normalized = hostname.replace(/\.$/, '');
- return normalized === 'localhost' || normalized.endsWith('.localhost');
+// The shared outbound URL guard, reported with the webhook-specific error the API already returns
+function toWebhookError(err: unknown): unknown {
+ return err instanceof OutboundUrlError ? new WebhookUrlError(err.code, `Webhook URL ${err.message}`) : err;
}
export function parseWebhookUrl(url: string): URL {
- let parsed: URL;
try {
- parsed = new URL(url);
- } catch {
- throw new WebhookUrlError('invalid', 'Webhook URL is not a valid URL');
- }
-
- if (!ALLOWED_PROTOCOLS.has(parsed.protocol)) {
- throw new WebhookUrlError('scheme', 'Webhook URL must use http or https');
- }
-
- if (!parsed.hostname) {
- throw new WebhookUrlError('invalid', 'Webhook URL must include a host');
+ return parseOutboundUrl({ url, allowPrivate: isPrivateWebhookUrlsAllowed() });
+ } catch (err) {
+ throw toWebhookError(err);
}
-
- if (isPrivateWebhookUrlsAllowed()) return parsed;
-
- const host = stripBrackets(parsed.hostname);
- if (isLocalHostname(host) || (isIP(host) !== 0 && !isPublicAddress(host))) {
- throw new WebhookUrlError('private', 'Webhook URL must point to a public address');
- }
-
- return parsed;
}
export async function resolveWebhookUrl(url: string): Promise<URL> {
- const parsed = parseWebhookUrl(url);
- if (isPrivateWebhookUrlsAllowed()) return parsed;
-
- const host = stripBrackets(parsed.hostname);
- if (isIP(host) !== 0) return parsed;
-
- let addresses: Array<{ address: string }>;
try {
- addresses = await dns.lookup(host, { all: true });
- } catch {
- throw new WebhookUrlError('unresolvable', 'Webhook URL host could not be resolved');
+ return await resolveOutboundUrl({ url, allowPrivate: isPrivateWebhookUrlsAllowed() });
+ } catch (err) {
+ throw toWebhookError(err);
}
-
- if (addresses.length === 0) {
- throw new WebhookUrlError('unresolvable', 'Webhook URL host could not be resolved');
- }
-
- if (addresses.some(({ address }) => !isPublicAddress(address))) {
- throw new WebhookUrlError('private', 'Webhook URL must point to a public address');
- }
-
- return parsed;
}
diff --git a/api/src/types/tasks.types.ts b/api/src/types/tasks.types.ts
index e34c27f..90214d5 100644
--- a/api/src/types/tasks.types.ts
+++ b/api/src/types/tasks.types.ts
@@ -27,6 +27,8 @@ export type TaskItemInDb = {
transaction_type: 1 | 0 | null;
node_graph_position: Record<string, unknown> | null;
recurrence_rule_id: number | null;
+ recurrence_instance_date: string | null;
+ sprint_id: number | null;
// history_id?: number | null;
};
diff --git a/api/src/utils/OutboundUrlError.ts b/api/src/utils/OutboundUrlError.ts
new file mode 100644
index 0000000..57f6c0b
--- /dev/null
+++ b/api/src/utils/OutboundUrlError.ts
@@ -0,0 +1,11 @@
+import type { OutboundUrlErrorCode } from './outbound-url.types';
+
+export class OutboundUrlError extends Error {
+ readonly code: OutboundUrlErrorCode;
+
+ constructor(code: OutboundUrlErrorCode, message: string) {
+ super(message);
+ this.name = 'OutboundUrlError';
+ this.code = code;
+ }
+}
diff --git a/api/src/utils/outbound-url.ts b/api/src/utils/outbound-url.ts
new file mode 100644
index 0000000..f82080f
--- /dev/null
+++ b/api/src/utils/outbound-url.ts
@@ -0,0 +1,110 @@
+import { promises as dns } from 'dns';
+import { BlockList, isIP } from 'net';
+import { OutboundUrlError } from './OutboundUrlError';
+import type { OutboundUrlArgs } from './outbound-url.types';
+
+// Guards every URL the server fetches on a user's behalf (webhooks, SSO metadata, SSO domain proof) against SSRF:
+// loopback, private, link-local, cloud-metadata and other non-public ranges are refused, both as literal addresses
+// and after DNS resolution. Callers also disable redirects so a public host cannot bounce the request inward.
+const ALLOWED_PROTOCOLS = new Set(['http:', 'https:']);
+
+const BLOCKED_IPV4: Array<[string, number]> = [
+ ['0.0.0.0', 8],
+ ['10.0.0.0', 8],
+ ['100.64.0.0', 10],
+ ['127.0.0.0', 8],
+ ['169.254.0.0', 16],
+ ['172.16.0.0', 12],
+ ['192.0.0.0', 24],
+ ['192.0.2.0', 24],
+ ['192.88.99.0', 24],
+ ['192.168.0.0', 16],
+ ['198.18.0.0', 15],
+ ['198.51.100.0', 24],
+ ['203.0.113.0', 24],
+ ['224.0.0.0', 4],
+ ['240.0.0.0', 4],
+];
+
+const BLOCKED_IPV6: Array<[string, number]> = [
+ ['::', 128],
+ ['::1', 128],
+ ['64:ff9b::', 96],
+ ['100::', 64],
+ ['2001:db8::', 32],
+ ['fc00::', 7],
+ ['fe80::', 10],
+ ['ff00::', 8],
+];
+
+const blockList = new BlockList();
+for (const [address, prefix] of BLOCKED_IPV4) blockList.addSubnet(address, prefix, 'ipv4');
+for (const [address, prefix] of BLOCKED_IPV6) blockList.addSubnet(address, prefix, 'ipv6');
+
+export function isPublicAddress(address: string): boolean {
+ const family = isIP(address);
+ if (family === 0) return false;
+ return !blockList.check(address, family === 6 ? 'ipv6' : 'ipv4');
+}
+
+function stripBrackets(hostname: string): string {
+ return hostname.startsWith('[') && hostname.endsWith(']') ? hostname.slice(1, -1) : hostname;
+}
+
+function isLocalHostname(hostname: string): boolean {
+ const normalized = hostname.replace(/\.$/, '');
+ return normalized === 'localhost' || normalized.endsWith('.localhost');
+}
+
+// Checks the URL as written: scheme, host, and literal addresses / localhost names
+export function parseOutboundUrl(args: OutboundUrlArgs): URL {
+ let parsed: URL;
+ try {
+ parsed = new URL(args.url);
+ } catch {
+ throw new OutboundUrlError('invalid', 'is not a valid URL');
+ }
+
+ if (!ALLOWED_PROTOCOLS.has(parsed.protocol)) {
+ throw new OutboundUrlError('scheme', 'must use http or https');
+ }
+
+ if (!parsed.hostname) {
+ throw new OutboundUrlError('invalid', 'must include a host');
+ }
+
+ if (args.allowPrivate) return parsed;
+
+ const host = stripBrackets(parsed.hostname);
+ if (isLocalHostname(host) || (isIP(host) !== 0 && !isPublicAddress(host))) {
+ throw new OutboundUrlError('private', 'must point to a public address');
+ }
+
+ return parsed;
+}
+
+// parseOutboundUrl plus DNS: a public-looking name that resolves to a private address is refused too
+export async function resolveOutboundUrl(args: OutboundUrlArgs): Promise<URL> {
+ const parsed = parseOutboundUrl(args);
+ if (args.allowPrivate) return parsed;
+
+ const host = stripBrackets(parsed.hostname);
+ if (isIP(host) !== 0) return parsed;
+
+ let addresses: Array<{ address: string }>;
+ try {
+ addresses = await dns.lookup(host, { all: true });
+ } catch {
+ throw new OutboundUrlError('unresolvable', 'host could not be resolved');
+ }
+
+ if (addresses.length === 0) {
+ throw new OutboundUrlError('unresolvable', 'host could not be resolved');
+ }
+
+ if (addresses.some(({ address }) => !isPublicAddress(address))) {
+ throw new OutboundUrlError('private', 'must point to a public address');
+ }
+
+ return parsed;
+}
diff --git a/api/src/utils/outbound-url.types.ts b/api/src/utils/outbound-url.types.ts
new file mode 100644
index 0000000..96e2bdf
--- /dev/null
+++ b/api/src/utils/outbound-url.types.ts
@@ -0,0 +1,8 @@
+export const OUTBOUND_URL_ERROR_CODES = ['invalid', 'scheme', 'private', 'unresolvable'] as const;
+export type OutboundUrlErrorCode = (typeof OUTBOUND_URL_ERROR_CODES)[number];
+
+export type OutboundUrlArgs = {
+ url: string;
+ // Self-hosted opt-out per feature (WEBHOOKS_ALLOW_PRIVATE_URLS, SSO_ALLOW_PRIVATE_URLS)
+ allowPrivate: boolean;
+};
diff --git a/docs/2.features/2.tasks.md b/docs/2.features/2.tasks.md
index a03835f..36b49f0 100644
--- a/docs/2.features/2.tasks.md
+++ b/docs/2.features/2.tasks.md
@@ -59,6 +59,33 @@ TaskView keeps a history of changes for every task. If something was accidentall
Open a task, go to the history section, and you'll see a log of what changed and when. Click **Restore** on any previous version to bring it back.
+A version saved before the task was moved to another project restores the task's content only: the task stays in its current project, list, kanban column and sprint.
+
+## Moving tasks to another project
+
+Open a task and click **Move** in the detail panel, then pick a project. Only projects of the same organization where you can add tasks are listed. Subtasks cannot be moved on their own: they move together with their parent task.
+
+Before you confirm, TaskView shows exactly what will happen:
+
+- **Moved:** the task with its whole subtask tree, its content (description, note, priority, dates, amount, estimate), its history and its logged time.
+- **Removed:** tags, assignees, links to attached files (the files themselves stay in the old project), dependencies with tasks that stay behind, sprint results, links to Git issues and repeat rules. Dependencies between the moved tasks are kept.
+
+::callout{icon="i-lucide-triangle-alert" color="warning"}
+Dependencies between the moved task and tasks that stay in the old project are deleted for good: dependencies cannot connect tasks of different projects. Check the tasks that stay. If the task sat in a chain such as A → moved task → B, the chain breaks, and B no longer waits for anything through it. TaskView does not connect A and B for you.
+::
+- **Reset:** the list, kanban column, sprint and graph position. The task lands in **All tasks** and the Backlog of the new project.
+
+What moves also depends on your permissions in the target project:
+
+- Without the permission to add subtasks, the subtasks stay in the old project as separate tasks.
+- Logged time moves only if you may log time there: your own entries with the log permission, everyone's with the permission to manage all time. Entries that do not move stay in the old project's reports.
+
+Moving a task needs the permission to delete tasks in the old project. For the old project a move is a removal: whoever may delete the task may also move it, and the move takes away its tags, assignees and the other links listed above without separate permissions for each of them.
+
+If you cannot delete tasks in the old project, the task is **copied** instead: the original stays where it is, and a new task with the same content and subtasks is created in the target project. Logged time is not copied, so no hours are counted twice.
+
+The move happens in a single transaction: either everything above is applied, or nothing is.
+
## Deleting tasks
Delete a task from the context menu or the detail panel. Deleted tasks go through the history system, so you **can not** recover them.
diff --git a/docs/2.features/7.webhooks.md b/docs/2.features/7.webhooks.md
index 18be245..c560864 100644
--- a/docs/2.features/7.webhooks.md
+++ b/docs/2.features/7.webhooks.md
@@ -14,6 +14,7 @@ Webhooks let you receive HTTP POST requests when events happen in your projects.
| `task.created` | A new task is created in the project |
| `task.updated` | A task is updated (description, status, priority, deadline, etc.) |
| `task.deleted` | A task is deleted |
+| `task.moved` | A task is moved to another project. Sent to the webhooks of both projects |
| `task.assigneesChanged` | Task assignees are added or removed |
| `time-entry.started` | A timer is started on a task |
| `time-entry.stopped` | A running timer is stopped |
@@ -29,6 +30,11 @@ Webhooks let you receive HTTP POST requests when events happen in your projects.
| `sprint.resumed` | A paused sprint is resumed |
| `sprint.deleted` | A sprint is deleted (any status, including completed) |
| `task.assignedToSprint` | A task is added to, moved between, or removed from a sprint |
+| `file.uploaded` | A file is uploaded to the project or straight into a task |
+| `file.renamed` | A file is renamed |
+| `file.deleted` | A file is deleted forever |
+| `file.attached` | An existing project file is attached to a task |
+| `file.detached` | A file is removed from a task (the file itself stays in the project) |
## Setup
@@ -98,6 +104,34 @@ Sprint events carry the sprint payload. Lifecycle events (`sprint.activated`, `s
`task.assignedToSprint` carries `taskId`, `sprintId` (the new sprint, or `null` when removed), `prevSprintId`, `goalId`, and `initiatorId`. `sprint.deleted` carries `sprintId`, `goalId`, and `initiatorId` only, since the sprint no longer exists. `initiatorId` may be `null` for sprints generated automatically by a cadence.
+`task.moved` carries `task` (the task after the move), `taskIds` (the moved task and its subtasks), `fromGoalId`, `toGoalId` and `initiatorId`. When the user may not delete tasks in the source project, the task is copied instead and the target project receives `task.created` for every copied task.
+
+File events share one payload shape:
+
+```json
+{
+ "event": "file.attached",
+ "timestamp": "2026-10-05T12:00:00.000Z",
+ "goalId": 1,
+ "taskIds": [42],
+ "initiatorId": 7,
+ "file": {
+ "id": "6f1c2a8e-3b1d-4c9e-9a0b-2d5e7f8a1b3c",
+ "goalId": 1,
+ "name": "report.pdf",
+ "originalName": "report.pdf",
+ "mimeType": "application/pdf",
+ "sizeBytes": 248512,
+ "uploaderId": 7,
+ "uploaderEmail": "[email protected]",
+ "createdAt": "2026-10-05T11:58:00.000Z",
+ "linkedTaskIds": [17, 42]
+ }
+}
+```
+
+`taskIds` lists the tasks the event concerns: every task the file is attached to for `file.uploaded`, `file.renamed` and `file.deleted`, the single task for `file.attached` and `file.detached`. `file.linkedTaskIds` is the state after the change; for `file.deleted` it is the state just before deletion. Payloads carry metadata only - no download link, so the file content never leaves TaskView through a webhook. Fetch the content through the API with a token that has the `file_can_view` permission.
+
## Signature verification
Every request includes an `X-Webhook-Signature` header with an HMAC-SHA256 signature of the request body:
diff --git a/docs/4.configuration/1.environment-variables.md b/docs/4.configuration/1.environment-variables.md
index 9f69801..c461800 100644
--- a/docs/4.configuration/1.environment-variables.md
+++ b/docs/4.configuration/1.environment-variables.md
@@ -30,6 +30,7 @@ These must match your PostgreSQL setup.
| `PM2_INSTANCES` | No | `2` | Number of API worker processes (PM2 cluster mode). Accepts a number or `max` (one worker per CPU core). When using `max`, set `DB_POOL_MAX` yourself so the connection budget above still fits. |
| `APP_URL` | Yes | https://app.taskview.tech | Full URL of the web app (e.g. `https://tasks.company.com`). Used for OAuth redirects and email links. |
| `API_PUBLIC_URL` | No | - | Public URL of the **API server** as external systems see it (e.g. `https://api.company.com`). Used to build the SSO callback/ACS URL and the SCIM endpoint shown in organization settings. Set it when the API runs behind a reverse proxy — otherwise those URLs are derived from the browser's address and may show an internal host that your IdP cannot reach. The server refuses to start if the value is not a valid http(s) URL. |
+| `LOG_LEVEL` | No | `info` in production, `debug` otherwise | Minimum level written to the log files in `logs/`: `fatal`, `error`, `warn`, `info`, `debug`, `trace` or `silent`. An unknown value falls back to the default and is reported at startup. |
| `TRUST_PROXY` | No | `false` | Set when running behind a reverse proxy so `X-Forwarded-Proto`/`X-Forwarded-For` are honoured (correct `https` URLs, real client IP). Use the number of proxies in front of the app (`1` for a single Caddy/nginx), or an IP/subnet list (`10.0.0.0/8`, `uniquelocal`). Leave unset for direct access. Avoid `true` (trusts any hop, allows header spoofing). |
## Web app
@@ -53,6 +54,7 @@ Unlike everything else on this page, this variable is set on the **web app conta
| `ALLOW_PUBLIC_REGISTRATION` | No | `true` | Set to `false` to close the instance: strangers can no longer create accounts — the registration endpoint returns 403, and magic-link / social sign-in stop auto-creating users. Emails invited to an organization or project can still sign in and get their account created on first login. |
| `OAUTH_DYNAMIC_REGISTRATION` | No | `false` | Whether AI clients may register themselves as OAuth clients (RFC 7591) when connecting to the [MCP server](/docs/integrations/mcp#oauth-cloud-clients). Off by default: the registration endpoint returns 403 and cloud clients such as ChatGPT or Claude cannot start an OAuth connection. Set to `true` to let them connect. Turning it back off later does not affect apps that are already connected. |
| `SSO_TRUSTED_DOMAINS` | No | empty | Comma-separated email domains that skip DNS/HTTP ownership checks for SSO (air-gapped / closed-network installs). Example: `company.com,corp.local`. On a public instance leave this unset so every org must prove it owns the domain. |
+| `SSO_ALLOW_PRIVATE_URLS` | No | `false` | The server fetches SAML IdP metadata (the **Sync** button) and the SSO domain-ownership file. Those URLs may only point to public addresses: loopback, private, link-local and cloud-metadata ranges are refused, also when a public-looking host name resolves to them, and redirects are not followed. Set to `true` on a self-hosted install whose identity provider (Keycloak, Authentik) lives on the same private network. The value must be `true` or `false`; anything else stops the server at startup. |
| `WEBHOOKS_ALLOW_PRIVATE_URLS` | No | `false` | Outgoing [webhooks](/docs/features/webhooks) may only target public addresses: loopback, private (`10/8`, `172.16/12`, `192.168/16`), link-local and cloud-metadata ranges are refused when a webhook is saved and again on every delivery, and redirects are never followed. Set to `true` on a self-hosted install whose receivers (n8n, CI, internal bots) live on the same private network. Never enable this on a public multi-tenant instance. The value must be `true` or `false`; anything else stops the server at startup. |
::callout{icon="i-lucide-shield" color="warning"}
@@ -254,7 +256,7 @@ Attachments are **off until a provider is configured**: `FILE_STORAGE_PROVIDER`
| Variable | Required | Default | Description |
|---|---|---|---|
| `FILE_STORAGE_PROVIDER` | To enable files | - | Provider that receives new uploads: `local` or `s3`. Its settings must be present, otherwise attachments stay disabled. |
-| `FILE_MAX_SIZE_MB` | No | `50` | Maximum size of one uploaded file in megabytes. |
+| `FILE_MAX_SIZE_MB` | No | `10` | Maximum size of one uploaded file in megabytes. |
| `FILE_STORAGE_LOCAL_DIR` | For `local` | - | Directory for the `local` provider. In Docker mount it as a volume, e.g. `/taskview/files:/usr/src/app/data/files`. |
| `FILE_STORAGE_S3_BUCKET` | For `s3` | - | Bucket name. |
| `FILE_STORAGE_S3_REGION` | For `s3` | - | Region, e.g. `us-east-1`. Any value works for MinIO. |
@@ -263,6 +265,23 @@ Attachments are **off until a provider is configured**: `FILE_STORAGE_PROVIDER`
| `FILE_STORAGE_S3_SECRET_KEY` | For `s3` | - | Secret access key. |
| `FILE_STORAGE_S3_FORCE_PATH_STYLE` | No | `false` | Set to `true` for MinIO and most self-hosted S3-compatible servers. |
+### Storage quotas
+
+Quotas limit how much each organization can store. They are on by default: every organization gets 100 MB unless configured otherwise.
+
+| Variable | Required | Default | Description |
+|---|---|---|---|
+| `FILE_QUOTA_MODE` | No | `enforce` | `enforce` - uploads over the quota are rejected with `507`. `off` - no quotas. An unknown value means `off` and is reported at startup. |
+| `FILE_QUOTA_ORGANIZATION_MB` | No | `100` | Default quota of every organization, in megabytes. |
+
+Each organization, personal ones included, has its own quota: `FILE_QUOTA_ORGANIZATION_MB` by default, or the value of `tv_auth.organizations.file_quota_mb` (in megabytes) when it is set. The API never changes this column; set it from billing or by hand:
+
+```sql
+UPDATE tv_auth.organizations SET file_quota_mb = 20480 WHERE id = <organization id>;
+```
+
+Usage is a live sum of the files in the organization's projects, so deleting a file frees its space at once. Lowering a quota below current usage only blocks new uploads; nothing is deleted. The quota is never exceeded, parallel uploads included: an upload is cut as soon as it passes the remaining space, and each file is recorded under a lock on its organization after a final check.
+
### Encryption at rest
TaskView does not encrypt file contents itself: the API writes the bytes it received and the database keeps only metadata. Encrypt at the storage layer instead; the API does not need to know about it.
@@ -370,5 +389,5 @@ TELEGRAM_WEBHOOK_SECRET=
# Files (attachments stay disabled until a provider is configured; mount the directory as a volume)
FILE_STORAGE_PROVIDER=local
FILE_STORAGE_LOCAL_DIR=/usr/src/app/data/files
-# FILE_MAX_SIZE_MB=50
+# FILE_MAX_SIZE_MB=10
```
diff --git a/taskview-packages/taskview-api/src/api/files.ts b/taskview-packages/taskview-api/src/api/files.ts
index ff45dd3..46cad2c 100644
--- a/taskview-packages/taskview-api/src/api/files.ts
+++ b/taskview-packages/taskview-api/src/api/files.ts
@@ -7,6 +7,7 @@ import type {
TvFileLinkArgs,
TvFileListArgs,
TvFileListPage,
+ TvFileQuota,
TvFileRenameArgs,
TvFileStorageStatus,
TvFileUnlinkArgs,
@@ -16,6 +17,10 @@ import type {
export default class TvFilesApi extends TvApiBase {
protected moduleUrl = '/module/files';
+ public async quota(goalId: number) {
+ return this.request(this.$axios.get<AppResponse<TvFileQuota>>(`${this.moduleUrl}/goal/${goalId}/quota`));
+ }
+
public async status() {
return this.request(this.$axios.get<AppResponse<TvFileStorageStatus>>(`${this.moduleUrl}/status`));
}
diff --git a/taskview-packages/taskview-api/src/api/files.types.ts b/taskview-packages/taskview-api/src/api/files.types.ts
index f6710b6..29a0d64 100644
--- a/taskview-packages/taskview-api/src/api/files.types.ts
+++ b/taskview-packages/taskview-api/src/api/files.types.ts
@@ -23,6 +23,14 @@ export type TvFileDownloadUrl = {
expiresAt: string;
};
+export type TvFileQuotaMode = 'off' | 'enforce';
+
+export type TvFileQuota = {
+ mode: TvFileQuotaMode;
+ quotaBytes: number | null;
+ usedBytes: number | null;
+};
+
export type TvFileStorageStatus = {
enabled: boolean;
maxFileSizeBytes: number;
diff --git a/taskview-packages/taskview-api/src/api/sso.ts b/taskview-packages/taskview-api/src/api/sso.ts
index da4b767..2a09d51 100644
--- a/taskview-packages/taskview-api/src/api/sso.ts
+++ b/taskview-packages/taskview-api/src/api/sso.ts
@@ -1,6 +1,8 @@
import TvApiBase from './base'
import type { AppResponse } from './base.types'
import type {
+ SsoArgParseMetadata,
+ SsoParsedMetadata,
SsoConfig,
SsoConfigArgCreate,
SsoConfigArgUpdate,
@@ -45,10 +47,10 @@ export default class TvSsoApi extends TvApiBase {
)
}
- public async parseMetadata(url: string) {
+ public async parseMetadata(args: SsoArgParseMetadata) {
return this.request(
- this.$axios.get<AppResponse<{ samlEntryPoint: string, samlCert: string, samlLogoutUrl: string }>>(`${this.moduleUrl}/admin/metadata`, {
- params: { url },
+ this.$axios.get<AppResponse<SsoParsedMetadata>>(`${this.moduleUrl}/admin/metadata`, {
+ params: { url: args.url, organizationId: args.organizationId },
})
)
}
diff --git a/taskview-packages/taskview-api/src/api/sso.types.ts b/taskview-packages/taskview-api/src/api/sso.types.ts
index 8848e3e..fd01a8d 100644
--- a/taskview-packages/taskview-api/src/api/sso.types.ts
+++ b/taskview-packages/taskview-api/src/api/sso.types.ts
@@ -107,3 +107,15 @@ export type SsoPublicUrls = {
scimEndpointUrl: string
apiPublicUrlConfigured: boolean
}
+
+// The organization is required: the endpoint is restricted to its admins
+export type SsoArgParseMetadata = {
+ url: string
+ organizationId: number
+}
+
+export type SsoParsedMetadata = {
+ samlEntryPoint: string
+ samlCert: string
+ samlLogoutUrl: string
+}
diff --git a/taskview-packages/taskview-api/src/api/tasks.api.types.ts b/taskview-packages/taskview-api/src/api/tasks.api.types.ts
index db6864a..891c336 100644
--- a/taskview-packages/taskview-api/src/api/tasks.api.types.ts
+++ b/taskview-packages/taskview-api/src/api/tasks.api.types.ts
@@ -106,4 +106,46 @@ export type TaskResponseToggleAssignee = {
export type TaskResponseFetchTaskHistory = { history: Task[] };
-export type TaskResponseRecoveryTaskHistory = { recovery: boolean };
\ No newline at end of file
+export type TaskResponseRecoveryTaskHistory = { recovery: boolean };
+
+export type TaskArgMoveToProject = {
+ taskId: number;
+ targetGoalId: number;
+};
+
+// 'move' keeps the task id and removes it from the source project; 'copy' happens when the user may not delete
+// tasks in the source project: the original stays and a new task is created in the target project
+export type TaskMoveMode = 'move' | 'copy';
+
+export type TaskMoveBlockReason = 'not_found' | 'same_project' | 'other_organization' | 'is_subtask' | 'no_target_permission';
+
+export type TaskMoveRemovals = {
+ tags: number;
+ assignees: number;
+ fileLinks: number;
+ dependencies: number;
+ sprintOutcomes: number;
+ integrationLinks: number;
+ recurrence: number;
+};
+
+export type TaskMoveLeftBehind = {
+ subtasks: number;
+ timeEntries: number;
+};
+
+export type TaskResponseMovePreview = {
+ allowed: boolean;
+ reason: TaskMoveBlockReason | null;
+ mode: TaskMoveMode | null;
+ tasks: number;
+ timeEntries: number;
+ removals: TaskMoveRemovals | null;
+ leftBehind: TaskMoveLeftBehind | null;
+};
+
+export type TaskResponseMoveToProject = {
+ mode: TaskMoveMode;
+ taskId: number;
+ goalId: number;
+};
diff --git a/taskview-packages/taskview-api/src/api/tasks.ts b/taskview-packages/taskview-api/src/api/tasks.ts
index 931e0bf..e3f19ed 100644
--- a/taskview-packages/taskview-api/src/api/tasks.ts
+++ b/taskview-packages/taskview-api/src/api/tasks.ts
@@ -1,6 +1,6 @@
import TvApiBase from "./base"
import type { AppResponse } from "./base.types";
-import { type TaskArgAdd, type TaskResponseAdd, type TaskArgDelete, type TaskResponseDelete, type TaskArgUpdate, type TaskResponseUpdate, type TaskResponseFetchById, type TaskArgFetch, type TaskResponseFetch, type TaskArgToggleAssignee, type TaskResponseToggleAssignee, type TaskResponseFetchTaskHistory, type TaskResponseRecoveryTaskHistory } from "./tasks.api.types"
+import { type TaskArgAdd, type TaskResponseAdd, type TaskArgDelete, type TaskResponseDelete, type TaskArgUpdate, type TaskResponseUpdate, type TaskResponseFetchById, type TaskArgFetch, type TaskResponseFetch, type TaskArgToggleAssignee, type TaskResponseToggleAssignee, type TaskResponseFetchTaskHistory, type TaskResponseRecoveryTaskHistory, type TaskArgMoveToProject, type TaskResponseMovePreview, type TaskResponseMoveToProject } from "./tasks.api.types"
export default class TvTaskApi extends TvApiBase {
protected moduleUrl = '/module/tasks';
@@ -71,4 +71,18 @@ export default class TvTaskApi extends TvApiBase {
)
);
}
-}
\ No newline at end of file
+
+ public async movePreview(args: TaskArgMoveToProject) {
+ return this.request(
+ this.$axios.get<AppResponse<TaskResponseMovePreview>>(
+ `${this.moduleUrl}/${args.taskId}/move-preview`, { params: { targetGoalId: args.targetGoalId } }
+ )
+ );
+ }
+
+ public async moveToProject(args: TaskArgMoveToProject) {
+ return this.request(
+ this.$axios.post<AppResponse<TaskResponseMoveToProject>>(`${this.moduleUrl}/move`, args)
+ );
+ }
+}
diff --git a/taskview-packages/taskview-api/src/api/webhooks.types.ts b/taskview-packages/taskview-api/src/api/webhooks.types.ts
index 34f9e60..71ad49f 100644
--- a/taskview-packages/taskview-api/src/api/webhooks.types.ts
+++ b/taskview-packages/taskview-api/src/api/webhooks.types.ts
@@ -46,6 +46,7 @@ export const WEBHOOK_EVENTS = [
'task.created',
'task.updated',
'task.deleted',
+ 'task.moved',
'task.assigneesChanged',
'time-entry.started',
'time-entry.stopped',
@@ -61,6 +62,11 @@ export const WEBHOOK_EVENTS = [
'sprint.resumed',
'sprint.deleted',
'task.assignedToSprint',
+ 'file.uploaded',
+ 'file.renamed',
+ 'file.deleted',
+ 'file.attached',
+ 'file.detached',
] as const;
export type WebhookEvent = typeof WEBHOOK_EVENTS[number];
diff --git a/taskview-packages/taskview-db-schemas/src/schemas/organizations.schema.ts b/taskview-packages/taskview-db-schemas/src/schemas/organizations.schema.ts
index 54e7f30..73c1d47 100644
--- a/taskview-packages/taskview-db-schemas/src/schemas/organizations.schema.ts
+++ b/taskview-packages/taskview-db-schemas/src/schemas/organizations.schema.ts
@@ -10,6 +10,7 @@ export const OrganizationsSchema = pgSchema('tv_auth').table('organizations', {
isPersonal: integer('is_personal').notNull().default(0),
plan: varchar().notNull().default('free'),
timeTrackingAutostopHours: integer('time_tracking_autostop_hours').default(24),
+ fileQuotaMb: integer('file_quota_mb'),
createdAt: timestamp('created_at').defaultNow(),
updatedAt: timestamp('updated_at').defaultNow(),
})
diff --git a/taskview-packages/taskview-mcp/src/tools/tasks.ts b/taskview-packages/taskview-mcp/src/tools/tasks.ts
index a029634..7aafa16 100644
--- a/taskview-packages/taskview-mcp/src/tools/tasks.ts
+++ b/taskview-packages/taskview-mcp/src/tools/tasks.ts
@@ -97,7 +97,7 @@ export function registerTasksTools(server: McpServer, api: TvApi) {
note: z.string().optional().describe('Task note, separate from the description (the title). Stored and rendered as HTML: wrap paragraphs in <p>, lists in <ul>/<ol>; plain newlines collapse. Replaces the whole note - read the current one with get_task first when appending'),
priorityId: z.union([z.literal(1), z.literal(2), z.literal(3)]).optional()
.describe('Priority: 1=low, 2=medium, 3=high'),
- goalListId: z.coerce.number().optional().nullable().describe('Move to a different list'),
+ goalListId: z.coerce.number().optional().nullable().describe('Move to a different list of the same project. Lists of other projects are rejected; moving a task between projects is done in the app'),
startDate: z.string().optional().nullable().describe('Start date (ISO format)'),
endDate: z.string().optional().nullable().describe('End/due date (ISO format)'),
statusId: z.coerce.number().optional().nullable().describe('Kanban column status ID'),
diff --git a/web/src/components/features/files/FilesProjectTab.vue b/web/src/components/features/files/FilesProjectTab.vue
index a0b4f12..556dee3 100644
--- a/web/src/components/features/files/FilesProjectTab.vue
+++ b/web/src/components/features/files/FilesProjectTab.vue
@@ -40,6 +40,10 @@
</div>
<div class="flex flex-col gap-4 px-2">
+ <FilesQuotaUsage
+ v-if="storageEnabled"
+ :goal-id="goalId"
+ />
<UAlert
v-if="!storageEnabled"
color="warning"
@@ -142,6 +146,7 @@ import FileProjectRow from './parts/FileProjectRow.vue'
import FileRenameDialog from './parts/FileRenameDialog.vue'
import FileDeleteDialog from './parts/FileDeleteDialog.vue'
import FileTaskPickerDialog from './parts/FileTaskPickerDialog.vue'
+import FilesQuotaUsage from './parts/FilesQuotaUsage.vue'
const props = defineProps<{
goalId: number
@@ -178,7 +183,14 @@ const actions = useFileActions({ files, taskId: noTask })
const reload = () => filesStore.fetchForGoal({ goalId: props.goalId, search: search.value, type: type.value })
const debouncedReload = useDebounceFn(reload, 300)
-watch(() => props.goalId, () => void reload(), { immediate: true })
+watch(
+ () => props.goalId,
+ (id) => {
+ void reload()
+ void filesStore.fetchQuota(id)
+ },
+ { immediate: true },
+)
watch(search, () => void debouncedReload())
watch(type, () => void reload())
diff --git a/web/src/components/features/files/parts/FilesQuotaUsage.vue b/web/src/components/features/files/parts/FilesQuotaUsage.vue
new file mode 100644
index 0000000..d36a776
--- /dev/null
+++ b/web/src/components/features/files/parts/FilesQuotaUsage.vue
@@ -0,0 +1,39 @@
+<template>
+ <div
+ v-if="usage"
+ class="flex flex-col gap-1.5"
+ data-testid="files-quota-usage"
+ >
+ <div class="flex items-center justify-between text-xs text-muted">
+ <span>{{ t('files.quota.usage', { used: formatBytes(usage.used), total: formatBytes(usage.total) }) }}</span>
+ <span>{{ usage.percent }}%</span>
+ </div>
+ <UProgress
+ :model-value="usage.percent"
+ size="xs"
+ :color="usage.percent >= 90 ? 'error' : usage.percent >= 75 ? 'warning' : 'primary'"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from 'vue'
+import { useI18n } from 'vue-i18n'
+import { useFilesStore } from '@/stores/files.store'
+import { useFileKind } from '@/composables/useFileKind'
+
+const props = defineProps<{
+ goalId: number
+}>()
+
+const { t } = useI18n()
+const { formatBytes } = useFileKind()
+const filesStore = useFilesStore()
+
+const usage = computed(() => {
+ const quota = filesStore.quotaByGoal[props.goalId]
+ if (!quota || quota.mode !== 'enforce' || quota.quotaBytes === null || quota.usedBytes === null) return null
+ const percent = quota.quotaBytes > 0 ? Math.min(100, Math.round((quota.usedBytes / quota.quotaBytes) * 100)) : 100
+ return { used: quota.usedBytes, total: quota.quotaBytes, percent }
+})
+</script>
diff --git a/web/src/components/features/main/screen-main/DashboardList/parts/DashboardAddTask.vue b/web/src/components/features/main/screen-main/DashboardList/parts/DashboardAddTask.vue
index b8b90cc..8505dc0 100644
--- a/web/src/components/features/main/screen-main/DashboardList/parts/DashboardAddTask.vue
+++ b/web/src/components/features/main/screen-main/DashboardList/parts/DashboardAddTask.vue
@@ -16,6 +16,7 @@
size="sm"
:disabled="disabled"
:ui="{ base: 'rounded-full hover:bg-primary/10 hover:text-primary' }"
+ data-testid="dashboard-add-task"
@click.stop
/>
<button
@@ -23,6 +24,7 @@
v-bind="props"
type="button"
:disabled="disabled"
+ data-testid="dashboard-add-task"
class="flex items-center gap-2.5 w-full px-4 py-3 rounded-2xl border border-dashed border-default text-muted hover:text-primary hover:border-primary hover:bg-primary/5 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
>
<span class="flex items-center justify-center size-6 rounded-full border border-dashed border-current shrink-0">
diff --git a/web/src/components/features/main/screen-main/DashboardList/parts/DashboardSection.vue b/web/src/components/features/main/screen-main/DashboardList/parts/DashboardSection.vue
index c9524ab..8953df0 100644
--- a/web/src/components/features/main/screen-main/DashboardList/parts/DashboardSection.vue
+++ b/web/src/components/features/main/screen-main/DashboardList/parts/DashboardSection.vue
@@ -1,5 +1,8 @@
<template>
- <div class="relative">
+ <div
+ class="relative"
+ :data-testid="`dashboard-section-${sectionKey}`"
+ >
<!-- Timeline connecting line under the icon -->
<div class="absolute left-6 top-14 bottom-0 w-px bg-accented hidden sm:block" />
diff --git a/web/src/components/features/main/screen-main/parts/MainScreenAddTaskDialog.vue b/web/src/components/features/main/screen-main/parts/MainScreenAddTaskDialog.vue
index 06021bc..531edd0 100644
--- a/web/src/components/features/main/screen-main/parts/MainScreenAddTaskDialog.vue
+++ b/web/src/components/features/main/screen-main/parts/MainScreenAddTaskDialog.vue
@@ -25,6 +25,7 @@
v-model="taskDescription"
:placeholder="t('tasks.addPlaceholder')"
class="w-full"
+ data-testid="main-add-task-input"
@keyup.enter="addTask"
/>
</UFormField>
@@ -54,6 +55,7 @@
variant="soft"
class="w-full justify-start"
:ui="{leadingIcon: 'size-4.5'}"
+ data-testid="main-add-task-deadline"
/>
<template #content>
<UCalendar
@@ -88,6 +90,7 @@
:disabled="!canAdd"
:loading="loading"
variant="soft"
+ data-testid="main-add-task-submit"
@click="addTask"
>
{{ t('tasks.add') }}
@@ -219,15 +222,7 @@ async function addTask() {
})
if (task) {
- // Add task to appropriate list based on deadline
- if (props.noDates) {
- baseScreenStore.tasks.unshift(task)
- } else if (props.upcomingTask) {
- baseScreenStore.tasksUpcoming.unshift(task)
- } else {
- baseScreenStore.tasksToday.unshift(task)
- }
-
+ baseScreenStore.addCreatedTask(task)
emit('added')
close()
}
diff --git a/web/src/components/features/organizations/parts/OrgSsoConfigForm.vue b/web/src/components/features/organizations/parts/OrgSsoConfigForm.vue
index cc91fc0..e9f229d 100644
--- a/web/src/components/features/organizations/parts/OrgSsoConfigForm.vue
+++ b/web/src/components/features/organizations/parts/OrgSsoConfigForm.vue
@@ -29,6 +29,7 @@
<SsoSamlForm
v-if="form.protocol === 'saml'"
v-model:form="form"
+ :organization-id="organizationId"
:callback-url-placeholder="callbackUrlPlaceholder"
:has-secrets="hasSecrets"
/>
@@ -84,6 +85,7 @@ const form = defineModel<SsoFormData>('form', { required: true })
import type { SsoConfig } from 'taskview-api'
defineProps<{
+ organizationId: number
isEditing: boolean
saving: boolean
callbackUrlPlaceholder: string
diff --git a/web/src/components/features/organizations/parts/OrgSsoSettings.vue b/web/src/components/features/organizations/parts/OrgSsoSettings.vue
index b3f8500..acba179 100644
--- a/web/src/components/features/organizations/parts/OrgSsoSettings.vue
+++ b/web/src/components/features/organizations/parts/OrgSsoSettings.vue
@@ -26,6 +26,7 @@
<template v-if="showForm">
<OrgSsoConfigForm
v-model:form="form"
+ :organization-id="organizationId"
:is-editing="isEditing"
:saving="saving"
:callback-url-placeholder="callbackUrlPlaceholder"
diff --git a/web/src/components/features/organizations/parts/SsoSamlForm.vue b/web/src/components/features/organizations/parts/SsoSamlForm.vue
index 7f7b2d4..0d18086 100644
--- a/web/src/components/features/organizations/parts/SsoSamlForm.vue
+++ b/web/src/components/features/organizations/parts/SsoSamlForm.vue
@@ -153,7 +153,8 @@ const form = defineModel<SamlFormData>('form', { required: true })
import type { SsoConfig } from 'taskview-api'
-defineProps<{
+const props = defineProps<{
+ organizationId: number
callbackUrlPlaceholder: string
hasSecrets?: SsoConfig
}>()
@@ -185,7 +186,7 @@ async function syncMetadata() {
syncing.value = true
try {
- const result = await $tvApi.sso.parseMetadata(metadataUrl.value.trim())
+ const result = await $tvApi.sso.parseMetadata({ url: metadataUrl.value.trim(), organizationId: props.organizationId })
if (result.samlEntryPoint) form.value.samlEntryPoint = result.samlEntryPoint
if (result.samlCert) form.value.samlCert = result.samlCert
if (result.samlLogoutUrl) form.value.samlLogoutUrl = result.samlLogoutUrl
diff --git a/web/src/components/features/tasks/TvTaskDetailOverlay.vue b/web/src/components/features/tasks/TvTaskDetailOverlay.vue
index e9bb1e1..bc9fdb0 100644
--- a/web/src/components/features/tasks/TvTaskDetailOverlay.vue
+++ b/web/src/components/features/tasks/TvTaskDetailOverlay.vue
@@ -25,22 +25,12 @@
<TaskDetailPanel />
</template>
<template #footer>
- <div class="flex justify-between gap-2 w-full">
- <UButton
- :label="t('common.delete')"
- color="error"
- variant="soft"
- data-testid="task-detail-delete-button"
- @click="openDeleteDialog"
- />
- <UButton
- :label="t('common.close')"
- color="neutral"
- variant="soft"
- data-testid="task-detail-close-button"
- @click="closeTask"
- />
- </div>
+ <TaskDetailFooter
+ :can-move="canMove"
+ @delete="openDeleteDialog"
+ @move="isMoveDialogOpen = true"
+ @close="closeTask"
+ />
</template>
</USlideover>
@@ -75,22 +65,12 @@
<TaskDetailPanel />
</template>
<template #footer>
- <div class="flex justify-between gap-2 w-full">
- <UButton
- :label="t('common.delete')"
- color="error"
- variant="soft"
- data-testid="task-detail-delete-button"
- @click="openDeleteDialog"
- />
- <UButton
- :label="t('common.close')"
- color="neutral"
- variant="soft"
- data-testid="task-detail-close-button"
- @click="closeTask"
- />
- </div>
+ <TaskDetailFooter
+ :can-move="canMove"
+ @delete="openDeleteDialog"
+ @move="isMoveDialogOpen = true"
+ @close="closeTask"
+ />
</template>
</UModal>
@@ -100,6 +80,12 @@
:task="task"
@confirm="handleDelete"
/>
+
+ <TaskMoveDialog
+ v-model:open="isMoveDialogOpen"
+ :task="task"
+ @moved="handleMoved"
+ />
</template>
</template>
@@ -109,6 +95,11 @@ import { storeToRefs } from 'pinia'
import { useI18n } from 'vue-i18n'
import TaskDetailPanel from './TaskDetailPanel.vue'
import TaskDeleteDialog from '@/components/features/tasks/parts/TaskDeleteDialog.vue'
+import TaskMoveDialog from '@/components/features/tasks/parts/TaskMoveDialog.vue'
+import TaskDetailFooter from '@/components/features/tasks/parts/TaskDetailFooter.vue'
+import { useRouter } from 'vue-router'
+import { ALL_TASKS_LIST_ID, type TaskResponseMoveToProject } from 'taskview-api'
+import { useOrganizationStore } from '@/stores/organization.store'
import { useTasksStore } from '@/stores/tasks.store'
import { useGoalsStore } from '@/stores/goals.store'
import { useAppStore } from '@/stores/app.store'
@@ -149,6 +140,13 @@ const canViewTaskDetails = computed(() =>
)
const isDeleteDialogOpen = ref(false)
+const isMoveDialogOpen = ref(false)
+const router = useRouter()
+const toast = useToast()
+const organizationStore = useOrganizationStore()
+
+// Subtasks move only together with their parent task
+const canMove = computed(() => !!task.value && !task.value.parentId)
const { taskDetailDisplayMode: displayMode } = storeToRefs(appStore)
function openDeleteDialog() {
@@ -164,4 +162,31 @@ async function handleDelete() {
closeTask()
}
}
+
+function handleMoved(result: TaskResponseMoveToProject) {
+ const project = goalsStore.goalMap.get(result.goalId)?.name ?? ''
+ const open = async () => {
+ await router.push({
+ name: 'user',
+ params: {
+ orgSlug: organizationStore.currentOrgSlug,
+ projectId: String(result.goalId),
+ listId: String(ALL_TASKS_LIST_ID),
+ taskId: String(result.taskId),
+ },
+ })
+ }
+
+ isMoveDialogOpen.value = false
+ if (result.mode === 'move') {
+ tasksStore.removeTaskLocally(result.taskId)
+ broadcastRemoval(result.taskId)
+ closeTask()
+ }
+ toast.add({
+ title: t(result.mode === 'move' ? 'tasks.move.moved' : 'tasks.move.copied', { project }),
+ color: 'success',
+ actions: [{ label: t('tasks.move.open'), onClick: open }],
+ })
+}
</script>
diff --git a/web/src/components/features/tasks/parts/TaskDetailFooter.vue b/web/src/components/features/tasks/parts/TaskDetailFooter.vue
new file mode 100644
index 0000000..b5f0436
--- /dev/null
+++ b/web/src/components/features/tasks/parts/TaskDetailFooter.vue
@@ -0,0 +1,45 @@
+<template>
+ <div class="flex justify-between gap-2 w-full">
+ <div class="flex gap-2">
+ <UButton
+ :label="t('common.delete')"
+ color="error"
+ variant="soft"
+ data-testid="task-detail-delete-button"
+ @click="emit('delete')"
+ />
+ <UButton
+ v-if="canMove"
+ :label="t('tasks.move.button')"
+ icon="i-lucide-folder-input"
+ color="neutral"
+ variant="soft"
+ data-testid="task-detail-move-button"
+ @click="emit('move')"
+ />
+ </div>
+ <UButton
+ :label="t('common.close')"
+ color="neutral"
+ variant="soft"
+ data-testid="task-detail-close-button"
+ @click="emit('close')"
+ />
+ </div>
+</template>
+
+<script setup lang="ts">
+import { useI18n } from 'vue-i18n'
+
+defineProps<{
+ canMove: boolean
+}>()
+
+const emit = defineEmits<{
+ delete: []
+ move: []
+ close: []
+}>()
+
+const { t } = useI18n()
+</script>
diff --git a/web/src/components/features/tasks/parts/TaskFiles.vue b/web/src/components/features/tasks/parts/TaskFiles.vue
index 1ad49c0..36294c9 100644
--- a/web/src/components/features/tasks/parts/TaskFiles.vue
+++ b/web/src/components/features/tasks/parts/TaskFiles.vue
@@ -130,6 +130,13 @@ const { uploads, upload, openDialog, retry, cancel } = useFileUpload({ goalId, t
const { isDragging } = useFileDropZone({ target: dropTarget, enabled: canUpload, onFiles: upload })
const actions = useFileActions({ files, taskId })
void filesStore.fetchStorageStatus()
+watch(
+ () => [props.goalId, canManageFiles.value] as const,
+ ([id, allowed]) => {
+ if (allowed) void filesStore.fetchQuota(id)
+ },
+ { immediate: true },
+)
watch(
() => [props.taskId, canViewFiles.value] as const,
diff --git a/web/src/components/features/tasks/parts/TaskMoveDialog.vue b/web/src/components/features/tasks/parts/TaskMoveDialog.vue
new file mode 100644
index 0000000..ca1ee57
--- /dev/null
+++ b/web/src/components/features/tasks/parts/TaskMoveDialog.vue
@@ -0,0 +1,129 @@
+<template>
+ <UModal
+ v-model:open="isOpen"
+ :title="t('tasks.move.title')"
+ :fullscreen="isFullscreenModal"
+ :ui="{ footer: 'justify-end!' }"
+ >
+ <template #body>
+ <div class="flex flex-col gap-4">
+ <UFormField :label="t('tasks.move.project')">
+ <USelectMenu
+ v-model="targetGoalId"
+ :items="targets"
+ value-key="value"
+ :placeholder="t('tasks.move.selectProject')"
+ :disabled="targets.length === 0"
+ :search-input="false"
+ size="xl"
+ class="w-full"
+ data-testid="task-move-target"
+ />
+ </UFormField>
+
+ <p
+ v-if="targets.length === 0"
+ class="text-sm text-muted"
+ >
+ {{ t('tasks.move.noProjects') }}
+ </p>
+
+ <div
+ v-if="previewLoading"
+ class="flex justify-center py-4"
+ >
+ <UIcon
+ name="i-lucide-loader-circle"
+ class="size-6 animate-spin text-muted"
+ />
+ </div>
+ <TaskMovePreview
+ v-else-if="preview"
+ :preview="preview"
+ />
+ </div>
+ </template>
+
+ <template #footer>
+ <div class="flex justify-end gap-2">
+ <UButton
+ :label="t('common.cancel')"
+ color="neutral"
+ variant="soft"
+ @click="isOpen = false"
+ />
+ <UButton
+ :label="preview?.mode === 'copy' ? t('tasks.move.submitCopy') : t('tasks.move.submitMove')"
+ variant="soft"
+ :disabled="!preview?.allowed"
+ :loading="moving"
+ data-testid="task-move-submit"
+ @click="submit"
+ />
+ </div>
+ </template>
+ </UModal>
+</template>
+
+<script setup lang="ts">
+import { computed, ref, watch } from 'vue'
+import { useI18n } from 'vue-i18n'
+import type { Task, TaskResponseMovePreview, TaskResponseMoveToProject } from 'taskview-api'
+import { useGoalsStore } from '@/stores/goals.store'
+import { useTasksStore } from '@/stores/tasks.store'
+import { useTaskView } from '@/composables/useTaskView'
+import { AllGoalPermissions } from '@/types/goals.types'
+import TaskMovePreview from './TaskMovePreview.vue'
+
+const props = defineProps<{
+ task: Task | null
+}>()
+
+const emit = defineEmits<{
+ moved: [result: TaskResponseMoveToProject]
+}>()
+
+const isOpen = defineModel<boolean>('open', { required: true })
+
+const { t } = useI18n()
+const goalsStore = useGoalsStore()
+const tasksStore = useTasksStore()
+const { isFullscreenModal } = useTaskView()
+
+const targetGoalId = ref<number | undefined>(undefined)
+const preview = ref<TaskResponseMovePreview | null>(null)
+const previewLoading = ref(false)
+const moving = ref(false)
+
+const targets = computed(() => {
+ const sourceGoal = props.task ? goalsStore.goalMap.get(props.task.goalId) : undefined
+ return goalsStore.goals
+ .filter((g) => g.id !== props.task?.goalId && !g.archive && g.organizationId === sourceGoal?.organizationId)
+ .filter((g) => !!g.permissions[AllGoalPermissions.COMPONENT_CAN_ADD_TASKS])
+ .map((g) => ({ label: g.isInbox ? t('projects.inbox') : g.name, value: g.id }))
+})
+
+watch(isOpen, (open) => {
+ if (open) return
+ targetGoalId.value = undefined
+ preview.value = null
+})
+
+watch(targetGoalId, async (goalId) => {
+ preview.value = null
+ if (!goalId || !props.task) return
+ previewLoading.value = true
+ preview.value = await tasksStore.previewMoveToProject({ taskId: props.task.id, targetGoalId: goalId })
+ previewLoading.value = false
+})
+
+async function submit() {
+ if (!props.task || !targetGoalId.value || !preview.value?.allowed) return
+ moving.value = true
+ const result = await tasksStore.moveToProject({ taskId: props.task.id, targetGoalId: targetGoalId.value })
+ moving.value = false
+ if (!result) return
+ isOpen.value = false
+ emit('moved', result)
+}
+</script>
diff --git a/web/src/components/features/tasks/parts/TaskMovePreview.vue b/web/src/components/features/tasks/parts/TaskMovePreview.vue
new file mode 100644
index 0000000..d45737e
--- /dev/null
+++ b/web/src/components/features/tasks/parts/TaskMovePreview.vue
@@ -0,0 +1,91 @@
+<template>
+ <div
+ class="flex flex-col gap-3"
+ data-testid="task-move-preview"
+ >
+ <UAlert
+ v-if="!preview.allowed"
+ color="error"
+ variant="soft"
+ icon="i-lucide-ban"
+ :title="t(`tasks.move.reasons.${preview.reason}`)"
+ data-testid="task-move-blocked"
+ />
+
+ <template v-else>
+ <UAlert
+ v-if="preview.mode === 'copy'"
+ color="warning"
+ variant="soft"
+ icon="i-lucide-copy"
+ :title="t('tasks.move.copyNotice')"
+ :description="t('tasks.move.copyTime')"
+ data-testid="task-move-copy-notice"
+ />
+
+ <TaskMovePreviewSection
+ :title="preview.mode === 'copy' ? t('tasks.move.copying') : t('tasks.move.moving')"
+ icon="i-lucide-arrow-right-left"
+ :items="moving"
+ />
+ <TaskMovePreviewSection
+ :title="t('tasks.move.removed')"
+ :hint="t('tasks.move.removedHint')"
+ icon="i-lucide-unlink"
+ :items="removed"
+ data-testid="task-move-removed"
+ />
+ <TaskMovePreviewSection
+ :title="t('tasks.move.leftBehind')"
+ icon="i-lucide-lock"
+ :items="leftBehind"
+ data-testid="task-move-left-behind"
+ />
+ </template>
+ </div>
+</template>
+
+<script setup lang="ts">
+import { computed } from 'vue'
+import { useI18n } from 'vue-i18n'
+import type { TaskMoveRemovals, TaskResponseMovePreview } from 'taskview-api'
+import TaskMovePreviewSection from './TaskMovePreviewSection.vue'
+
+const props = defineProps<{
+ preview: TaskResponseMovePreview
+}>()
+
+const { t } = useI18n()
+
+const REMOVAL_KEYS: (keyof TaskMoveRemovals)[] = [
+ 'tags',
+ 'assignees',
+ 'fileLinks',
+ 'dependencies',
+ 'sprintOutcomes',
+ 'integrationLinks',
+ 'recurrence',
+]
+
+const moving = computed(() => {
+ const items = [t('tasks.move.movingTask')]
+ const subtasks = props.preview.tasks - 1
+ if (subtasks > 0) items.push(t('tasks.move.movingSubtasks', { count: subtasks }))
+ if (props.preview.timeEntries > 0) items.push(t('tasks.move.movingTime', { count: props.preview.timeEntries }))
+ return items
+})
+
+const removed = computed(() =>
+ REMOVAL_KEYS.filter((key) => (props.preview.removals?.[key] ?? 0) > 0).map((key) =>
+ t(`tasks.move.removals.${key}`, { count: props.preview.removals?.[key] ?? 0 }),
+ ),
+)
+
+const leftBehind = computed(() => {
+ const items: string[] = []
+ const behind = props.preview.leftBehind
+ if (behind && behind.subtasks > 0) items.push(t('tasks.move.leftBehindSubtasks', { count: behind.subtasks }))
+ if (behind && behind.timeEntries > 0) items.push(t('tasks.move.leftBehindTime', { count: behind.timeEntries }))
+ return items
+})
+</script>
diff --git a/web/src/components/features/tasks/parts/TaskMovePreviewSection.vue b/web/src/components/features/tasks/parts/TaskMovePreviewSection.vue
new file mode 100644
index 0000000..e96c2b8
--- /dev/null
+++ b/web/src/components/features/tasks/parts/TaskMovePreviewSection.vue
@@ -0,0 +1,37 @@
+<template>
+ <div
+ v-if="items.length > 0"
+ class="flex flex-col gap-1.5 rounded-xl bg-elevated/50 p-3"
+ >
+ <div class="flex items-center gap-2 text-sm font-medium">
+ <UIcon
+ :name="icon"
+ class="size-4 text-muted"
+ />
+ {{ title }}
+ </div>
+ <ul class="flex flex-col gap-1 pl-6 text-sm text-muted list-disc">
+ <li
+ v-for="item in items"
+ :key="item"
+ >
+ {{ item }}
+ </li>
+ </ul>
+ <p
+ v-if="hint"
+ class="pl-6 text-xs text-dimmed"
+ >
+ {{ hint }}
+ </p>
+ </div>
+</template>
+
+<script setup lang="ts">
+defineProps<{
+ title: string
+ icon: string
+ items: string[]
+ hint?: string
+}>()
+</script>
diff --git a/web/src/locales/de.ts b/web/src/locales/de.ts
index 4ff6f76..79f02f2 100644
--- a/web/src/locales/de.ts
+++ b/web/src/locales/de.ts
@@ -578,6 +578,46 @@ export default {
sortLowestFirst: 'Niedrigste zuerst',
deleteConfirm: 'Aufgabe löschen',
deleteMessage: 'Sind Sie sicher, dass Sie "{name}" löschen möchten? Diese Aktion kann nicht rückgängig gemacht werden.',
+ move: {
+ button: 'Verschieben',
+ title: 'Aufgabe in ein anderes Projekt verschieben',
+ project: 'Projekt',
+ selectProject: 'Projekt auswählen',
+ noProjects: 'In dieser Organisation gibt es kein anderes Projekt, in dem Sie Aufgaben anlegen dürfen',
+ submitMove: 'Verschieben',
+ submitCopy: 'Kopieren',
+ copyNotice: 'Sie dürfen in diesem Projekt keine Aufgaben löschen, daher wird die Aufgabe kopiert. Das Original bleibt hier.',
+ copyTime: 'Erfasste Zeit wird nicht kopiert, sie bleibt bei der ursprünglichen Aufgabe.',
+ moving: 'Wird verschoben',
+ copying: 'Wird kopiert',
+ movingTask: 'Die Aufgabe selbst',
+ movingSubtasks: 'Unteraufgaben: {count}',
+ movingTime: 'Zeiteinträge: {count}',
+ removed: 'Wird entfernt',
+ removedHint: 'Liste, Kanban-Spalte und Sprint werden im neuen Projekt zurückgesetzt.',
+ leftBehind: 'Wird nicht verschoben: keine Berechtigung im Zielprojekt',
+ leftBehindSubtasks: 'Unteraufgaben: {count}. Sie bleiben hier als eigenständige Aufgaben.',
+ leftBehindTime: 'Zeiteinträge: {count}. Sie bleiben in den Berichten dieses Projekts.',
+ moved: 'Aufgabe nach „{project}“ verschoben',
+ copied: 'Aufgabe nach „{project}“ kopiert',
+ open: 'Öffnen',
+ removals: {
+ tags: 'Tags: {count}',
+ assignees: 'Zuständige: {count}',
+ fileLinks: 'Angehängte Dateien: {count}. Die Dateien bleiben in diesem Projekt.',
+ dependencies: 'Abhängigkeiten zu anderen Aufgaben: {count}. Sie werden endgültig gelöscht: prüfen Sie die Reihenfolge der Aufgaben, die in diesem Projekt bleiben.',
+ sprintOutcomes: 'Sprint-Ergebnisse: {count}',
+ integrationLinks: 'Verknüpfungen mit Git-Issues: {count}',
+ recurrence: 'Wiederholungsregeln: {count}. Die Aufgabe wird davon gelöst.',
+ },
+ reasons: {
+ not_found: 'Aufgabe nicht gefunden',
+ same_project: 'Die Aufgabe ist bereits in diesem Projekt',
+ other_organization: 'Aufgaben können nur innerhalb einer Organisation verschoben werden',
+ is_subtask: 'Unteraufgaben werden nur zusammen mit ihrer übergeordneten Aufgabe verschoben',
+ no_target_permission: 'Sie dürfen in diesem Projekt keine Aufgaben anlegen',
+ },
+ },
},
tags: {
createTag: 'Tag erstellen',
@@ -1448,6 +1488,9 @@ export default {
noPermission: 'Sie haben keine Berechtigung, die Dateien dieses Projekts zu sehen',
storageDisabled: 'Der Dateispeicher ist auf diesem Server nicht konfiguriert',
storageDisabledHint: 'Anhänge sind nicht verfügbar.',
+ quota: {
+ usage: '{used} von {total} belegt',
+ },
filters: {
all: 'Alle',
images: 'Bilder',
@@ -1491,6 +1534,7 @@ export default {
errors: {
tooLarge: 'Datei ist zu groß',
tooLargeLimit: 'Datei ist größer als {size}',
+ quotaExceeded: 'Nicht genug Speicherplatz',
forbidden: 'Keine Berechtigung zum Hochladen',
notFound: 'Aufgabe nicht gefunden',
uploadFailed: 'Hochladen fehlgeschlagen',
diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts
index d838f74..463a6e4 100644
--- a/web/src/locales/en.ts
+++ b/web/src/locales/en.ts
@@ -592,6 +592,46 @@ export default {
sortLowestFirst: 'Lowest first',
deleteConfirm: 'Delete Task',
deleteMessage: 'Are you sure you want to delete "{name}"? This action cannot be undone.',
+ move: {
+ button: 'Move',
+ title: 'Move task to another project',
+ project: 'Project',
+ selectProject: 'Select a project',
+ noProjects: 'There is no other project in this organization where you can add tasks',
+ submitMove: 'Move',
+ submitCopy: 'Copy',
+ copyNotice: 'You cannot delete tasks in this project, so the task will be copied. The original stays here.',
+ copyTime: 'Logged time is not copied, it stays with the original task.',
+ moving: 'Will be moved',
+ copying: 'Will be copied',
+ movingTask: 'The task itself',
+ movingSubtasks: 'Subtasks: {count}',
+ movingTime: 'Time entries: {count}',
+ removed: 'Will be removed',
+ removedHint: 'The list, kanban column and sprint are reset in the new project.',
+ leftBehind: 'Will not be moved: no permission in the target project',
+ leftBehindSubtasks: 'Subtasks: {count}. They stay here as separate tasks.',
+ leftBehindTime: 'Time entries: {count}. They stay in this project\'s reports.',
+ moved: 'Task moved to "{project}"',
+ copied: 'Task copied to "{project}"',
+ open: 'Open',
+ removals: {
+ tags: 'Tags: {count}',
+ assignees: 'Assignees: {count}',
+ fileLinks: 'Attached files: {count}. The files stay in this project.',
+ dependencies: 'Dependencies with other tasks: {count}. They are deleted for good: check the order of the tasks that stay in this project.',
+ sprintOutcomes: 'Sprint results: {count}',
+ integrationLinks: 'Links to Git issues: {count}',
+ recurrence: 'Repeat rules: {count}. The task is detached from them.',
+ },
+ reasons: {
+ not_found: 'Task not found',
+ same_project: 'The task is already in this project',
+ other_organization: 'Tasks can only be moved within one organization',
+ is_subtask: 'Subtasks move together with their parent task',
+ no_target_permission: 'You cannot add tasks to this project',
+ },
+ },
},
tags: {
createTag: 'Create tag',
@@ -1462,6 +1502,9 @@ export default {
noPermission: 'You do not have permission to view files of this project',
storageDisabled: 'File storage is not configured on this server',
storageDisabledHint: 'Attachments are unavailable.',
+ quota: {
+ usage: 'Used {used} of {total}',
+ },
filters: {
all: 'All',
images: 'Images',
@@ -1505,6 +1548,7 @@ export default {
errors: {
tooLarge: 'File is too large',
tooLargeLimit: 'File is larger than {size}',
+ quotaExceeded: 'Not enough storage space',
forbidden: 'No permission to upload',
notFound: 'Task not found',
uploadFailed: 'Upload failed',
diff --git a/web/src/locales/es.ts b/web/src/locales/es.ts
index dbab8e2..51c76b9 100644
--- a/web/src/locales/es.ts
+++ b/web/src/locales/es.ts
@@ -578,6 +578,46 @@ export default {
sortLowestFirst: 'Menor primero',
deleteConfirm: 'Eliminar tarea',
deleteMessage: '¿Seguro que quieres eliminar "{name}"? Esta acción no se puede deshacer.',
+ move: {
+ button: 'Mover',
+ title: 'Mover la tarea a otro proyecto',
+ project: 'Proyecto',
+ selectProject: 'Selecciona un proyecto',
+ noProjects: 'No hay otro proyecto en esta organización donde puedas añadir tareas',
+ submitMove: 'Mover',
+ submitCopy: 'Copiar',
+ copyNotice: 'No puedes eliminar tareas en este proyecto, así que la tarea se copiará. La original se queda aquí.',
+ copyTime: 'El tiempo registrado no se copia, se queda con la tarea original.',
+ moving: 'Se moverá',
+ copying: 'Se copiará',
+ movingTask: 'La tarea en sí',
+ movingSubtasks: 'Subtareas: {count}',
+ movingTime: 'Registros de tiempo: {count}',
+ removed: 'Se eliminará',
+ removedHint: 'La lista, la columna del kanban y el sprint se restablecen en el nuevo proyecto.',
+ leftBehind: 'No se moverá: sin permiso en el proyecto de destino',
+ leftBehindSubtasks: 'Subtareas: {count}. Se quedan aquí como tareas independientes.',
+ leftBehindTime: 'Registros de tiempo: {count}. Se quedan en los informes de este proyecto.',
+ moved: 'Tarea movida a «{project}»',
+ copied: 'Tarea copiada a «{project}»',
+ open: 'Abrir',
+ removals: {
+ tags: 'Etiquetas: {count}',
+ assignees: 'Responsables: {count}',
+ fileLinks: 'Archivos adjuntos: {count}. Los archivos se quedan en este proyecto.',
+ dependencies: 'Dependencias con otras tareas: {count}. Se eliminan definitivamente: revisa el orden de las tareas que se quedan en este proyecto.',
+ sprintOutcomes: 'Resultados de sprints: {count}',
+ integrationLinks: 'Vínculos con issues de Git: {count}',
+ recurrence: 'Reglas de repetición: {count}. La tarea se desvincula de ellas.',
+ },
+ reasons: {
+ not_found: 'Tarea no encontrada',
+ same_project: 'La tarea ya está en este proyecto',
+ other_organization: 'Las tareas solo se pueden mover dentro de una organización',
+ is_subtask: 'Las subtareas solo se mueven junto con su tarea principal',
+ no_target_permission: 'No puedes añadir tareas a este proyecto',
+ },
+ },
},
tags: {
createTag: 'Crear etiqueta',
@@ -1448,6 +1488,9 @@ export default {
noPermission: 'No tienes permiso para ver los archivos de este proyecto',
storageDisabled: 'El almacenamiento de archivos no está configurado en este servidor',
storageDisabledHint: 'Los adjuntos no están disponibles.',
+ quota: {
+ usage: 'Usado {used} de {total}',
+ },
filters: {
all: 'Todos',
images: 'Imágenes',
@@ -1491,6 +1534,7 @@ export default {
errors: {
tooLarge: 'El archivo es demasiado grande',
tooLargeLimit: 'El archivo supera {size}',
+ quotaExceeded: 'No hay suficiente espacio de almacenamiento',
forbidden: 'Sin permiso para subir',
notFound: 'Tarea no encontrada',
uploadFailed: 'Error al subir',
diff --git a/web/src/locales/pt-br.ts b/web/src/locales/pt-br.ts
index 154078d..ab602ec 100644
--- a/web/src/locales/pt-br.ts
+++ b/web/src/locales/pt-br.ts
@@ -591,6 +591,46 @@ export default {
sortLowestFirst: 'Menor primeiro',
deleteConfirm: 'Excluir tarefa',
deleteMessage: 'Tem certeza de que deseja excluir "{name}"? Esta ação não pode ser desfeita.',
+ move: {
+ button: 'Mover',
+ title: 'Mover tarefa para outro projeto',
+ project: 'Projeto',
+ selectProject: 'Selecione um projeto',
+ noProjects: 'Não há outro projeto nesta organização onde você possa adicionar tarefas',
+ submitMove: 'Mover',
+ submitCopy: 'Copiar',
+ copyNotice: 'Você não pode excluir tarefas neste projeto, então a tarefa será copiada. A original fica aqui.',
+ copyTime: 'O tempo registrado não é copiado, ele fica com a tarefa original.',
+ moving: 'Será movido',
+ copying: 'Será copiado',
+ movingTask: 'A própria tarefa',
+ movingSubtasks: 'Subtarefas: {count}',
+ movingTime: 'Registros de tempo: {count}',
+ removed: 'Será removido',
+ removedHint: 'A lista, a coluna do kanban e o sprint são redefinidos no novo projeto.',
+ leftBehind: 'Não será movido: sem permissão no projeto de destino',
+ leftBehindSubtasks: 'Subtarefas: {count}. Elas ficam aqui como tarefas separadas.',
+ leftBehindTime: 'Registros de tempo: {count}. Eles ficam nos relatórios deste projeto.',
+ moved: 'Tarefa movida para "{project}"',
+ copied: 'Tarefa copiada para "{project}"',
+ open: 'Abrir',
+ removals: {
+ tags: 'Tags: {count}',
+ assignees: 'Responsáveis: {count}',
+ fileLinks: 'Arquivos anexados: {count}. Os arquivos ficam neste projeto.',
+ dependencies: 'Dependências com outras tarefas: {count}. Elas são excluídas definitivamente: verifique a ordem das tarefas que ficam neste projeto.',
+ sprintOutcomes: 'Resultados de sprints: {count}',
+ integrationLinks: 'Vínculos com issues do Git: {count}',
+ recurrence: 'Regras de repetição: {count}. A tarefa é desvinculada delas.',
+ },
+ reasons: {
+ not_found: 'Tarefa não encontrada',
+ same_project: 'A tarefa já está neste projeto',
+ other_organization: 'Tarefas só podem ser movidas dentro de uma organização',
+ is_subtask: 'Subtarefas só são movidas junto com a tarefa principal',
+ no_target_permission: 'Você não pode adicionar tarefas a este projeto',
+ },
+ },
},
tags: {
createTag: 'Criar tag',
@@ -1459,6 +1499,9 @@ export default {
noPermission: 'Você não tem permissão para ver os arquivos deste projeto',
storageDisabled: 'O armazenamento de arquivos não está configurado neste servidor',
storageDisabledHint: 'Os anexos não estão disponíveis.',
+ quota: {
+ usage: 'Usado {used} de {total}',
+ },
filters: {
all: 'Todos',
images: 'Imagens',
@@ -1502,6 +1545,7 @@ export default {
errors: {
tooLarge: 'O arquivo é muito grande',
tooLargeLimit: 'O arquivo é maior que {size}',
+ quotaExceeded: 'Espaço de armazenamento insuficiente',
forbidden: 'Sem permissão para enviar',
notFound: 'Tarefa não encontrada',
uploadFailed: 'Falha no envio',
diff --git a/web/src/locales/ru.ts b/web/src/locales/ru.ts
index c63f8f2..97fc907 100644
--- a/web/src/locales/ru.ts
+++ b/web/src/locales/ru.ts
@@ -559,6 +559,46 @@ export default {
sortLowestFirst: 'Сначала низкий',
deleteConfirm: 'Удалить задачу',
deleteMessage: 'Вы уверены, что хотите удалить "{name}"? Это действие нельзя отменить.',
+ move: {
+ button: 'Перенести',
+ title: 'Перенести задачу в другой проект',
+ project: 'Проект',
+ selectProject: 'Выберите проект',
+ noProjects: 'В этой организации нет другого проекта, куда вы можете добавлять задачи',
+ submitMove: 'Перенести',
+ submitCopy: 'Скопировать',
+ copyNotice: 'У вас нет права удалять задачи в этом проекте, поэтому задача будет скопирована. Исходная останется здесь.',
+ copyTime: 'Учтённое время не копируется, оно остаётся у исходной задачи.',
+ moving: 'Будет перенесено',
+ copying: 'Будет скопировано',
+ movingTask: 'Сама задача',
+ movingSubtasks: 'Подзадач: {count}',
+ movingTime: 'Записей времени: {count}',
+ removed: 'Будет удалено',
+ removedHint: 'Список, колонка канбана и спринт в новом проекте сбрасываются.',
+ leftBehind: 'Не будет перенесено: нет прав в целевом проекте',
+ leftBehindSubtasks: 'Подзадач: {count}. Они останутся здесь как отдельные задачи.',
+ leftBehindTime: 'Записей времени: {count}. Они останутся в отчётах этого проекта.',
+ moved: 'Задача перенесена в «{project}»',
+ copied: 'Задача скопирована в «{project}»',
+ open: 'Открыть',
+ removals: {
+ tags: 'Тегов: {count}',
+ assignees: 'Исполнителей: {count}',
+ fileLinks: 'Прикреплённых файлов: {count}. Сами файлы останутся в этом проекте.',
+ dependencies: 'Зависимостей с другими задачами: {count}. Эти связи удаляются насовсем: проверьте порядок задач, которые остаются в этом проекте.',
+ sprintOutcomes: 'Итогов спринтов: {count}',
+ integrationLinks: 'Связей с issue в Git: {count}',
+ recurrence: 'Правил повторения: {count}. Задача будет от них отвязана.',
+ },
+ reasons: {
+ not_found: 'Задача не найдена',
+ same_project: 'Задача уже в этом проекте',
+ other_organization: 'Переносить задачи можно только внутри одной организации',
+ is_subtask: 'Подзадачи переносятся только вместе с родительской задачей',
+ no_target_permission: 'Вы не можете добавлять задачи в этот проект',
+ },
+ },
},
tags: {
createTag: 'Создать тег',
@@ -1397,6 +1437,9 @@ export default {
noPermission: 'У вас нет прав на просмотр файлов этого проекта',
storageDisabled: 'Хранилище файлов не настроено на этом сервере',
storageDisabledHint: 'Вложения недоступны.',
+ quota: {
+ usage: 'Использовано {used} из {total}',
+ },
filters: {
all: 'Все',
images: 'Картинки',
@@ -1440,6 +1483,7 @@ export default {
errors: {
tooLarge: 'Файл слишком большой',
tooLargeLimit: 'Файл больше {size}',
+ quotaExceeded: 'Недостаточно места в хранилище',
forbidden: 'Нет прав на загрузку',
notFound: 'Задача не найдена',
uploadFailed: 'Не удалось загрузить',
diff --git a/web/src/stores/base-screen.store.ts b/web/src/stores/base-screen.store.ts
index b71e2cd..ae6084c 100644
--- a/web/src/stores/base-screen.store.ts
+++ b/web/src/stores/base-screen.store.ts
@@ -12,6 +12,7 @@ import {
type MainScreenAllStateResponse,
} from '@/types/base-screen.types'
import type { AppResponse } from '@/types/global-app.types'
+import type { BaseScreenTaskBucket } from '@/types/base-screen.types'
import type { TaskItem } from '@/types/tasks.types'
import { useOrganizationStore } from '@/stores/organization.store'
@@ -115,18 +116,18 @@ export const useBaseScreenStore = defineStore('base-screen-store', {
localTask.complete = task.complete
switch (prop) {
- case 'tasks':
- this.processLastAdded(task)
- break
- case 'tasksToday':
- this.processToday(task)
- break
- case 'tasksUpcoming':
- this.processUpcoming(task)
- break
- case 'tasksLastCompleted':
- this.processLastCompleted(task)
- break
+ case 'tasks':
+ this.processLastAdded(task)
+ break
+ case 'tasksToday':
+ this.processToday(task)
+ break
+ case 'tasksUpcoming':
+ this.processUpcoming(task)
+ break
+ case 'tasksLastCompleted':
+ this.processLastCompleted(task)
+ break
}
}
},
@@ -156,17 +157,25 @@ export const useBaseScreenStore = defineStore('base-screen-store', {
}
},
+ bucketForTask(task: TaskItem): BaseScreenTaskBucket {
+ if (!task.endDate) return 'tasks'
+ const today = useDateFormat(new Date(), 'YYYY-MM-DD').value
+ return task.endDate.slice(0, 10) <= today ? 'tasksToday' : 'tasksUpcoming'
+ },
+
+ addCreatedTask(task: TaskItem) {
+ const bucket = this.bucketForTask(task)
+ if (!this[bucket].some((t) => t.id === task.id)) this[bucket].unshift(task)
+ },
+
processLastCompleted(task: TaskItem) {
if (task.complete) return
- const deadline = new Date(useDateFormat(new Date(task.endDate || ''), 'YYYY-MM-DD').value)
- const today = new Date(useDateFormat(new Date(), 'YYYY-MM-DD').value)
-
const removeTask = () => {
this.tasksLastCompleted = this.tasksLastCompleted.filter((t) => t.id !== task.id)
}
- const key = !task.endDate ? 'tasks' : deadline <= today ? 'tasksToday' : 'tasksUpcoming'
+ const key = this.bucketForTask(task)
const existingTask = this[key].find((tsk) => tsk.id === task.id)
diff --git a/web/src/stores/files.store.ts b/web/src/stores/files.store.ts
index b4c6df8..6940b7e 100644
--- a/web/src/stores/files.store.ts
+++ b/web/src/stores/files.store.ts
@@ -12,6 +12,7 @@ import type {
const PAGE_SIZE = 50
export const FILE_TOO_LARGE_ERROR_KEY = 'files.errors.tooLarge'
+export const FILE_QUOTA_EXCEEDED_ERROR_KEY = 'files.errors.quotaExceeded'
export const useFilesStore = defineStore('files', {
state: (): FilesStoreState => ({
@@ -20,9 +21,16 @@ export const useFilesStore = defineStore('files', {
project: { goalId: null, items: [], nextCursor: null, search: '', type: 'all', loading: false },
uploads: [],
storage: { enabled: null, maxFileSizeBytes: null },
+ quotaByGoal: {},
}),
getters: {
storageEnabled: (state): boolean => state.storage.enabled !== false,
+
+ quotaRemaining: (state) => (goalId: number): number | null => {
+ const quota = state.quotaByGoal[goalId]
+ if (!quota || quota.mode !== 'enforce' || quota.quotaBytes === null || quota.usedBytes === null) return null
+ return Math.max(0, quota.quotaBytes - quota.usedBytes)
+ },
filesForTask: (state) => (taskId: number): TvFile[] => state.byTask[taskId] ?? [],
uploadsFor: (state) => (goalId: number, taskId: number | null): FileUploadItem[] =>
state.uploads.filter((u) => u.goalId === goalId && u.taskId === taskId),
@@ -34,6 +42,15 @@ export const useFilesStore = defineStore('files', {
if (status) this.storage = { enabled: status.enabled, maxFileSizeBytes: status.maxFileSizeBytes }
},
+ async fetchQuota(goalId: number): Promise<void> {
+ const quota = await $tvApi.files.quota(goalId).catch(logError)
+ if (quota) this.quotaByGoal[goalId] = quota
+ },
+
+ refreshLoadedQuotas() {
+ for (const goalId of Object.keys(this.quotaByGoal)) void this.fetchQuota(Number(goalId))
+ },
+
async fetchForTask(taskId: number): Promise<void> {
this.loadingTasks[taskId] = true
const files = await $tvApi.files
@@ -103,6 +120,11 @@ export const useFilesStore = defineStore('files', {
this.uploads.push({ ...item, status: 'error', errorKey: FILE_TOO_LARGE_ERROR_KEY })
return null
}
+ const remaining = this.quotaRemaining(args.goalId)
+ if (remaining !== null && args.file.size > remaining) {
+ this.uploads.push({ ...item, status: 'error', errorKey: FILE_QUOTA_EXCEEDED_ERROR_KEY })
+ return null
+ }
this.uploads.push(item)
@@ -120,6 +142,7 @@ export const useFilesStore = defineStore('files', {
})
this.removeUpload(item.id)
this.applyUploaded(uploaded)
+ if (this.quotaByGoal[args.goalId]) void this.fetchQuota(args.goalId)
return uploaded
} catch (err) {
const current = this.uploads.find((u) => u.id === item.id)
@@ -186,6 +209,7 @@ export const useFilesStore = defineStore('files', {
this.byTask[Number(taskId)] = this.byTask[Number(taskId)].filter((f) => f.id !== fileId)
}
this.project.items = this.project.items.filter((f) => f.id !== fileId)
+ this.refreshLoadedQuotas()
return true
},
@@ -223,6 +247,7 @@ export const useFilesStore = defineStore('files', {
errorKeyFor(err: unknown): string {
const status = (err as { response?: { status?: number } })?.response?.status
if (status === 413) return FILE_TOO_LARGE_ERROR_KEY
+ if (status === 507) return FILE_QUOTA_EXCEEDED_ERROR_KEY
if (status === 403) return 'files.errors.forbidden'
if (status === 404) return 'files.errors.notFound'
return 'files.errors.uploadFailed'
diff --git a/web/src/stores/tasks.store.ts b/web/src/stores/tasks.store.ts
index be80c91..b5c5a00 100644
--- a/web/src/stores/tasks.store.ts
+++ b/web/src/stores/tasks.store.ts
@@ -12,6 +12,9 @@ import {
type TaskArgToggleAssignee,
type TaskArgUpdate,
type TaskBase,
+ type TaskArgMoveToProject,
+ type TaskResponseMovePreview,
+ type TaskResponseMoveToProject,
} from 'taskview-api'
import { $tvApi } from '@/plugins/axios'
import { DEFAULT_ID } from '@/types/app.types'
@@ -295,12 +298,16 @@ export const useTasksStore = defineStore('tasks', {
if (!result) return false
+ this.removeTaskLocally(id)
+ return true
+ },
+
+ removeTaskLocally(id: number) {
const taskIndex = this.tasks.findIndex((task) => task.id === id)
if (taskIndex !== -1) {
this.tasks.splice(taskIndex, 1)
} else {
- // Check if it's a subtask
for (const task of this.tasks) {
const subIndex = task.subtasks.findIndex((s) => s.id === id)
if (subIndex !== -1) {
@@ -318,8 +325,14 @@ export const useTasksStore = defineStore('tasks', {
this.selectedTask.subtasks.splice(subIndex, 1)
}
}
+ },
- return true
+ async previewMoveToProject(args: TaskArgMoveToProject): Promise<TaskResponseMovePreview | null> {
+ return (await $tvApi.tasks.movePreview(args).catch(logError)) ?? null
+ },
+
+ async moveToProject(args: TaskArgMoveToProject): Promise<TaskResponseMoveToProject | null> {
+ return (await $tvApi.tasks.moveToProject(args).catch(logError)) ?? null
},
async updateTaskNote(data: TaskArgUpdate): Promise<boolean> {
@@ -376,24 +389,11 @@ export const useTasksStore = defineStore('tasks', {
const task = this.tasks.find((tsk) => +tsk.id === +data.taskId)
- const toggleTag = (task: Task) => {
- if (action === 'delete') {
- const tagIndex = task.tags.indexOf(data.tagId)
- if (tagIndex !== -1) {
- task.tags.splice(tagIndex, 1)
- }
- } else {
- task.tags.push(data.tagId)
- }
- }
-
- if (task) {
- toggleTag(task)
- this.updateSelectedTask(task)
- } else if (this.selectedTask?.id === data.taskId) {
- toggleTag(this.selectedTask)
- }
+ const toggled = (tags: Task['tags']) =>
+ action === 'delete' ? tags.filter((id) => id !== data.tagId) : [...tags.filter((id) => id !== data.tagId), data.tagId]
+ if (task) task.tags = toggled(task.tags)
+ if (this.selectedTask?.id === data.taskId && this.selectedTask !== task) this.selectedTask.tags = toggled(this.selectedTask.tags)
},
async udpatePriority(data: TaskArgUpdate): Promise<void> {
@@ -473,13 +473,8 @@ export const useTasksStore = defineStore('tasks', {
if (!updateAssignee) return
const task = this.tasks.find((tsk) => tsk.id === data.taskId)
-
- if (task) {
- task.assignedUsers = updateAssignee.userIds
- this.updateSelectedTask(task)
- } else if (this.selectedTask?.id === data.taskId) {
- this.selectedTask.assignedUsers = updateAssignee.userIds
- }
+ if (task) task.assignedUsers = updateAssignee.userIds
+ if (this.selectedTask?.id === data.taskId) this.selectedTask.assignedUsers = updateAssignee.userIds
},
// we do not fetch assigned users from server separately, we fetch all tasks with assigned users
diff --git a/web/src/types/base-screen.types.ts b/web/src/types/base-screen.types.ts
index 0a50ecd..c9c17a0 100644
--- a/web/src/types/base-screen.types.ts
+++ b/web/src/types/base-screen.types.ts
@@ -72,3 +72,6 @@ export const DIALOG_WIDTH = 600
export const DIALOG_DESKTOP_HEIGHT = '50%'
export type BaseScreenSearchResponse = TaskItem[];
+
+// Dashboard list a not-completed task belongs to, by its deadline (same rule as the server's /start lists)
+export type BaseScreenTaskBucket = 'tasks' | 'tasksToday' | 'tasksUpcoming';
diff --git a/web/src/types/files.types.ts b/web/src/types/files.types.ts
index e65d74e..aa1e96c 100644
--- a/web/src/types/files.types.ts
+++ b/web/src/types/files.types.ts
@@ -1,4 +1,4 @@
-import type { TvFile, TvFileKindFilter } from 'taskview-api'
+import type { TvFile, TvFileKindFilter, TvFileQuota } from 'taskview-api'
export type FileKind = 'image' | 'pdf' | 'video' | 'audio' | 'text' | 'other'
@@ -37,6 +37,7 @@ export type FilesStoreState = {
project: FilesProjectListState
uploads: FileUploadItem[]
storage: FilesStorageState
+ quotaByGoal: Record<number, TvFileQuota>
}
export type FilesUploadArgs = {