feat(v2.4): 切换计划与开发任务主写

This commit is contained in:
2026-07-08 12:34:33 +08:00
parent 5f5a211c99
commit 1bf630a7bc
21 changed files with 1612 additions and 28 deletions

View File

@@ -6,6 +6,8 @@ import { ProductModule } from './modules/product/product.module';
import { ProjectModule } from './modules/project/project.module';
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 { AiModule } from './modules/ai/ai.module';
import { ConfigModule } from './modules/config/config.module';
import { DataModule } from './modules/data/data.module';
@@ -19,6 +21,8 @@ import { HealthModule } from './modules/health/health.module';
ProductModule,
ProjectModule,
VersionModule,
VersionPlanModule,
DevTaskModule,
RequirementModule,
ConfigModule,
DataModule,

View File

@@ -0,0 +1,57 @@
import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
import { CreateDevTaskDto } from './dto/create-dev-task.dto';
import { UpdateDevTaskDto } from './dto/update-dev-task.dto';
import { DevTaskService } from './dev-task.service';
@Controller('versions/:versionId/dev-tasks')
export class DevTaskController {
constructor(private readonly devTaskService: DevTaskService) {}
@Post()
create(@Param('versionId') versionId: string, @Body() dto: CreateDevTaskDto) {
return this.devTaskService.create(versionId, dto);
}
@Get()
findAll(@Param('versionId') versionId: string) {
return this.devTaskService.findAll(versionId);
}
@Patch(':id')
update(@Param('versionId') versionId: string, @Param('id') id: string, @Body() dto: UpdateDevTaskDto) {
return this.devTaskService.update(versionId, id, dto);
}
@Patch(':id/status')
updateStatus(
@Param('versionId') versionId: string,
@Param('id') id: string,
@Body('status') status: string,
) {
return this.devTaskService.updateStatus(versionId, id, status);
}
@Patch(':id/block')
setBlocked(
@Param('versionId') versionId: string,
@Param('id') id: string,
@Body('blocked') blocked: boolean,
@Body('reason') reason?: string,
) {
return this.devTaskService.setBlocked(versionId, id, blocked, reason);
}
@Patch(':id/transfer')
transfer(
@Param('versionId') versionId: string,
@Param('id') id: string,
@Body('assigneeId') assigneeId: string,
) {
return this.devTaskService.transfer(versionId, id, assigneeId);
}
@Delete(':id')
remove(@Param('versionId') versionId: string, @Param('id') id: string) {
return this.devTaskService.remove(versionId, id);
}
}

View File

@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { WorkActivityModule } from '../work-activity/work-activity.module';
import { DevTaskController } from './dev-task.controller';
import { DevTaskService } from './dev-task.service';
@Module({
imports: [WorkActivityModule],
controllers: [DevTaskController],
providers: [DevTaskService],
exports: [DevTaskService],
})
export class DevTaskModule {}

View File

