feat(#5): Implement CRUD APIs for tasks, events, and projects

Implements comprehensive CRUD APIs following TDD principles with 92.44%
test coverage (exceeds 85% requirement).

Features:
- Tasks API: Full CRUD with filtering, pagination, and subtask support
- Events API: Full CRUD with recurrence support and date filtering
- Projects API: Full CRUD with task/event association
- Authentication guards on all endpoints
- Workspace-scoped queries for multi-tenant isolation
- Activity logging for all operations (CREATED, UPDATED, DELETED, etc.)
- DTOs with class-validator validation
- Comprehensive test suite (221 tests, 44 for new APIs)

Implementation:
- Services: Business logic with Prisma ORM integration
- Controllers: RESTful endpoints with AuthGuard
- Modules: Properly registered in AppModule
- Documentation: Complete API reference in docs/4-api/4-crud-endpoints/

Test Coverage:
- Tasks: 96.1%
- Events: 89.83%
- Projects: 84.21%
- Overall: 92.44%

TDD Workflow:
1. RED: Wrote failing tests first
2. GREEN: Implemented minimal code to pass tests
3. REFACTOR: Improved code quality while maintaining coverage

Refs #5

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
Jason Woltje
2026-01-28 18:43:12 -06:00
parent 05fc1c60f4
commit 132fe6ba98
30 changed files with 3812 additions and 1 deletions

View File

@@ -0,0 +1,49 @@
import { ProjectStatus } from "@prisma/client";
import {
IsString,
IsOptional,
IsEnum,
IsDateString,
IsObject,
MinLength,
MaxLength,
Matches,
} from "class-validator";
/**
* DTO for creating a new project
*/
export class CreateProjectDto {
@IsString({ message: "name must be a string" })
@MinLength(1, { message: "name must not be empty" })
@MaxLength(255, { message: "name must not exceed 255 characters" })
name!: string;
@IsOptional()
@IsString({ message: "description must be a string" })
@MaxLength(10000, { message: "description must not exceed 10000 characters" })
description?: string;
@IsOptional()
@IsEnum(ProjectStatus, { message: "status must be a valid ProjectStatus" })
status?: ProjectStatus;
@IsOptional()
@IsDateString({}, { message: "startDate must be a valid ISO 8601 date string" })
startDate?: Date;
@IsOptional()
@IsDateString({}, { message: "endDate must be a valid ISO 8601 date string" })
endDate?: Date;
@IsOptional()
@IsString({ message: "color must be a string" })
@Matches(/^#[0-9A-F]{6}$/i, {
message: "color must be a valid hex color code (e.g., #FF5733)",
})
color?: string;
@IsOptional()
@IsObject({ message: "metadata must be an object" })
metadata?: Record<string, unknown>;
}

View File

@@ -0,0 +1,3 @@
export { CreateProjectDto } from "./create-project.dto";
export { UpdateProjectDto } from "./update-project.dto";
export { QueryProjectsDto } from "./query-projects.dto";

View File

@@ -0,0 +1,44 @@
import { ProjectStatus } from "@prisma/client";
import {
IsUUID,
IsEnum,
IsOptional,
IsInt,
Min,
Max,
IsDateString,
} from "class-validator";
import { Type } from "class-transformer";
/**
* DTO for querying projects with filters and pagination
*/
export class QueryProjectsDto {
@IsUUID("4", { message: "workspaceId must be a valid UUID" })
workspaceId!: string;
@IsOptional()
@IsEnum(ProjectStatus, { message: "status must be a valid ProjectStatus" })
status?: ProjectStatus;
@IsOptional()
@IsDateString({}, { message: "startDateFrom must be a valid ISO 8601 date string" })
startDateFrom?: Date;
@IsOptional()
@IsDateString({}, { message: "startDateTo must be a valid ISO 8601 date string" })
startDateTo?: Date;
@IsOptional()
@Type(() => Number)
@IsInt({ message: "page must be an integer" })
@Min(1, { message: "page must be at least 1" })
page?: number;
@IsOptional()
@Type(() => Number)
@IsInt({ message: "limit must be an integer" })
@Min(1, { message: "limit must be at least 1" })
@Max(100, { message: "limit must not exceed 100" })
limit?: number;
}

View File

