feat(v2.4): 切换测试与缺陷主写
This commit is contained in:
@@ -8,6 +8,8 @@ import { RequirementModule } from './modules/requirement/requirement.module';
|
||||
import { VersionModule } from './modules/version/version.module';
|
||||
import { VersionPlanModule } from './modules/version-plan/version-plan.module';
|
||||
import { DevTaskModule } from './modules/dev-task/dev-task.module';
|
||||
import { TestCaseModule } from './modules/test-case/test-case.module';
|
||||
import { BugModule } from './modules/bug/bug.module';
|
||||
import { AiModule } from './modules/ai/ai.module';
|
||||
import { ConfigModule } from './modules/config/config.module';
|
||||
import { DataModule } from './modules/data/data.module';
|
||||
@@ -23,6 +25,8 @@ import { HealthModule } from './modules/health/health.module';
|
||||
VersionModule,
|
||||
VersionPlanModule,
|
||||
DevTaskModule,
|
||||
TestCaseModule,
|
||||
BugModule,
|
||||
RequirementModule,
|
||||
ConfigModule,
|
||||
DataModule,
|
||||
|
||||
49
apps/server/src/modules/bug/bug.controller.ts
Normal file
49
apps/server/src/modules/bug/bug.controller.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
|
||||
import { CreateBugDto } from './dto/create-bug.dto';
|
||||
import { UpdateBugDto } from './dto/update-bug.dto';
|
||||
import { BugService } from './bug.service';
|
||||
|
||||
@Controller('versions/:versionId/bugs')
|
||||
export class BugController {
|
||||
constructor(private readonly bugService: BugService) {}
|
||||
|
||||
@Post()
|
||||
create(@Param('versionId') versionId: string, @Body() dto: CreateBugDto) {
|
||||
return this.bugService.create(versionId, dto);
|
||||
}
|
||||
|
||||
@Get()
|
||||
findAll(@Param('versionId') versionId: string) {
|
||||
return this.bugService.findAll(versionId);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(@Param('versionId') versionId: string, @Param('id') id: string, @Body() dto: UpdateBugDto) {
|
||||
return this.bugService.update(versionId, id, dto);
|
||||
}
|
||||
|
||||
@Patch(':id/status')
|
||||
updateStatus(
|
||||
@Param('versionId') versionId: string,
|
||||
@Param('id') id: string,
|
||||
@Body('status') status: string,
|
||||
@Body() body: { operator?: string; resolution?: string },
|
||||
) {
|
||||
return this.bugService.updateStatus(versionId, id, status, body);
|
||||
}
|
||||
|
||||
@Patch(':id/transfer')
|
||||
transfer(
|
||||
@Param('versionId') versionId: string,
|
||||
@Param('id') id: string,
|
||||
@Body('assigneeId') assigneeId: string,
|
||||
@Body('operator') operator?: string,
|
||||
) {
|
||||
return this.bugService.transfer(versionId, id, assigneeId, operator);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
remove(@Param('versionId') versionId: string, @Param('id') id: string) {
|
||||
return this.bugService.remove(versionId, id);
|
||||
}
|
||||
}
|
||||
12
apps/server/src/modules/bug/bug.module.ts
Normal file
12
apps/server/src/modules/bug/bug.module.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { WorkActivityModule } from '../work-activity/work-activity.module';
|
||||
import { BugController } from './bug.controller';
|
||||
import { BugService } from './bug.service';
|
||||
|
||||
@Module({
|
||||
imports: [WorkActivityModule],
|
||||
controllers: [BugController],
|
||||
providers: [BugService],
|
||||
exports: [BugService],
|
||||
})
|
||||
export class BugModule {}
|
||||
153
apps/server/src/modules/bug/bug.service.spec.ts
Normal file
153
apps/server/src/modules/bug/bug.service.spec.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { BugService } from './bug.service';
|
||||
|
||||
describe('BugService domain writes', () => {
|
||||
const makeService = () => {
|
||||
const workActivity = {
|
||||
record: jest.fn().mockResolvedValue({ id: 'activity-1' }),
|
||||
};
|
||||
const prisma = {
|
||||
version: {
|
||||
findUnique: jest.fn(),
|
||||
},
|
||||
bug: {
|
||||
create: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
findFirst: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
update: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
prisma,
|
||||
workActivity,
|
||||
service: new BugService(prisma as any, workActivity as any),
|
||||
};
|
||||
};
|
||||
|
||||
it('creates bugs directly under a version partition', async () => {
|
||||
const { prisma, workActivity, service } = makeService();
|
||||
prisma.version.findUnique.mockResolvedValue({ id: 'version-1', productId: 'product-1', projectId: 'project-1' });
|
||||
prisma.bug.create.mockResolvedValue({ id: 'bug-1', versionId: 'version-1', title: '登录报错' });
|
||||
|
||||
await service.create('version-1', {
|
||||
bugNo: 'BUG-001',
|
||||
testCaseId: 'tc-1',
|
||||
title: '登录报错',
|
||||
description: '登录按钮无响应',
|
||||
severity: 'critical',
|
||||
priority: 'P0',
|
||||
assigneeId: 'dev-1',
|
||||
reportedBy: 'tester-1',
|
||||
plannedFixAt: '2026-07-08T18:00:00.000Z',
|
||||
} as any);
|
||||
|
||||
expect(prisma.bug.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
versionId: 'version-1',
|
||||
productId: 'product-1',
|
||||
projectId: 'project-1',
|
||||
testCaseId: 'tc-1',
|
||||
testCaseVersionId: 'version-1',
|
||||
code: 'BUG-001',
|
||||
title: '登录报错',
|
||||
severity: 'critical',
|
||||
priority: 0,
|
||||
assigneeId: 'dev-1',
|
||||
reporterId: 'tester-1',
|
||||
plannedFixAt: new Date('2026-07-08T18:00:00.000Z'),
|
||||
status: 'open',
|
||||
}),
|
||||
});
|
||||
expect(workActivity.record).toHaveBeenCalledWith(expect.objectContaining({
|
||||
versionId: 'version-1',
|
||||
sourceType: 'bug',
|
||||
sourceId: 'bug-1',
|
||||
action: 'bug_created',
|
||||
}));
|
||||
});
|
||||
|
||||
it('changes status and records closing evidence inside the version partition', async () => {
|
||||
const { prisma, workActivity, service } = makeService();
|
||||
prisma.bug.findFirst.mockResolvedValue({
|
||||
id: 'bug-1',
|
||||
versionId: 'version-1',
|
||||
productId: 'product-1',
|
||||
projectId: 'project-1',
|
||||
status: 'verifying',
|
||||
title: '登录报错',
|
||||
assigneeId: 'dev-1',
|
||||
reporterId: 'tester-1',
|
||||
});
|
||||
prisma.bug.update.mockResolvedValue({
|
||||
id: 'bug-1',
|
||||
versionId: 'version-1',
|
||||
productId: 'product-1',
|
||||
projectId: 'project-1',
|
||||
status: 'closed',
|
||||
title: '登录报错',
|
||||
assigneeId: 'dev-1',
|
||||
reporterId: 'tester-1',
|
||||
});
|
||||
|
||||
await service.updateStatus('version-1', 'bug-1', 'closed', { operator: 'tester-1', resolution: '复测通过' });
|
||||
|
||||
expect(prisma.bug.update).toHaveBeenCalledWith({
|
||||
where: { id_versionId: { id: 'bug-1', versionId: 'version-1' } },
|
||||
data: expect.objectContaining({
|
||||
status: 'closed',
|
||||
closedAt: expect.any(Date),
|
||||
resolution: '复测通过',
|
||||
}),
|
||||
});
|
||||
expect(workActivity.record).toHaveBeenCalledWith(expect.objectContaining({
|
||||
versionId: 'version-1',
|
||||
sourceType: 'bug',
|
||||
sourceId: 'bug-1',
|
||||
action: 'bug_closed',
|
||||
}));
|
||||
});
|
||||
|
||||
it('transfers bugs by id plus version id and records activity evidence', async () => {
|
||||
const { prisma, workActivity, service } = makeService();
|
||||
prisma.bug.findFirst.mockResolvedValue({
|
||||
id: 'bug-1',
|
||||
versionId: 'version-1',
|
||||
productId: 'product-1',
|
||||
projectId: 'project-1',
|
||||
status: 'open',
|
||||
title: '登录报错',
|
||||
assigneeId: 'dev-1',
|
||||
reporterId: 'tester-1',
|
||||
});
|
||||
prisma.bug.update.mockResolvedValue({
|
||||
id: 'bug-1',
|
||||
versionId: 'version-1',
|
||||
productId: 'product-1',
|
||||
projectId: 'project-1',
|
||||
title: '登录报错',
|
||||
assigneeId: 'dev-2',
|
||||
reporterId: 'tester-1',
|
||||
});
|
||||
|
||||
await service.transfer('version-1', 'bug-1', 'dev-2', 'tester-1');
|
||||
|
||||
expect(prisma.bug.update).toHaveBeenCalledWith({
|
||||
where: { id_versionId: { id: 'bug-1', versionId: 'version-1' } },
|
||||
data: { assigneeId: 'dev-2' },
|
||||
});
|
||||
expect(workActivity.record).toHaveBeenCalledWith(expect.objectContaining({
|
||||
action: 'bug_transferred',
|
||||
metadata: expect.objectContaining({ fromAssigneeId: 'dev-1', toAssigneeId: 'dev-2' }),
|
||||
}));
|
||||
});
|
||||
|
||||
it('rejects updates outside the version partition', async () => {
|
||||
const { prisma, service } = makeService();
|
||||
prisma.bug.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(service.update('version-1', 'missing-bug', { title: 'Ghost' })).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(prisma.bug.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
176
apps/server/src/modules/bug/bug.service.ts
Normal file
176
apps/server/src/modules/bug/bug.service.ts
Normal file
@@ -0,0 +1,176 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { WorkActivityService } from '../work-activity/work-activity.service';
|
||||
import { CreateBugDto } from './dto/create-bug.dto';
|
||||
import { UpdateBugDto } from './dto/update-bug.dto';
|
||||
|
||||
@Injectable()
|
||||
export class BugService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly workActivity: WorkActivityService,
|
||||
) {}
|
||||
|
||||
async create(versionId: string, dto: CreateBugDto) {
|
||||
const version = await this.ensureVersion(versionId);
|
||||
const item = await this.prisma.bug.create({
|
||||
data: {
|
||||
...this.toBugData(dto),
|
||||
versionId,
|
||||
productId: version.productId,
|
||||
projectId: version.projectId,
|
||||
testCaseVersionId: dto.testCaseVersionId ?? (dto.testCaseId ? versionId : null),
|
||||
code: dto.code?.trim() || dto.bugNo?.trim() || createFallbackCode('BUG'),
|
||||
title: dto.title,
|
||||
status: dto.status ?? 'open',
|
||||
},
|
||||
});
|
||||
const activity = await this.recordBugActivity(item, 'bug_created', 'creation', `新建 Bug:${item.title}`, {
|
||||
operator: dto.reporterId ?? dto.reportedBy,
|
||||
});
|
||||
return { item, activities: [activity] };
|
||||
}
|
||||
|
||||
findAll(versionId: string) {
|
||||
return this.prisma.bug.findMany({
|
||||
where: { versionId },
|
||||
orderBy: [{ status: 'asc' }, { updatedAt: 'desc' }],
|
||||
});
|
||||
}
|
||||
|
||||
async update(versionId: string, id: string, dto: UpdateBugDto) {
|
||||
await this.ensureBugInVersion(versionId, id);
|
||||
const item = await this.prisma.bug.update({
|
||||
where: { id_versionId: { id, versionId } },
|
||||
data: this.toBugData(dto),
|
||||
});
|
||||
return { item, activities: [] };
|
||||
}
|
||||
|
||||
async updateStatus(
|
||||
versionId: string,
|
||||
id: string,
|
||||
status: string,
|
||||
options: { operator?: string; resolution?: string } = {},
|
||||
) {
|
||||
const current = await this.ensureBugInVersion(versionId, id);
|
||||
const data: Record<string, unknown> = { status };
|
||||
if (status === 'fixed' && !current.resolvedAt) data.resolvedAt = new Date();
|
||||
if (status === 'closed' && !current.closedAt) data.closedAt = new Date();
|
||||
if (options.resolution?.trim()) data.resolution = options.resolution.trim();
|
||||
const item = await this.prisma.bug.update({
|
||||
where: { id_versionId: { id, versionId } },
|
||||
data,
|
||||
});
|
||||
const activity = await this.recordStatusActivity(item, current.status, status, options.operator);
|
||||
return { item, activities: activity ? [activity] : [] };
|
||||
}
|
||||
|
||||
async transfer(versionId: string, id: string, assigneeId: string, operator?: string) {
|
||||
const current = await this.ensureBugInVersion(versionId, id);
|
||||
const item = await this.prisma.bug.update({
|
||||
where: { id_versionId: { id, versionId } },
|
||||
data: { assigneeId },
|
||||
});
|
||||
const activity = await this.recordBugActivity(
|
||||
item,
|
||||
'bug_transferred',
|
||||
'progress',
|
||||
`转交 Bug:${item.title} → ${assigneeId}`,
|
||||
{ fromAssigneeId: current.assigneeId, toAssigneeId: assigneeId, operator },
|
||||
);
|
||||
return { item, activities: [activity] };
|
||||
}
|
||||
|
||||
async remove(versionId: string, id: string) {
|
||||
await this.ensureBugInVersion(versionId, id);
|
||||
return this.prisma.bug.delete({ where: { id_versionId: { id, versionId } } });
|
||||
}
|
||||
|
||||
private toBugData(dto: Partial<CreateBugDto>) {
|
||||
return {
|
||||
...(dto.testCaseId !== undefined && { testCaseId: emptyToNull(dto.testCaseId) }),
|
||||
...(dto.testCaseVersionId !== undefined && { testCaseVersionId: emptyToNull(dto.testCaseVersionId) }),
|
||||
...(dto.code !== undefined || dto.bugNo !== undefined ? { code: dto.code?.trim() || dto.bugNo?.trim() } : {}),
|
||||
...(dto.title !== undefined && { title: dto.title }),
|
||||
...(dto.description !== undefined && { description: dto.description ?? '' }),
|
||||
...(dto.status !== undefined && { status: dto.status }),
|
||||
...(dto.severity !== undefined && { severity: dto.severity ?? 'minor' }),
|
||||
...(dto.priority !== undefined && { priority: parsePriority(dto.priority) ?? 0 }),
|
||||
...(dto.assigneeId !== undefined && { assigneeId: emptyToNull(dto.assigneeId) }),
|
||||
...(dto.reporterId !== undefined || dto.reportedBy !== undefined ? { reporterId: emptyToNull(dto.reporterId ?? dto.reportedBy) } : {}),
|
||||
...(dto.plannedFixAt !== undefined && { plannedFixAt: parseOptionalDate(dto.plannedFixAt) }),
|
||||
...(dto.resolvedAt !== undefined && { resolvedAt: parseOptionalDate(dto.resolvedAt) }),
|
||||
...(dto.closedAt !== undefined && { closedAt: parseOptionalDate(dto.closedAt) }),
|
||||
...(dto.resolution !== undefined && { resolution: emptyToNull(dto.resolution) }),
|
||||
};
|
||||
}
|
||||
|
||||
private async ensureVersion(versionId: string) {
|
||||
const version = await this.prisma.version.findUnique({ where: { id: versionId } });
|
||||
if (!version) throw new NotFoundException('版本不存在');
|
||||
if (!version.projectId) throw new BadRequestException('Bug 所属版本必须归属于项目');
|
||||
return { ...version, projectId: version.projectId };
|
||||
}
|
||||
|
||||
private async ensureBugInVersion(versionId: string, id: string) {
|
||||
const bug = await this.prisma.bug.findFirst({ where: { id, versionId } });
|
||||
if (!bug) throw new NotFoundException('Bug 不存在');
|
||||
return bug;
|
||||
}
|
||||
|
||||
private recordStatusActivity(bug: any, fromStatus: string, toStatus: string, operator?: string) {
|
||||
if (toStatus === 'fixing') {
|
||||
return this.recordBugActivity(bug, 'bug_fixing', 'progress', `开始修复 Bug:${bug.title}`, { fromStatus, toStatus, operator });
|
||||
}
|
||||
if (toStatus === 'fixed') {
|
||||
return this.recordBugActivity(bug, 'bug_fixed', 'delivery', `已修复 Bug:${bug.title}`, { fromStatus, toStatus, operator });
|
||||
}
|
||||
if (toStatus === 'closed') {
|
||||
return this.recordBugActivity(bug, 'bug_closed', 'delivery', `已关闭 Bug:${bug.title}`, { fromStatus, toStatus, operator });
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private recordBugActivity(bug: any, action: string, category: string, summary: string, metadata: Record<string, unknown> = {}) {
|
||||
return this.workActivity.record({
|
||||
versionId: bug.versionId,
|
||||
productId: bug.productId,
|
||||
projectId: bug.projectId,
|
||||
actorId: metadata.operator as string | undefined ?? bug.assigneeId ?? bug.reporterId,
|
||||
sourceType: 'bug',
|
||||
sourceId: bug.id,
|
||||
action,
|
||||
category,
|
||||
title: bug.title,
|
||||
summary,
|
||||
metadata,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function createFallbackCode(prefix: string) {
|
||||
return `${prefix}-${Date.now().toString(36).toUpperCase()}`;
|
||||
}
|
||||
|
||||
function emptyToNull(value: string | null | undefined): string | null {
|
||||
if (value === null) return null;
|
||||
if (value === undefined) return null;
|
||||
const trimmed = value.trim();
|
||||
return trimmed ? trimmed : null;
|
||||
}
|
||||
|
||||
function parseOptionalDate(value: string | null | undefined): Date | null {
|
||||
if (!value) return null;
|
||||
const date = new Date(value);
|
||||
return Number.isFinite(date.getTime()) ? date : null;
|
||||
}
|
||||
|
||||
function parsePriority(value: string | number | null | undefined): number | undefined {
|
||||
if (value === null || value === undefined || value === '') return undefined;
|
||||
if (typeof value === 'number') return Number.isFinite(value) ? Math.max(0, Math.min(4, Math.floor(value))) : undefined;
|
||||
const match = /^P([0-4])$/i.exec(value.trim());
|
||||
if (match) return Number(match[1]);
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? Math.max(0, Math.min(4, Math.floor(parsed))) : undefined;
|
||||
}
|
||||
65
apps/server/src/modules/bug/dto/create-bug.dto.ts
Normal file
65
apps/server/src/modules/bug/dto/create-bug.dto.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
import { IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class CreateBugDto {
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
testCaseId?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
testCaseVersionId?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
code?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
bugNo?: string;
|
||||
|
||||
@IsString()
|
||||
title!: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
status?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
severity?: string;
|
||||
|
||||
@IsOptional()
|
||||
priority?: string | number;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
assigneeId?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
reporterId?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
reportedBy?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
plannedFixAt?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
resolvedAt?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
closedAt?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
resolution?: string;
|
||||
}
|
||||
4
apps/server/src/modules/bug/dto/update-bug.dto.ts
Normal file
4
apps/server/src/modules/bug/dto/update-bug.dto.ts
Normal file
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { CreateBugDto } from './create-bug.dto';
|
||||
|
||||
export class UpdateBugDto extends PartialType(CreateBugDto) {}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { IsArray, IsBoolean, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class CreateTestCaseDto {
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
requirementId?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
requirementProductId?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
categoryId?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
code?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
caseNo?: string;
|
||||
|
||||
@IsString()
|
||||
title!: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
description?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
status?: string;
|
||||
|
||||
@IsOptional()
|
||||
roundNo?: number;
|
||||
|
||||
@IsOptional()
|
||||
priority?: string | number;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
assigneeId?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
creatorId?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
createdBy?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
plannedTestAt?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
plannedEndAt?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
startedAt?: string;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
completedAt?: string;
|
||||
|
||||
@IsOptional()
|
||||
estimateHours?: number;
|
||||
|
||||
@IsOptional()
|
||||
aiEstimateHours?: number;
|
||||
|
||||
@IsArray()
|
||||
@IsOptional()
|
||||
references?: unknown[];
|
||||
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
aiDraft?: boolean;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
aiDraftAt?: string;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/mapped-types';
|
||||
import { CreateTestCaseDto } from './create-test-case.dto';
|
||||
|
||||
export class UpdateTestCaseDto extends PartialType(CreateTestCaseDto) {}
|
||||
43
apps/server/src/modules/test-case/test-case.controller.ts
Normal file
43
apps/server/src/modules/test-case/test-case.controller.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
|
||||
import { CreateTestCaseDto } from './dto/create-test-case.dto';
|
||||
import { UpdateTestCaseDto } from './dto/update-test-case.dto';
|
||||
import { TestCaseService } from './test-case.service';
|
||||
|
||||
@Controller('versions/:versionId/test-cases')
|
||||
export class TestCaseController {
|
||||
constructor(private readonly testCaseService: TestCaseService) {}
|
||||
|
||||
@Post()
|
||||
create(@Param('versionId') versionId: string, @Body() dto: CreateTestCaseDto) {
|
||||
return this.testCaseService.create(versionId, dto);
|
||||
}
|
||||
|
||||
@Post('batch')
|
||||
createMany(@Param('versionId') versionId: string, @Body('items') items: CreateTestCaseDto[]) {
|
||||
return this.testCaseService.createMany(versionId, items ?? []);
|
||||
}
|
||||
|
||||
@Get()
|
||||
findAll(@Param('versionId') versionId: string) {
|
||||
return this.testCaseService.findAll(versionId);
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(@Param('versionId') versionId: string, @Param('id') id: string, @Body() dto: UpdateTestCaseDto) {
|
||||
return this.testCaseService.update(versionId, id, dto);
|
||||
}
|
||||
|
||||
@Patch(':id/status')
|
||||
updateStatus(
|
||||
@Param('versionId') versionId: string,
|
||||
@Param('id') id: string,
|
||||
@Body('status') status: string,
|
||||
) {
|
||||
return this.testCaseService.updateStatus(versionId, id, status);
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
remove(@Param('versionId') versionId: string, @Param('id') id: string) {
|
||||
return this.testCaseService.remove(versionId, id);
|
||||
}
|
||||
}
|
||||
12
apps/server/src/modules/test-case/test-case.module.ts
Normal file
12
apps/server/src/modules/test-case/test-case.module.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { WorkActivityModule } from '../work-activity/work-activity.module';
|
||||
import { TestCaseController } from './test-case.controller';
|
||||
import { TestCaseService } from './test-case.service';
|
||||
|
||||
@Module({
|
||||
imports: [WorkActivityModule],
|
||||
controllers: [TestCaseController],
|
||||
providers: [TestCaseService],
|
||||
exports: [TestCaseService],
|
||||
})
|
||||
export class TestCaseModule {}
|
||||
141
apps/server/src/modules/test-case/test-case.service.spec.ts
Normal file
141
apps/server/src/modules/test-case/test-case.service.spec.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import { TestCaseService } from './test-case.service';
|
||||
|
||||
describe('TestCaseService domain writes', () => {
|
||||
const makeService = () => {
|
||||
const workActivity = {
|
||||
record: jest.fn().mockResolvedValue({ id: 'activity-1' }),
|
||||
};
|
||||
const prisma = {
|
||||
version: {
|
||||
findUnique: jest.fn(),
|
||||
},
|
||||
testCase: {
|
||||
create: jest.fn(),
|
||||
createMany: jest.fn(),
|
||||
delete: jest.fn(),
|
||||
findFirst: jest.fn(),
|
||||
findMany: jest.fn(),
|
||||
update: jest.fn(),
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
prisma,
|
||||
workActivity,
|
||||
service: new TestCaseService(prisma as any, workActivity as any),
|
||||
};
|
||||
};
|
||||
|
||||
it('creates test cases directly under a version partition', async () => {
|
||||
const { prisma, workActivity, service } = makeService();
|
||||
prisma.version.findUnique.mockResolvedValue({ id: 'version-1', productId: 'product-1', projectId: 'project-1' });
|
||||
prisma.testCase.create.mockResolvedValue({ id: 'tc-1', versionId: 'version-1', title: '登录冒烟' });
|
||||
|
||||
await service.create('version-1', {
|
||||
requirementId: 'req-1',
|
||||
requirementProductId: 'product-1',
|
||||
caseNo: 'TC-001',
|
||||
title: '登录冒烟',
|
||||
categoryId: 'cat-test',
|
||||
assigneeId: 'tester-1',
|
||||
priority: 'P1',
|
||||
plannedTestAt: '2026-07-08T09:00:00.000Z',
|
||||
plannedEndAt: '2026-07-08T10:00:00.000Z',
|
||||
estimateHours: 1,
|
||||
references: [{ type: 'requirement', id: 'REQ-001', label: 'REQ-001 登录' }],
|
||||
createdBy: 'member-pm',
|
||||
} as any);
|
||||
|
||||
expect(prisma.testCase.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({
|
||||
versionId: 'version-1',
|
||||
productId: 'product-1',
|
||||
projectId: 'project-1',
|
||||
requirementId: 'req-1',
|
||||
requirementProductId: 'product-1',
|
||||
code: 'TC-001',
|
||||
title: '登录冒烟',
|
||||
categoryId: 'cat-test',
|
||||
assigneeId: 'tester-1',
|
||||
priority: 1,
|
||||
plannedTestAt: new Date('2026-07-08T09:00:00.000Z'),
|
||||
plannedEndAt: new Date('2026-07-08T10:00:00.000Z'),
|
||||
estimateHours: 1,
|
||||
status: 'pending',
|
||||
}),
|
||||
});
|
||||
expect(workActivity.record).toHaveBeenCalledWith(expect.objectContaining({
|
||||
versionId: 'version-1',
|
||||
sourceType: 'test_case',
|
||||
sourceId: 'tc-1',
|
||||
action: 'test_case_created',
|
||||
}));
|
||||
});
|
||||
|
||||
it('changes status by id plus version id and records activity evidence', async () => {
|
||||
const { prisma, workActivity, service } = makeService();
|
||||
prisma.testCase.findFirst.mockResolvedValue({
|
||||
id: 'tc-1',
|
||||
versionId: 'version-1',
|
||||
productId: 'product-1',
|
||||
projectId: 'project-1',
|
||||
status: 'pending',
|
||||
title: '登录冒烟',
|
||||
assigneeId: 'tester-1',
|
||||
});
|
||||
prisma.testCase.update.mockResolvedValue({
|
||||
id: 'tc-1',
|
||||
versionId: 'version-1',
|
||||
productId: 'product-1',
|
||||
projectId: 'project-1',
|
||||
status: 'running',
|
||||
title: '登录冒烟',
|
||||
assigneeId: 'tester-1',
|
||||
});
|
||||
|
||||
await service.updateStatus('version-1', 'tc-1', 'running');
|
||||
|
||||
expect(prisma.testCase.update).toHaveBeenCalledWith({
|
||||
where: { id_versionId: { id: 'tc-1', versionId: 'version-1' } },
|
||||
data: expect.objectContaining({
|
||||
status: 'running',
|
||||
startedAt: expect.any(Date),
|
||||
}),
|
||||
});
|
||||
expect(workActivity.record).toHaveBeenCalledWith(expect.objectContaining({
|
||||
versionId: 'version-1',
|
||||
sourceType: 'test_case',
|
||||
sourceId: 'tc-1',
|
||||
action: 'test_case_started',
|
||||
}));
|
||||
});
|
||||
|
||||
it('creates copied round test cases in the same version partition', async () => {
|
||||
const { prisma, service } = makeService();
|
||||
prisma.version.findUnique.mockResolvedValue({ id: 'version-1', productId: 'product-1', projectId: 'project-1' });
|
||||
prisma.testCase.createMany.mockResolvedValue({ count: 2 });
|
||||
prisma.testCase.findMany.mockResolvedValue([{ id: 'tc-copy-1' }, { id: 'tc-copy-2' }]);
|
||||
|
||||
await service.createMany('version-1', [
|
||||
{ caseNo: 'TC-101', title: '第二轮登录', roundNo: 2, createdBy: 'tester-1' },
|
||||
{ caseNo: 'TC-102', title: '第二轮支付', roundNo: 2, createdBy: 'tester-1' },
|
||||
] as any);
|
||||
|
||||
expect(prisma.testCase.createMany).toHaveBeenCalledWith({
|
||||
data: [
|
||||
expect.objectContaining({ versionId: 'version-1', productId: 'product-1', projectId: 'project-1', roundNo: 2, status: 'pending' }),
|
||||
expect.objectContaining({ versionId: 'version-1', productId: 'product-1', projectId: 'project-1', roundNo: 2, status: 'pending' }),
|
||||
],
|
||||
skipDuplicates: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects updates outside the version partition', async () => {
|
||||
const { prisma, service } = makeService();
|
||||
prisma.testCase.findFirst.mockResolvedValue(null);
|
||||
|
||||
await expect(service.update('version-1', 'missing-case', { title: 'Ghost' })).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(prisma.testCase.update).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
194
apps/server/src/modules/test-case/test-case.service.ts
Normal file
194
apps/server/src/modules/test-case/test-case.service.ts
Normal file
@@ -0,0 +1,194 @@
|
||||
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import type { Prisma } from '@prisma/client';
|
||||
import { PrismaService } from '../../prisma/prisma.service';
|
||||
import { WorkActivityService } from '../work-activity/work-activity.service';
|
||||
import { CreateTestCaseDto } from './dto/create-test-case.dto';
|
||||
import { UpdateTestCaseDto } from './dto/update-test-case.dto';
|
||||
|
||||
@Injectable()
|
||||
export class TestCaseService {
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly workActivity: WorkActivityService,
|
||||
) {}
|
||||
|
||||
async create(versionId: string, dto: CreateTestCaseDto) {
|
||||
const version = await this.ensureVersion(versionId);
|
||||
const item = await this.prisma.testCase.create({
|
||||
data: {
|
||||
...this.toTestCaseData(dto),
|
||||
versionId,
|
||||
productId: version.productId,
|
||||
projectId: version.projectId,
|
||||
code: dto.code?.trim() || dto.caseNo?.trim() || createFallbackCode('TC'),
|
||||
title: dto.title,
|
||||
status: dto.status ?? 'pending',
|
||||
},
|
||||
});
|
||||
const activity = await this.recordTestCaseActivity(item, 'test_case_created', 'creation', `新建测试用例:${item.title}`);
|
||||
return { item, activities: [activity] };
|
||||
}
|
||||
|
||||
async createMany(versionId: string, dtos: CreateTestCaseDto[]) {
|
||||
if (dtos.length === 0) return { items: [], activities: [] };
|
||||
const version = await this.ensureVersion(versionId);
|
||||
const rows = dtos.map((dto) => ({
|
||||
...this.toTestCaseData(dto),
|
||||
versionId,
|
||||
productId: version.productId,
|
||||
projectId: version.projectId,
|
||||
code: dto.code?.trim() || dto.caseNo?.trim() || createFallbackCode('TC'),
|
||||
title: dto.title,
|
||||
status: dto.status ?? 'pending',
|
||||
}));
|
||||
await this.prisma.testCase.createMany({ data: rows, skipDuplicates: true });
|
||||
const items = await this.prisma.testCase.findMany({
|
||||
where: { versionId, code: { in: rows.map((row) => row.code) } },
|
||||
});
|
||||
const activities = await Promise.all(items.map((item) => (
|
||||
this.recordTestCaseActivity(item, 'test_case_created', 'creation', `新建测试用例:${item.title}`)
|
||||
)));
|
||||
return { items, activities };
|
||||
}
|
||||
|
||||
findAll(versionId: string) {
|
||||
return this.prisma.testCase.findMany({
|
||||
where: { versionId },
|
||||
orderBy: [{ roundNo: 'asc' }, { code: 'asc' }],
|
||||
});
|
||||
}
|
||||
|
||||
async update(versionId: string, id: string, dto: UpdateTestCaseDto) {
|
||||
await this.ensureTestCaseInVersion(versionId, id);
|
||||
const item = await this.prisma.testCase.update({
|
||||
where: { id_versionId: { id, versionId } },
|
||||
data: this.toTestCaseData(dto),
|
||||
});
|
||||
return { item, activities: [] };
|
||||
}
|
||||
|
||||
async updateStatus(versionId: string, id: string, status: string) {
|
||||
const current = await this.ensureTestCaseInVersion(versionId, id);
|
||||
const data: Record<string, unknown> = { status };
|
||||
if (status === 'running' && !current.startedAt) data.startedAt = new Date();
|
||||
if ((status === 'passed' || status === 'failed' || status === 'blocked') && !current.completedAt) {
|
||||
data.completedAt = new Date();
|
||||
}
|
||||
const item = await this.prisma.testCase.update({
|
||||
where: { id_versionId: { id, versionId } },
|
||||
data,
|
||||
});
|
||||
const activity = await this.recordStatusActivity(item, current.status, status);
|
||||
return { item, activities: activity ? [activity] : [] };
|
||||
}
|
||||
|
||||
async remove(versionId: string, id: string) {
|
||||
await this.ensureTestCaseInVersion(versionId, id);
|
||||
return this.prisma.testCase.delete({ where: { id_versionId: { id, versionId } } });
|
||||
}
|
||||
|
||||
private toTestCaseData(dto: Partial<CreateTestCaseDto>) {
|
||||
return {
|
||||
...(dto.requirementId !== undefined && { requirementId: emptyToNull(dto.requirementId) }),
|
||||
...(dto.requirementProductId !== undefined && { requirementProductId: emptyToNull(dto.requirementProductId) }),
|
||||
...(dto.categoryId !== undefined && { categoryId: emptyToNull(dto.categoryId) }),
|
||||
...(dto.code !== undefined || dto.caseNo !== undefined ? { code: dto.code?.trim() || dto.caseNo?.trim() } : {}),
|
||||
...(dto.title !== undefined && { title: dto.title }),
|
||||
...(dto.description !== undefined && { description: dto.description ?? '' }),
|
||||
...(dto.status !== undefined && { status: dto.status }),
|
||||
...(dto.roundNo !== undefined && { roundNo: normalizeRoundNo(dto.roundNo) }),
|
||||
...(dto.priority !== undefined && { priority: parsePriority(dto.priority) ?? 0 }),
|
||||
...(dto.assigneeId !== undefined && { assigneeId: emptyToNull(dto.assigneeId) }),
|
||||
...(dto.creatorId !== undefined || dto.createdBy !== undefined ? { creatorId: emptyToNull(dto.creatorId ?? dto.createdBy) } : {}),
|
||||
...(dto.plannedTestAt !== undefined && { plannedTestAt: parseOptionalDate(dto.plannedTestAt) }),
|
||||
...(dto.plannedEndAt !== undefined && { plannedEndAt: parseOptionalDate(dto.plannedEndAt) }),
|
||||
...(dto.startedAt !== undefined && { startedAt: parseOptionalDate(dto.startedAt) }),
|
||||
...(dto.completedAt !== undefined && { completedAt: parseOptionalDate(dto.completedAt) }),
|
||||
...(dto.estimateHours !== undefined && { estimateHours: dto.estimateHours }),
|
||||
...(dto.aiEstimateHours !== undefined && { aiEstimateHours: dto.aiEstimateHours }),
|
||||
...(dto.references !== undefined && { references: toJsonInput(dto.references) }),
|
||||
...(dto.aiDraft !== undefined && { aiDraft: dto.aiDraft }),
|
||||
...(dto.aiDraftAt !== undefined && { aiDraftAt: parseOptionalDate(dto.aiDraftAt) }),
|
||||
};
|
||||
}
|
||||
|
||||
private async ensureVersion(versionId: string) {
|
||||
const version = await this.prisma.version.findUnique({ where: { id: versionId } });
|
||||
if (!version) throw new NotFoundException('版本不存在');
|
||||
if (!version.projectId) throw new BadRequestException('测试用例所属版本必须归属于项目');
|
||||
return { ...version, projectId: version.projectId };
|
||||
}
|
||||
|
||||
private async ensureTestCaseInVersion(versionId: string, id: string) {
|
||||
const testCase = await this.prisma.testCase.findFirst({ where: { id, versionId } });
|
||||
if (!testCase) throw new NotFoundException('测试用例不存在');
|
||||
return testCase;
|
||||
}
|
||||
|
||||
private recordStatusActivity(testCase: any, fromStatus: string, toStatus: string) {
|
||||
if (toStatus === 'running') {
|
||||
return this.recordTestCaseActivity(testCase, 'test_case_started', 'progress', `开始测试:${testCase.title}`, { fromStatus, toStatus });
|
||||
}
|
||||
if (toStatus === 'passed') {
|
||||
return this.recordTestCaseActivity(testCase, 'test_case_passed', 'delivery', `测试通过:${testCase.title}`, { fromStatus, toStatus });
|
||||
}
|
||||
if (toStatus === 'failed') {
|
||||
return this.recordTestCaseActivity(testCase, 'test_case_failed', 'risk', `测试不通过:${testCase.title}`, { fromStatus, toStatus });
|
||||
}
|
||||
if (toStatus === 'blocked') {
|
||||
return this.recordTestCaseActivity(testCase, 'test_case_blocked', 'risk', `测试阻塞:${testCase.title}`, { fromStatus, toStatus });
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private recordTestCaseActivity(testCase: any, action: string, category: string, summary: string, metadata: Record<string, unknown> = {}) {
|
||||
return this.workActivity.record({
|
||||
versionId: testCase.versionId,
|
||||
productId: testCase.productId,
|
||||
projectId: testCase.projectId,
|
||||
actorId: testCase.assigneeId ?? testCase.creatorId,
|
||||
sourceType: 'test_case',
|
||||
sourceId: testCase.id,
|
||||
action,
|
||||
category,
|
||||
title: testCase.title,
|
||||
summary,
|
||||
metadata,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function createFallbackCode(prefix: string) {
|
||||
return `${prefix}-${Date.now().toString(36).toUpperCase()}`;
|
||||
}
|
||||
|
||||
function emptyToNull(value: string | null | undefined): string | null {
|
||||
if (value === null) return null;
|
||||
if (value === undefined) return null;
|
||||
const trimmed = value.trim();
|
||||
return trimmed ? trimmed : null;
|
||||
}
|
||||
|
||||
function parseOptionalDate(value: string | null | undefined): Date | null {
|
||||
if (!value) return null;
|
||||
const date = new Date(value);
|
||||
return Number.isFinite(date.getTime()) ? date : null;
|
||||
}
|
||||
|
||||
function normalizeRoundNo(value: number | null | undefined): number {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value) || value < 1) return 1;
|
||||
return Math.floor(value);
|
||||
}
|
||||
|
||||
function parsePriority(value: string | number | null | undefined): number | undefined {
|
||||
if (value === null || value === undefined || value === '') return undefined;
|
||||
if (typeof value === 'number') return Number.isFinite(value) ? Math.max(0, Math.min(4, Math.floor(value))) : undefined;
|
||||
const match = /^P([0-4])$/i.exec(value.trim());
|
||||
if (match) return Number(match[1]);
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? Math.max(0, Math.min(4, Math.floor(parsed))) : undefined;
|
||||
}
|
||||
|
||||
function toJsonInput(value: unknown): Prisma.InputJsonValue {
|
||||
return value as Prisma.InputJsonValue;
|
||||
}
|
||||
Reference in New Issue
Block a user