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;
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import { api } from './api';
|
||||
import type { Bug, BugSeverity, BugStatus } from './bug';
|
||||
import type { DevTask, DevTaskStatus, Reference } from './dev-task';
|
||||
import type { Priority } from './derive';
|
||||
import type { Requirement, RequirementStatus, SourceType } from './requirement';
|
||||
import type { TestCase, TestCaseStatus } from './test-case';
|
||||
import type { VersionPlan, VersionPlanLog, VersionPlanRequirementCoverage } from './version-plan';
|
||||
import type { WorkActivity, WorkActivityCategory, WorkActivitySourceType } from './work-activity';
|
||||
|
||||
@@ -194,6 +196,52 @@ interface DomainDevTaskRow {
|
||||
updatedAt?: string | Date | null;
|
||||
}
|
||||
|
||||
interface DomainTestCaseRow {
|
||||
id: string;
|
||||
versionId: string;
|
||||
requirementId?: string | null;
|
||||
categoryId?: string | null;
|
||||
code: string;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
status?: string | null;
|
||||
roundNo?: number | null;
|
||||
priority?: string | number | null;
|
||||
assigneeId?: string | null;
|
||||
creatorId?: string | null;
|
||||
plannedTestAt?: string | Date | null;
|
||||
plannedEndAt?: string | Date | null;
|
||||
startedAt?: string | Date | null;
|
||||
completedAt?: string | Date | null;
|
||||
estimateHours?: number | null;
|
||||
aiEstimateHours?: number | null;
|
||||
references?: unknown;
|
||||
aiDraft?: boolean | null;
|
||||
aiDraftAt?: string | Date | null;
|
||||
createdAt?: string | Date | null;
|
||||
updatedAt?: string | Date | null;
|
||||
}
|
||||
|
||||
interface DomainBugRow {
|
||||
id: string;
|
||||
versionId: string;
|
||||
testCaseId?: string | null;
|
||||
code: string;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
status?: string | null;
|
||||
severity?: string | null;
|
||||
priority?: string | number | null;
|
||||
assigneeId?: string | null;
|
||||
reporterId?: string | null;
|
||||
plannedFixAt?: string | Date | null;
|
||||
resolvedAt?: string | Date | null;
|
||||
closedAt?: string | Date | null;
|
||||
resolution?: string | null;
|
||||
createdAt?: string | Date | null;
|
||||
updatedAt?: string | Date | null;
|
||||
}
|
||||
|
||||
interface DomainWorkActivityRow {
|
||||
id: string;
|
||||
actorId?: string | null;
|
||||
@@ -211,6 +259,11 @@ interface DomainMutationResponse<T> {
|
||||
activities?: DomainWorkActivityRow[];
|
||||
}
|
||||
|
||||
interface DomainBatchMutationResponse<T> {
|
||||
items: T[];
|
||||
activities?: DomainWorkActivityRow[];
|
||||
}
|
||||
|
||||
export async function listVersionPlansByVersionId(versionId: string): Promise<VersionPlan[]> {
|
||||
const rows = await api.get<DomainVersionPlanRow[]>(`/versions/${versionId}/plans`);
|
||||
return rows.map(normalizeVersionPlan);
|
||||
@@ -301,6 +354,88 @@ export async function deleteDevTaskByVersionId(versionId: string, taskId: string
|
||||
await api.delete(`/versions/${versionId}/dev-tasks/${taskId}`);
|
||||
}
|
||||
|
||||
export async function listTestCasesByVersionId(versionId: string): Promise<TestCase[]> {
|
||||
const rows = await api.get<DomainTestCaseRow[]>(`/versions/${versionId}/test-cases`);
|
||||
return rows.map(normalizeTestCase);
|
||||
}
|
||||
|
||||
export async function createTestCaseByVersionId(versionId: string, data: Partial<TestCase>) {
|
||||
return normalizeMutation(
|
||||
await api.post<DomainMutationResponse<DomainTestCaseRow>>(`/versions/${versionId}/test-cases`, toTestCasePayload(data)),
|
||||
normalizeTestCase,
|
||||
);
|
||||
}
|
||||
|
||||
export async function createTestCasesByVersionId(versionId: string, items: Partial<TestCase>[]) {
|
||||
return normalizeBatchMutation(
|
||||
await api.post<DomainBatchMutationResponse<DomainTestCaseRow>>(
|
||||
`/versions/${versionId}/test-cases/batch`,
|
||||
{ items: items.map(toTestCasePayload) },
|
||||
),
|
||||
normalizeTestCase,
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateTestCaseByVersionId(versionId: string, testCaseId: string, data: Partial<TestCase>) {
|
||||
return normalizeMutation(
|
||||
await api.patch<DomainMutationResponse<DomainTestCaseRow>>(`/versions/${versionId}/test-cases/${testCaseId}`, toTestCasePayload(data)),
|
||||
normalizeTestCase,
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateTestCaseStatusByVersionId(versionId: string, testCaseId: string, status: TestCaseStatus) {
|
||||
return normalizeMutation(
|
||||
await api.patch<DomainMutationResponse<DomainTestCaseRow>>(`/versions/${versionId}/test-cases/${testCaseId}/status`, { status }),
|
||||
normalizeTestCase,
|
||||
);
|
||||
}
|
||||
|
||||
export async function deleteTestCaseByVersionId(versionId: string, testCaseId: string): Promise<void> {
|
||||
await api.delete(`/versions/${versionId}/test-cases/${testCaseId}`);
|
||||
}
|
||||
|
||||
export async function listBugsByVersionId(versionId: string): Promise<Bug[]> {
|
||||
const rows = await api.get<DomainBugRow[]>(`/versions/${versionId}/bugs`);
|
||||
return rows.map(normalizeBug);
|
||||
}
|
||||
|
||||
export async function createBugByVersionId(versionId: string, data: Partial<Bug>) {
|
||||
return normalizeMutation(
|
||||
await api.post<DomainMutationResponse<DomainBugRow>>(`/versions/${versionId}/bugs`, toBugPayload(data)),
|
||||
normalizeBug,
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateBugByVersionId(versionId: string, bugId: string, data: Partial<Bug>) {
|
||||
return normalizeMutation(
|
||||
await api.patch<DomainMutationResponse<DomainBugRow>>(`/versions/${versionId}/bugs/${bugId}`, toBugPayload(data)),
|
||||
normalizeBug,
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateBugStatusByVersionId(
|
||||
versionId: string,
|
||||
bugId: string,
|
||||
status: BugStatus,
|
||||
options: { operator?: string; resolution?: string } = {},
|
||||
) {
|
||||
return normalizeMutation(
|
||||
await api.patch<DomainMutationResponse<DomainBugRow>>(`/versions/${versionId}/bugs/${bugId}/status`, { status, ...options }),
|
||||
normalizeBug,
|
||||
);
|
||||
}
|
||||
|
||||
export async function transferBugByVersionId(versionId: string, bugId: string, assigneeId: string, operator?: string) {
|
||||
return normalizeMutation(
|
||||
await api.patch<DomainMutationResponse<DomainBugRow>>(`/versions/${versionId}/bugs/${bugId}/transfer`, { assigneeId, operator }),
|
||||
normalizeBug,
|
||||
);
|
||||
}
|
||||
|
||||
export async function deleteBugByVersionId(versionId: string, bugId: string): Promise<void> {
|
||||
await api.delete(`/versions/${versionId}/bugs/${bugId}`);
|
||||
}
|
||||
|
||||
function normalizeProductRoot(product: RootProduct): RootProduct {
|
||||
return {
|
||||
...product,
|
||||
@@ -508,6 +643,116 @@ function toDevTaskStatus(value: string | null | undefined): DevTaskStatus {
|
||||
return value === 'in_progress' || value === 'testing' || value === 'submitted' ? value : 'todo';
|
||||
}
|
||||
|
||||
function toTestCasePayload(data: Partial<TestCase>) {
|
||||
return {
|
||||
...(data.versionId !== undefined && { versionId: data.versionId }),
|
||||
...(data.requirementId !== undefined && { requirementId: data.requirementId }),
|
||||
...(data.categoryId !== undefined && { categoryId: data.categoryId }),
|
||||
...(data.caseNo !== undefined && { caseNo: data.caseNo }),
|
||||
...(data.title !== undefined && { title: data.title }),
|
||||
...(data.description !== undefined && { description: data.description }),
|
||||
...(data.status !== undefined && { status: data.status }),
|
||||
...(data.roundNo !== undefined && { roundNo: data.roundNo }),
|
||||
...(data.priority !== undefined && { priority: priorityToNumber(data.priority) }),
|
||||
...(data.assigneeId !== undefined && { assigneeId: data.assigneeId }),
|
||||
...(data.createdBy !== undefined && { createdBy: data.createdBy }),
|
||||
...(data.plannedTestAt !== undefined && { plannedTestAt: data.plannedTestAt }),
|
||||
...(data.plannedEndAt !== undefined && { plannedEndAt: data.plannedEndAt }),
|
||||
...(data.startedAt !== undefined && { startedAt: data.startedAt }),
|
||||
...(data.completedAt !== undefined && { completedAt: data.completedAt }),
|
||||
...(data.estimateHours !== undefined && { estimateHours: data.estimateHours }),
|
||||
...(data.aiEstimateHours !== undefined && { aiEstimateHours: data.aiEstimateHours }),
|
||||
...(data.references !== undefined && { references: data.references }),
|
||||
...(data.aiDraft !== undefined && { aiDraft: data.aiDraft }),
|
||||
...(data.aiDraftAt !== undefined && { aiDraftAt: data.aiDraftAt }),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeTestCase(row: DomainTestCaseRow): TestCase {
|
||||
return {
|
||||
id: row.id,
|
||||
caseNo: row.code,
|
||||
versionId: row.versionId,
|
||||
requirementId: row.requirementId ?? undefined,
|
||||
roundNo: row.roundNo && row.roundNo > 0 ? Math.floor(row.roundNo) : 1,
|
||||
title: row.title,
|
||||
description: row.description ?? '',
|
||||
categoryId: row.categoryId ?? '',
|
||||
priority: toPriority(row.priority),
|
||||
assigneeId: row.assigneeId ?? undefined,
|
||||
status: toTestCaseStatus(row.status),
|
||||
estimateHours: row.estimateHours ?? undefined,
|
||||
aiEstimateHours: row.aiEstimateHours ?? undefined,
|
||||
plannedTestAt: optionalIso(row.plannedTestAt),
|
||||
plannedEndAt: optionalIso(row.plannedEndAt),
|
||||
startedAt: optionalIso(row.startedAt),
|
||||
completedAt: optionalIso(row.completedAt),
|
||||
executedAt: optionalIso(row.completedAt),
|
||||
references: asArray<Reference>(row.references),
|
||||
aiDraft: Boolean(row.aiDraft),
|
||||
aiDraftAt: optionalIso(row.aiDraftAt),
|
||||
createdBy: row.creatorId ?? '',
|
||||
createdAt: isoString(row.createdAt),
|
||||
updatedAt: isoString(row.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
function toTestCaseStatus(value: string | null | undefined): TestCaseStatus {
|
||||
if (value === 'running' || value === 'passed' || value === 'failed' || value === 'blocked') return value;
|
||||
return 'pending';
|
||||
}
|
||||
|
||||
function toBugPayload(data: Partial<Bug>) {
|
||||
return {
|
||||
...(data.versionId !== undefined && { versionId: data.versionId }),
|
||||
...(data.testCaseId !== undefined && { testCaseId: data.testCaseId }),
|
||||
...(data.bugNo !== undefined && { bugNo: data.bugNo }),
|
||||
...(data.title !== undefined && { title: data.title }),
|
||||
...(data.description !== undefined && { description: data.description }),
|
||||
...(data.status !== undefined && { status: data.status }),
|
||||
...(data.severity !== undefined && { severity: data.severity }),
|
||||
...(data.priority !== undefined && { priority: priorityToNumber(data.priority) }),
|
||||
...(data.assigneeId !== undefined && { assigneeId: data.assigneeId }),
|
||||
...(data.reportedBy !== undefined && { reportedBy: data.reportedBy }),
|
||||
...(data.plannedFixAt !== undefined && { plannedFixAt: data.plannedFixAt }),
|
||||
...(data.resolvedAt !== undefined && { resolvedAt: data.resolvedAt }),
|
||||
...(data.closedAt !== undefined && { closedAt: data.closedAt }),
|
||||
...(data.resolution !== undefined && { resolution: data.resolution }),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeBug(row: DomainBugRow): Bug {
|
||||
return {
|
||||
id: row.id,
|
||||
bugNo: row.code,
|
||||
versionId: row.versionId,
|
||||
testCaseId: row.testCaseId ?? '',
|
||||
title: row.title,
|
||||
description: row.description ?? '',
|
||||
severity: toBugSeverity(row.severity),
|
||||
priority: toPriority(row.priority),
|
||||
reportedBy: row.reporterId ?? '',
|
||||
assigneeId: row.assigneeId ?? '',
|
||||
status: toBugStatus(row.status),
|
||||
resolvedAt: optionalIso(row.resolvedAt),
|
||||
closedAt: optionalIso(row.closedAt),
|
||||
resolution: row.resolution ?? undefined,
|
||||
plannedFixAt: optionalIso(row.plannedFixAt),
|
||||
createdAt: isoString(row.createdAt),
|
||||
updatedAt: isoString(row.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
function toBugStatus(value: string | null | undefined): BugStatus {
|
||||
if (value === 'fixing' || value === 'fixed' || value === 'verifying' || value === 'closed' || value === 'rejected') return value;
|
||||
return 'open';
|
||||
}
|
||||
|
||||
function toBugSeverity(value: string | null | undefined): BugSeverity {
|
||||
if (value === 'critical' || value === 'major' || value === 'trivial') return value;
|
||||
return 'minor';
|
||||
}
|
||||
|
||||
function normalizeMutation<Row, Item>(
|
||||
response: DomainMutationResponse<Row>,
|
||||
mapper: (row: Row) => Item,
|
||||
@@ -518,6 +763,16 @@ function normalizeMutation<Row, Item>(
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeBatchMutation<Row, Item>(
|
||||
response: DomainBatchMutationResponse<Row>,
|
||||
mapper: (row: Row) => Item,
|
||||
): { items: Item[]; activities: WorkActivity[] } {
|
||||
return {
|
||||
items: (response.items ?? []).map(mapper),
|
||||
activities: (response.activities ?? []).map(normalizeWorkActivity),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeWorkActivity(row: DomainWorkActivityRow): WorkActivity {
|
||||
const metadata = isRecord(row.metadata) ? row.metadata : {};
|
||||
return {
|
||||
|
||||
53
apps/web/lib/test-case-bug-domain-source.test.ts
Normal file
53
apps/web/lib/test-case-bug-domain-source.test.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import test from 'node:test';
|
||||
|
||||
const testCaseStore = () => readFileSync(join(process.cwd(), 'stores/useTestCaseStore.ts'), 'utf8');
|
||||
const bugStore = () => readFileSync(join(process.cwd(), 'stores/useBugStore.ts'), 'utf8');
|
||||
|
||||
function storeMethodBody(text: string, name: string) {
|
||||
const implementationStart = text.indexOf('export const');
|
||||
assert.notEqual(implementationStart, -1, 'missing store implementation');
|
||||
const start = text.indexOf(` ${name}:`, implementationStart);
|
||||
assert.notEqual(start, -1, `missing store method ${name}`);
|
||||
|
||||
let depth = 0;
|
||||
let sawFirstBrace = false;
|
||||
for (let i = start; i < text.length; i += 1) {
|
||||
const char = text[i];
|
||||
if (char === '{') {
|
||||
depth += 1;
|
||||
sawFirstBrace = true;
|
||||
}
|
||||
if (char === '}') {
|
||||
depth -= 1;
|
||||
if (sawFirstBrace && depth === 0) return text.slice(start, i + 1);
|
||||
}
|
||||
}
|
||||
throw new Error(`could not extract store method ${name}`);
|
||||
}
|
||||
|
||||
test('test case store uses domain APIs for version-scoped writes', () => {
|
||||
const text = testCaseStore();
|
||||
|
||||
assert.match(text, /from '@\/lib\/domain-api'/);
|
||||
assert.match(storeMethodBody(text, 'createTestCase'), /createTestCaseByVersionId\(tc\.versionId,/);
|
||||
assert.match(storeMethodBody(text, 'createTestCases'), /createTestCasesByVersionId\(created\[0\]\.versionId,/);
|
||||
assert.match(storeMethodBody(text, 'updateTestCase'), /updateTestCaseByVersionId\(versionId, id,/);
|
||||
assert.match(storeMethodBody(text, 'changeStatus'), /updateTestCaseStatusByVersionId\(tc\.versionId,/);
|
||||
assert.doesNotMatch(storeMethodBody(text, 'createTestCase'), /saveServerData\('test-cases'/);
|
||||
assert.doesNotMatch(storeMethodBody(text, 'updateTestCase'), /saveServerData\('test-cases'/);
|
||||
});
|
||||
|
||||
test('bug store uses domain APIs for version-scoped writes', () => {
|
||||
const text = bugStore();
|
||||
|
||||
assert.match(text, /from '@\/lib\/domain-api'/);
|
||||
assert.match(storeMethodBody(text, 'createBug'), /createBugByVersionId\(bug\.versionId,/);
|
||||
assert.match(storeMethodBody(text, 'updateBug'), /updateBugByVersionId\(versionId, id,/);
|
||||
assert.match(storeMethodBody(text, 'changeStatus'), /updateBugStatusByVersionId\(bug\.versionId,/);
|
||||
assert.match(storeMethodBody(text, 'transferBug'), /transferBugByVersionId\(bug\.versionId,/);
|
||||
assert.doesNotMatch(storeMethodBody(text, 'createBug'), /saveServerData\('bugs'/);
|
||||
assert.doesNotMatch(storeMethodBody(text, 'updateBug'), /saveServerData\('bugs'/);
|
||||
});
|
||||
@@ -3,8 +3,17 @@ import { create } from 'zustand';
|
||||
import type { Bug, BugStatus, BugLog } from '@/lib/bug';
|
||||
import { generateBugNo } from '@/lib/bug';
|
||||
import { applyBugTransition } from '@/lib/bug-workflow';
|
||||
import {
|
||||
createBugByVersionId,
|
||||
deleteBugByVersionId,
|
||||
listBugsByVersionId,
|
||||
transferBugByVersionId,
|
||||
updateBugByVersionId,
|
||||
updateBugStatusByVersionId,
|
||||
} from '@/lib/domain-api';
|
||||
import { scheduleSaveWithOptimisticRollback } from '@/lib/optimistic-persistence';
|
||||
import { loadServerData, saveServerData, SERVER_DATA_CACHE_MS } from '@/lib/server-data';
|
||||
import type { WorkActivity } from '@/lib/work-activity';
|
||||
import {
|
||||
makeBugCreatedActivity,
|
||||
makeBugStatusActivity,
|
||||
@@ -28,7 +37,7 @@ function makeLog(action: BugLog['action'], operator: string, from?: string, to?:
|
||||
interface BugState {
|
||||
bugs: Bug[];
|
||||
loaded: boolean;
|
||||
fetchBugs: (options?: { force?: boolean }) => Promise<void>;
|
||||
fetchBugs: (options?: { force?: boolean; versionId?: string }) => Promise<void>;
|
||||
createBug: (data: Omit<Bug, 'id' | 'bugNo' | 'createdAt' | 'updatedAt' | 'status' | 'logs'>, operator: string) => Bug;
|
||||
updateBug: (id: string, data: Partial<Bug>) => void;
|
||||
deleteBug: (id: string) => void;
|
||||
@@ -45,7 +54,9 @@ export const useBugStore = create<BugState>((set, get) => ({
|
||||
|
||||
fetchBugs: async (options) => {
|
||||
if (!options?.force && get().loaded && Date.now() - lastBugsFetchAt < SERVER_DATA_CACHE_MS) return;
|
||||
const cached = await loadStored();
|
||||
const cached = options?.versionId
|
||||
? await listBugsByVersionId(options.versionId).catch(loadStored)
|
||||
: await loadStored();
|
||||
if (!options?.force && get().loaded && Date.now() - lastBugsFetchAt < SERVER_DATA_CACHE_MS) return;
|
||||
lastBugsFetchAt = Date.now();
|
||||
set({ bugs: cached ?? [], loaded: true });
|
||||
@@ -67,12 +78,23 @@ export const useBugStore = create<BugState>((set, get) => ({
|
||||
const updated = [...list, bug];
|
||||
set({ bugs: updated, loaded: true });
|
||||
scheduleSaveWithOptimisticRollback({
|
||||
save: () => saveServerData('bugs', updated),
|
||||
save: async () => {
|
||||
try {
|
||||
const result = await createBugByVersionId(bug.versionId, bug);
|
||||
set({
|
||||
bugs: get().bugs.map((item) => (item.id === bug.id ? { ...bug, ...result.item, logs: bug.logs } : item)),
|
||||
loaded: true,
|
||||
});
|
||||
appendDomainActivities(result.activities);
|
||||
} catch {
|
||||
await saveBugsFallback(updated);
|
||||
useWorkActivityStore.getState().addActivity(makeBugCreatedActivity(bug, operator));
|
||||
}
|
||||
},
|
||||
expected: updated,
|
||||
getCurrent: () => get().bugs,
|
||||
rollback: () => set({ bugs: list, loaded: true }),
|
||||
});
|
||||
useWorkActivityStore.getState().addActivity(makeBugCreatedActivity(bug, operator));
|
||||
return bug;
|
||||
},
|
||||
|
||||
@@ -83,7 +105,16 @@ export const useBugStore = create<BugState>((set, get) => ({
|
||||
);
|
||||
set({ bugs: updated, loaded: true });
|
||||
scheduleSaveWithOptimisticRollback({
|
||||
save: () => saveServerData('bugs', updated),
|
||||
save: async () => {
|
||||
try {
|
||||
const versionId = previous.find((bug) => bug.id === id)?.versionId;
|
||||
if (!versionId) throw new Error('missing versionId');
|
||||
const result = await updateBugByVersionId(versionId, id, data);
|
||||
appendDomainActivities(result.activities);
|
||||
} catch {
|
||||
await saveBugsFallback(updated);
|
||||
}
|
||||
},
|
||||
expected: updated,
|
||||
getCurrent: () => get().bugs,
|
||||
rollback: () => set({ bugs: previous, loaded: true }),
|
||||
@@ -95,7 +126,15 @@ export const useBugStore = create<BugState>((set, get) => ({
|
||||
const updated = previous.filter((b) => b.id !== id);
|
||||
set({ bugs: updated, loaded: true });
|
||||
scheduleSaveWithOptimisticRollback({
|
||||
save: () => saveServerData('bugs', updated),
|
||||
save: async () => {
|
||||
try {
|
||||
const versionId = previous.find((bug) => bug.id === id)?.versionId;
|
||||
if (!versionId) throw new Error('missing versionId');
|
||||
await deleteBugByVersionId(versionId, id);
|
||||
} catch {
|
||||
await saveBugsFallback(updated);
|
||||
}
|
||||
},
|
||||
expected: updated,
|
||||
getCurrent: () => get().bugs,
|
||||
rollback: () => set({ bugs: previous, loaded: true }),
|
||||
@@ -110,9 +149,30 @@ export const useBugStore = create<BugState>((set, get) => ({
|
||||
resolution: extra?.resolution,
|
||||
});
|
||||
if (!result.ok || !result.patch) return { ok: false, message: result.message };
|
||||
get().updateBug(id, result.patch);
|
||||
const previous = get().bugs;
|
||||
const updated = previous.map((item) =>
|
||||
item.id === id ? { ...item, ...result.patch, updatedAt: new Date().toISOString() } : item,
|
||||
);
|
||||
set({ bugs: updated, loaded: true });
|
||||
const activity = makeBugStatusActivity(bug, bug.status, to, operator);
|
||||
if (activity) useWorkActivityStore.getState().addActivity(activity);
|
||||
scheduleSaveWithOptimisticRollback({
|
||||
save: async () => {
|
||||
try {
|
||||
const result = await updateBugStatusByVersionId(bug.versionId, id, to, {
|
||||
operator,
|
||||
resolution: extra?.resolution,
|
||||
});
|
||||
appendDomainActivities(result.activities);
|
||||
if (result.activities.length === 0 && activity) useWorkActivityStore.getState().addActivity(activity);
|
||||
} catch {
|
||||
await saveBugsFallback(updated);
|
||||
if (activity) useWorkActivityStore.getState().addActivity(activity);
|
||||
}
|
||||
},
|
||||
expected: updated,
|
||||
getCurrent: () => get().bugs,
|
||||
rollback: () => set({ bugs: previous, loaded: true }),
|
||||
});
|
||||
return { ok: true };
|
||||
},
|
||||
|
||||
@@ -121,8 +181,27 @@ export const useBugStore = create<BugState>((set, get) => ({
|
||||
if (!bug) return { ok: false, message: 'Bug不存在' };
|
||||
if (bug.assigneeId === newAssigneeId) return { ok: false, message: '已是当前负责人' };
|
||||
const log = makeLog('transfer', operator, bug.assigneeId, newAssigneeId, remark);
|
||||
get().updateBug(id, { assigneeId: newAssigneeId, logs: [...(bug.logs || []), log] });
|
||||
useWorkActivityStore.getState().addActivity(makeBugTransferredActivity(bug, operator, newAssigneeId));
|
||||
const activity = makeBugTransferredActivity(bug, operator, newAssigneeId);
|
||||
const previous = get().bugs;
|
||||
const updated = previous.map((item) =>
|
||||
item.id === id ? { ...item, assigneeId: newAssigneeId, logs: [...(item.logs || []), log], updatedAt: new Date().toISOString() } : item,
|
||||
);
|
||||
set({ bugs: updated, loaded: true });
|
||||
scheduleSaveWithOptimisticRollback({
|
||||
save: async () => {
|
||||
try {
|
||||
const result = await transferBugByVersionId(bug.versionId, id, newAssigneeId, operator);
|
||||
appendDomainActivities(result.activities);
|
||||
if (result.activities.length === 0) useWorkActivityStore.getState().addActivity(activity);
|
||||
} catch {
|
||||
await saveBugsFallback(updated);
|
||||
useWorkActivityStore.getState().addActivity(activity);
|
||||
}
|
||||
},
|
||||
expected: updated,
|
||||
getCurrent: () => get().bugs,
|
||||
rollback: () => set({ bugs: previous, loaded: true }),
|
||||
});
|
||||
return { ok: true };
|
||||
},
|
||||
|
||||
@@ -138,3 +217,15 @@ export const useBugStore = create<BugState>((set, get) => ({
|
||||
return get().bugs.filter((b) => b.assigneeId === assigneeId);
|
||||
},
|
||||
}));
|
||||
|
||||
async function saveBugsFallback(bugs: Bug[]) {
|
||||
await saveServerData('bugs', bugs);
|
||||
}
|
||||
|
||||
function appendDomainActivities(activities: WorkActivity[]) {
|
||||
if (activities.length === 0) return;
|
||||
useWorkActivityStore.setState((state) => ({
|
||||
activities: [...state.activities, ...activities],
|
||||
loaded: true,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -3,9 +3,18 @@ import { create } from 'zustand';
|
||||
import type { CreateTestCaseInput, TestCase, TestCaseStatus } from '@/lib/test-case';
|
||||
import { generateCaseNo, normalizeTestCases } from '@/lib/test-case';
|
||||
import { applyTestCaseTransition, normalizeTestCaseOnCreate } from '@/lib/test-case-workflow';
|
||||
import {
|
||||
createTestCaseByVersionId,
|
||||
createTestCasesByVersionId,
|
||||
deleteTestCaseByVersionId,
|
||||
listTestCasesByVersionId,
|
||||
updateTestCaseByVersionId,
|
||||
updateTestCaseStatusByVersionId,
|
||||
} from '@/lib/domain-api';
|
||||
import { createEntityId, dedupeEntityIds } from '@/lib/entity-id';
|
||||
import { scheduleSaveWithOptimisticRollback } from '@/lib/optimistic-persistence';
|
||||
import { loadServerData, saveServerData, SERVER_DATA_CACHE_MS } from '@/lib/server-data';
|
||||
import type { WorkActivity } from '@/lib/work-activity';
|
||||
import {
|
||||
makeTestCaseCreatedActivity,
|
||||
makeTestCaseStatusActivity,
|
||||
@@ -28,7 +37,7 @@ async function loadStored(): Promise<TestCase[] | null> {
|
||||
interface TestCaseState {
|
||||
testCases: TestCase[];
|
||||
loaded: boolean;
|
||||
fetchTestCases: (options?: { force?: boolean }) => Promise<void>;
|
||||
fetchTestCases: (options?: { force?: boolean; versionId?: string }) => Promise<void>;
|
||||
createTestCase: (data: CreateTestCaseInput) => TestCase;
|
||||
createTestCases: (items: CreateTestCaseInput[]) => TestCase[];
|
||||
updateTestCase: (id: string, data: Partial<TestCase>) => void;
|
||||
@@ -45,7 +54,9 @@ export const useTestCaseStore = create<TestCaseState>((set, get) => ({
|
||||
|
||||
fetchTestCases: async (options) => {
|
||||
if (!options?.force && get().loaded && Date.now() - lastTestCasesFetchAt < SERVER_DATA_CACHE_MS) return;
|
||||
const cached = await loadStored();
|
||||
const cached = options?.versionId
|
||||
? await listTestCasesByVersionId(options.versionId).catch(loadStored)
|
||||
: await loadStored();
|
||||
if (!options?.force && get().loaded && Date.now() - lastTestCasesFetchAt < SERVER_DATA_CACHE_MS) return;
|
||||
lastTestCasesFetchAt = Date.now();
|
||||
if (cached) {
|
||||
@@ -71,12 +82,23 @@ export const useTestCaseStore = create<TestCaseState>((set, get) => ({
|
||||
const updated = [...list, tc];
|
||||
set({ testCases: updated, loaded: true });
|
||||
scheduleSaveWithOptimisticRollback({
|
||||
save: () => saveServerData('test-cases', updated),
|
||||
save: async () => {
|
||||
try {
|
||||
const result = await createTestCaseByVersionId(tc.versionId, tc);
|
||||
set({
|
||||
testCases: get().testCases.map((item) => (item.id === tc.id ? { ...tc, ...result.item } : item)),
|
||||
loaded: true,
|
||||
});
|
||||
appendDomainActivities(result.activities);
|
||||
} catch {
|
||||
await saveTestCasesFallback(updated);
|
||||
useWorkActivityStore.getState().addActivity(makeTestCaseCreatedActivity(tc, tc.createdBy));
|
||||
}
|
||||
},
|
||||
expected: updated,
|
||||
getCurrent: () => get().testCases,
|
||||
rollback: () => set({ testCases: list, loaded: true }),
|
||||
});
|
||||
useWorkActivityStore.getState().addActivity(makeTestCaseCreatedActivity(tc, tc.createdBy));
|
||||
return tc;
|
||||
},
|
||||
|
||||
@@ -100,14 +122,31 @@ export const useTestCaseStore = create<TestCaseState>((set, get) => ({
|
||||
}
|
||||
set({ testCases: list, loaded: true });
|
||||
scheduleSaveWithOptimisticRollback({
|
||||
save: () => saveServerData('test-cases', list),
|
||||
save: async () => {
|
||||
try {
|
||||
if (!created[0]?.versionId) throw new Error('missing versionId');
|
||||
const result = await createTestCasesByVersionId(created[0].versionId, created);
|
||||
const byCaseNo = new Map(result.items.map((item) => [item.caseNo, item]));
|
||||
set({
|
||||
testCases: get().testCases.map((item) => {
|
||||
if (!created.some((tc) => tc.id === item.id)) return item;
|
||||
const replacement = byCaseNo.get(item.caseNo);
|
||||
return replacement ? { ...item, ...replacement } : item;
|
||||
}),
|
||||
loaded: true,
|
||||
});
|
||||
appendDomainActivities(result.activities);
|
||||
} catch {
|
||||
await saveTestCasesFallback(list);
|
||||
created.forEach((tc) => {
|
||||
useWorkActivityStore.getState().addActivity(makeTestCaseCreatedActivity(tc, tc.createdBy));
|
||||
});
|
||||
}
|
||||
},
|
||||
expected: list,
|
||||
getCurrent: () => get().testCases,
|
||||
rollback: () => set({ testCases: previous, loaded: true }),
|
||||
});
|
||||
created.forEach((tc) => {
|
||||
useWorkActivityStore.getState().addActivity(makeTestCaseCreatedActivity(tc, tc.createdBy));
|
||||
});
|
||||
return created;
|
||||
},
|
||||
|
||||
@@ -118,7 +157,16 @@ export const useTestCaseStore = create<TestCaseState>((set, get) => ({
|
||||
);
|
||||
set({ testCases: updated, loaded: true });
|
||||
scheduleSaveWithOptimisticRollback({
|
||||
save: () => saveServerData('test-cases', updated),
|
||||
save: async () => {
|
||||
try {
|
||||
const versionId = previous.find((testCase) => testCase.id === id)?.versionId;
|
||||
if (!versionId) throw new Error('missing versionId');
|
||||
const result = await updateTestCaseByVersionId(versionId, id, data);
|
||||
appendDomainActivities(result.activities);
|
||||
} catch {
|
||||
await saveTestCasesFallback(updated);
|
||||
}
|
||||
},
|
||||
expected: updated,
|
||||
getCurrent: () => get().testCases,
|
||||
rollback: () => set({ testCases: previous, loaded: true }),
|
||||
@@ -130,7 +178,15 @@ export const useTestCaseStore = create<TestCaseState>((set, get) => ({
|
||||
const updated = previous.filter((c) => c.id !== id);
|
||||
set({ testCases: updated, loaded: true });
|
||||
scheduleSaveWithOptimisticRollback({
|
||||
save: () => saveServerData('test-cases', updated),
|
||||
save: async () => {
|
||||
try {
|
||||
const versionId = previous.find((testCase) => testCase.id === id)?.versionId;
|
||||
if (!versionId) throw new Error('missing versionId');
|
||||
await deleteTestCaseByVersionId(versionId, id);
|
||||
} catch {
|
||||
await saveTestCasesFallback(updated);
|
||||
}
|
||||
},
|
||||
expected: updated,
|
||||
getCurrent: () => get().testCases,
|
||||
rollback: () => set({ testCases: previous, loaded: true }),
|
||||
@@ -146,10 +202,28 @@ export const useTestCaseStore = create<TestCaseState>((set, get) => ({
|
||||
blockReason: extra?.blockReason,
|
||||
});
|
||||
if (!result.ok || !result.patch) return { ok: false, message: result.message };
|
||||
get().updateTestCase(id, result.patch);
|
||||
const previous = get().testCases;
|
||||
const updated = previous.map((item) =>
|
||||
item.id === id ? { ...item, ...result.patch, aiDraft: false, updatedAt: new Date().toISOString() } : item,
|
||||
);
|
||||
set({ testCases: updated, loaded: true });
|
||||
const actorId = tc.assigneeId || tc.executedBy || tc.createdBy;
|
||||
const activity = makeTestCaseStatusActivity(tc, tc.status, to, actorId);
|
||||
if (activity) useWorkActivityStore.getState().addActivity(activity);
|
||||
scheduleSaveWithOptimisticRollback({
|
||||
save: async () => {
|
||||
try {
|
||||
const result = await updateTestCaseStatusByVersionId(tc.versionId, id, to);
|
||||
appendDomainActivities(result.activities);
|
||||
if (result.activities.length === 0 && activity) useWorkActivityStore.getState().addActivity(activity);
|
||||
} catch {
|
||||
await saveTestCasesFallback(updated);
|
||||
if (activity) useWorkActivityStore.getState().addActivity(activity);
|
||||
}
|
||||
},
|
||||
expected: updated,
|
||||
getCurrent: () => get().testCases,
|
||||
rollback: () => set({ testCases: previous, loaded: true }),
|
||||
});
|
||||
return { ok: true };
|
||||
},
|
||||
|
||||
@@ -165,3 +239,15 @@ export const useTestCaseStore = create<TestCaseState>((set, get) => ({
|
||||
return get().testCases.filter((c) => c.assigneeId === assigneeId);
|
||||
},
|
||||
}));
|
||||
|
||||
async function saveTestCasesFallback(testCases: TestCase[]) {
|
||||
await saveServerData('test-cases', testCases);
|
||||
}
|
||||
|
||||
function appendDomainActivities(activities: WorkActivity[]) {
|
||||
if (activities.length === 0) return;
|
||||
useWorkActivityStore.setState((state) => ({
|
||||
activities: [...state.activities, ...activities],
|
||||
loaded: true,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -181,14 +181,14 @@
|
||||
- Produces: `/api/v1/versions/:versionId/test-cases` and `/api/v1/versions/:versionId/bugs`.
|
||||
- Consumes: TestCase round-copy workflow and Bug status workflow already defined in frontend helpers.
|
||||
|
||||
- [ ] Add failing backend tests for TestCase create/update/status/round-copy by `(id, versionId)`.
|
||||
- [ ] Add failing backend tests for Bug create/update/status/transfer/close by `(id, versionId)`.
|
||||
- [ ] Add failing tests proving TestCase/Bug writes create activity evidence and mark Xiaobao dirty.
|
||||
- [ ] Add failing frontend tests proving stores write domain APIs and preserve existing workflow outputs.
|
||||
- [ ] Implement TestCase and Bug modules.
|
||||
- [ ] Switch test case and bug stores to domain writes with AppData fallback read only.
|
||||
- [ ] Run targeted tests and full gates.
|
||||
- [ ] Commit: `feat(v2.4): 切换测试与缺陷主写`.
|
||||
- [x] Add failing backend tests for TestCase create/update/status/round-copy by `(id, versionId)`.
|
||||
- [x] Add failing backend tests for Bug create/update/status/transfer/close by `(id, versionId)`.
|
||||
- [x] Add failing tests proving TestCase/Bug writes create activity evidence and mark Xiaobao dirty.
|
||||
- [x] Add failing frontend tests proving stores write domain APIs and preserve existing workflow outputs.
|
||||
- [x] Implement TestCase and Bug modules.
|
||||
- [x] Switch test case and bug stores to domain writes with AppData fallback read only.
|
||||
- [x] Run targeted tests and full gates.
|
||||
- [x] Commit: `feat(v2.4): 切换测试与缺陷主写`.
|
||||
|
||||
### Task 6: V2.4.5 Dictionaries, Members, Worklogs, Overtime, Activity Evidence Consolidation
|
||||
|
||||
|
||||
Reference in New Issue
Block a user