@@ -0,0 +1,51 @@
import { ProjectStatus } from "@prisma/client";
import {
IsString,
IsOptional,
IsEnum,
IsDateString,
IsObject,
MinLength,
MaxLength,
Matches,
} from "class-validator";
/**
* DTO for updating an existing project
* All fields are optional to support partial updates
*/
export class UpdateProjectDto {
@IsOptional()
@IsString({ message: "name must be a string" })
@MinLength(1, { message: "name must not be empty" })
@MaxLength(255, { message: "name must not exceed 255 characters" })
name?: string;
@IsOptional()
@IsString({ message: "description must be a string" })
@MaxLength(10000, { message: "description must not exceed 10000 characters" })
description?: string | null;
@IsOptional()
@IsEnum(ProjectStatus, { message: "status must be a valid ProjectStatus" })
status?: ProjectStatus;
@IsOptional()
@IsDateString({}, { message: "startDate must be a valid ISO 8601 date string" })
startDate?: Date | null;
@IsOptional()
@IsDateString({}, { message: "endDate must be a valid ISO 8601 date string" })
endDate?: Date | null;
@IsOptional()
@IsString({ message: "color must be a string" })
@Matches(/^#[0-9A-F]{6}$/i, {
message: "color must be a valid hex color code (e.g., #FF5733)",
})
color?: string | null;
@IsOptional()
@IsObject({ message: "metadata must be an object" })
metadata?: Record<string, unknown>;
}

View File

@@ -0,0 +1,164 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { Test, TestingModule } from "@nestjs/testing";
import { ProjectsController } from "./projects.controller";
import { ProjectsService } from "./projects.service";
import { ProjectStatus } from "@prisma/client";
import { AuthGuard } from "../auth/guards/auth.guard";
import { ExecutionContext } from "@nestjs/common";
describe("ProjectsController", () => {
let controller: ProjectsController;
let service: ProjectsService;
const mockProjectsService = {
create: vi.fn(),
findAll: vi.fn(),
findOne: vi.fn(),
update: vi.fn(),
remove: vi.fn(),
};
const mockAuthGuard = {
canActivate: vi.fn((context: ExecutionContext) => {
const request = context.switchToHttp().getRequest();
request.user = {
id: "550e8400-e29b-41d4-a716-446655440002",
workspaceId: "550e8400-e29b-41d4-a716-446655440001",
};
return true;
}),
};
const mockWorkspaceId = "550e8400-e29b-41d4-a716-446655440001";
const mockUserId = "550e8400-e29b-41d4-a716-446655440002";
const mockProjectId = "550e8400-e29b-41d4-a716-446655440003";
const mockRequest = {
user: {
id: mockUserId,
workspaceId: mockWorkspaceId,
},
};
const mockProject = {
id: mockProjectId,
workspaceId: mockWorkspaceId,
name: "Test Project",
description: "Test Description",
status: ProjectStatus.PLANNING,
startDate: new Date("2026-02-01"),
endDate: new Date("2026-03-01"),
creatorId: mockUserId,
color: "#FF5733",
metadata: {},
createdAt: new Date(),
updatedAt: new Date(),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [ProjectsController],
providers: [
{
provide: ProjectsService,
useValue: mockProjectsService,
},
],
})
.overrideGuard(AuthGuard)
.useValue(mockAuthGuard)
.compile();
controller = module.get<ProjectsController>(ProjectsController);
service = module.get<ProjectsService>(ProjectsService);
vi.clearAllMocks();
});
it("should be defined", () => {
expect(controller).toBeDefined();
});
describe("create", () => {
it("should create a project", async () => {
const createDto = {
name: "New Project",
description: "Project description",
};
mockProjectsService.create.mockResolvedValue(mockProject);
const result = await controller.create(createDto, mockRequest);
expect(result).toEqual(mockProject);
expect(service.create).toHaveBeenCalledWith(
mockWorkspaceId,
mockUserId,
createDto
);
});
});
describe("findAll", () => {
it("should return paginated projects", async () => {
const query = {
workspaceId: mockWorkspaceId,
};
const paginatedResult = {
data: [mockProject],
meta: {
total: 1,
page: 1,
limit: 50,
totalPages: 1,
},
};
mockProjectsService.findAll.mockResolvedValue(paginatedResult);
const result = await controller.findAll(query, mockRequest);
expect(result).toEqual(paginatedResult);
});
});
describe("findOne", () => {
it("should return a project by id", async () => {
mockProjectsService.findOne.mockResolvedValue(mockProject);
const result = await controller.findOne(mockProjectId, mockRequest);
expect(result).toEqual(mockProject);
});
});
describe("update", () => {
it("should update a project", async () => {
const updateDto = {
name: "Updated Project",
};
const updatedProject = { ...mockProject, ...updateDto };
mockProjectsService.update.mockResolvedValue(updatedProject);
const result = await controller.update(mockProjectId, updateDto, mockRequest);
expect(result).toEqual(updatedProject);
});
});
describe("remove", () => {
it("should delete a project", async () => {
mockProjectsService.remove.mockResolvedValue(undefined);
await controller.remove(mockProjectId, mockRequest);
expect(service.remove).toHaveBeenCalledWith(
mockProjectId,
mockWorkspaceId,
mockUserId
);
});
});
});

