31 Commits

Author SHA1 Message Date
morteza 30d86c9775 task time 2026-07-15 10:37:19 +03:30
realrafi 4263d7118e refactor: changed the findTasksByTaskPhase to include task info like remark, etc 2026-07-14 21:39:37 +03:30
morteza f35df6492c remove unused joins 2026-07-14 15:07:53 +03:30
realrafi 008bddb97a fix&feature: fixxing some logical bogs and adding cursor pagination 2026-07-14 13:51:16 +03:30
realrafi 8e23a06793 refactor: order the taskPhases by order attr in projectDetail API 2026-07-12 14:52:24 +03:30
realrafi 1440b62373 fix: fixing getTaskDetail returning null 2026-07-11 12:38:00 +03:30
realrafi d93e4be6ef refactor: made the findOne project by id to return users of each project as well 2026-07-11 11:36:17 +03:30
realrafi 9ded147354 feat: added fineOne API for workspace & project for update purposes 2026-07-09 20:39:08 +03:30
realrafi 4cb20f6c0d refactor: removed unnecessary methods from checkListItem repo 2026-07-08 11:16:32 +03:30
realrafi 95c947a587 refactor: removed unnecessary functions from attachment 2026-07-08 11:15:20 +03:30
realrafi 8348692481 refactor: updated permissions 2026-07-08 11:09:43 +03:30
realrafi 677fc5b384 refactor: removed some functions and added toggleStatus to checklistitem 2026-07-08 11:08:28 +03:30
realrafi 8481a0e86f refactor: removed unnecessary functions from remark 2026-07-08 10:50:40 +03:30
realrafi b32d613a1b refactor: removed unnecessary functions from task 2026-07-08 10:48:03 +03:30
realrafi b0668c7b2c refactor: removed unnecessary functions from taskphase 2026-07-08 10:32:45 +03:30
realrafi ff08da1330 refactor: changed project functions logic of permissions 2026-07-08 10:27:01 +03:30
realrafi 29d647556c refactor: changed the get workspaces by user logic 2026-07-07 15:53:18 +03:30
realrafi a22d6ceb81 refactor: making the checklistitem service to use enum messages 2026-07-07 12:03:42 +03:30
realrafi eb6fbc3ce5 refactor: refactored attachment entirely 2026-07-07 11:59:05 +03:30
realrafi 9565eda0fd refactor: refactored the checkListItem 2026-07-07 11:51:42 +03:30
realrafi 8533682303 refactor: refactored remark entirely 2026-07-06 17:00:44 +03:30
realrafi e5c14bf5cc refactor: refactored taskDetailAPI by adding some values 2026-07-06 16:44:19 +03:30
realrafi e310411a4d refactor: refactored the getProjectDetail function to include more values 2026-07-06 16:17:02 +03:30
realrafi 0cd5a6a0cc feat: added getTaskDetail API 2026-07-06 16:01:36 +03:30
realrafi da71c20d6d refactor: refactored task APIs 2026-07-06 15:21:34 +03:30
realrafi 263ede68b2 refactor: removed typo forward slash from API paths 2026-07-06 14:30:41 +03:30
realrafi d9283e3a90 refactor: refactored the taskphase 2026-07-06 14:26:03 +03:30
realrafi 5964a9b20d feat: added project detail API 2026-07-06 14:05:38 +03:30
realrafi 5715cbe9b1 refactor: changed the getUserProjects to get projects in a specific workspace 2026-07-06 13:24:36 +03:30
realrafi 2590a222b4 refactor: removing useless get projects by workspace function 2026-07-06 12:16:23 +03:30
realrafi 16a0c14149 feat: added get user projects function in project 2026-07-06 12:06:33 +03:30
49 changed files with 1262 additions and 629 deletions
+75
View File
@@ -0,0 +1,75 @@
NODE_ENV=production
PORT=3500
DB_NAME=dscDev
DB_USER=postgres
DB_PASS=1RWVdlUcZSf6PoFBQO8cprZk2DTkC89ttqeJN7aU2WQRDUEusK4z2FfNqNtV4I10
DB_HOST=78.157.34.13
DB_PORT=5432
SMS_API_URL=https://api.sms.ir/v1
SMS_API_KEY=QkkNxhyXZ6GtEf1soOTtikomO3mA4LaNQDH8mol8huDIwh00
SMS_PATTERN_OTP=842088
SMS_PATTERN_INVOICE=683883
SMS_PATTERN_LOGIN=149141
SMS_PATTERN_INVOICE_CREATED=829067
SMS_PATTERN_ANNOUNCEMENT=752330
SMS_PATTERN_WALLET_CHARGE=727726
SMS_PATTERN_WALLET_DEDUCTION=360785
SMS_PATTERN_TICKET_CREATED=853506
SMS_PATTERN_TICKET_ANSWERED=179464
SMS_PATTERN_TICKET_ASSIGNED_ADMIN=321927
SMS_PATTERN_INVOICE_APPROVED=303807
SMS_PATTERN_INVOICE_PAID=533817
SMS_PATTERN_RECURRING_INVOICE_DRAFT=219287
SMS_PATTERN_SUBSCRIPTION_CANCELLED=166142
SMS_PATTERN_INVOICE_REMINDER=370266
SMS_PATTERN_INVOICE_OVERDUE=160735
SMS_PATTERN_PAYMENT_REMINDER=629772
SMS_PATTERN_PAYMENT_CANCELLATION=197945
SMS_PATTERN_BLOG_NEW_COMMENT=378881
SMS_PATTERN_NEW_SERVICE_REVIEW=593446
SMS_PATTERN_NEW_CUSTOMER=966214
SMS_PATTERN_NEW_SUBSCRIPTION=757095
SMS_PATTERN_NEW_TICKET_GLOBAL=536596
SMS_PATTERN_NEW_CRITICISM=983724
SMS_PATTERN_USER_PASSWORD=486237
SMTP_HOST=smtps.danakcorp.com
SMTP_PORT=465
SMTP_USER=no-reply-danakcorp.com
SMTP_PASS=Mahyar.SR4@
MAIL_FROM=no-reply <no-reply@danakcorp.com>
EMAIL_SECRET=xDkdptbC2N7LoR2Aa4Q9U/aAGOi4DxG2748
REDIS_URI=redis://localhost:6379/1
CACHE_TTL=180000
THROTTLE_TTL=300000
THROTTLE_LIMIT=10
JWT_SECRET_KEY=2ygxIB1PJhK/L2PToqR3+52gRmUIdPfwTguYlB7ZRCdRyvA/N36jjkjbYJLoMxEL\n6xGmk5CQmCmn9c0FsBlN1g
JWT_ISSUER=console-danak
ACCESS_TOKEN_EXPIRE=80000
REFRESH_TOKEN_EXPIRE=6
BUCKET_NAME=danak-project
BUCKET_REGION=default
BUCKET_URL=https://s3.ir-thr-at1.arvanstorage.ir
BUCKET_ACCESS_KEY=4bd15218-60f1-4ce7-a7aa-3fd319b13372
BUCKET_SECRET_KEY=de772e5bd62fb04fb3669e67e09ddb101db60c65d77eea66b215ce58275e6a76
BUCKET_UPLOAD_URL=https://storage.danakcorp.com
ZARINPAL_MERCHANT_ID=fc0b7503-bba5-40d1-9f9d-dae52ac02eef
PARSIAN_LOGIN_ACCOUNT=uqXnB2q8rjkL6vN0xOh0
SITE_URL=https://console.danakcorp.com
API_URL=https://api.danakcorp.com
CALLBACK_URL=https://api.danakcorp.com/payments/verify
TELEGRAM_BOT_TOKEN=7839690719:AAGsyfwympR4rDLm2JCx43CQh52s1o865uY
TELEGRAM_BOT_NAME=danak_logs_bot
TELEGRAM_CHAT_ID=7801476800
EXTERNAL_API_KEYS=uqXssnB2q8rs2soa9almm1jkL6vN0xOh0
DMENU_BACKEND_URL=https://dmenu-api.danakcorp.com
DMENU_USERNAME=danak@dsc.com
DMENU_PASSWORD=DsCdAnAk?@ABC
DKALA_BACKEND_URL=https://dkala-api.danakcorp.com
DKALA_USERNAME=danak@dsc.com
DKALA_PASSWORD=DsCdAnAk?@ABC
DPAGE_BACKEND_URL=https://dpage-api.danakcorp.com
DPAGE_USERNAME=danak@dsc.com
DPAGE_PASSWORD=DsCdAnAk?@ABC
DMAIL_BACKEND_URL=https://dmail-api.danakcorp.com
DMAIL_USERNAME=danak@dsc.com
DMAIL_PASSWORD=DsCdAnAk?@ABC
-11
View File
@@ -1,11 +0,0 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class Migrations1783244654421 implements MigrationInterface {
public async up(queryRunner: QueryRunner): Promise<void> {
}
public async down(queryRunner: QueryRunner): Promise<void> {
}
}
@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class TaskmanagerAddingNewEnumValueForPermissionEnumType1783324039378 implements MigrationInterface {
name = 'TaskmanagerAddingNewEnumValueForPermissionEnumType1783324039378'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TYPE "public"."permission_name_enum" RENAME TO "permission_name_enum_old"`);
await queryRunner.query(`CREATE TYPE "public"."permission_name_enum" AS ENUM('services', 'customers', 'agents', 'developers', 'invoices', 'transactions', 'discounts', 'admins', 'tickets', 'criticisms', 'contacts_us', 'advertisements', 'announcements', 'blogs', 'learnings', 'logs', 'settings', 'bank_accounts', 'payments', 'manage_sso_clients', 'support_plan', 'dmenu', 'dkala', 'dpage', 'dmail', 'reseller', 'workspace', 'project')`);
await queryRunner.query(`ALTER TABLE "permission" ALTER COLUMN "name" TYPE "public"."permission_name_enum" USING "name"::"text"::"public"."permission_name_enum"`);
await queryRunner.query(`DROP TYPE "public"."permission_name_enum_old"`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TYPE "public"."permission_name_enum_old" AS ENUM('services', 'customers', 'agents', 'developers', 'invoices', 'transactions', 'discounts', 'admins', 'tickets', 'criticisms', 'contacts_us', 'advertisements', 'announcements', 'blogs', 'learnings', 'logs', 'settings', 'bank_accounts', 'payments', 'manage_sso_clients', 'support_plan', 'dmenu', 'dkala', 'dpage', 'dmail', 'reseller', 'workspace')`);
await queryRunner.query(`ALTER TABLE "permission" ALTER COLUMN "name" TYPE "public"."permission_name_enum_old" USING "name"::"text"::"public"."permission_name_enum_old"`);
await queryRunner.query(`DROP TYPE "public"."permission_name_enum"`);
await queryRunner.query(`ALTER TYPE "public"."permission_name_enum_old" RENAME TO "permission_name_enum"`);
}
}
@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class TMAddingTaskPhasePermissionToPermissionEnumType1783335279945 implements MigrationInterface {
name = 'TMAddingTaskPhasePermissionToPermissionEnumType1783335279945'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TYPE "public"."permission_name_enum" RENAME TO "permission_name_enum_old"`);
await queryRunner.query(`CREATE TYPE "public"."permission_name_enum" AS ENUM('services', 'customers', 'agents', 'developers', 'invoices', 'transactions', 'discounts', 'admins', 'tickets', 'criticisms', 'contacts_us', 'advertisements', 'announcements', 'blogs', 'learnings', 'logs', 'settings', 'bank_accounts', 'payments', 'manage_sso_clients', 'support_plan', 'dmenu', 'dkala', 'dpage', 'dmail', 'reseller', 'workspace', 'project', 'task_phase')`);
await queryRunner.query(`ALTER TABLE "permission" ALTER COLUMN "name" TYPE "public"."permission_name_enum" USING "name"::"text"::"public"."permission_name_enum"`);
await queryRunner.query(`DROP TYPE "public"."permission_name_enum_old"`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TYPE "public"."permission_name_enum_old" AS ENUM('services', 'customers', 'agents', 'developers', 'invoices', 'transactions', 'discounts', 'admins', 'tickets', 'criticisms', 'contacts_us', 'advertisements', 'announcements', 'blogs', 'learnings', 'logs', 'settings', 'bank_accounts', 'payments', 'manage_sso_clients', 'support_plan', 'dmenu', 'dkala', 'dpage', 'dmail', 'reseller', 'workspace', 'project')`);
await queryRunner.query(`ALTER TABLE "permission" ALTER COLUMN "name" TYPE "public"."permission_name_enum_old" USING "name"::"text"::"public"."permission_name_enum_old"`);
await queryRunner.query(`DROP TYPE "public"."permission_name_enum"`);
await queryRunner.query(`ALTER TYPE "public"."permission_name_enum_old" RENAME TO "permission_name_enum"`);
}
}
@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class TMaddingSomeNewPermissionsToTheEnum1783428145772 implements MigrationInterface {
name = 'TMaddingSomeNewPermissionsToTheEnum1783428145772'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TYPE "public"."permission_name_enum" RENAME TO "permission_name_enum_old"`);
await queryRunner.query(`CREATE TYPE "public"."permission_name_enum" AS ENUM('services', 'customers', 'agents', 'developers', 'invoices', 'transactions', 'discounts', 'admins', 'tickets', 'criticisms', 'contacts_us', 'advertisements', 'announcements', 'blogs', 'learnings', 'logs', 'settings', 'bank_accounts', 'payments', 'manage_sso_clients', 'support_plan', 'dmenu', 'dkala', 'dpage', 'dmail', 'reseller', 'workspace', 'view_all_workspaces', 'project', 'view_all_projects', 'task', 'task_phase', 'remark')`);
await queryRunner.query(`ALTER TABLE "permission" ALTER COLUMN "name" TYPE "public"."permission_name_enum" USING "name"::"text"::"public"."permission_name_enum"`);
await queryRunner.query(`DROP TYPE "public"."permission_name_enum_old"`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TYPE "public"."permission_name_enum_old" AS ENUM('services', 'customers', 'agents', 'developers', 'invoices', 'transactions', 'discounts', 'admins', 'tickets', 'criticisms', 'contacts_us', 'advertisements', 'announcements', 'blogs', 'learnings', 'logs', 'settings', 'bank_accounts', 'payments', 'manage_sso_clients', 'support_plan', 'dmenu', 'dkala', 'dpage', 'dmail', 'reseller', 'workspace', 'project', 'task_phase')`);
await queryRunner.query(`ALTER TABLE "permission" ALTER COLUMN "name" TYPE "public"."permission_name_enum_old" USING "name"::"text"::"public"."permission_name_enum_old"`);
await queryRunner.query(`DROP TYPE "public"."permission_name_enum"`);
await queryRunner.query(`ALTER TYPE "public"."permission_name_enum_old" RENAME TO "permission_name_enum"`);
}
}
@@ -0,0 +1,20 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class TMChangingFewLastPermissions1783759715100 implements MigrationInterface {
name = 'TMChangingFewLastPermissions1783759715100'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TYPE "public"."permission_name_enum" RENAME TO "permission_name_enum_old"`);
await queryRunner.query(`CREATE TYPE "public"."permission_name_enum" AS ENUM('services', 'customers', 'agents', 'developers', 'invoices', 'transactions', 'discounts', 'admins', 'tickets', 'criticisms', 'contacts_us', 'advertisements', 'announcements', 'blogs', 'learnings', 'logs', 'settings', 'bank_accounts', 'payments', 'manage_sso_clients', 'support_plan', 'dmenu', 'dkala', 'dpage', 'dmail', 'reseller', 'workspace', 'view_all_workspaces', 'project', 'view_all_projects', 'task', 'task_phase')`);
await queryRunner.query(`ALTER TABLE "permission" ALTER COLUMN "name" TYPE "public"."permission_name_enum" USING "name"::"text"::"public"."permission_name_enum"`);
await queryRunner.query(`DROP TYPE "public"."permission_name_enum_old"`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TYPE "public"."permission_name_enum_old" AS ENUM('admins', 'advertisements', 'agents', 'announcements', 'bank_accounts', 'blogs', 'contacts_us', 'criticisms', 'customers', 'developers', 'discounts', 'dkala', 'dmail', 'dmenu', 'dpage', 'invoices', 'learnings', 'logs', 'manage_sso_clients', 'payments', 'project', 'remark', 'reseller', 'services', 'settings', 'support_plan', 'task', 'task_phase', 'tickets', 'transactions', 'view_all_projects', 'view_all_workspaces', 'workspace')`);
await queryRunner.query(`ALTER TABLE "permission" ALTER COLUMN "name" TYPE "public"."permission_name_enum_old" USING "name"::"text"::"public"."permission_name_enum_old"`);
await queryRunner.query(`DROP TYPE "public"."permission_name_enum"`);
await queryRunner.query(`ALTER TYPE "public"."permission_name_enum_old" RENAME TO "permission_name_enum"`);
}
}
@@ -0,0 +1,14 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class AddedPriorityToTaskEntity1784014433653 implements MigrationInterface {
name = 'AddedPriorityToTaskEntity1784014433653'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "tm_tasks" ADD "priority" integer NOT NULL DEFAULT '1'`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "tm_tasks" DROP COLUMN "priority"`);
}
}
@@ -0,0 +1,39 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class AddTaskTimeTable1784100000000 implements MigrationInterface {
name = "AddTaskTimeTable1784100000000";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`
CREATE TABLE "tm_times" (
"id" uuid NOT NULL DEFAULT uuid_generate_v4(),
"createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
"startedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
"endedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
"duration" integer NOT NULL,
"adminId" uuid NOT NULL,
"taskId" uuid NOT NULL,
CONSTRAINT "PK_tm_times" PRIMARY KEY ("id")
)
`);
await queryRunner.query(`
ALTER TABLE "tm_times"
ADD CONSTRAINT "FK_tm_times_admin"
FOREIGN KEY ("adminId") REFERENCES "user"("id")
ON DELETE RESTRICT ON UPDATE NO ACTION
`);
await queryRunner.query(`
ALTER TABLE "tm_times"
ADD CONSTRAINT "FK_tm_times_task"
FOREIGN KEY ("taskId") REFERENCES "tm_tasks"("id")
ON DELETE CASCADE ON UPDATE NO ACTION
`);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`ALTER TABLE "tm_times" DROP CONSTRAINT "FK_tm_times_task"`);
await queryRunner.query(`ALTER TABLE "tm_times" DROP CONSTRAINT "FK_tm_times_admin"`);
await queryRunner.query(`DROP TABLE "tm_times"`);
}
}
@@ -0,0 +1,25 @@
import { MigrationInterface, QueryRunner } from "typeorm";
export class MakeTaskTimeEndedAtAndDurationNullable1784200000000
implements MigrationInterface
{
name = "MakeTaskTimeEndedAtAndDurationNullable1784200000000";
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "tm_times" ALTER COLUMN "endedAt" DROP NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "tm_times" ALTER COLUMN "duration" DROP NOT NULL`,
);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "tm_times" ALTER COLUMN "endedAt" SET NOT NULL`,
);
await queryRunner.query(
`ALTER TABLE "tm_times" ALTER COLUMN "duration" SET NOT NULL`,
);
}
}
+19 -4
View File
@@ -1,11 +1,21 @@
import { ApiPropertyOptional } from "@nestjs/swagger"; import { ApiPropertyOptional } from "@nestjs/swagger";
import { Type } from "class-transformer"; import { Type } from "class-transformer";
import { IsInt, IsISO8601, IsOptional, Max, Min } from "class-validator"; import { IsEnum, IsInt, IsOptional, IsString, Max, Min } from "class-validator";
export enum CursorDirection {
NEXT = "next",
PREV = "prev",
}
export class CursorPaginationDto { export class CursorPaginationDto {
@IsOptional() @IsOptional()
@IsISO8601() @IsString()
@ApiPropertyOptional({ type: "string", description: "Cursor (createdAt of last seen item)", example: "2026-07-01T10:00:00.000Z" }) @ApiPropertyOptional({
type: "string",
description:
"Base64encoded cursor containing the priority, createdAt (ISO) and id of the last seen item. Leave empty for the first page.",
example: "MjAyNi0wNy0wMVQxMDowMDowMC4wMDBafDU=",
})
cursor?: string; cursor?: string;
@IsOptional() @IsOptional()
@@ -15,4 +25,9 @@ export class CursorPaginationDto {
@Type(() => Number) @Type(() => Number)
@ApiPropertyOptional({ type: "number", required: false, default: 10 }) @ApiPropertyOptional({ type: "number", required: false, default: 10 })
limit?: number; limit?: number;
}
@IsOptional()
@IsEnum(CursorDirection)
@ApiPropertyOptional({ enum: CursorDirection, default: CursorDirection.NEXT, description: "Direction to page in relative to 'cursor'." })
direction?: CursorDirection;
}
@@ -0,0 +1,29 @@
import { applyDecorators } from "@nestjs/common";
import { ApiQuery } from "@nestjs/swagger";
import { CursorDirection } from "../DTO/cursor-pagination.dto";
export function CursorPagination() {
return applyDecorators(
ApiQuery({
name: "cursor",
required: false,
type: "string",
description: "Base64encoded cursor of the last item (contains priority, createdAt and id). Leave empty for the first page.",
example: "MjAyNi0wNy0wMVQxMDowMDowMC4wMDBafDU=",
}),
ApiQuery({
name: "limit",
required: false,
type: "number",
description: "Number of items per page (max 50)",
example: 10,
}),
ApiQuery({
name: "direction",
required: false,
enum: CursorDirection,
description: "Direction to page in relative to 'cursor': 'next' (default) or 'prev'.",
example: CursorDirection.NEXT,
}),
);
}
+37 -2
View File
@@ -920,11 +920,46 @@ export const enum WorkSpaceMessage {
WORKSPACE_EXISTS = "فضای کار با این اسم وجود دارد!", WORKSPACE_EXISTS = "فضای کار با این اسم وجود دارد!",
WORKSPACE_NOT_FOUND = "فضای کار مورد نظر شما وجود ندارد!", WORKSPACE_NOT_FOUND = "فضای کار مورد نظر شما وجود ندارد!",
USERS_DONT_BELONG_TO_THIS_WORKSPACE = "کاربران تعیین شده برای این فضای کاری نیستند!", USERS_DONT_BELONG_TO_THIS_WORKSPACE = "کاربران تعیین شده برای این فضای کاری نیستند!",
WORKSPACE_SAME_NAME_EXISTS = "فضای کاری با این اسم از قبل وجود دارد!" WORKSPACE_SAME_NAME_EXISTS = "فضای کاری با این اسم از قبل وجود دارد!",
WORKSPACE_ID_PARAM_NOT_EMPTY = "پارامتر شناسه فضای کار نباید خالی باشد!",
WORKSPACE_ID_UUID = "شناسه فضای کار باید uuid باشد",
FORBIDDEN = "شما اجازه دسترسی به این فضای کار را ندارید و یا عضو آن نیستید!"
} }
export const enum ProjectMessage { export const enum ProjectMessage {
PROJECT_EXISTS = "پروژه مورد نظر شما از قبل وجود دارد!", PROJECT_EXISTS = "پروژه مورد نظر شما از قبل وجود دارد!",
PROJECT_NOT_FOUND = "پروژه مورد نظر شما وجود ندارد!", PROJECT_NOT_FOUND = "پروژه مورد نظر شما وجود ندارد!",
PROJECT_CONTAINS_TASK_PHASES = "پروژه شامل فاز تسک است. لطفا ابتدا فاز تسک های این پروژه را حذف کنید." PROJECT_CONTAINS_TASK_PHASES = "پروژه شامل فاز تسک است. لطفا ابتدا فاز تسک های این پروژه را حذف کنید.",
NOT_MEMBER_OF_PROJECT = "شما عضو این پروژه نیستید!",
}
export const enum TaskPhaseMessage {
TASK_PHASE_NOT_FOUND = "فاز تسک مورد نظر پیدا نشد!",
TASK_PHASE_NOT_SAME_PROJECT = "فاز تسک جدید با فاز تسک قبلی در یک پروژه نیستند!"
}
export const enum TaskMessage {
TASK_NOT_FOUND = "تسک مورد نظر پیدا نشد!",
USERS_ASSIGNED_TO_TASK_NOT_PROJECT_MEMBER = "حداقل یکی از کاربران تعیین شده عضو پروژه نیستند!",
USER_NOT_TASK_MEMBER = "شما عضو این تسک نیستید!",
TASKS_NOT_IN_THE_SAME_TASK_PHASE = "تسک های مورد نظر داخل یک فاز تسک یکسان نیستند!"
}
export const enum remarkMessage {
REMARK_NOT_FOUND = "برچسب مورد نظر پیدا نشد!"
}
export const enum checkListItemMessage {
CHECKLISTITEM_NOT_FOUND = "آیتم چک لیست پیدا نشد!"
}
export const enum attachmentMessage {
ATTACHMENT_NOT_FOUND = "ضمیمه پیدا نشد!"
}
export const enum timeMessage {
TIME_NOT_FOUND = "زمان ثبت شده پیدا نشد!",
INVALID_TIME_RANGE = "زمان پایان باید بعد از زمان شروع باشد!",
TIME_ALREADY_STARTED = "برای این تسک یک زمان در حال اجرا وجود دارد!",
NO_RUNNING_TIME = "زمان در حال اجرایی برای این تسک پیدا نشد!"
} }
@@ -1,25 +0,0 @@
import { CursorPaginatedResult } from "../interfaces/cursor-paginated-result.interface";
export function buildCursorPageFormat<T extends { createdAt: Date }>(
data: T[],
limit: number,
previousCursor?: Date,
): CursorPaginatedResult<T> {
const hasMore = data.length > limit;
if (hasMore) data.pop();
const nextCursor = hasMore ? data[data.length - 1].createdAt.toISOString() : null;
const prevCursor = previousCursor ? previousCursor.toISOString() : null;
return {
data,
meta: {
nextCursor,
prevCursor,
hasMore,
limit,
},
};
}
@@ -0,0 +1,7 @@
export interface ICursorPageFormat {
limit: number;
nextCursor: string | null;
previousCursor: string | null;
hasNextPage: boolean;
hasPreviousPage: boolean;
}
@@ -1,9 +0,0 @@
export interface CursorPaginatedResult<T> {
data: T[];
meta: {
nextCursor: string | null;
prevCursor: string | null;
hasMore: boolean;
limit: number;
};
}
@@ -3,6 +3,7 @@ import { FastifyRequest } from "fastify";
import { Observable, map } from "rxjs"; import { Observable, map } from "rxjs";
import { IPageFormat } from "../../common/interfaces/IPagination"; import { IPageFormat } from "../../common/interfaces/IPagination";
import { ICursorPageFormat } from "../../common/interfaces/ICursor-pagination";
@Injectable() @Injectable()
export class PaginationInterceptor implements NestInterceptor { export class PaginationInterceptor implements NestInterceptor {
@@ -10,7 +11,11 @@ export class PaginationInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> { intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
const request = context.switchToHttp().getRequest<FastifyRequest>(); const request = context.switchToHttp().getRequest<FastifyRequest>();
const query = request.query as { page: string; limit: string }; const query = request.query as {
page: string;
limit: string;
cursor?: string; // for cursor pagination
};
const page = parseInt(query.page, 10) || 1; const page = parseInt(query.page, 10) || 1;
const limit = parseInt(query.limit, 10) || 10; const limit = parseInt(query.limit, 10) || 10;
@@ -20,17 +25,40 @@ export class PaginationInterceptor implements NestInterceptor {
return next.handle().pipe( return next.handle().pipe(
map((data) => { map((data) => {
// ---------- Offset (pagebased) pagination ----------
if (data && (data.paginate || data.count)) { if (data && (data.paginate || data.count)) {
const { count, paginate, ...response } = data; const { count, paginate, ...response } = data;
this.logger.log(`paginate response from ${className}.${handlerName}`); this.logger.log(`offset paginate response from ${className}.${handlerName}`);
const pager = this.formatPage(page, limit, count, request); const pager = this.formatPage(page, limit, count, request);
return { pager, ...response };
return {
pager,
...response,
};
} }
// ---------- Cursorbased pagination ----------
if (data && data.cursorPaginate === true) {
const {
data: items,
nextCursor,
previousCursor,
hasNextPage,
hasPreviousPage,
cursorPaginate,
...rest
} = data;
this.logger.log(`cursor paginate response from ${className}.${handlerName}`);
const pager: ICursorPageFormat = {
limit,
nextCursor,
previousCursor,
hasNextPage,
hasPreviousPage,
};
return { items, pager, ...rest };
}
// ---------- No pagination ----------
return data; return data;
}), }),
); );
@@ -1,33 +1,19 @@
import { Controller, Get, Post, Patch, Delete, Param, Body, Query } from '@nestjs/common'; import { Controller, Post, Patch, Delete, Param, Body } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger'; import { ApiTags, ApiOperation, ApiResponse, ApiParam } from '@nestjs/swagger';
import { AttachmentService } from '../providers/attachment.service'; import { AttachmentService } from '../providers/attachment.service';
import { CreateAttachmentDto } from '../dto/attachment/create-attachment.dto'; import { CreateAttachmentDto } from '../dto/attachment/create-attachment.dto';
import { UpdateAttachmentDto } from '../dto/attachment/update-attachment.dto'; import { UpdateAttachmentDto } from '../dto/attachment/update-attachment.dto';
import { TMAttachment } from '../entities/attachment.entity'; import { TMAttachment } from '../entities/attachment.entity';
import { AuthGuards } from '../../../common/decorators/auth-guard.decorator';
import { AdminRoute } from '../../../common/decorators/admin.decorator';
@AuthGuards()
@AdminRoute()
@ApiTags('Task Manager - Attachments') @ApiTags('Task Manager - Attachments')
@Controller('task-manager/attachments') @Controller('task-manager/attachments')
export class AttachmentController { export class AttachmentController {
constructor(private readonly attachmentService: AttachmentService) {} constructor(private readonly attachmentService: AttachmentService) {}
@Get()
@ApiOperation({ summary: 'Get all attachments, optionally filtered by task' })
@ApiQuery({ name: 'taskId', required: false, description: 'Filter attachments by task ID' })
@ApiResponse({ status: 200, description: 'List of attachments', type: [TMAttachment] })
findAll(@Query('taskId') taskId?: string): Promise<TMAttachment[]> {
if (taskId) return this.attachmentService.findByTask(taskId);
return this.attachmentService.findAll();
}
@Get(':id')
@ApiOperation({ summary: 'Get an attachment by ID' })
@ApiParam({ name: 'id', description: 'Attachment ID' })
@ApiResponse({ status: 200, description: 'Attachment found', type: TMAttachment })
@ApiResponse({ status: 404, description: 'Attachment not found' })
findOne(@Param('id') id: string): Promise<TMAttachment> {
return this.attachmentService.findOne(id);
}
@Post() @Post()
@ApiOperation({ summary: 'Create a new attachment' }) @ApiOperation({ summary: 'Create a new attachment' })
@ApiResponse({ status: 201, description: 'Attachment created', type: TMAttachment }) @ApiResponse({ status: 201, description: 'Attachment created', type: TMAttachment })
@@ -1,36 +1,20 @@
import { Controller, Get, Post, Patch, Delete, Param, Body, Query } from "@nestjs/common"; import { Controller, Post, Patch, Delete, Param, Body } from "@nestjs/common";
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from "@nestjs/swagger"; import { ApiTags, ApiOperation, ApiResponse, ApiParam } from "@nestjs/swagger";
import { CheckListItemService } from "../providers/check-list-item.service"; import { CheckListItemService } from "../providers/check-list-item.service";
import { CreateCheckListItemDto } from "../dto/check-list-item/create-check-list-item.dto"; import { CreateCheckListItemDto } from "../dto/check-list-item/create-check-list-item.dto";
import { UpdateCheckListItemDto } from "../dto/check-list-item/update-check-list-item.dto"; import { UpdateCheckListItemDto } from "../dto/check-list-item/update-check-list-item.dto";
import { CursorPaginationDto } from "../../../common/DTO/cursor-pagination.dto";
import { TMCheckListItem } from "../entities/check-list-item.entity"; import { TMCheckListItem } from "../entities/check-list-item.entity";
import { AuthGuards } from "../../../common/decorators/auth-guard.decorator";
import { AdminRoute } from "../../../common/decorators/admin.decorator";
import { ParamDto } from "../../../common/DTO/param.dto";
@AuthGuards()
@AdminRoute()
@ApiTags("Task Manager - Check List Items") @ApiTags("Task Manager - Check List Items")
@Controller("task-manager/check-list-items") @Controller("task-manager/check-list-items")
export class CheckListItemController { export class CheckListItemController {
constructor(private readonly checkListItemService: CheckListItemService) {} constructor(private readonly checkListItemService: CheckListItemService) {}
@Get()
@ApiOperation({ summary: "Get all check list items, optionally filtered by task" })
@ApiQuery({ name: "taskId", required: false, description: "Filter check list items by task ID" })
@ApiQuery({ name: "cursor", required: false, description: "Cursor for pagination (createdAt ISO string)" })
@ApiQuery({ name: "limit", required: false, description: "Number of records to return (max 50)" })
@ApiResponse({ status: 200, description: "Cursor-paginated list of check list items" })
findAll(@Query() pagination: CursorPaginationDto, @Query("taskId") taskId?: string) {
if (taskId) return this.checkListItemService.findByTask(taskId, pagination);
return this.checkListItemService.findAll(pagination);
}
@Get(":id")
@ApiOperation({ summary: "Get a check list item by ID" })
@ApiParam({ name: "id", description: "CheckListItem ID" })
@ApiResponse({ status: 200, description: "CheckListItem found", type: TMCheckListItem })
@ApiResponse({ status: 404, description: "CheckListItem not found" })
findOne(@Param("id") id: string): Promise<TMCheckListItem> {
return this.checkListItemService.findOne(id);
}
@Post() @Post()
@ApiOperation({ summary: "Create a new check list item" }) @ApiOperation({ summary: "Create a new check list item" })
@ApiResponse({ status: 201, description: "CheckListItem created", type: TMCheckListItem }) @ApiResponse({ status: 201, description: "CheckListItem created", type: TMCheckListItem })
@@ -56,4 +40,13 @@ export class CheckListItemController {
remove(@Param("id") id: string): Promise<TMCheckListItem> { remove(@Param("id") id: string): Promise<TMCheckListItem> {
return this.checkListItemService.remove(id); return this.checkListItemService.remove(id);
} }
@Patch("change-status/:id")
@ApiOperation({summary: "change status of a check list item."})
@ApiParam({name: "id", description: "CheckListItem ID"})
@ApiResponse({status: 200, description: "successfully changed the status!"})
@ApiResponse({ status: 404, description: "CheckListItem not found" })
changeStatus(@Param() paramDto: ParamDto) {
return this.checkListItemService.toggleStatus(paramDto.id);
}
} }
@@ -8,28 +8,24 @@ import { TMProject } from "../entities/project.entity";
import { AdminRoute } from "../../../common/decorators/admin.decorator"; import { AdminRoute } from "../../../common/decorators/admin.decorator";
import { PermissionsDec } from "../../../common/decorators/permission.decorator"; import { PermissionsDec } from "../../../common/decorators/permission.decorator";
import { PermissionEnum } from "../../users/enums/permission.enum"; import { PermissionEnum } from "../../users/enums/permission.enum";
import { UserDec } from "../../../common/decorators/user.decorator";
import { AuthGuards } from "../../../common/decorators/auth-guard.decorator";
import { ParamDto } from "../../../common/DTO/param.dto";
import { ITokenPayload } from "../../auth/interfaces/IToken-payload";
@AuthGuards()
@AdminRoute() @AdminRoute()
@ApiTags("Task Manager - Projects") @ApiTags("Task Manager - Projects")
@Controller("task-manager/projects") @Controller("task-manager/projects")
export class ProjectController { export class ProjectController {
constructor(private readonly projectService: ProjectService) {} constructor(private readonly projectService: ProjectService) {}
@Get() @Get(':id')
@PermissionsDec(PermissionEnum.PROJECT) @ApiOperation({summary: 'Get one project by ID'})
@ApiOperation({ summary: "Get all projects, optionally filtered by workspace" }) @ApiResponse({status: 200, description: 'received the project successfully!'})
@ApiResponse({ status: 200, description: "Paginated list of projects" }) @ApiResponse({status: 404, description: 'Project Not Found!'})
findAll(@Query() pagination: PaginationDto): Promise<{ projects: TMProject[]; count: number; paginate: true }> { @ApiResponse({status: 400, description: 'Bad Request!'})
return this.projectService.findAll(pagination); findOne(@Param('id') id: string) {
}
@Get(":id")
@PermissionsDec(PermissionEnum.PROJECT)
@ApiOperation({ summary: "Get a project by ID" })
@ApiParam({ name: "id", description: "Project ID" })
@ApiResponse({ status: 200, description: "Project found", type: TMProject })
@ApiResponse({ status: 404, description: "Project not found" })
findOne(@Param("id") id: string): Promise<TMProject> {
return this.projectService.findOneOrFail(id); return this.projectService.findOneOrFail(id);
} }
@@ -64,16 +60,24 @@ export class ProjectController {
return this.projectService.remove(id); return this.projectService.remove(id);
} }
@Get("/workspace/:wsId") @Get("user/workspace/:id")
@PermissionsDec(PermissionEnum.PROJECT) @ApiOperation({ summary: "Get user projects in a specific workspace!" })
@ApiOperation({ summary: "Get projects of a specific workspace" }) @ApiResponse({ status: 200, description: "Got user projects successfully!" })
@ApiParam({ name: "wsId", description: "Workspace ID" }) @ApiResponse({ status: 400, description: "Bad Request!" })
@ApiResponse({ status: 200, description: "received projects successfully!" }) findUserProjectsByWorkspace(
@ApiResponse({ status: 404, description: "WorkSpace not found" }) @UserDec() user: ITokenPayload,
findByWorkspace( @Param() paramDto: ParamDto,
@Param("wsId") wsId: string,
@Query() pagination: PaginationDto, @Query() pagination: PaginationDto,
): Promise<{ projects: TMProject[]; count: number; paginate: true }> { ): Promise<{ projects: TMProject[]; count: number; paginate: true }> {
return this.projectService.findByWorkspace(wsId, pagination); return this.projectService.findUserProjectsByWorkspace(user.id, user.permissions, paramDto.id, pagination);
}
@Get("detail/:id")
@ApiOperation({ summary: "Get project detail" })
@ApiResponse({ status: 200, description: "Got Project Detail Successfully!" })
@ApiResponse({ status: 400, description: "Bad request!" })
@ApiResponse({ status: 404, description: "The project was not found!" })
getProjectDetail(@Param() paramDto: ParamDto, @UserDec() user: ITokenPayload): Promise<TMProject | null> {
return this.projectService.getProjectDetail(paramDto.id, user.id, user.permissions);
} }
} }
@@ -1,33 +1,19 @@
import { Controller, Get, Post, Patch, Delete, Param, Body, Query } from "@nestjs/common"; import { Controller, Post, Patch, Delete, Param, Body } from "@nestjs/common";
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from "@nestjs/swagger"; import { ApiTags, ApiOperation, ApiResponse, ApiParam } from "@nestjs/swagger";
import { RemarkService } from "../providers/remark.service"; import { RemarkService } from "../providers/remark.service";
import { CreateRemarkDto } from "../dto/remark/create-remark.dto"; import { CreateRemarkDto } from "../dto/remark/create-remark.dto";
import { UpdateRemarkDto } from "../dto/remark/update-remark.dto"; import { UpdateRemarkDto } from "../dto/remark/update-remark.dto";
import { TMRemark } from "../entities/remark.entity"; import { TMRemark } from "../entities/remark.entity";
import { AuthGuards } from "../../../common/decorators/auth-guard.decorator";
import { AdminRoute } from "../../../common/decorators/admin.decorator";
@AuthGuards()
@AdminRoute()
@ApiTags("Task Manager - Remarks") @ApiTags("Task Manager - Remarks")
@Controller("task-manager/remarks") @Controller("task-manager/remarks")
export class RemarkController { export class RemarkController {
constructor(private readonly remarkService: RemarkService) {} constructor(private readonly remarkService: RemarkService) {}
@Get()
@ApiOperation({ summary: "Get all remarks, optionally filtered by task" })
@ApiQuery({ name: "taskId", required: false, description: "Filter remarks by task ID" })
@ApiResponse({ status: 200, description: "List of remarks", type: [TMRemark] })
findAll(@Query("taskId") taskId?: string): Promise<TMRemark[]> {
if (taskId) return this.remarkService.findByTask(taskId);
return this.remarkService.findAll();
}
@Get(":id")
@ApiOperation({ summary: "Get a remark by ID" })
@ApiParam({ name: "id", description: "Remark ID" })
@ApiResponse({ status: 200, description: "Remark found", type: TMRemark })
@ApiResponse({ status: 404, description: "Remark not found" })
findOne(@Param("id") id: string): Promise<TMRemark> {
return this.remarkService.findOne(id);
}
@Post() @Post()
@ApiOperation({ summary: "Create a new remark" }) @ApiOperation({ summary: "Create a new remark" })
@ApiResponse({ status: 201, description: "Remark created", type: TMRemark }) @ApiResponse({ status: 201, description: "Remark created", type: TMRemark })
@@ -1,33 +1,22 @@
import { Controller, Get, Post, Patch, Delete, Param, Body, Query } from "@nestjs/common"; import { Controller, Post, Patch, Delete, Param, Body } from "@nestjs/common";
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from "@nestjs/swagger"; import { ApiTags, ApiOperation, ApiResponse, ApiParam } from "@nestjs/swagger";
import { TaskPhaseService } from "../providers/task-phase.service"; import { TaskPhaseService } from "../providers/task-phase.service";
import { CreateTaskPhaseDto } from "../dto/task-phase/create-task-phase.dto"; import { CreateTaskPhaseDto } from "../dto/task-phase/create-task-phase.dto";
import { UpdateTaskPhaseDto } from "../dto/task-phase/update-task-phase.dto"; import { UpdateTaskPhaseDto } from "../dto/task-phase/update-task-phase.dto";
import { TMTaskPhase } from "../entities/task-phase.entity"; import { TMTaskPhase } from "../entities/task-phase.entity";
import { AuthGuards } from "../../../common/decorators/auth-guard.decorator";
import { AdminRoute } from "../../../common/decorators/admin.decorator";
import { PermissionsDec } from "../../../common/decorators/permission.decorator";
import { PermissionEnum } from "../../users/enums/permission.enum";
@AuthGuards()
@AdminRoute()
@PermissionsDec(PermissionEnum.TASK_PHASE)
@ApiTags("Task Manager - Task Phases") @ApiTags("Task Manager - Task Phases")
@Controller("task-manager/task-phases") @Controller("task-manager/task-phases")
export class TaskPhaseController { export class TaskPhaseController {
constructor(private readonly taskPhaseService: TaskPhaseService) {} constructor(private readonly taskPhaseService: TaskPhaseService) {}
@Get()
@ApiOperation({ summary: "Get all task phases, optionally filtered by project" })
@ApiQuery({ name: "projectId", required: false, description: "Filter task phases by project ID" })
@ApiResponse({ status: 200, description: "List of task phases", type: [TMTaskPhase] })
findAll(@Query("projectId") projectId?: string): Promise<TMTaskPhase[]> {
if (projectId) return this.taskPhaseService.findByProject(projectId);
return this.taskPhaseService.findAll();
}
@Get(":id")
@ApiOperation({ summary: "Get a task phase by ID" })
@ApiParam({ name: "id", description: "TaskPhase ID" })
@ApiResponse({ status: 200, description: "TaskPhase found", type: TMTaskPhase })
@ApiResponse({ status: 404, description: "TaskPhase not found" })
findOne(@Param("id") id: string): Promise<TMTaskPhase> {
return this.taskPhaseService.findOne(id);
}
@Post() @Post()
@ApiOperation({ summary: "Create a new task phase" }) @ApiOperation({ summary: "Create a new task phase" })
@ApiResponse({ status: 201, description: "TaskPhase created", type: TMTaskPhase }) @ApiResponse({ status: 201, description: "TaskPhase created", type: TMTaskPhase })
@@ -1,67 +1,104 @@
import { Controller, Get, Post, Patch, Delete, Param, Body, Query } from '@nestjs/common'; import { Controller, Get, Post, Patch, Delete, Param, Body, Query } from "@nestjs/common";
import { ApiTags, ApiOperation, ApiResponse, ApiParam, ApiQuery } from '@nestjs/swagger'; import { ApiTags, ApiOperation, ApiResponse, ApiParam } from "@nestjs/swagger";
import { TaskService } from '../providers/task.service'; import { TaskService } from "../providers/task.service";
import { CreateTaskDto } from '../dto/task/create-task.dto'; import { CreateTaskDto } from "../dto/task/create-task.dto";
import { UpdateTaskDto } from '../dto/task/update-task.dto'; import { UpdateTaskDto } from "../dto/task/update-task.dto";
import { ChangeTaskPhaseDto } from '../dto/task/change-task-phase.dto'; import { ChangeTaskPhaseDto } from "../dto/task/change-task-phase.dto";
import { TMTask } from '../entities/task.entity'; import { TMTask } from "../entities/task.entity";
import { AuthGuards } from "../../../common/decorators/auth-guard.decorator";
import { AdminRoute } from "../../../common/decorators/admin.decorator";
import { UserDec } from "../../../common/decorators/user.decorator";
import { ParamDto } from "../../../common/DTO/param.dto";
import { PermissionsDec } from "../../../common/decorators/permission.decorator";
import { PermissionEnum } from "../../users/enums/permission.enum";
import { ITokenPayload } from "../../auth/interfaces/IToken-payload";
import { CursorPagination } from "../../../common/decorators/cursor-pagination.decorator";
import { CursorPaginationDto } from "../../../common/DTO/cursor-pagination.dto";
@ApiTags('Task Manager - Tasks') @AuthGuards()
@Controller('task-manager/tasks') @AdminRoute()
@ApiTags("Task Manager - Tasks")
@Controller("task-manager/tasks")
export class TaskController { export class TaskController {
constructor(private readonly taskService: TaskService) {} constructor(private readonly taskService: TaskService) {}
@Get()
@ApiOperation({ summary: 'Get all tasks, optionally filtered by phase' })
@ApiQuery({ name: 'taskPhaseId', required: false, description: 'Filter tasks by task phase ID' })
@ApiResponse({ status: 200, description: 'List of tasks', type: [TMTask] })
findAll(@Query('taskPhaseId') taskPhaseId?: string): Promise<TMTask[]> {
if (taskPhaseId) return this.taskService.findByPhase(taskPhaseId);
return this.taskService.findAll();
}
@Get(':id')
@ApiOperation({ summary: 'Get a task by ID' })
@ApiParam({ name: 'id', description: 'Task ID' })
@ApiResponse({ status: 200, description: 'Task found', type: TMTask })
@ApiResponse({ status: 404, description: 'Task not found' })
findOne(@Param('id') id: string): Promise<TMTask> {
return this.taskService.findOne(id);
}
@Post() @Post()
@ApiOperation({ summary: 'Create a new task' }) @PermissionsDec(PermissionEnum.TASK)
@ApiResponse({ status: 201, description: 'Task created', type: TMTask }) @ApiOperation({ summary: "Create a new task" })
@ApiResponse({ status: 404, description: 'TaskPhase not found' }) @ApiResponse({ status: 201, description: "Task created", type: TMTask })
@ApiResponse({ status: 404, description: "TaskPhase not found" })
create(@Body() body: CreateTaskDto): Promise<TMTask> { create(@Body() body: CreateTaskDto): Promise<TMTask> {
return this.taskService.create(body); return this.taskService.create(body);
} }
@Patch(':id') @Patch(":id")
@ApiOperation({ summary: 'Update a task' }) @PermissionsDec(PermissionEnum.TASK)
@ApiParam({ name: 'id', description: 'Task ID' }) @ApiOperation({ summary: "Update a task" })
@ApiResponse({ status: 200, description: 'Task updated', type: TMTask }) @ApiParam({ name: "id", description: "Task ID" })
@ApiResponse({ status: 404, description: 'Task or TaskPhase not found' }) @ApiResponse({ status: 200, description: "Task updated", type: TMTask })
update(@Param('id') id: string, @Body() body: UpdateTaskDto): Promise<TMTask> { @ApiResponse({ status: 404, description: "Task or TaskPhase not found" })
update(@Param("id") id: string, @Body() body: UpdateTaskDto): Promise<TMTask> {
return this.taskService.update(id, body); return this.taskService.update(id, body);
} }
@Patch(':id/change-phase') @Patch(":id/change-phase")
@ApiOperation({ summary: 'Move a task to a different phase within the same project' }) @PermissionsDec(PermissionEnum.TASK)
@ApiParam({ name: 'id', description: 'Task ID' }) @ApiOperation({ summary: "Move a task to a different phase within the same project" })
@ApiResponse({ status: 200, description: 'Task phase changed', type: TMTask }) @ApiParam({ name: "id", description: "Task ID" })
@ApiResponse({ status: 400, description: 'Target phase belongs to a different project' }) @ApiResponse({ status: 200, description: "Task phase changed", type: TMTask })
@ApiResponse({ status: 404, description: 'Task or TaskPhase not found' }) @ApiResponse({ status: 400, description: "Target phase belongs to a different project" })
changePhase(@Param('id') id: string, @Body() body: ChangeTaskPhaseDto): Promise<TMTask> { @ApiResponse({ status: 404, description: "Task or TaskPhase not found" })
changePhase(@Param("id") id: string, @Body() body: ChangeTaskPhaseDto): Promise<TMTask> {
return this.taskService.changePhase(id, body); return this.taskService.changePhase(id, body);
} }
@Delete(':id') @Delete(":id")
@ApiOperation({ summary: 'Delete a task' }) @PermissionsDec(PermissionEnum.TASK)
@ApiParam({ name: 'id', description: 'Task ID' }) @ApiOperation({ summary: "Delete a task" })
@ApiResponse({ status: 200, description: 'Task deleted' }) @ApiParam({ name: "id", description: "Task ID" })
@ApiResponse({ status: 404, description: 'Task not found' }) @ApiResponse({ status: 200, description: "Task deleted" })
remove(@Param('id') id: string): Promise<void> { @ApiResponse({ status: 404, description: "Task not found" })
remove(@Param("id") id: string): Promise<void> {
return this.taskService.remove(id); return this.taskService.remove(id);
} }
}
@Get("detail/:id")
@ApiOperation({ summary: "Get Task Detail" })
@ApiParam({ name: "id", description: "Task ID" })
@ApiResponse({ status: 200, description: "Task detail received!" })
@ApiResponse({ status: 404, description: "Task not found" })
getTaskDetail(@UserDec() user: ITokenPayload, @Param() paramDto: ParamDto): Promise<TMTask | null> {
return this.taskService.getTaskDetail(user.id, user.permissions, paramDto.id);
}
@Get("task-phase/:id")
@ApiOperation({ summary: "Get Tasks by task phase" })
@ApiParam({ name: "id", description: "Task phase id" })
@ApiResponse({ status: 200, description: "Got Tasks by task phase successfully!" })
@ApiResponse({ status: 400, description: "Bad request from user." })
@CursorPagination()
findByTaskPhase(
@Param("id") taskPhaseId: string,
@Query() pagination: CursorPaginationDto,
): Promise<{
data: TMTask[];
nextCursor: string | null;
previousCursor: string | null;
hasNextPage: boolean;
hasPreviousPage: boolean;
cursorPaginate: true;
}> {
return this.taskService.findTasksByTaskPhase(taskPhaseId, pagination);
}
@Patch("change-priority/:srcid/:desid")
@ApiOperation({ summary: "changing the task priority" })
@ApiParam({ name: "srcid", description: "ID of the source task" })
@ApiParam({ name: "desid", description: "ID of the destination task" })
@ApiResponse({ status: 200, description: "Changed the task priority successfully!" })
@ApiResponse({ status: 400, description: "Bad Request from user." })
@ApiResponse({ status: 404, description: "Task not found!" })
changePriority(@Param("srcid") srcId: string, @Param("desid") desId: string): Promise<TMTask> {
return this.taskService.changePriority(srcId, desId);
}
}
@@ -0,0 +1,69 @@
import { Controller, Post, Patch, Delete, Param, Body, Get } from "@nestjs/common";
import { ApiTags, ApiOperation, ApiResponse, ApiParam } from "@nestjs/swagger";
import { TimeService } from "../providers/time.service";
import { CreateTimeDto } from "../dto/time/create-time.dto";
import { UpdateTimeDto } from "../dto/time/update-time.dto";
import { TMTime } from "../entities/time.entity";
import { AuthGuards } from "../../../common/decorators/auth-guard.decorator";
import { AdminRoute } from "../../../common/decorators/admin.decorator";
import { UserDec } from "../../../common/decorators/user.decorator";
@AuthGuards()
@AdminRoute()
@ApiTags("Task Manager - Times")
@Controller("task-manager/times")
export class TimeController {
constructor(private readonly timeService: TimeService) { }
@Get("task/:taskId")
@ApiOperation({ summary: "Get all time entries for a task" })
@ApiParam({ name: "taskId", description: "Task ID" })
getTaskTimes(@UserDec("id") adminId: string, @Param("taskId") taskId: string): Promise<TMTime[]> {
return this.timeService.getTaskTimes(adminId, taskId);
}
@Post()
@ApiOperation({ summary: "Create a new time entry for a task" })
@ApiResponse({ status: 201, description: "Time entry created", type: TMTime })
@ApiResponse({ status: 404, description: "Task not found" })
create(@UserDec("id") adminId: string, @Body() body: CreateTimeDto): Promise<TMTime> {
return this.timeService.create(adminId, body);
}
@Post("start/:taskId")
@ApiOperation({ summary: "Start tracking time for a task" })
@ApiParam({ name: "taskId", description: "Task ID" })
@ApiResponse({ status: 201, description: "Time tracking started", type: TMTime })
@ApiResponse({ status: 400, description: "A running time entry already exists" })
@ApiResponse({ status: 404, description: "Task not found" })
start(@UserDec("id") adminId: string, @Param("taskId") taskId: string): Promise<TMTime> {
return this.timeService.start(adminId, taskId);
}
@Post("end/:taskId")
@ApiOperation({ summary: "Stop the current running time entry for a task" })
@ApiParam({ name: "taskId", description: "Task ID" })
@ApiResponse({ status: 200, description: "Time tracking stopped", type: TMTime })
@ApiResponse({ status: 400, description: "No running time entry found" })
@ApiResponse({ status: 404, description: "Task not found" })
end(@UserDec("id") adminId: string, @Param("taskId") taskId: string): Promise<TMTime> {
return this.timeService.end(adminId, taskId);
}
@Patch(":id")
@ApiOperation({ summary: "Update a time entry" })
@ApiParam({ name: "id", description: "Time entry ID" })
@ApiResponse({ status: 200, description: "Time entry updated", type: TMTime })
@ApiResponse({ status: 404, description: "Time entry or Task not found" })
update(@Param("id") id: string, @Body() body: UpdateTimeDto): Promise<TMTime> {
return this.timeService.update(id, body);
}
@Delete(":id")
@ApiOperation({ summary: "Delete a time entry" })
@ApiParam({ name: "id", description: "Time entry ID" })
@ApiResponse({ status: 200, description: "Time entry deleted" })
@ApiResponse({ status: 404, description: "Time entry not found" })
remove(@Param("id") id: string): Promise<void> {
return this.timeService.remove(id);
}
}
@@ -4,12 +4,12 @@ import { WorkspaceService } from '../providers/workspace.service';
import { CreateWorkspaceDto } from '../dto/workspace/create-workspace.dto'; import { CreateWorkspaceDto } from '../dto/workspace/create-workspace.dto';
import { UpdateWorkspaceDto } from '../dto/workspace/update-workspace.dto'; import { UpdateWorkspaceDto } from '../dto/workspace/update-workspace.dto';
import { TMWorkspace } from '../entities/workspace.entity'; import { TMWorkspace } from '../entities/workspace.entity';
// import { AuthGuards } from '../../../common/decorators/auth-guard.decorator';
import { AdminRoute } from '../../../common/decorators/admin.decorator'; import { AdminRoute } from '../../../common/decorators/admin.decorator';
import { PermissionsDec } from '../../../common/decorators/permission.decorator'; import { PermissionsDec } from '../../../common/decorators/permission.decorator';
import { PermissionEnum } from '../../users/enums/permission.enum'; import { PermissionEnum } from '../../users/enums/permission.enum';
import { UserDec } from '../../../common/decorators/user.decorator'; import { UserDec } from '../../../common/decorators/user.decorator';
import { AuthGuards } from '../../../common/decorators/auth-guard.decorator'; import { AuthGuards } from '../../../common/decorators/auth-guard.decorator';
import { ITokenPayload } from '../../auth/interfaces/IToken-payload';
@AuthGuards() @AuthGuards()
@AdminRoute() @AdminRoute()
@@ -18,20 +18,12 @@ import { AuthGuards } from '../../../common/decorators/auth-guard.decorator';
export class WorkspaceController { export class WorkspaceController {
constructor(private readonly workspaceService: WorkspaceService) {} constructor(private readonly workspaceService: WorkspaceService) {}
@Get()
@PermissionsDec(PermissionEnum.WORKSPACE)
@ApiOperation({ summary: 'Get all workspaces' })
@ApiResponse({ status: 200, description: 'List of workspaces', type: [TMWorkspace] })
findAll(): Promise<TMWorkspace[]> {
return this.workspaceService.findAll();
}
@Get(':id') @Get(':id')
@PermissionsDec(PermissionEnum.WORKSPACE) @PermissionsDec(PermissionEnum.WORKSPACE)
@ApiOperation({ summary: 'Get a workspace by ID' }) @ApiOperation({summary: "Get one workspace by ID"})
@ApiParam({ name: 'id', description: 'Workspace ID' }) @ApiResponse({status: 200, description: 'Received workspace', type: TMWorkspace})
@ApiResponse({ status: 200, description: 'Workspace found', type: TMWorkspace }) @ApiResponse({status: 404, description: 'Workspace Not Found!'})
@ApiResponse({ status: 404, description: 'Workspace not found' }) @ApiResponse({status: 400, description: 'Bad Request!'})
findOne(@Param('id') id: string): Promise<TMWorkspace> { findOne(@Param('id') id: string): Promise<TMWorkspace> {
return this.workspaceService.findOneOrFail(id); return this.workspaceService.findOneOrFail(id);
} }
@@ -64,11 +56,11 @@ export class WorkspaceController {
return this.workspaceService.remove(id); return this.workspaceService.remove(id);
} }
@Get('/byuser') @Get('byuser')
@ApiOperation({summary: 'Get User WorkSpaces'}) @ApiOperation({summary: 'Get User WorkSpaces'})
@ApiResponse({ status: 200, description: 'Got Workspaces successfully!' }) @ApiResponse({ status: 200, description: 'Got Workspaces successfully!' })
@ApiResponse({ status: 404, description: 'Bad Request!' }) @ApiResponse({ status: 404, description: 'Bad Request!' })
findByUser(@UserDec('id') userId: string) { findByUser(@UserDec() user: ITokenPayload) {
return this.workspaceService.findByUser(userId); return this.workspaceService.findByUser(user.id, user.permissions);
} }
} }
@@ -0,0 +1,19 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsDateString, IsNotEmpty, IsUUID } from "class-validator";
export class CreateTimeDto {
@ApiProperty({ description: "Start time of the entry", example: "2026-07-15T08:00:00.000Z" })
@IsDateString()
@IsNotEmpty()
startedAt: string;
@ApiProperty({ description: "End time of the entry", example: "2026-07-15T10:30:00.000Z" })
@IsDateString()
@IsNotEmpty()
endedAt: string;
@ApiProperty({ description: "ID of the task this time entry belongs to", example: "a1b2c3d4-e5f6-7890-abcd-ef1234567890" })
@IsUUID()
@IsNotEmpty()
taskId: string;
}
@@ -0,0 +1,4 @@
import { PartialType } from "@nestjs/swagger";
import { CreateTimeDto } from "./create-time.dto";
export class UpdateTimeDto extends PartialType(CreateTimeDto) {}
@@ -4,6 +4,7 @@ import { TMTaskPhase } from "./task-phase.entity";
import { TMRemark } from "./remark.entity"; import { TMRemark } from "./remark.entity";
import { TMAttachment } from "./attachment.entity"; import { TMAttachment } from "./attachment.entity";
import { TMCheckListItem } from "./check-list-item.entity"; import { TMCheckListItem } from "./check-list-item.entity";
import { TMTime } from "./time.entity";
import { User } from "../../users/entities/user.entity"; import { User } from "../../users/entities/user.entity";
@Entity("tm_tasks") @Entity("tm_tasks")
@@ -23,6 +24,9 @@ export class TMTask extends BaseEntity {
@Column({ type: "timestamptz", nullable: true }) @Column({ type: "timestamptz", nullable: true })
endDate: Date; endDate: Date;
@Column({type: 'int', default: 1})
priority: number;
// --- Relations --- // --- Relations ---
@ManyToOne(() => TMTaskPhase, (taskPhase) => taskPhase.tasks, { @ManyToOne(() => TMTaskPhase, (taskPhase) => taskPhase.tasks, {
@@ -50,6 +54,11 @@ export class TMTask extends BaseEntity {
}) })
checkListItems: TMCheckListItem[]; checkListItems: TMCheckListItem[];
@OneToMany(() => TMTime, (time) => time.task, {
cascade: ["insert", "update"],
})
times: TMTime[];
@ManyToMany(() => User, (user) => user.tasks) @ManyToMany(() => User, (user) => user.tasks)
@JoinTable({ @JoinTable({
name: "tm_task_users", name: "tm_task_users",
@@ -57,4 +66,10 @@ export class TMTask extends BaseEntity {
inverseJoinColumn: { name: "userId", referencedColumnName: "id" }, inverseJoinColumn: { name: "userId", referencedColumnName: "id" },
}) })
users: User[]; users: User[];
// deriven(calculated) attributes. not database columns
attachmentCount?: number;
checkListItemCount?: number;
completedCheckListItemCount?: number;
time?: number;
} }
@@ -0,0 +1,38 @@
import { Column, Entity, JoinColumn, ManyToOne } from "typeorm";
import { BaseEntity } from "../../../common/entities/base.entity";
import { TMTask } from "./task.entity";
import { User } from "../../users/entities/user.entity";
@Entity("tm_times")
export class TMTime extends BaseEntity {
@Column({ type: "timestamptz" })
startedAt: Date;
@Column({ type: "timestamptz", nullable: true })
endedAt: Date | null;
@Column({ type: "int", nullable: true })
duration: number | null;
// --- Relations ---
@ManyToOne(() => User, {
nullable: false,
onDelete: "RESTRICT",
})
@JoinColumn({ name: "adminId" })
admin: User;
@Column({ type: "uuid" })
adminId: string;
@ManyToOne(() => TMTask, (task) => task.times, {
nullable: false,
onDelete: "CASCADE",
})
@JoinColumn({ name: "taskId" })
task: TMTask;
@Column({ type: "uuid" })
taskId: string;
}
@@ -1,45 +1,36 @@
import { Injectable, NotFoundException } from "@nestjs/common"; import { Injectable, NotFoundException } from "@nestjs/common";
import { AttachmentRepository } from "../repositories/attachment.repository"; import { AttachmentRepository } from "../repositories/attachment.repository";
import { TaskRepository } from "../repositories/task.repository";
import { TMAttachment } from "../entities/attachment.entity"; import { TMAttachment } from "../entities/attachment.entity";
import { CreateAttachmentDto } from "../dto/attachment/create-attachment.dto"; import { CreateAttachmentDto } from "../dto/attachment/create-attachment.dto";
import { UpdateAttachmentDto } from "../dto/attachment/update-attachment.dto"; import { UpdateAttachmentDto } from "../dto/attachment/update-attachment.dto";
import { attachmentMessage } from "../../../common/enums/message.enum";
import { TaskService } from "./task.service";
@Injectable() @Injectable()
export class AttachmentService { export class AttachmentService {
constructor( constructor(
private readonly attachmentRepository: AttachmentRepository, private readonly attachmentRepository: AttachmentRepository,
private readonly taskRepository: TaskRepository, private readonly taskService: TaskService,
) {} ) {}
findAll(): Promise<TMAttachment[]> { async findOneOrFail(id: string): Promise<TMAttachment> {
return this.attachmentRepository.findAll(); const attachment = await this.attachmentRepository.findOne({ where: { id }, relations: { task: true } });
} if (!attachment) throw new NotFoundException(attachmentMessage.ATTACHMENT_NOT_FOUND);
findByTask(taskId: string): Promise<TMAttachment[]> {
return this.attachmentRepository.findByTask(taskId);
}
async findOne(id: string): Promise<TMAttachment> {
const attachment = await this.attachmentRepository.findOneById(id);
if (!attachment) throw new NotFoundException(`Attachment #${id} not found`);
return attachment; return attachment;
} }
async create(dto: CreateAttachmentDto): Promise<TMAttachment> { async create(dto: CreateAttachmentDto): Promise<TMAttachment> {
const task = await this.taskRepository.findOneById(dto.taskId); await this.taskService.findOneOrFail(dto.taskId);
if (!task) throw new NotFoundException(`Task #${dto.taskId} not found`);
const attachment = this.attachmentRepository.create(dto); const attachment = this.attachmentRepository.create(dto);
return this.attachmentRepository.save(attachment); return this.attachmentRepository.save(attachment);
} }
async update(id: string, dto: UpdateAttachmentDto): Promise<TMAttachment> { async update(id: string, dto: UpdateAttachmentDto): Promise<TMAttachment> {
const attachment = await this.findOne(id); const attachment = await this.findOneOrFail(id);
if (dto.taskId) { if (dto.taskId) {
const task = await this.taskRepository.findOneById(dto.taskId); await this.taskService.findOneOrFail(dto.taskId);
if (!task) throw new NotFoundException(`Task #${dto.taskId} not found`);
} }
Object.assign(attachment, dto); Object.assign(attachment, dto);
@@ -47,7 +38,7 @@ export class AttachmentService {
} }
async remove(id: string): Promise<void> { async remove(id: string): Promise<void> {
await this.findOne(id); await this.findOneOrFail(id);
await this.attachmentRepository.delete(id); await this.attachmentRepository.delete(id);
} }
} }
@@ -1,61 +1,36 @@
import { Injectable, NotFoundException } from '@nestjs/common'; import { Injectable, NotFoundException } from '@nestjs/common';
import { CheckListItemRepository } from '../repositories/check-list-item.repository'; import { CheckListItemRepository } from '../repositories/check-list-item.repository';
import { TaskRepository } from '../repositories/task.repository';
import { TMCheckListItem } from '../entities/check-list-item.entity'; import { TMCheckListItem } from '../entities/check-list-item.entity';
import { CreateCheckListItemDto } from '../dto/check-list-item/create-check-list-item.dto'; import { CreateCheckListItemDto } from '../dto/check-list-item/create-check-list-item.dto';
import { UpdateCheckListItemDto } from '../dto/check-list-item/update-check-list-item.dto'; import { UpdateCheckListItemDto } from '../dto/check-list-item/update-check-list-item.dto';
import { CursorPaginationDto } from '../../../common/DTO/cursor-pagination.dto'; import { checkListItemMessage } from '../../../common/enums/message.enum';
import { CursorPaginatedResult } from '../../../common/interfaces/cursor-paginated-result.interface'; import { TaskService } from './task.service';
import { buildCursorPageFormat } from '../../../common/helpers/cursor-paginated.helper';
@Injectable() @Injectable()
export class CheckListItemService { export class CheckListItemService {
constructor( constructor(
private readonly checkListItemRepository: CheckListItemRepository, private readonly checkListItemRepository: CheckListItemRepository,
private readonly taskRepository: TaskRepository, private readonly taskService: TaskService,
) {} ) {}
async findAll(pagination: CursorPaginationDto): Promise<CursorPaginatedResult<TMCheckListItem>> { async findOneOrFail(id: string): Promise<TMCheckListItem> {
const limit = pagination.limit ?? 10;
const cursorDate = pagination.cursor ? new Date(pagination.cursor) : undefined;
const [data] = await this.checkListItemRepository.findAll(limit, cursorDate);
return buildCursorPageFormat(data, limit, cursorDate);
}
async findByTask(
taskId: string,
pagination: CursorPaginationDto,
): Promise<CursorPaginatedResult<TMCheckListItem>> {
const limit = pagination.limit ?? 10;
const cursorDate = pagination.cursor ? new Date(pagination.cursor) : undefined;
const [data] = await this.checkListItemRepository.findByTask(taskId, limit, cursorDate);
return buildCursorPageFormat(data, limit, cursorDate);
}
async findOne(id: string): Promise<TMCheckListItem> {
const checkListItem = await this.checkListItemRepository.findOneById(id); const checkListItem = await this.checkListItemRepository.findOneById(id);
if (!checkListItem) throw new NotFoundException(`CheckListItem #${id} not found`); if (!checkListItem) throw new NotFoundException(checkListItemMessage.CHECKLISTITEM_NOT_FOUND);
return checkListItem; return checkListItem;
} }
async create(dto: CreateCheckListItemDto): Promise<TMCheckListItem> { async create(dto: CreateCheckListItemDto): Promise<TMCheckListItem> {
const task = await this.taskRepository.findOneById(dto.taskId); await this.taskService.findOneOrFail(dto.taskId);
if (!task) throw new NotFoundException(`Task #${dto.taskId} not found`);
const checkListItem = this.checkListItemRepository.create(dto); const checkListItem = this.checkListItemRepository.create(dto);
return this.checkListItemRepository.save(checkListItem); return this.checkListItemRepository.save(checkListItem);
} }
async update(id: string, dto: UpdateCheckListItemDto): Promise<TMCheckListItem> { async update(id: string, dto: UpdateCheckListItemDto): Promise<TMCheckListItem> {
const checkListItem = await this.findOne(id); const checkListItem = await this.findOneOrFail(id);
if (dto.taskId) { if (dto.taskId) {
const task = await this.taskRepository.findOneById(dto.taskId); await this.taskService.findOneOrFail(dto.taskId);
if (!task) throw new NotFoundException(`Task #${dto.taskId} not found`);
} }
Object.assign(checkListItem, dto); Object.assign(checkListItem, dto);
@@ -63,8 +38,17 @@ export class CheckListItemService {
} }
async remove(id: string): Promise<TMCheckListItem> { async remove(id: string): Promise<TMCheckListItem> {
const checkListItem = await this.findOne(id); const checkListItem = await this.findOneOrFail(id);
await this.checkListItemRepository.delete(id); await this.checkListItemRepository.delete(id);
return checkListItem; return checkListItem;
} }
async toggleStatus(id: string) : Promise<TMCheckListItem> {
const checkListItem = await this.findOneOrFail(id);
const isDone = checkListItem.isDone;
checkListItem.isDone = !isDone;
await this.checkListItemRepository.save(checkListItem);
return checkListItem;
}
} }
@@ -1,4 +1,4 @@
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common"; import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm"; import { InjectRepository } from "@nestjs/typeorm";
import { In, Repository } from "typeorm"; import { In, Repository } from "typeorm";
import { ProjectRepository } from "../repositories/project.repository"; import { ProjectRepository } from "../repositories/project.repository";
@@ -9,6 +9,7 @@ import { PaginationDto } from "../../../common/DTO/pagination.dto";
import { User } from "../../users/entities/user.entity"; import { User } from "../../users/entities/user.entity";
import { ProjectMessage, WorkSpaceMessage } from "../../../common/enums/message.enum"; import { ProjectMessage, WorkSpaceMessage } from "../../../common/enums/message.enum";
import { WorkspaceService } from "./workspace.service"; import { WorkspaceService } from "./workspace.service";
import { PermissionEnum } from "../../users/enums/permission.enum";
@Injectable() @Injectable()
export class ProjectService { export class ProjectService {
@@ -19,57 +20,25 @@ export class ProjectService {
private readonly userRepository: Repository<User>, private readonly userRepository: Repository<User>,
) {} ) {}
async findAll(pagination: PaginationDto): Promise<{ projects: TMProject[]; count: number; paginate: true }> {
const page = pagination.page ?? 1;
const limit = pagination.limit ?? 10;
const skip = (page - 1) * limit;
const [projects, count] = await this.projectRepository.findAndCount({
skip: skip,
take: limit,
relations: {
users: true,
},
select: {
users: {
id: true,
firstName: true,
lastName: true,
},
},
});
return { projects, count, paginate: true };
}
async findByWorkspace(workspaceId: string, pagination: PaginationDto): Promise<{ projects: TMProject[]; count: number; paginate: true }> {
await this.workspaceService.findOneOrFail(workspaceId);
const page = pagination.page ?? 1;
const limit = pagination.limit ?? 10;
const skip = (page - 1) * limit;
const [projects, count] = await this.projectRepository.findAndCount({
where: { workspaceId },
relations: {
users: true,
},
select: {
users: {
id: true,
firstName: true,
lastName: true,
},
},
skip,
take: limit,
});
return { projects, count, paginate: true };
}
async findOneOrFail(id: string): Promise<TMProject> { async findOneOrFail(id: string): Promise<TMProject> {
const project = await this.projectRepository.findOne({ where: { id } }); const project = await this.projectRepository.findOne({
where: { id },
relations: {
users: true,
taskPhases: true
},
select: {
users: {
id: true,
firstName: true,
lastName: true
},
taskPhases: {
id: true,
name: true,
}
}
});
if (!project) throw new NotFoundException(ProjectMessage.PROJECT_NOT_FOUND); if (!project) throw new NotFoundException(ProjectMessage.PROJECT_NOT_FOUND);
return project; return project;
} }
@@ -140,8 +109,8 @@ export class ProjectService {
}, },
}); });
if(!project) throw new NotFoundException(ProjectMessage.PROJECT_NOT_FOUND); if (!project) throw new NotFoundException(ProjectMessage.PROJECT_NOT_FOUND);
const taskPhases = project.taskPhases; const taskPhases = project.taskPhases;
if (taskPhases !== undefined && taskPhases.length) { if (taskPhases !== undefined && taskPhases.length) {
throw new BadRequestException(ProjectMessage.PROJECT_CONTAINS_TASK_PHASES); throw new BadRequestException(ProjectMessage.PROJECT_CONTAINS_TASK_PHASES);
@@ -149,4 +118,51 @@ export class ProjectService {
await this.projectRepository.delete(id); await this.projectRepository.delete(id);
return project; return project;
} }
async findUserProjectsByWorkspace(
userId: string,
permissions: PermissionEnum[],
wsId: string,
pagination: PaginationDto,
): Promise<{ projects: TMProject[]; count: number; paginate: true }> {
const workspace = await this.workspaceService.findOneOrFail(wsId);
const page = pagination.page ?? 1;
const limit = pagination.limit ?? 10;
const skip = (page - 1) * limit;
const isPermissionIncluded = permissions.includes(PermissionEnum.VIEW_ALL_PROJECTS);
const isUserMemeberOfWorkspace = workspace.users.some((user) => user.id === userId);
var res: [TMProject[], number];
if (isUserMemeberOfWorkspace && !isPermissionIncluded) {
res = await this.projectRepository.findUserProjects(userId, wsId, skip, limit);
} else if (isPermissionIncluded) {
res = await this.projectRepository.findAndCount({ where: { workspaceId: wsId } });
} else {
throw new ForbiddenException(WorkSpaceMessage.FORBIDDEN);
}
const [projects, count] = res;
return { projects, count, paginate: true };
}
async getProjectDetail(projectId: string, userId: string, permissions: PermissionEnum[]): Promise<TMProject | null> {
const project = await this.projectRepository.findOne({
where: { id: projectId },
relations: {
users: true,
},
});
if (!project) throw new NotFoundException(ProjectMessage.PROJECT_NOT_FOUND);
const isUserMember = project.users.some((user) => user.id === userId);
if (!isUserMember && !permissions.includes(PermissionEnum.VIEW_ALL_PROJECTS))
throw new ForbiddenException(ProjectMessage.NOT_MEMBER_OF_PROJECT);
const projectDetail = await this.projectRepository.getProjectDetail(projectId);
return projectDetail;
}
} }
@@ -1,45 +1,36 @@
import { Injectable, NotFoundException } from "@nestjs/common"; import { Injectable, NotFoundException } from "@nestjs/common";
import { RemarkRepository } from "../repositories/remark.repository"; import { RemarkRepository } from "../repositories/remark.repository";
import { TaskRepository } from "../repositories/task.repository";
import { TMRemark } from "../entities/remark.entity"; import { TMRemark } from "../entities/remark.entity";
import { CreateRemarkDto } from "../dto/remark/create-remark.dto"; import { CreateRemarkDto } from "../dto/remark/create-remark.dto";
import { UpdateRemarkDto } from "../dto/remark/update-remark.dto"; import { UpdateRemarkDto } from "../dto/remark/update-remark.dto";
import { remarkMessage } from "../../../common/enums/message.enum";
import { TaskService } from './task.service';
@Injectable() @Injectable()
export class RemarkService { export class RemarkService {
constructor( constructor(
private readonly remarkRepository: RemarkRepository, private readonly remarkRepository: RemarkRepository,
private readonly taskRepository: TaskRepository, private readonly taskService: TaskService,
) {} ) {}
findAll(): Promise<TMRemark[]> { async findOneOrFail(id: string): Promise<TMRemark> {
return this.remarkRepository.findAll(); const remark = await this.remarkRepository.findOne({ where: { id } });
} if (!remark) throw new NotFoundException(remarkMessage.REMARK_NOT_FOUND);
findByTask(taskId: string): Promise<TMRemark[]> {
return this.remarkRepository.findByTask(taskId);
}
async findOne(id: string): Promise<TMRemark> {
const remark = await this.remarkRepository.findOneById(id);
if (!remark) throw new NotFoundException(`Remark #${id} not found`);
return remark; return remark;
} }
async create(dto: CreateRemarkDto): Promise<TMRemark> { async create(dto: CreateRemarkDto): Promise<TMRemark> {
const task = await this.taskRepository.findOneById(dto.taskId); await this.taskService.findOneOrFail(dto.taskId);
if (!task) throw new NotFoundException(`Task #${dto.taskId} not found`);
const remark = this.remarkRepository.create(dto); const remark = this.remarkRepository.create(dto);
return this.remarkRepository.save(remark); return this.remarkRepository.save(remark);
} }
async update(id: string, dto: UpdateRemarkDto): Promise<TMRemark> { async update(id: string, dto: UpdateRemarkDto): Promise<TMRemark> {
const remark = await this.findOne(id); const remark = await this.findOneOrFail(id);
if (dto.taskId) { if (dto.taskId) {
const task = await this.taskRepository.findOneById(dto.taskId); await this.taskService.findOneOrFail(dto.taskId);
if (!task) throw new NotFoundException(`Task #${dto.taskId} not found`);
} }
Object.assign(remark, dto); Object.assign(remark, dto);
@@ -47,7 +38,7 @@ export class RemarkService {
} }
async remove(id: string): Promise<void> { async remove(id: string): Promise<void> {
await this.findOne(id); await this.findOneOrFail(id);
await this.remarkRepository.delete(id); await this.remarkRepository.delete(id);
} }
} }
@@ -1,45 +1,35 @@
import { Injectable, NotFoundException } from "@nestjs/common"; import { Injectable, NotFoundException } from "@nestjs/common";
import { TaskPhaseRepository } from "../repositories/task-phase.repository"; import { TaskPhaseRepository } from "../repositories/task-phase.repository";
import { ProjectRepository } from "../repositories/project.repository";
import { TMTaskPhase } from "../entities/task-phase.entity"; import { TMTaskPhase } from "../entities/task-phase.entity";
import { CreateTaskPhaseDto } from "../dto/task-phase/create-task-phase.dto"; import { CreateTaskPhaseDto } from "../dto/task-phase/create-task-phase.dto";
import { UpdateTaskPhaseDto } from "../dto/task-phase/update-task-phase.dto"; import { UpdateTaskPhaseDto } from "../dto/task-phase/update-task-phase.dto";
import { TaskPhaseMessage } from "../../../common/enums/message.enum";
import { ProjectService } from "./project.service";
@Injectable() @Injectable()
export class TaskPhaseService { export class TaskPhaseService {
constructor( constructor(
private readonly taskPhaseRepository: TaskPhaseRepository, private readonly taskPhaseRepository: TaskPhaseRepository,
private readonly projectRepository: ProjectRepository, private readonly projectService: ProjectService
) {} ) {}
findAll(): Promise<TMTaskPhase[]> { async findOneOrFail(id: string): Promise<TMTaskPhase> {
return this.taskPhaseRepository.findAll(); const taskPhase = await this.taskPhaseRepository.findOne({where: {id}});
} if (!taskPhase) throw new NotFoundException(TaskPhaseMessage.TASK_PHASE_NOT_FOUND);
findByProject(projectId: string): Promise<TMTaskPhase[]> {
return this.taskPhaseRepository.findByProject(projectId);
}
async findOne(id: string): Promise<TMTaskPhase> {
const taskPhase = await this.taskPhaseRepository.findOneById(id);
if (!taskPhase) throw new NotFoundException(`TaskPhase #${id} not found`);
return taskPhase; return taskPhase;
} }
async create(dto: CreateTaskPhaseDto): Promise<TMTaskPhase> { async create(dto: CreateTaskPhaseDto): Promise<TMTaskPhase> {
const project = await this.projectRepository.findOneById(dto.projectId); await this.projectService.findOneOrFail(dto.projectId);
if (!project) throw new NotFoundException(`Project #${dto.projectId} not found`);
const taskPhase = this.taskPhaseRepository.create(dto); const taskPhase = this.taskPhaseRepository.create(dto);
return this.taskPhaseRepository.save(taskPhase); return this.taskPhaseRepository.save(taskPhase);
} }
async update(id: string, dto: UpdateTaskPhaseDto): Promise<TMTaskPhase> { async update(id: string, dto: UpdateTaskPhaseDto): Promise<TMTaskPhase> {
const taskPhase = await this.findOne(id); const taskPhase = await this.findOneOrFail(id);
if (dto.projectId) { if (dto.projectId) {
const project = await this.projectRepository.findOneById(dto.projectId); await this.projectService.findOneOrFail(dto.projectId);
if (!project) throw new NotFoundException(`Project #${dto.projectId} not found`);
} }
Object.assign(taskPhase, dto); Object.assign(taskPhase, dto);
@@ -47,7 +37,7 @@ export class TaskPhaseService {
} }
async remove(id: string): Promise<void> { async remove(id: string): Promise<void> {
await this.findOne(id); await this.findOneOrFail(id);
await this.taskPhaseRepository.delete(id); await this.taskPhaseRepository.delete(id);
} }
} }
@@ -1,13 +1,18 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; import { BadRequestException, ForbiddenException, Injectable, NotFoundException } from "@nestjs/common";
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from "@nestjs/typeorm";
import { In, Repository } from 'typeorm'; import { In, Repository } from "typeorm";
import { TaskRepository } from '../repositories/task.repository'; import { TaskRepository } from "../repositories/task.repository";
import { TaskPhaseRepository } from '../repositories/task-phase.repository'; import { TMTask } from "../entities/task.entity";
import { TMTask } from '../entities/task.entity'; import { CreateTaskDto } from "../dto/task/create-task.dto";
import { CreateTaskDto } from '../dto/task/create-task.dto'; import { UpdateTaskDto } from "../dto/task/update-task.dto";
import { UpdateTaskDto } from '../dto/task/update-task.dto'; import { ChangeTaskPhaseDto } from "../dto/task/change-task-phase.dto";
import { ChangeTaskPhaseDto } from '../dto/task/change-task-phase.dto'; import { User } from "../../users/entities/user.entity";
import { User } from '../../users/entities/user.entity'; import { TaskMessage, TaskPhaseMessage } from "../../../common/enums/message.enum";
import { TaskPhaseRepository } from "../repositories/task-phase.repository";
import { TMTaskPhase } from "../entities/task-phase.entity";
import { PermissionEnum } from "../../users/enums/permission.enum";
import { encodeCursor } from "../../utils/providers/cursor-pagination.utils";
import { CursorDirection, CursorPaginationDto } from "../../../common/DTO/cursor-pagination.dto";
@Injectable() @Injectable()
export class TaskService { export class TaskService {
@@ -18,25 +23,41 @@ export class TaskService {
private readonly userRepository: Repository<User>, private readonly userRepository: Repository<User>,
) {} ) {}
findAll(): Promise<TMTask[]> { async findOneOrFail(id: string): Promise<TMTask> {
return this.taskRepository.findAll(); const task = await this.taskRepository.findOne({
} where: { id },
relations: {
findByPhase(taskPhaseId: string): Promise<TMTask[]> { taskPhase: true,
return this.taskRepository.findByPhase(taskPhaseId); users: true,
} },
});
async findOne(id: string): Promise<TMTask> { if (!task) throw new NotFoundException(TaskMessage.TASK_NOT_FOUND);
const task = await this.taskRepository.findOneById(id);
if (!task) throw new NotFoundException(`Task #${id} not found`);
return task; return task;
} }
async findTaskPhaseOrFail(taskPhaseId: string): Promise<TMTaskPhase> {
const taskPhase = await this.taskPhaseRepository.findOne({
where: { id: taskPhaseId },
relations: {
project: {
users: true,
},
},
});
if (!taskPhase) throw new NotFoundException(TaskPhaseMessage.TASK_PHASE_NOT_FOUND);
return taskPhase;
}
async create(dto: CreateTaskDto): Promise<TMTask> { async create(dto: CreateTaskDto): Promise<TMTask> {
const { userIds, startDate, endDate, ...rest } = dto; const { userIds, startDate, endDate, ...rest } = dto;
const taskPhase = await this.taskPhaseRepository.findOneById(dto.taskPhaseId); const taskPhase = await this.findTaskPhaseOrFail(dto.taskPhaseId);
if (!taskPhase) throw new NotFoundException(`TaskPhase #${dto.taskPhaseId} not found`);
if (userIds?.length) {
const isUsersValid = userIds.every((userId) => taskPhase.project.users.some((user) => user.id === userId));
if (!isUsersValid) throw new BadRequestException(TaskMessage.USERS_ASSIGNED_TO_TASK_NOT_PROJECT_MEMBER);
}
const task = this.taskRepository.create({ const task = this.taskRepository.create({
...rest, ...rest,
@@ -52,12 +73,16 @@ export class TaskService {
} }
async update(id: string, dto: UpdateTaskDto): Promise<TMTask> { async update(id: string, dto: UpdateTaskDto): Promise<TMTask> {
const task = await this.findOne(id); const task = await this.findOneOrFail(id);
const { userIds, startDate, endDate, ...rest } = dto; const { userIds, startDate, endDate, ...rest } = dto;
if (dto.taskPhaseId) { if (dto.taskPhaseId) {
const taskPhase = await this.taskPhaseRepository.findOneById(dto.taskPhaseId); const taskPhase = await this.findTaskPhaseOrFail(dto.taskPhaseId);
if (!taskPhase) throw new NotFoundException(`TaskPhase #${dto.taskPhaseId} not found`);
if (userIds?.length) {
const isUsersValid = userIds.every((userId) => taskPhase.project.users.some((user) => user.id === userId));
if (!isUsersValid) throw new BadRequestException(TaskMessage.USERS_ASSIGNED_TO_TASK_NOT_PROJECT_MEMBER);
}
} }
Object.assign(task, { Object.assign(task, {
@@ -67,24 +92,19 @@ export class TaskService {
}); });
if (userIds) { if (userIds) {
task.users = userIds.length task.users = userIds.length ? await this.userRepository.findBy({ id: In(userIds) }) : [];
? await this.userRepository.findBy({ id: In(userIds) })
: [];
} }
return this.taskRepository.save(task); return this.taskRepository.save(task);
} }
async changePhase(id: string, dto: ChangeTaskPhaseDto): Promise<TMTask> { async changePhase(id: string, dto: ChangeTaskPhaseDto): Promise<TMTask> {
const task = await this.findOne(id); const task = await this.findOneOrFail(id);
const newPhase = await this.taskPhaseRepository.findOneById(dto.taskPhaseId); const newPhase = await this.findTaskPhaseOrFail(dto.taskPhaseId);
if (!newPhase) throw new NotFoundException(`TaskPhase #${dto.taskPhaseId} not found`);
if (task.taskPhase.projectId !== newPhase.projectId) { if (task.taskPhase.projectId !== newPhase.projectId) {
throw new BadRequestException( throw new BadRequestException(TaskPhaseMessage.TASK_PHASE_NOT_SAME_PROJECT);
`TaskPhase #${dto.taskPhaseId} does not belong to the same project as the current phase`,
);
} }
task.taskPhaseId = dto.taskPhaseId; task.taskPhaseId = dto.taskPhaseId;
@@ -94,7 +114,75 @@ export class TaskService {
} }
async remove(id: string): Promise<void> { async remove(id: string): Promise<void> {
await this.findOne(id); await this.findOneOrFail(id);
await this.taskRepository.delete(id); await this.taskRepository.delete(id);
} }
}
async getTaskDetail(userId: string, permissions: PermissionEnum[], taskId: string): Promise<TMTask | null> {
const task = await this.findOneOrFail(taskId);
const isTaskMember = task.users.some((user) => user.id === userId);
const hasPermission = permissions.includes(PermissionEnum.TASK);
if (!isTaskMember && !hasPermission) throw new ForbiddenException(TaskMessage.USER_NOT_TASK_MEMBER);
const taskDetail = await this.taskRepository.getTaskDetail(taskId);
return taskDetail;
}
async findTasksByTaskPhase(
taskPhaseId: string,
pagination: CursorPaginationDto,
): Promise<{
data: TMTask[];
nextCursor: string | null;
previousCursor: string | null;
hasNextPage: boolean;
hasPreviousPage: boolean;
cursorPaginate: true;
}> {
await this.findTaskPhaseOrFail(taskPhaseId);
const isBackward = pagination.direction === CursorDirection.PREV;
const { items, hasMore } = await this.taskRepository.findTasksByTaskPhase(taskPhaseId, pagination);
// paging backward always has more ahead (we came from there); paging forward relies on
// whether a cursor was even supplied to know whether anything precedes this page
const hasNextPage = items.length > 0 && (isBackward ? true : hasMore);
const hasPreviousPage = items.length > 0 && (isBackward ? hasMore : !!pagination.cursor);
const nextCursor = hasNextPage ? encodeCursor(items[items.length - 1]) : null;
const previousCursor = hasPreviousPage ? encodeCursor(items[0]) : null;
return { data: items, nextCursor, previousCursor, hasNextPage, hasPreviousPage, cursorPaginate: true };
}
async changePriority(srcTaskId: string, destTaskId: string): Promise<TMTask> {
const srcTask = await this.findOneOrFail(srcTaskId);
const desTask = await this.findOneOrFail(destTaskId);
if (srcTask.taskPhaseId !== desTask.taskPhaseId)
throw new BadRequestException(TaskMessage.TASKS_NOT_IN_THE_SAME_TASK_PHASE);
let movingUp: boolean = false;
if(srcTask.priority < desTask.priority) {
movingUp = true;
} else if(srcTask.priority < desTask.priority) {
movingUp = false;
} else {
if(srcTask.createdAt > desTask.createdAt) {
movingUp = true;
}else {
movingUp = false;
}
}
const priorityChange: number = movingUp ? 1 : -1;
srcTask.priority = desTask.priority + priorityChange;
await this.taskRepository.save(srcTask);
return srcTask;
}
}
@@ -0,0 +1,119 @@
import { BadRequestException, Injectable, NotFoundException } from "@nestjs/common";
import { IsNull } from "typeorm";
import { TimeRepository } from "../repositories/time.repository";
import { TMTime } from "../entities/time.entity";
import { CreateTimeDto } from "../dto/time/create-time.dto";
import { UpdateTimeDto } from "../dto/time/update-time.dto";
import { timeMessage } from "../../../common/enums/message.enum";
import { TaskService } from "./task.service";
@Injectable()
export class TimeService {
constructor(
private readonly timeRepository: TimeRepository,
private readonly taskService: TaskService,
) { }
private calculateDuration(startedAt: Date, endedAt: Date): number {
if (endedAt.getTime() < startedAt.getTime()) {
throw new BadRequestException(timeMessage.INVALID_TIME_RANGE);
}
return Math.floor((endedAt.getTime() - startedAt.getTime()) / 1000);
}
private async findRunningTime(adminId: string, taskId: string): Promise<TMTime | null> {
return this.timeRepository.findOne({
where: { adminId, taskId, endedAt: IsNull() },
order: { startedAt: "DESC" },
});
}
async findOneOrFail(id: string): Promise<TMTime> {
const time = await this.timeRepository.findOne({
where: { id },
relations: { admin: true, task: true },
});
if (!time) throw new NotFoundException(timeMessage.TIME_NOT_FOUND);
return time;
}
async start(adminId: string, taskId: string): Promise<TMTime> {
await this.taskService.findOneOrFail(taskId);
const runningTime = await this.findRunningTime(adminId, taskId);
if (runningTime) throw new BadRequestException(timeMessage.TIME_ALREADY_STARTED);
const time = this.timeRepository.create({
taskId,
adminId,
startedAt: new Date(),
endedAt: null,
duration: null,
});
return this.timeRepository.save(time);
}
async getTaskTimes(adminId: string, taskId: string): Promise<TMTime[]> {
return this.timeRepository.find({
where: { adminId, taskId },
order: { startedAt: "DESC" },
});
}
async end(adminId: string, taskId: string): Promise<TMTime> {
await this.taskService.findOneOrFail(taskId);
const runningTime = await this.findRunningTime(adminId, taskId);
if (!runningTime) throw new BadRequestException(timeMessage.NO_RUNNING_TIME);
const endedAt = new Date();
runningTime.endedAt = endedAt;
runningTime.duration = this.calculateDuration(runningTime.startedAt, endedAt);
return this.timeRepository.save(runningTime);
}
async create(adminId: string, dto: CreateTimeDto): Promise<TMTime> {
await this.taskService.findOneOrFail(dto.taskId);
const startedAt = new Date(dto.startedAt);
const endedAt = new Date(dto.endedAt);
const time = this.timeRepository.create({
taskId: dto.taskId,
adminId,
startedAt,
endedAt,
duration: this.calculateDuration(startedAt, endedAt),
});
return this.timeRepository.save(time);
}
async update(id: string, dto: UpdateTimeDto): Promise<TMTime> {
const time = await this.findOneOrFail(id);
if (dto.taskId) {
await this.taskService.findOneOrFail(dto.taskId);
}
const startedAt = dto.startedAt ? new Date(dto.startedAt) : time.startedAt;
const endedAt = dto.endedAt ? new Date(dto.endedAt) : time.endedAt;
Object.assign(time, {
...dto,
startedAt,
endedAt,
duration: endedAt ? this.calculateDuration(startedAt, endedAt) : null,
});
return this.timeRepository.save(time);
}
async remove(id: string): Promise<void> {
await this.findOneOrFail(id);
await this.timeRepository.delete(id);
}
}
@@ -7,6 +7,7 @@ import { CreateWorkspaceDto } from "../dto/workspace/create-workspace.dto";
import { UpdateWorkspaceDto } from "../dto/workspace/update-workspace.dto"; import { UpdateWorkspaceDto } from "../dto/workspace/update-workspace.dto";
import { User } from "../../users/entities/user.entity"; import { User } from "../../users/entities/user.entity";
import { WorkSpaceMessage } from "../../../common/enums/message.enum"; import { WorkSpaceMessage } from "../../../common/enums/message.enum";
import { PermissionEnum } from "../../users/enums/permission.enum";
@Injectable() @Injectable()
export class WorkspaceService { export class WorkspaceService {
@@ -16,10 +17,6 @@ export class WorkspaceService {
private readonly userRepository: Repository<User>, private readonly userRepository: Repository<User>,
) {} ) {}
findAll(): Promise<TMWorkspace[]> {
return this.workspaceRepository.find({});
}
async findOneOrFail(id: string): Promise<TMWorkspace> { async findOneOrFail(id: string): Promise<TMWorkspace> {
const workspace = await this.workspaceRepository.findOneWorkSpace(id); const workspace = await this.workspaceRepository.findOneWorkSpace(id);
if (!workspace) throw new NotFoundException(WorkSpaceMessage.WORKSPACE_NOT_FOUND); if (!workspace) throw new NotFoundException(WorkSpaceMessage.WORKSPACE_NOT_FOUND);
@@ -68,7 +65,10 @@ export class WorkspaceService {
return workspace; return workspace;
} }
async findByUser(userId: string): Promise<TMWorkspace[]> { async findByUser(userId: string, permissions: PermissionEnum[]): Promise<TMWorkspace[]> {
if(permissions.includes(PermissionEnum.VIEW_ALL_WORKSPACES)) {
return await this.workspaceRepository.find();
}
return await this.workspaceRepository.findByUser(userId); return await this.workspaceRepository.findByUser(userId);
} }
} }
@@ -4,44 +4,10 @@ import { Repository } from 'typeorm';
import { TMAttachment } from '../entities/attachment.entity'; import { TMAttachment } from '../entities/attachment.entity';
@Injectable() @Injectable()
export class AttachmentRepository { export class AttachmentRepository extends Repository<TMAttachment>{
constructor( constructor(
@InjectRepository(TMAttachment) @InjectRepository(TMAttachment) attachmentRepository: Repository<TMAttachment>,
private readonly repository: Repository<TMAttachment>, ) {
) {} super(attachmentRepository.target, attachmentRepository.manager, attachmentRepository.queryRunner);
findAll() {
return this.repository.find({
relations: ['task'],
});
}
findByTask(taskId: string) {
return this.repository.find({
where: { taskId },
});
}
findOneById(id: string) {
return this.repository.findOne({
where: { id },
relations: ['task'],
});
}
create(data: Partial<TMAttachment>) {
return this.repository.create(data);
}
save(attachment: TMAttachment) {
return this.repository.save(attachment);
}
update(id: string, data: Partial<TMAttachment>) {
return this.repository.update(id, data);
}
delete(id: string) {
return this.repository.delete(id);
} }
} }
@@ -1,62 +1,13 @@
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm'; import { InjectRepository } from '@nestjs/typeorm';
import { Repository, MoreThan } from 'typeorm'; import { Repository } from 'typeorm';
import { TMCheckListItem } from '../entities/check-list-item.entity'; import { TMCheckListItem } from '../entities/check-list-item.entity';
@Injectable() @Injectable()
export class CheckListItemRepository { export class CheckListItemRepository extends Repository<TMCheckListItem>{
constructor( constructor(
@InjectRepository(TMCheckListItem) @InjectRepository(TMCheckListItem) checkListItemRepository: Repository<TMCheckListItem>,
private readonly repository: Repository<TMCheckListItem>, ) {
) {} super(checkListItemRepository.target, checkListItemRepository.manager, checkListItemRepository.queryRunner);
findAll(limit: number, cursor?: Date) {
return this.repository.findAndCount({
where: cursor ? { createdAt: MoreThan(cursor) } : {},
order: { createdAt: 'ASC' },
take: limit + 1,
relations: ['task'],
});
}
findByTask(taskId: string, limit: number, cursor?: Date) {
return this.repository.findAndCount({
where: cursor
? { taskId, createdAt: MoreThan(cursor) }
: { taskId },
order: { createdAt: 'ASC' },
take: limit + 1,
relations: ['task'],
});
}
findOneById(id: string) {
return this.repository.findOne({
where: { id },
relations: ['task'],
});
}
findOneByCreatedAt(createdAt: Date) {
return this.repository.findOne({
where: { createdAt },
order: { createdAt: 'ASC' },
});
}
create(data: Partial<TMCheckListItem>) {
return this.repository.create(data);
}
save(checkListItem: TMCheckListItem) {
return this.repository.save(checkListItem);
}
update(id: string, data: Partial<TMCheckListItem>) {
return this.repository.update(id, data);
}
delete(id: string) {
return this.repository.delete(id);
} }
} }
@@ -5,9 +5,36 @@ import { TMProject } from "../entities/project.entity";
@Injectable() @Injectable()
export class ProjectRepository extends Repository<TMProject> { export class ProjectRepository extends Repository<TMProject> {
constructor( constructor(@InjectRepository(TMProject) projectRepository: Repository<TMProject>) {
@InjectRepository(TMProject) projectRepository: Repository<TMProject>,
) {
super(projectRepository.target, projectRepository.manager, projectRepository.queryRunner); super(projectRepository.target, projectRepository.manager, projectRepository.queryRunner);
} }
async findUserProjects(userId: string, wsId: string, skip?: number, take?: number): Promise<[TMProject[], number]> {
return this.createQueryBuilder("project")
.innerJoin("project.workspace", "workspace")
.innerJoin("project.users", "user")
.where("workspace.id = :wsId", { wsId })
.andWhere("user.id = :userId", { userId })
.skip(skip ?? 0)
.take(take ?? 10)
.getManyAndCount();
}
async getProjectDetail(projectId: string): Promise<TMProject | null> {
return this.createQueryBuilder("project")
.leftJoinAndSelect("project.taskPhases", "taskPhase")
.where("project.id = :projectId", { projectId })
.select([
"project.id",
"project.name",
"taskPhase.id",
"taskPhase.name",
"taskPhase.order",
])
.orderBy("taskPhase.order", "ASC")
.getOne();
}
} }
@@ -4,44 +4,10 @@ import { Repository } from "typeorm";
import { TMRemark } from "../entities/remark.entity"; import { TMRemark } from "../entities/remark.entity";
@Injectable() @Injectable()
export class RemarkRepository { export class RemarkRepository extends Repository<TMRemark>{
constructor( constructor(
@InjectRepository(TMRemark) @InjectRepository(TMRemark) remarkRepository: Repository<TMRemark>,
private readonly repository: Repository<TMRemark>, ) {
) {} super(remarkRepository.target, remarkRepository.manager, remarkRepository.queryRunner);
findAll() {
return this.repository.find({
relations: ["task"],
});
}
findByTask(taskId: string) {
return this.repository.find({
where: { taskId },
});
}
findOneById(id: string) {
return this.repository.findOne({
where: { id },
relations: ["task"],
});
}
create(data: Partial<TMRemark>) {
return this.repository.create(data);
}
save(remark: TMRemark) {
return this.repository.save(remark);
}
update(id: string, data: Partial<TMRemark>) {
return this.repository.update(id, data);
}
delete(id: string) {
return this.repository.delete(id);
} }
} }
@@ -4,47 +4,10 @@ import { Repository } from "typeorm";
import { TMTaskPhase } from "../entities/task-phase.entity"; import { TMTaskPhase } from "../entities/task-phase.entity";
@Injectable() @Injectable()
export class TaskPhaseRepository { export class TaskPhaseRepository extends Repository<TMTaskPhase> {
constructor( constructor(
@InjectRepository(TMTaskPhase) @InjectRepository(TMTaskPhase) taskPhaseRepository: Repository<TMTaskPhase>,
private readonly repository: Repository<TMTaskPhase>, ) {
) {} super(taskPhaseRepository.target, taskPhaseRepository.manager, taskPhaseRepository.queryRunner);
findAll() {
return this.repository.find({
relations: ["project", "tasks"],
order: { order: "ASC" },
});
}
findByProject(projectId: string) {
return this.repository.find({
where: { projectId },
relations: ["tasks"],
order: { order: "ASC" },
});
}
findOneById(id: string) {
return this.repository.findOne({
where: { id },
relations: ["project", "tasks"],
});
}
create(data: Partial<TMTaskPhase>) {
return this.repository.create(data);
}
save(taskPhase: TMTaskPhase) {
return this.repository.save(taskPhase);
}
update(id: string, data: Partial<TMTaskPhase>) {
return this.repository.update(id, data);
}
delete(id: string) {
return this.repository.delete(id);
} }
} }
@@ -2,47 +2,144 @@ import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm"; import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm"; import { Repository } from "typeorm";
import { TMTask } from "../entities/task.entity"; import { TMTask } from "../entities/task.entity";
import { TMTime } from "../entities/time.entity";
import { CursorDirection, CursorPaginationDto } from "../../../common/DTO/cursor-pagination.dto";
import { decodeCursor } from "../../utils/providers/cursor-pagination.utils";
@Injectable() @Injectable()
export class TaskRepository { export class TaskRepository extends Repository<TMTask> {
constructor( constructor(@InjectRepository(TMTask) taskRepository: Repository<TMTask>) {
@InjectRepository(TMTask) super(taskRepository.target, taskRepository.manager, taskRepository.queryRunner);
private readonly repository: Repository<TMTask>,
) {}
findAll() {
return this.repository.find({
relations: ["taskPhase", "remarks", "attachments", "checkListItems", "users"],
});
} }
findByPhase(taskPhaseId: string) { async getTaskDetail(taskId: string): Promise<TMTask | null> {
return this.repository.find({ const task = await this.createQueryBuilder("task")
where: { taskPhaseId }, .leftJoinAndSelect("task.remarks", "remark")
relations: ["remarks", "attachments", "checkListItems", "users"], .leftJoinAndSelect("task.attachments", "attachment")
}); .leftJoinAndSelect("task.checkListItems", "checkListItem")
.leftJoinAndSelect("task.users", "user")
.leftJoinAndSelect("task.times", "time")
.leftJoinAndSelect("time.admin", "timeAdmin")
.loadRelationCountAndMap("task.checkListItemCount", "task.checkListItems")
.loadRelationCountAndMap("task.completedCheckListItemCount", "task.checkListItems", "completedCheckListItems", (qb) =>
qb.where("completedCheckListItems.isDone = :isDone", { isDone: true }),
)
.select([
"task",
"remark.id",
"remark.title",
"remark.color",
"checkListItem.id",
"checkListItem.title",
"checkListItem.isDone",
"attachment.id",
"attachment.title",
"attachment.type",
"attachment.file",
"user.id",
"user.firstName",
"user.lastName",
"time.id",
"time.startedAt",
"time.endedAt",
"time.duration",
"time.adminId",
"timeAdmin.id",
"timeAdmin.firstName",
"timeAdmin.lastName",
])
.where("task.id = :taskId", { taskId })
.orderBy("checkListItem.createdAt", "ASC")
.addOrderBy("time.createdAt", "ASC")
.getOne();
if (task) {
task.time = task.times?.reduce((sum, entry) => sum + (entry.duration ?? 0), 0) ?? 0;
}
return task;
} }
findOneById(id: string) { async findTasksByTaskPhase(taskPhaseId: string, pagination: CursorPaginationDto): Promise<{ items: TMTask[]; hasMore: boolean }> {
return this.repository.findOne({ const limit = pagination.limit || 10;
where: { id }, const isBackward = pagination.direction === CursorDirection.PREV;
relations: ["taskPhase", "remarks", "attachments", "checkListItems", "users"],
});
}
create(data: Partial<TMTask>) { const createdAtExpr = `date_trunc('milliseconds', task.createdAt)`;
return this.repository.create(data);
}
save(task: TMTask) { const seekQuery = this.createQueryBuilder("task")
return this.repository.save(task); .select(["task.id", "task.priority", "task.createdAt"])
} .where("task.taskPhaseId = :taskPhaseId", { taskPhaseId })
.limit(limit + 1); // fetch one extra to check whether there's a further page
update(id: string, data: Partial<TMTask>) { if (isBackward) {
return this.repository.update(id, data); seekQuery.orderBy("task.priority", "ASC").addOrderBy(createdAtExpr, "DESC").addOrderBy("task.id", "DESC");
} } else {
seekQuery.orderBy("task.priority", "DESC").addOrderBy(createdAtExpr, "ASC").addOrderBy("task.id", "ASC");
}
delete(id: string) { if (pagination.cursor) {
return this.repository.delete(id); const { priority: cursorPriority, createdAt: cursorCreatedAt, id: cursorId } = decodeCursor(pagination.cursor);
const priorityOp = isBackward ? ">" : "<";
const seekOp = isBackward ? "<" : ">";
seekQuery.andWhere(
`(task.priority ${priorityOp} :cursorPriority
OR (task.priority = :cursorPriority AND ${createdAtExpr} ${seekOp} :cursorCreatedAt)
OR (task.priority = :cursorPriority AND ${createdAtExpr} = :cursorCreatedAt AND task.id ${seekOp} :cursorId))`,
{ cursorPriority, cursorCreatedAt, cursorId },
);
}
const seekRows = await seekQuery.getMany();
const hasMore = seekRows.length > limit;
if (hasMore) seekRows.pop();
// backward queries fetch in reverse order to seek from the cursor, so flip back to
// the normal display order before returning
const orderedRows = isBackward ? seekRows.reverse() : seekRows;
const ids = orderedRows.map((row) => row.id);
if (!ids.length) return { items: [], hasMore };
// Detail query: hydrates exactly the ids picked above with the relations/counts the
// response needs. IN (:...ids) doesn't preserve order, so re-order to match seekQuery.
const detailRows = await this.createQueryBuilder("task")
.leftJoinAndSelect("task.remarks", "remark")
.loadRelationCountAndMap("task.attachmentCount", "task.attachments")
.loadRelationCountAndMap("task.checkListItemCount", "task.checkListItems")
.loadRelationCountAndMap("task.completedCheckListItemCount", "task.checkListItems", "completedCheckListItems", (qb) =>
qb.where("completedCheckListItems.isDone = :isDone", { isDone: true }),
)
.select(["task", "remark.id", "remark.title", "remark.color"])
.where("task.id IN (:...ids)", { ids })
.getMany();
const timeSums = await this.manager
.createQueryBuilder(TMTime, "time")
.select("time.taskId", "taskId")
.addSelect("COALESCE(SUM(time.duration), 0)", "totalTime")
.where("time.taskId IN (:...ids)", { ids })
.groupBy("time.taskId")
.getRawMany<{ taskId: string; totalTime: string }>();
const timeByTaskId = new Map(timeSums.map((row) => [row.taskId, Number(row.totalTime)]));
const detailById = new Map(
detailRows.map((task) => {
task.time = timeByTaskId.get(task.id) ?? 0;
return [task.id, task];
}),
);
const items = ids.map((id) => detailById.get(id)).filter((task): task is TMTask => task !== undefined);
return { items, hasMore };
} }
} }
@@ -0,0 +1,11 @@
import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { TMTime } from "../entities/time.entity";
@Injectable()
export class TimeRepository extends Repository<TMTime> {
constructor(@InjectRepository(TMTime) timeRepository: Repository<TMTime>) {
super(timeRepository.target, timeRepository.manager, timeRepository.queryRunner);
}
}
@@ -8,6 +8,7 @@ import { TMTask } from "./entities/task.entity";
import { TMRemark } from "./entities/remark.entity"; import { TMRemark } from "./entities/remark.entity";
import { TMAttachment } from "./entities/attachment.entity"; import { TMAttachment } from "./entities/attachment.entity";
import { TMCheckListItem } from "./entities/check-list-item.entity"; import { TMCheckListItem } from "./entities/check-list-item.entity";
import { TMTime } from "./entities/time.entity";
import { WorkspaceRepository } from "./repositories/workspace.repository"; import { WorkspaceRepository } from "./repositories/workspace.repository";
import { WorkspaceController } from "./controllers/workspace.controller"; import { WorkspaceController } from "./controllers/workspace.controller";
import { WorkspaceService } from "./providers/workspace.service"; import { WorkspaceService } from "./providers/workspace.service";
@@ -30,10 +31,13 @@ import { RemarkService } from "./providers/remark.service";
import { AttachmentController } from "./controllers/attachment.controller"; import { AttachmentController } from "./controllers/attachment.controller";
import { AttachmentRepository } from "./repositories/attachment.repository"; import { AttachmentRepository } from "./repositories/attachment.repository";
import { AttachmentService } from "./providers/attachment.service"; import { AttachmentService } from "./providers/attachment.service";
import { TimeController } from "./controllers/time.controller";
import { TimeRepository } from "./repositories/time.repository";
import { TimeService } from "./providers/time.service";
@Module({ @Module({
imports: [ imports: [
TypeOrmModule.forFeature([TMWorkspace, TMProject, TMTaskPhase, TMTask, TMRemark, TMAttachment, TMCheckListItem, User]), TypeOrmModule.forFeature([TMWorkspace, TMProject, TMTaskPhase, TMTask, TMRemark, TMAttachment, TMCheckListItem, TMTime, User]),
], ],
controllers: [ controllers: [
WorkspaceController, WorkspaceController,
@@ -42,7 +46,8 @@ import { AttachmentService } from "./providers/attachment.service";
TaskController, TaskController,
CheckListItemController, CheckListItemController,
RemarkController, RemarkController,
AttachmentController AttachmentController,
TimeController,
], ],
providers: [ providers: [
WorkspaceRepository, WorkspaceRepository,
@@ -58,7 +63,9 @@ import { AttachmentService } from "./providers/attachment.service";
RemarkRepository, RemarkRepository,
RemarkService, RemarkService,
AttachmentRepository, AttachmentRepository,
AttachmentService AttachmentService,
TimeRepository,
TimeService,
] ]
}) })
export class TaskManagerModule {} export class TaskManagerModule {}
+6 -2
View File
@@ -25,6 +25,10 @@ export enum PermissionEnum {
DPAGE = "dpage", DPAGE = "dpage",
DMAIL = 'dmail', DMAIL = 'dmail',
RESELLER="reseller", RESELLER="reseller",
WORKSPACE="workspace", WORKSPACE="workspace", // create, update, remove, read-one(for update purposes)
PROJECT="project" VIEW_ALL_WORKSPACES="view_all_workspaces",
PROJECT="project", // create, update, remove
VIEW_ALL_PROJECTS="view_all_projects",
TASK="task", // read, create, update, remove
TASK_PHASE="task_phase",
} }
@@ -0,0 +1,28 @@
import { BadRequestException } from "@nestjs/common";
interface CursorPayload {
priority: number;
createdAt: Date;
id: string;
}
export function decodeCursor(cursor: string): CursorPayload {
try {
const decoded = Buffer.from(cursor, "base64").toString("utf-8");
const [priorityStr, timestamp, id] = decoded.split("|");
if (!priorityStr || !timestamp || !id) throw new Error("Invalid format");
const priority = parseInt(priorityStr, 10);
if (isNaN(priority)) throw new Error("Priority not a number");
const createdAt = new Date(timestamp);
if (isNaN(createdAt.getTime())) throw new Error("Invalid date");
return { priority, createdAt, id };
} catch {
throw new BadRequestException(
"Invalid cursor. Expected base64encoded string containing priority, ISO date and id (separated by '|').",
);
}
}
export function encodeCursor(task: { priority: number; createdAt: Date; id: string }): string {
return Buffer.from(`${task.priority}|${task.createdAt.toISOString()}|${task.id}`).toString("base64");
}