@@ -0,0 +1,153 @@
import { NotFoundException } from '@nestjs/common';
import { DevTaskService } from './dev-task.service';
describe('DevTaskService domain writes', () => {
const makeService = () => {
const workActivity = {
record: jest.fn().mockResolvedValue({ id: 'activity-1' }),
};
const prisma = {
version: {
findUnique: jest.fn(),
},
devTask: {
create: jest.fn(),
delete: jest.fn(),
findFirst: jest.fn(),
findMany: jest.fn(),
update: jest.fn(),
},
};
return {
prisma,
workActivity,
service: new DevTaskService(prisma as any, workActivity as any),
};
};
it('creates dev tasks 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.devTask.create.mockResolvedValue({ id: 'task-1', versionId: 'version-1', title: '开发登录' });
await service.create('version-1', {
requirementId: 'req-1',
requirementProductId: 'product-1',
taskNo: 'DEV-001',
title: '开发登录',
categoryId: 'cat-fe',
assigneeId: 'member-1',
priority: 'P1',
expectedStartAt: '2026-07-08T09:00:00.000Z',
expectedEndAt: '2026-07-08T18:00:00.000Z',
estimateHours: 8,
references: [{ type: 'requirement', id: 'REQ-001', label: 'REQ-001 登录' }],
createdBy: 'member-pm',
} as any);
expect(prisma.devTask.create).toHaveBeenCalledWith({
data: expect.objectContaining({
versionId: 'version-1',
productId: 'product-1',
projectId: 'project-1',
requirementId: 'req-1',
requirementProductId: 'product-1',
code: 'DEV-001',
title: '开发登录',
categoryId: 'cat-fe',
assigneeId: 'member-1',
priority: 1,
expectedStartAt: new Date('2026-07-08T09:00:00.000Z'),
expectedEndAt: new Date('2026-07-08T18:00:00.000Z'),
estimateHours: 8,
}),
});
expect(workActivity.record).toHaveBeenCalledWith(expect.objectContaining({
versionId: 'version-1',
sourceType: 'dev_task',
sourceId: 'task-1',
action: 'dev_task_created',
}));
});
it('changes status by id plus version id and records activity evidence', async () => {
const { prisma, workActivity, service } = makeService();
prisma.devTask.findFirst.mockResolvedValue({
id: 'task-1',
versionId: 'version-1',
productId: 'product-1',
projectId: 'project-1',
status: 'todo',
title: '开发登录',
assigneeId: 'member-1',
});
prisma.devTask.update.mockResolvedValue({
id: 'task-1',
versionId: 'version-1',
productId: 'product-1',
projectId: 'project-1',
status: 'in_progress',
title: '开发登录',
assigneeId: 'member-1',
});
await service.updateStatus('version-1', 'task-1', 'in_progress');
expect(prisma.devTask.update).toHaveBeenCalledWith({
where: { id_versionId: { id: 'task-1', versionId: 'version-1' } },
data: expect.objectContaining({
status: 'in_progress',
startDate: expect.any(Date),
}),
});
expect(workActivity.record).toHaveBeenCalledWith(expect.objectContaining({
versionId: 'version-1',
sourceType: 'dev_task',
sourceId: 'task-1',
action: 'dev_task_started',
}));
});
it('blocks and unblocks tasks inside the version partition', async () => {
const { prisma, workActivity, service } = makeService();
prisma.devTask.findFirst.mockResolvedValue({
id: 'task-1',
versionId: 'version-1',
productId: 'product-1',
projectId: 'project-1',
status: 'in_progress',
title: '开发登录',
assigneeId: 'member-1',
});
prisma.devTask.update.mockResolvedValue({
id: 'task-1',
versionId: 'version-1',
productId: 'product-1',
projectId: 'project-1',
isBlocked: true,
blockReason: '接口未就绪',
title: '开发登录',
assigneeId: 'member-1',
});
await service.setBlocked('version-1', 'task-1', true, '接口未就绪');
expect(prisma.devTask.update).toHaveBeenCalledWith({
where: { id_versionId: { id: 'task-1', versionId: 'version-1' } },
data: { isBlocked: true, blockReason: '接口未就绪' },
});
expect(workActivity.record).toHaveBeenCalledWith(expect.objectContaining({
action: 'dev_task_blocked',
metadata: expect.objectContaining({ blocker: '接口未就绪' }),
}));
});
it('rejects updates outside the version partition', async () => {
const { prisma, service } = makeService();
prisma.devTask.findFirst.mockResolvedValue(null);
await expect(service.update('version-1', 'missing-task', { title: 'Ghost' })).rejects.toBeInstanceOf(NotFoundException);
expect(prisma.devTask.update).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,205 @@
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 { CreateDevTaskDto } from './dto/create-dev-task.dto';
import { UpdateDevTaskDto } from './dto/update-dev-task.dto';
@Injectable()
export class DevTaskService {
constructor(
private readonly prisma: PrismaService,
private readonly workActivity: WorkActivityService,
) {}
async create(versionId: string, dto: CreateDevTaskDto) {
const version = await this.ensureVersion(versionId);
if (!version.projectId) {
throw new BadRequestException('开发任务所属版本必须归属于项目');
}
const item = await this.prisma.devTask.create({
data: {
...this.toTaskData(dto),
versionId,
productId: version.productId,
projectId: version.projectId,
code: dto.code?.trim() || dto.taskNo?.trim() || createFallbackDevCode(),
title: dto.title,
status: dto.status ?? 'todo',
isBlocked: dto.isBlocked ?? false,
},
});
const activity = await this.recordTaskActivity(item, 'dev_task_created', 'creation', `新建开发任务:${item.title}`);
return { item, activities: [activity] };
}
findAll(versionId: string) {
return this.prisma.devTask.findMany({
where: { versionId },
orderBy: [{ status: 'asc' }, { updatedAt: 'desc' }],
});
}
async update(versionId: string, id: string, dto: UpdateDevTaskDto) {
await this.ensureTaskInVersion(versionId, id);
const item = await this.prisma.devTask.update({
where: { id_versionId: { id, versionId } },
data: this.toTaskData(dto),
});
return { item, activities: [] };
}
async updateStatus(versionId: string, id: string, status: string) {
const current = await this.ensureTaskInVersion(versionId, id);
const data: Record<string, unknown> = { status };
if (status === 'in_progress' && !current.startDate) data.startDate = new Date();
if (status === 'submitted' && !current.completedAt) data.completedAt = new Date();
const item = await this.prisma.devTask.update({
where: { id_versionId: { id, versionId } },
data,
});
const activity = await this.recordStatusActivity(item, current.status, status);
return { item, activities: activity ? [activity] : [] };
}
async setBlocked(versionId: string, id: string, blocked: boolean, reason?: string) {
await this.ensureTaskInVersion(versionId, id);
const item = await this.prisma.devTask.update({
where: { id_versionId: { id, versionId } },
data: {
isBlocked: blocked,
blockReason: blocked ? reason : null,
},
});
const activity = await this.recordTaskActivity(
item,
blocked ? 'dev_task_blocked' : 'dev_task_unblocked',
blocked ? 'risk' : 'progress',
blocked ? `标记阻塞:${reason?.trim() || item.title}` : `解除阻塞:${item.title}`,
{ blocker: blocked ? reason : undefined },
);
return { item, activities: [activity] };
}
async transfer(versionId: string, id: string, assigneeId: string) {
const current = await this.ensureTaskInVersion(versionId, id);
const item = await this.prisma.devTask.update({
where: { id_versionId: { id, versionId } },
data: { assigneeId },
});
const activity = await this.recordTaskActivity(
item,
'dev_task_transferred',
'progress',
`转派开发任务:${item.title}`,
{ fromAssigneeId: current.assigneeId, toAssigneeId: assigneeId },
);
return { item, activities: [activity] };
}
async remove(versionId: string, id: string) {
await this.ensureTaskInVersion(versionId, id);
return this.prisma.devTask.delete({ where: { id_versionId: { id, versionId } } });
}
private toTaskData(dto: Partial<CreateDevTaskDto>) {
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.taskNo !== undefined ? { code: dto.code?.trim() || dto.taskNo?.trim() } : {}),
...(dto.title !== undefined && { title: dto.title }),
...(dto.description !== undefined && { description: dto.description ?? '' }),
...(dto.status !== undefined && { status: dto.status }),
...(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.isBlocked !== undefined && { isBlocked: dto.isBlocked }),
...(dto.blockReason !== undefined && { blockReason: emptyToNull(dto.blockReason) }),
...(dto.expectedStartAt !== undefined && { expectedStartAt: parseOptionalDate(dto.expectedStartAt) }),
...(dto.expectedEndAt !== undefined && { expectedEndAt: parseOptionalDate(dto.expectedEndAt) }),
...(dto.actualStartAt !== undefined || dto.startDate !== undefined
? { startDate: parseOptionalDate(dto.actualStartAt ?? dto.startDate) }
: {}),
...(dto.actualEndAt !== undefined || dto.completedAt !== undefined
? { completedAt: parseOptionalDate(dto.actualEndAt ?? 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('版本不存在');
return version;
}
private async ensureTaskInVersion(versionId: string, id: string) {
const task = await this.prisma.devTask.findFirst({ where: { id, versionId } });
if (!task) throw new NotFoundException('开发任务不存在');
return task;
}
private recordStatusActivity(task: any, fromStatus: string, toStatus: string) {
if (toStatus === 'in_progress') {
return this.recordTaskActivity(task, 'dev_task_started', 'progress', `开始开发:${task.title}`, { fromStatus, toStatus });
}
if (toStatus === 'testing') {
return this.recordTaskActivity(task, 'dev_task_self_testing', 'progress', `进入自测:${task.title}`, { fromStatus, toStatus });
}
if (toStatus === 'submitted') {
return this.recordTaskActivity(task, 'dev_task_submitted', 'delivery', `已提测开发任务:${task.title}`, { fromStatus, toStatus });
}
return undefined;
}
private recordTaskActivity(task: any, action: string, category: string, summary: string, metadata: Record<string, unknown> = {}) {
return this.workActivity.record({
versionId: task.versionId,
productId: task.productId,
projectId: task.projectId,
actorId: task.assigneeId ?? task.creatorId,
sourceType: 'dev_task',
sourceId: task.id,
action,
category,
title: task.title,
summary,
metadata,
});
}
}
function createFallbackDevCode() {
return `DEV-${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;
}
function toJsonInput(value: unknown): Prisma.InputJsonValue {
return value as Prisma.InputJsonValue;
}

View File

@@ -0,0 +1,99 @@
import { IsArray, IsBoolean, IsOptional, IsString } from 'class-validator';
export class CreateDevTaskDto {
@IsString()
@IsOptional()
requirementId?: string;
@IsString()
@IsOptional()
requirementProductId?: string;
@IsString()
@IsOptional()
categoryId?: string;
@IsString()
@IsOptional()
code?: string;
@IsString()
@IsOptional()
taskNo?: string;
@IsString()
title!: string;
@IsString()
@IsOptional()
description?: string;
@IsString()
@IsOptional()
status?: string;
@IsOptional()
priority?: string | number;
@IsString()
@IsOptional()
assigneeId?: string;
@IsString()
@IsOptional()
creatorId?: string;
@IsString()
@IsOptional()
createdBy?: string;
@IsBoolean()
@IsOptional()
isBlocked?: boolean;
@IsString()
@IsOptional()
blockReason?: string;
@IsString()
@IsOptional()
expectedStartAt?: string;
@IsString()
@IsOptional()
expectedEndAt?: string;
@IsString()
@IsOptional()
actualStartAt?: string;
@IsString()
@IsOptional()
actualEndAt?: string;
@IsString()
@IsOptional()
startDate?: string;
@IsString()
@IsOptional()
completedAt?: string;
@IsOptional()
estimateHours?: number;
@IsOptional()
aiEstimateHours?: number;
@IsArray()
@IsOptional()
references?: unknown[];
@IsBoolean()
@IsOptional()
aiDraft?: boolean;
@IsString()
@IsOptional()
aiDraftAt?: string;
}

View File

@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateDevTaskDto } from './create-dev-task.dto';
export class UpdateDevTaskDto extends PartialType(CreateDevTaskDto) {}

View File

@@ -0,0 +1,59 @@
import { IsArray, IsIn, IsOptional, IsString } from 'class-validator';
export class CreateVersionPlanDto {
@IsIn(['research', 'product', 'ui'])
type!: 'research' | 'product' | 'ui';
@IsString()
title!: string;
@IsString()
@IsOptional()
status?: string;
@IsString()
@IsOptional()
owner?: string;
@IsString()
@IsOptional()
ownerId?: string;
@IsString()
@IsOptional()
startTime?: string;
@IsString()
@IsOptional()
endTime?: string;
@IsString()
@IsOptional()
expectedStartAt?: string;
@IsString()
@IsOptional()
expectedEndAt?: string;
@IsString()
@IsOptional()
actualStartAt?: string;
@IsString()
@IsOptional()
completedAt?: string;
@IsString()
@IsOptional()
resultUrl?: string;
@IsArray()
@IsOptional()
linkedRequirementIds?: string[];
@IsOptional()
requirementCoverage?: unknown[];
@IsOptional()
logs?: unknown[];
}

View File

@@ -0,0 +1,4 @@
import { PartialType } from '@nestjs/mapped-types';
import { CreateVersionPlanDto } from './create-version-plan.dto';
export class UpdateVersionPlanDto extends PartialType(CreateVersionPlanDto) {}

View File

@@ -0,0 +1,34 @@
import { Body, Controller, Delete, Get, Param, Patch, Post } from '@nestjs/common';
import { CreateVersionPlanDto } from './dto/create-version-plan.dto';
import { UpdateVersionPlanDto } from './dto/update-version-plan.dto';
import { VersionPlanService } from './version-plan.service';
@Controller('versions/:versionId/plans')
export class VersionPlanController {
constructor(private readonly versionPlanService: VersionPlanService) {}
@Post()
create(@Param('versionId') versionId: string, @Body() dto: CreateVersionPlanDto) {
return this.versionPlanService.create(versionId, dto);
}
@Get()
findAll(@Param('versionId') versionId: string) {
return this.versionPlanService.findAll(versionId);
}
@Patch(':id')
update(@Param('versionId') versionId: string, @Param('id') id: string, @Body() dto: UpdateVersionPlanDto) {
return this.versionPlanService.update(versionId, id, dto);
}
@Patch(':id/complete')
complete(@Param('versionId') versionId: string, @Param('id') id: string, @Body() dto: UpdateVersionPlanDto) {
return this.versionPlanService.complete(versionId, id, dto);
}
@Delete(':id')
remove(@Param('versionId') versionId: string, @Param('id') id: string) {
return this.versionPlanService.remove(versionId, id);
}
}

View File

@@ -0,0 +1,12 @@
import { Module } from '@nestjs/common';
import { WorkActivityModule } from '../work-activity/work-activity.module';
import { VersionPlanController } from './version-plan.controller';
import { VersionPlanService } from './version-plan.service';
@Module({
imports: [WorkActivityModule],
controllers: [VersionPlanController],
providers: [VersionPlanService],
exports: [VersionPlanService],
})
export class VersionPlanModule {}

View File

@@ -0,0 +1,109 @@
import { NotFoundException } from '@nestjs/common';
import { VersionPlanService } from './version-plan.service';
describe('VersionPlanService domain writes', () => {
const makeService = () => {
const workActivity = {
record: jest.fn().mockResolvedValue({ id: 'activity-1' }),
};
const prisma = {
version: {
findUnique: jest.fn(),
},
versionPlan: {
create: jest.fn(),
delete: jest.fn(),
findFirst: jest.fn(),
findMany: jest.fn(),
update: jest.fn(),
},
};
return {
prisma,
workActivity,
service: new VersionPlanService(prisma as any, workActivity as any),
};
};
it('creates version plans 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.versionPlan.create.mockResolvedValue({ id: 'plan-1', versionId: 'version-1', title: '产品方案' });
await service.create('version-1', {
type: 'product',
title: '产品方案',
owner: 'member-1',
startTime: '2026-07-08T09:00:00.000Z',
endTime: '2026-07-08T18:00:00.000Z',
linkedRequirementIds: ['req-1'],
} as any);
expect(prisma.versionPlan.create).toHaveBeenCalledWith({
data: expect.objectContaining({
versionId: 'version-1',
productId: 'product-1',
projectId: 'project-1',
type: 'product',
title: '产品方案',
ownerId: 'member-1',
expectedStartAt: new Date('2026-07-08T09:00:00.000Z'),
expectedEndAt: new Date('2026-07-08T18:00:00.000Z'),
requirementCoverage: [{ requirementId: 'req-1', status: 'not_started' }],
}),
});
expect(workActivity.record).toHaveBeenCalledWith(expect.objectContaining({
versionId: 'version-1',
sourceType: 'version_plan',
sourceId: 'plan-1',
action: 'version_plan_created',
}));
});
it('updates plan status inside version scope and records activity evidence', async () => {
const { prisma, workActivity, service } = makeService();
prisma.versionPlan.findFirst.mockResolvedValue({
id: 'plan-1',
versionId: 'version-1',
productId: 'product-1',
projectId: 'project-1',
status: 'pending',
title: '产品方案',
ownerId: 'member-1',
});
prisma.versionPlan.update.mockResolvedValue({
id: 'plan-1',
versionId: 'version-1',
productId: 'product-1',
projectId: 'project-1',
status: 'in_progress',
title: '产品方案',
ownerId: 'member-1',
});
await service.update('version-1', 'plan-1', { status: 'in_progress' });
expect(prisma.versionPlan.update).toHaveBeenCalledWith({
where: { id: 'plan-1' },
data: expect.objectContaining({
status: 'in_progress',
actualStartAt: expect.any(Date),
}),
});
expect(workActivity.record).toHaveBeenCalledWith(expect.objectContaining({
versionId: 'version-1',
sourceType: 'version_plan',
sourceId: 'plan-1',
action: 'version_plan_started',
}));
});
it('rejects plan updates outside the version partition', async () => {
const { prisma, service } = makeService();
prisma.versionPlan.findFirst.mockResolvedValue(null);
await expect(service.update('version-1', 'missing-plan', { title: 'Ghost' })).rejects.toBeInstanceOf(NotFoundException);
expect(prisma.versionPlan.update).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,152 @@
import { 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 { CreateVersionPlanDto } from './dto/create-version-plan.dto';
import { UpdateVersionPlanDto } from './dto/update-version-plan.dto';
@Injectable()
export class VersionPlanService {
constructor(
private readonly prisma: PrismaService,
private readonly workActivity: WorkActivityService,
) {}
async create(versionId: string, dto: CreateVersionPlanDto) {
const version = await this.ensureVersion(versionId);
const item = await this.prisma.versionPlan.create({
data: {
...this.toPlanData(dto),
versionId,
productId: version.productId,
projectId: version.projectId,
type: dto.type,
title: dto.title,
status: dto.status ?? 'pending',
},
});
const activity = await this.recordPlanActivity(item, 'version_plan_created', 'creation', `新建计划:${item.title}`);
return { item, activities: [activity] };
}
findAll(versionId: string) {
return this.prisma.versionPlan.findMany({
where: { versionId },
orderBy: [{ type: 'asc' }, { createdAt: 'desc' }],
});
}
async update(versionId: string, id: string, dto: UpdateVersionPlanDto) {
const current = await this.ensurePlanInVersion(versionId, id);
const data = this.toPlanData(dto);
if (dto.status === 'in_progress' && !current.actualStartAt) {
data.actualStartAt = new Date();
}
if (dto.status === 'completed' && !current.completedAt) {
data.completedAt = new Date();
}
const item = await this.prisma.versionPlan.update({
where: { id },
data,
});
const activity = current.status !== item.status ? await this.recordStatusActivity(item, current.status, item.status) : undefined;
return { item, activities: activity ? [activity] : [] };
}
async complete(versionId: string, id: string, dto: UpdateVersionPlanDto) {
return this.update(versionId, id, {
...dto,
status: 'completed',
completedAt: dto.completedAt ?? new Date().toISOString(),
});
}
async remove(versionId: string, id: string) {
await this.ensurePlanInVersion(versionId, id);
return this.prisma.versionPlan.delete({ where: { id } });
}
private toPlanData(dto: Partial<CreateVersionPlanDto>) {
return {
...(dto.type !== undefined && { type: dto.type }),
...(dto.title !== undefined && { title: dto.title }),
...(dto.status !== undefined && { status: dto.status }),
...(dto.owner !== undefined || dto.ownerId !== undefined ? { ownerId: emptyToNull(dto.ownerId ?? dto.owner) } : {}),
...(dto.startTime !== undefined || dto.expectedStartAt !== undefined
? { expectedStartAt: parseOptionalDate(dto.expectedStartAt ?? dto.startTime) }
: {}),
...(dto.endTime !== undefined || dto.expectedEndAt !== undefined
? { expectedEndAt: parseOptionalDate(dto.expectedEndAt ?? dto.endTime) }
: {}),
...(dto.actualStartAt !== undefined && { actualStartAt: parseOptionalDate(dto.actualStartAt) }),
...(dto.completedAt !== undefined && { completedAt: parseOptionalDate(dto.completedAt) }),
...(dto.resultUrl !== undefined && { resultUrl: emptyToNull(dto.resultUrl) }),
...(dto.requirementCoverage !== undefined || dto.linkedRequirementIds !== undefined
? { requirementCoverage: toJsonInput(dto.requirementCoverage ?? buildRequirementCoverage(dto.linkedRequirementIds)) }
: {}),
...(dto.logs !== undefined && { logs: toJsonInput(dto.logs) }),
};
}
private async ensureVersion(versionId: string) {
const version = await this.prisma.version.findUnique({ where: { id: versionId } });
if (!version) throw new NotFoundException('版本不存在');
return version;
}
private async ensurePlanInVersion(versionId: string, id: string) {
const plan = await this.prisma.versionPlan.findFirst({ where: { id, versionId } });
if (!plan) throw new NotFoundException('计划不存在');
return plan;
}
private recordStatusActivity(plan: any, fromStatus: string, toStatus: string) {
if (toStatus === 'in_progress') {
return this.recordPlanActivity(plan, 'version_plan_started', 'progress', `开始计划:${plan.title}`, { fromStatus, toStatus });
}
if (toStatus === 'completed') {
return this.recordPlanActivity(plan, 'version_plan_completed', 'delivery', `完成计划:${plan.title}`, { fromStatus, toStatus });
}
return undefined;
}
private recordPlanActivity(plan: any, action: string, category: string, summary: string, metadata: Record<string, unknown> = {}) {
return this.workActivity.record({
versionId: plan.versionId,
productId: plan.productId,
projectId: plan.projectId,
actorId: plan.ownerId,
sourceType: 'version_plan',
sourceId: plan.id,
action,
category,
title: plan.title,
summary,
metadata,
});
}
}
function buildRequirementCoverage(requirementIds: string[] | undefined) {
return (requirementIds ?? []).map((requirementId) => ({
requirementId,
status: 'not_started',
}));
}
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 toJsonInput(value: unknown): Prisma.InputJsonValue {
return value as Prisma.InputJsonValue;
}

View File

@@ -0,0 +1,8 @@
import { Module } from '@nestjs/common';
import { WorkActivityService } from './work-activity.service';
@Module({
providers: [WorkActivityService],
exports: [WorkActivityService],
})
export class WorkActivityModule {}

View File

@@ -0,0 +1,63 @@
import { WorkActivityService } from './work-activity.service';
describe('WorkActivityService relational evidence', () => {
const makeService = () => {
const prisma = {
workActivity: {
create: jest.fn().mockResolvedValue({ id: 'activity-1' }),
},
xiaobaoRiskSummary: {
upsert: jest.fn().mockResolvedValue({}),
},
};
return {
prisma,
service: new WorkActivityService(prisma as any),
};
};
it('records activity rows and marks the affected version summary dirty', async () => {
const { prisma, service } = makeService();
await service.record({
versionId: 'version-1',
productId: 'product-1',
projectId: 'project-1',
actorId: 'member-1',
sourceType: 'dev_task',
sourceId: 'task-1',
action: 'dev_task_started',
title: '开发登录',
category: 'progress',
summary: '开始开发:开发登录',
metadata: { fromStatus: 'todo', toStatus: 'in_progress' },
});
expect(prisma.workActivity.create).toHaveBeenCalledWith({
data: expect.objectContaining({
versionId: 'version-1',
productId: 'product-1',
projectId: 'project-1',
actorId: 'member-1',
sourceType: 'dev_task',
sourceId: 'task-1',
sourceVersionId: 'version-1',
action: 'dev_task_started',
title: '开发登录',
metadata: expect.objectContaining({
category: 'progress',
summary: '开始开发:开发登录',
fromStatus: 'todo',
toStatus: 'in_progress',
}),
}),
});
expect(prisma.xiaobaoRiskSummary.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: { versionId: 'version-1' },
update: { dirty: true },
}),
);
});
});

View File

@@ -0,0 +1,87 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../../prisma/prisma.service';
export interface WorkActivityRecordInput {
versionId?: string | null;
productId?: string | null;
projectId?: string | null;
actorId?: string | null;
actorName?: string | null;
sourceType: string;
sourceId: string;
sourceVersionId?: string | null;
action: string;
title: string;
category?: string;
summary?: string;
metadata?: Record<string, unknown>;
occurredAt?: string | Date | null;
}
@Injectable()
export class WorkActivityService {
constructor(private readonly prisma: PrismaService) {}
async record(input: WorkActivityRecordInput) {
const versionId = input.versionId ?? input.sourceVersionId ?? null;
const metadata = {
...(input.metadata ?? {}),
...(input.category ? { category: input.category } : {}),
...(input.summary ? { summary: input.summary } : {}),
};
const activity = await this.prisma.workActivity.create({
data: {
versionId,
productId: input.productId ?? null,
projectId: input.projectId ?? null,
actorId: input.actorId ?? null,
actorName: input.actorName ?? '',
sourceType: input.sourceType,
sourceId: input.sourceId,
sourceVersionId: input.sourceVersionId ?? versionId,
action: input.action,
title: input.title,
metadata,
occurredAt: parseDate(input.occurredAt) ?? new Date(),
},
});
if (versionId) {
await this.markXiaobaoSummaryDirty(versionId);
}
return activity;
}
async markXiaobaoSummaryDirty(versionId: string) {
const riskSignature = `dirty:${versionId}`;
await this.prisma.xiaobaoRiskSummary.upsert({
where: { versionId },
update: { dirty: true },
create: {
versionId,
riskLevel: 'attention',
riskScore: 1,
confidence: 0,
riskSignature,
summary: {
versionId,
riskLevel: 'attention',
riskScore: 1,
confidence: 0,
riskSignature,
dirty: true,
},
dirty: true,
},
});
}
}
function parseDate(value: string | Date | null | undefined): Date | undefined {
if (!value) return undefined;
if (value instanceof Date) return value;
const date = new Date(value);
return Number.isFinite(date.getTime()) ? date : undefined;
}