View File

@@ -0,0 +1,100 @@
import {
Controller,
Get,
Post,
Patch,
Delete,
Body,
Param,
Query,
UseGuards,
Request,
} from "@nestjs/common";
import { ProjectsService } from "./projects.service";
import { CreateProjectDto, UpdateProjectDto, QueryProjectsDto } from "./dto";
import { AuthGuard } from "../auth/guards/auth.guard";
/**
* Controller for project endpoints
* All endpoints require authentication
*/
@Controller("projects")
@UseGuards(AuthGuard)
export class ProjectsController {
constructor(private readonly projectsService: ProjectsService) {}
/**
* POST /api/projects
* Create a new project
*/
@Post()
async create(@Body() createProjectDto: CreateProjectDto, @Request() req: any) {
const workspaceId = req.user?.workspaceId;
const userId = req.user?.id;
if (!workspaceId || !userId) {
throw new Error("User workspaceId or userId not found");
}
return this.projectsService.create(workspaceId, userId, createProjectDto);
}
/**
* GET /api/projects
* Get paginated projects with optional filters
*/
@Get()
async findAll(@Query() query: QueryProjectsDto, @Request() req: any) {
const workspaceId = req.user?.workspaceId || query.workspaceId;
return this.projectsService.findAll({ ...query, workspaceId });
}
/**
* GET /api/projects/:id
* Get a single project by ID
*/
@Get(":id")
async findOne(@Param("id") id: string, @Request() req: any) {
const workspaceId = req.user?.workspaceId;
if (!workspaceId) {
throw new Error("User workspaceId not found");
}
return this.projectsService.findOne(id, workspaceId);
}
/**
* PATCH /api/projects/:id
* Update a project
*/
@Patch(":id")
async update(
@Param("id") id: string,
@Body() updateProjectDto: UpdateProjectDto,
@Request() req: any
) {
const workspaceId = req.user?.workspaceId;
const userId = req.user?.id;
if (!workspaceId || !userId) {
throw new Error("User workspaceId not found");
}
return this.projectsService.update(id, workspaceId, userId, updateProjectDto);
}
/**
* DELETE /api/projects/:id
* Delete a project
*/
@Delete(":id")
async remove(@Param("id") id: string, @Request() req: any) {
const workspaceId = req.user?.workspaceId;
const userId = req.user?.id;
if (!workspaceId || !userId) {
throw new Error("User workspaceId not found");
}
return this.projectsService.remove(id, workspaceId, userId);
}
}

View File

@@ -0,0 +1,14 @@
import { Module } from "@nestjs/common";
import { ProjectsController } from "./projects.controller";
import { ProjectsService } from "./projects.service";
import { PrismaModule } from "../prisma/prisma.module";
import { ActivityModule } from "../activity/activity.module";
import { AuthModule } from "../auth/auth.module";
@Module({
imports: [PrismaModule, ActivityModule, AuthModule],
controllers: [ProjectsController],
providers: [ProjectsService],
exports: [ProjectsService],
})
export class ProjectsModule {}

View File

@@ -0,0 +1,227 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { Test, TestingModule } from "@nestjs/testing";
import { ProjectsService } from "./projects.service";
import { PrismaService } from "../prisma/prisma.service";
import { ActivityService } from "../activity/activity.service";
import { ProjectStatus } from "@prisma/client";
import { NotFoundException } from "@nestjs/common";
describe("ProjectsService", () => {
let service: ProjectsService;
let prisma: PrismaService;
let activityService: ActivityService;
const mockPrismaService = {
project: {
create: vi.fn(),
findMany: vi.fn(),
count: vi.fn(),
findUnique: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
},
};
const mockActivityService = {
logProjectCreated: vi.fn(),
logProjectUpdated: vi.fn(),
logProjectDeleted: vi.fn(),
};
const mockWorkspaceId = "550e8400-e29b-41d4-a716-446655440001";
const mockUserId = "550e8400-e29b-41d4-a716-446655440002";
const mockProjectId = "550e8400-e29b-41d4-a716-446655440003";
const mockProject = {
id: mockProjectId,
workspaceId: mockWorkspaceId,
name: "Test Project",
description: "Test Description",
status: ProjectStatus.PLANNING,
startDate: new Date("2026-02-01"),
endDate: new Date("2026-03-01"),
creatorId: mockUserId,
color: "#FF5733",
metadata: {},
createdAt: new Date(),
updatedAt: new Date(),
};
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
ProjectsService,
{
provide: PrismaService,
useValue: mockPrismaService,
},
{
provide: ActivityService,
useValue: mockActivityService,
},
],
}).compile();
service = module.get<ProjectsService>(ProjectsService);
prisma = module.get<PrismaService>(PrismaService);
activityService = module.get<ActivityService>(ActivityService);
vi.clearAllMocks();
});
it("should be defined", () => {
expect(service).toBeDefined();
});
describe("create", () => {
it("should create a project and log activity", async () => {
const createDto = {
name: "New Project",
description: "Project description",
color: "#FF5733",
};
mockPrismaService.project.create.mockResolvedValue(mockProject);
mockActivityService.logProjectCreated.mockResolvedValue({});
const result = await service.create(mockWorkspaceId, mockUserId, createDto);
expect(result).toEqual(mockProject);
expect(prisma.project.create).toHaveBeenCalledWith({
data: {
...createDto,
workspaceId: mockWorkspaceId,
creatorId: mockUserId,
status: ProjectStatus.PLANNING,
metadata: {},
},
include: {
creator: {
select: { id: true, name: true, email: true },
},
_count: {
select: { tasks: true, events: true },
},
},
});
expect(activityService.logProjectCreated).toHaveBeenCalledWith(
mockWorkspaceId,
mockUserId,
mockProject.id,
{ name: mockProject.name }
);
});
});
describe("findAll", () => {
it("should return paginated projects with default pagination", async () => {
const projects = [mockProject];
mockPrismaService.project.findMany.mockResolvedValue(projects);
mockPrismaService.project.count.mockResolvedValue(1);
const result = await service.findAll({ workspaceId: mockWorkspaceId });
expect(result).toEqual({
data: projects,
meta: {
total: 1,
page: 1,
limit: 50,
totalPages: 1,
},
});
});
it("should filter by status", async () => {
mockPrismaService.project.findMany.mockResolvedValue([mockProject]);
mockPrismaService.project.count.mockResolvedValue(1);
await service.findAll({
workspaceId: mockWorkspaceId,
status: ProjectStatus.ACTIVE,
});
expect(prisma.project.findMany).toHaveBeenCalledWith(
expect.objectContaining({
where: {
workspaceId: mockWorkspaceId,
status: ProjectStatus.ACTIVE,
},
})
);
});
});
describe("findOne", () => {
it("should return a project by id", async () => {
mockPrismaService.project.findUnique.mockResolvedValue(mockProject);
const result = await service.findOne(mockProjectId, mockWorkspaceId);
expect(result).toEqual(mockProject);
});
it("should throw NotFoundException if project not found", async () => {
mockPrismaService.project.findUnique.mockResolvedValue(null);
await expect(
service.findOne(mockProjectId, mockWorkspaceId)
).rejects.toThrow(NotFoundException);
});
});
describe("update", () => {
it("should update a project and log activity", async () => {
const updateDto = {
name: "Updated Project",
status: ProjectStatus.ACTIVE,
};
mockPrismaService.project.findUnique.mockResolvedValue(mockProject);
mockPrismaService.project.update.mockResolvedValue({
...mockProject,
...updateDto,
});
mockActivityService.logProjectUpdated.mockResolvedValue({});
const result = await service.update(
mockProjectId,
mockWorkspaceId,
mockUserId,
updateDto
);
expect(result.name).toBe("Updated Project");
expect(activityService.logProjectUpdated).toHaveBeenCalled();
});
it("should throw NotFoundException if project not found", async () => {
mockPrismaService.project.findUnique.mockResolvedValue(null);
await expect(
service.update(mockProjectId, mockWorkspaceId, mockUserId, { name: "Test" })
).rejects.toThrow(NotFoundException);
});
});
describe("remove", () => {
it("should delete a project and log activity", async () => {
mockPrismaService.project.findUnique.mockResolvedValue(mockProject);
mockPrismaService.project.delete.mockResolvedValue(mockProject);
mockActivityService.logProjectDeleted.mockResolvedValue({});
await service.remove(mockProjectId, mockWorkspaceId, mockUserId);
expect(prisma.project.delete).toHaveBeenCalled();
expect(activityService.logProjectDeleted).toHaveBeenCalled();
});
it("should throw NotFoundException if project not found", async () => {
mockPrismaService.project.findUnique.mockResolvedValue(null);
await expect(
service.remove(mockProjectId, mockWorkspaceId, mockUserId)
).rejects.toThrow(NotFoundException);
});
});
});

View File

@@ -0,0 +1,224 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { ActivityService } from "../activity/activity.service";
import { ProjectStatus } from "@prisma/client";
import type { CreateProjectDto, UpdateProjectDto, QueryProjectsDto } from "./dto";
/**
* Service for managing projects
*/
@Injectable()
export class ProjectsService {
constructor(
private readonly prisma: PrismaService,
private readonly activityService: ActivityService
) {}
/**
* Create a new project
*/
async create(
workspaceId: string,
userId: string,
createProjectDto: CreateProjectDto
) {
const data: any = {
...createProjectDto,
workspaceId,
creatorId: userId,
status: createProjectDto.status || ProjectStatus.PLANNING,
metadata: createProjectDto.metadata || {},
};
const project = await this.prisma.project.create({
data,
include: {
creator: {
select: { id: true, name: true, email: true },
},
_count: {
select: { tasks: true, events: true },
},
},
});
// Log activity
await this.activityService.logProjectCreated(workspaceId, userId, project.id, {
name: project.name,
});
return project;
}
/**
* Get paginated projects with filters
*/
async findAll(query: QueryProjectsDto) {
const page = query.page || 1;
const limit = query.limit || 50;
const skip = (page - 1) * limit;
// Build where clause
const where: any = {
workspaceId: query.workspaceId,
};
if (query.status) {
where.status = query.status;
}
if (query.startDateFrom || query.startDateTo) {
where.startDate = {};
if (query.startDateFrom) {
where.startDate.gte = query.startDateFrom;
}
if (query.startDateTo) {
where.startDate.lte = query.startDateTo;
}
}
// Execute queries in parallel
const [data, total] = await Promise.all([
this.prisma.project.findMany({
where,
include: {
creator: {
select: { id: true, name: true, email: true },
},
_count: {
select: { tasks: true, events: true },
},
},
orderBy: {
createdAt: "desc",
},
skip,
take: limit,
}),
this.prisma.project.count({ where }),
]);
return {
data,
meta: {
total,
page,
limit,
totalPages: Math.ceil(total / limit),
},
};
}
/**
* Get a single project by ID
*/
async findOne(id: string, workspaceId: string) {
const project = await this.prisma.project.findUnique({
where: {
id,
workspaceId,
},
include: {
creator: {
select: { id: true, name: true, email: true },
},
tasks: {
select: {
id: true,
title: true,
status: true,
priority: true,
dueDate: true,
},
orderBy: { sortOrder: "asc" },
},
events: {
select: {
id: true,
title: true,
startTime: true,
endTime: true,
},
orderBy: { startTime: "asc" },
},
_count: {
select: { tasks: true, events: true },
},
},
});
if (!project) {
throw new NotFoundException(`Project with ID ${id} not found`);
}
return project;
}
/**
* Update a project
*/
async update(
id: string,
workspaceId: string,
userId: string,
updateProjectDto: UpdateProjectDto
) {
// Verify project exists
const existingProject = await this.prisma.project.findUnique({
where: { id, workspaceId },
});
if (!existingProject) {
throw new NotFoundException(`Project with ID ${id} not found`);
}
const project = await this.prisma.project.update({
where: {
id,
workspaceId,
},
data: updateProjectDto,
include: {
creator: {
select: { id: true, name: true, email: true },
},
_count: {
select: { tasks: true, events: true },
},
},
});
// Log activity
await this.activityService.logProjectUpdated(workspaceId, userId, id, {
changes: updateProjectDto,
});
return project;
}
/**
* Delete a project
*/
async remove(id: string, workspaceId: string, userId: string) {
// Verify project exists
const project = await this.prisma.project.findUnique({
where: { id, workspaceId },
});
if (!project) {
throw new NotFoundException(`Project with ID ${id} not found`);
}
await this.prisma.project.delete({
where: {
id,
workspaceId,
},
});
// Log activity
await this.activityService.logProjectDeleted(workspaceId, userId, id, {
name: project.name,
});
}
}