merge: 合并功能分支全部改动到 master
# Conflicts: # docs/decisions.md
This commit is contained in:
256
AGENTS.md
Normal file
256
AGENTS.md
Normal file
@@ -0,0 +1,256 @@
|
||||
# AGENTS.md
|
||||
|
||||
This file provides guidance to Codex (Codex.ai/code) when working with code in this repository.
|
||||
|
||||
## ⚠️ 必读文档(开始任何工作前先读)
|
||||
|
||||
以下 4 个文档定义了项目的架构、决策、流程和路线图。**每次新会话开始时必须先读这些**,避免重新讨论已决定的方案:
|
||||
|
||||
- `docs/architecture.md` — 整体架构、心智模型、关键设计原则
|
||||
- `docs/decisions.md` — 关键设计决策记录(含为什么这么做)
|
||||
- `docs/workflow.md` — 工作流程、协作偏好、命名规范
|
||||
- `docs/roadmap.md` — V1/V2/V3 路线图和已完成清单
|
||||
|
||||
文档更新触发条件:
|
||||
- **architecture.md**:新增核心模块、模块边界变更、系统架构调整、新增服务、数据流变化
|
||||
- **decisions.md**:方案评审完成、多方案比较后定方案、废弃旧方案、重要设计决策
|
||||
- **workflow.md**:新增业务流程、流程节点修改、状态机变更、审批流程变更
|
||||
- **roadmap.md**:Phase 完成、Milestone 完成、新增计划、优先级调整
|
||||
|
||||
不影响以上四类的小改动(UI 排版、bug fix、文案)不需要更新文档。
|
||||
|
||||
## Project Overview
|
||||
|
||||
FTB 智能项目管理系统 — 一个集成 AI 能力的项目管理平台,核心层级:产品 → 项目 → 迭代 → 任务。
|
||||
|
||||
### 核心功能模块
|
||||
|
||||
- **产品管理**:产品 CRUD,作为最顶层组织容器
|
||||
- **需求池**:需求创建、编辑、状态流转(draft → reviewing → approved/rejected → delivered)
|
||||
- **项目管理**:归属于产品,项目 CRUD + 成员管理
|
||||
- **版本管理**:产品发布版本,关联任务追踪发布范围
|
||||
- **迭代管理**:项目内 Sprint,时间盒开发周期
|
||||
- **任务管理**:任务 CRUD、状态机、看板视图、甘特图、子任务
|
||||
- **与我相关**:个人任务汇总(分配给我的、我创建的、我关注的)
|
||||
- **成员与权限**:用户管理 + 项目级 RBAC(Owner/Admin/Member/Viewer)
|
||||
- **AI 辅助**:任务智能分解、工期预估、风险预警
|
||||
|
||||
## Tech Stack
|
||||
|
||||
| 层级 | 技术 | 说明 |
|
||||
|------|------|------|
|
||||
| 前端框架 | Next.js 14+ (App Router) | SSR + 文件路由 |
|
||||
| UI 组件 | Shadcn/ui + Tailwind CSS | 现代风格,完全可定制 |
|
||||
| 状态管理 | Zustand | 轻量级,替代 Redux |
|
||||
| 拖拽 | dnd-kit | 看板拖拽交互 |
|
||||
| 图表 | Recharts | 燃尽图、数据看板 |
|
||||
| 后端框架 | NestJS | 模块化架构,TypeScript |
|
||||
| ORM | Prisma | 类型安全的数据库访问 |
|
||||
| 数据库 | PostgreSQL | 关系型数据,适合任务依赖建模 |
|
||||
| AI 集成 | Anthropic SDK | 任务分解、风险分析、智能建议 |
|
||||
| 认证 | NextAuth.js | OAuth + JWT |
|
||||
| 实时通信 | Socket.io | 看板实时同步、通知推送 |
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
ftb-project-management/
|
||||
├── apps/
|
||||
│ ├── web/ # Next.js 前端
|
||||
│ │ ├── app/
|
||||
│ │ │ ├── products/ # 产品列表 + 详情(含需求池)✅
|
||||
│ │ │ ├── projects/ # 项目相关页面(待实现)
|
||||
│ │ │ ├── workspace/ # "与我相关"(待实现)
|
||||
│ │ │ └── admin/ # 全局管理(待实现)
|
||||
│ │ ├── components/
|
||||
│ │ │ ├── product/ # 产品+需求组件 ✅
|
||||
│ │ │ ├── ui/ # Shadcn 基础组件
|
||||
│ │ │ ├── board/ # 看板组件(待实现)
|
||||
│ │ │ └── gantt/ # 甘特图组件(待实现)
|
||||
│ │ ├── stores/ # Zustand stores ✅
|
||||
│ │ ├── hooks/ # 自定义 Hooks
|
||||
│ │ └── lib/ # API 封装 + 常量 ✅
|
||||
│ └── server/ # NestJS 后端
|
||||
│ ├── src/
|
||||
│ │ ├── modules/
|
||||
│ │ │ ├── product/ # 产品 CRUD ✅
|
||||
│ │ │ ├── requirement/ # 需求管理 + 状态机 ✅
|
||||
│ │ │ ├── project/ # 项目(待实现)
|
||||
│ │ │ ├── version/ # 版本(待实现)
|
||||
│ │ │ ├── sprint/ # 迭代(待实现)
|
||||
│ │ │ ├── task/ # 任务(待实现)
|
||||
│ │ │ ├── member/ # 成员权限(待实现)
|
||||
│ │ │ ├── dashboard/ # 与我相关(待实现)
|
||||
│ │ │ └── ai/ # AI 能力(待实现)
|
||||
│ │ ├── prisma/ # PrismaService(全局) ✅
|
||||
│ │ └── common/ # 守卫、拦截器、管道
|
||||
│ └── prisma/ # Schema + Migrations ✅
|
||||
├── packages/
|
||||
│ └── shared/ # 前后端共享类型、枚举 ✅
|
||||
├── docker-compose.yml # PostgreSQL + Redis
|
||||
└── turbo.json # Turborepo monorepo 管理
|
||||
```
|
||||
|
||||
## Build & Dev Commands
|
||||
|
||||
```bash
|
||||
# 安装依赖(monorepo 根目录)
|
||||
pnpm install
|
||||
|
||||
# 启动全部服务(前端 + 后端 + 数据库)
|
||||
pnpm dev
|
||||
|
||||
# 单独启动
|
||||
pnpm dev --filter=web # 前端 localhost:3000
|
||||
pnpm dev --filter=server # 后端 localhost:3001
|
||||
|
||||
# 数据库
|
||||
pnpm db:migrate # 执行 Prisma 迁移
|
||||
pnpm db:seed # 填充测试数据
|
||||
pnpm db:studio # 打开 Prisma Studio
|
||||
|
||||
# 测试
|
||||
pnpm test # 全部测试
|
||||
pnpm test --filter=server # 仅后端测试
|
||||
pnpm test -- --watch # 监听模式
|
||||
pnpm test -- -t "任务创建" # 运行单个测试
|
||||
|
||||
# 构建 & 检查
|
||||
pnpm build # 生产构建
|
||||
pnpm lint # ESLint 检查
|
||||
pnpm type-check # TypeScript 类型检查
|
||||
|
||||
# Docker
|
||||
docker-compose up -d # 启动 PostgreSQL + Redis
|
||||
docker-compose down # 停止容器
|
||||
```
|
||||
|
||||
## Data Model (核心实体关系)
|
||||
|
||||
```
|
||||
Product(产品,顶层容器)
|
||||
├── Requirement(需求池)
|
||||
├── Version(发布版本)
|
||||
└── Project(项目)
|
||||
├── Sprint(迭代)
|
||||
└── Task(任务)
|
||||
├── Task(子任务,自引用)
|
||||
├── Comment(评论)
|
||||
└── TaskWatcher(关注者)
|
||||
|
||||
User ── ProjectMember(项目成员 + 角色)
|
||||
```
|
||||
|
||||
关键设计决策:
|
||||
- 需求状态机:`draft → reviewing → approved/rejected → delivered`,rejected 可回退到 draft
|
||||
- 任务状态机:`todo → in_progress → in_review → done → closed`
|
||||
- 任务支持无限层级子任务(parent_id 自引用)
|
||||
- 需求可一键转为任务(Requirement → Task)
|
||||
- 任务可关联到版本(标记发布范围)
|
||||
- 权限模型:Owner > Admin > Member > Viewer(项目级 RBAC)
|
||||
- AI 操作记录独立表存储(AiLog),便于审计和 token 追踪
|
||||
|
||||
## API Endpoints(已实现)
|
||||
|
||||
```
|
||||
# 产品
|
||||
GET/POST /api/v1/products
|
||||
GET/PATCH/DELETE /api/v1/products/:id
|
||||
|
||||
# 需求(嵌套在产品下)
|
||||
GET/POST /api/v1/products/:productId/requirements
|
||||
GET/PATCH/DELETE /api/v1/products/:productId/requirements/:id
|
||||
PATCH /api/v1/products/:productId/requirements/:id/status
|
||||
```
|
||||
|
||||
## AI Module 设计
|
||||
|
||||
AI 模块作为独立 NestJS Module,对外暴露服务接口:
|
||||
|
||||
- `AiTaskService.decompose(description)` — 将需求描述拆解为子任务
|
||||
- `AiRiskService.analyze(projectId)` — 分析项目风险并生成预警
|
||||
- `AiScheduleService.suggest(projectId)` — 基于成员负载给出排期建议
|
||||
|
||||
所有 AI 调用走统一的 `AiGateway`,负责 prompt 管理、token 计量、降级处理。
|
||||
|
||||
## Conventions
|
||||
|
||||
- 包管理器:pnpm(monorepo workspace)
|
||||
- 分支命名:`feature/模块-描述`、`fix/模块-描述`、`hotfix/描述`
|
||||
- Commit 格式:`类型(模块): 描述`(中文)
|
||||
- 类型:feat / fix / refactor / docs / test / chore
|
||||
- API 路径:RESTful 嵌套资源,如 `/api/v1/products/:productId/requirements/:id`
|
||||
- 前端路由:`/products/[id]`、`/projects/[id]/board`、`/projects/[id]/gantt`
|
||||
- 数据库表名 snake_case,TypeScript 字段 camelCase(Prisma `@map` 映射)
|
||||
- 组件文件 PascalCase,工具函数文件 camelCase
|
||||
- Zustand store 按功能域拆分:`useProductStore`、`useRequirementStore`
|
||||
|
||||
### 后端模块开发模式
|
||||
|
||||
每个 NestJS 业务模块遵循统一结构:
|
||||
|
||||
```
|
||||
modules/<name>/
|
||||
├── <name>.module.ts # Module 声明
|
||||
├── <name>.controller.ts # RESTful 端点
|
||||
├── <name>.service.ts # 业务逻辑
|
||||
└── dto/
|
||||
├── create-<name>.dto.ts
|
||||
└── update-<name>.dto.ts
|
||||
```
|
||||
|
||||
- DTO 属性使用 `!` 声明确定赋值(class-validator 负责运行时校验)
|
||||
- PrismaService 通过 @Global() PrismaModule 注入,无需各模块重复导入
|
||||
- 状态变更使用独立端点 `PATCH /:id/status`,与通用 PATCH 分离
|
||||
|
||||
### 前端开发模式
|
||||
|
||||
- 页面组件统一标记 `'use client'`(管理后台不使用 SSR)
|
||||
- Store 通过 `lib/api.ts` 封装的 fetch 与后端通信
|
||||
- 组件按功能域分组在 `components/<domain>/` 下
|
||||
|
||||
## Environment Variables
|
||||
|
||||
项目根目录提供 `.env.example`,开发者复制为 `.env.local` 使用。
|
||||
|
||||
```bash
|
||||
# 数据库
|
||||
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/ftb_pm
|
||||
|
||||
# 认证
|
||||
NEXTAUTH_SECRET=your-random-secret-key
|
||||
NEXTAUTH_URL=http://localhost:3000
|
||||
|
||||
# AI
|
||||
ANTHROPIC_API_KEY=sk-ant-xxx
|
||||
|
||||
# Redis(Socket.io 适配器 + 缓存)
|
||||
REDIS_URL=redis://localhost:6379
|
||||
|
||||
# 邮件通知(可选)
|
||||
SMTP_HOST=smtp.example.com
|
||||
SMTP_PORT=465
|
||||
SMTP_USER=noreply@example.com
|
||||
SMTP_PASS=your-smtp-password
|
||||
```
|
||||
|
||||
## Deployment
|
||||
|
||||
采用 Docker Compose 部署到云服务器(推荐 2核4G),一套配置本地和线上通用。
|
||||
|
||||
```yaml
|
||||
# docker-compose.prod.yml 核心服务
|
||||
services:
|
||||
web: # Next.js 前端,端口 3000
|
||||
server: # NestJS 后端,端口 3001
|
||||
postgres: # PostgreSQL 数据库,端口 5432
|
||||
redis: # Redis 缓存 + Socket.io,端口 6379
|
||||
nginx: # 反向代理 + SSL 终止,端口 80/443
|
||||
```
|
||||
|
||||
部署流程:
|
||||
1. 服务器安装 Docker + Docker Compose
|
||||
2. 配置 `.env.production` 环境变量
|
||||
3. `docker-compose -f docker-compose.prod.yml up -d`
|
||||
4. Nginx 配置域名 + Let's Encrypt SSL 证书
|
||||
5. 数据库迁移:`docker exec server pnpm db:migrate`
|
||||
@@ -18,7 +18,7 @@ import { VersionStatus, VERSION_STATUS_LABEL, VERSION_STATUS_BG } from '@/lib/ve
|
||||
import { STATUS_PROGRESS, calcGroupProgress as calcDevTaskProgress, getEstimateHours, aggregateDevTaskHours } from '@/lib/dev-task';
|
||||
import { CapsuleStages } from '@/components/version/CapsuleStages';
|
||||
import { MemberChips } from '@/components/version/MemberChips';
|
||||
import type { VersionPlan } from '@/lib/version-plan';
|
||||
import { getRequirementCoverageSummary, type VersionPlan } from '@/lib/version-plan';
|
||||
import type { DevTask } from '@/lib/dev-task';
|
||||
import type { TestCase } from '@/lib/test-case';
|
||||
import type { Bug } from '@/lib/bug';
|
||||
@@ -139,13 +139,12 @@ function VersionCard({ version, progress, plans, devTasks, testCases, bugs, requ
|
||||
if (p.status === 'completed') doneItems += count;
|
||||
else doneItems += tasks.filter((t) => t.status === 'completed').length;
|
||||
} else {
|
||||
const linked = p.linkedRequirementIds || [];
|
||||
const count = Math.max(linked.length, 1);
|
||||
const summary = getRequirementCoverageSummary(p);
|
||||
const count = Math.max(summary.total, 1);
|
||||
totalItems += count;
|
||||
if (p.status === 'completed') doneItems += count;
|
||||
else {
|
||||
const completed = p.completedRequirementIds || [];
|
||||
doneItems += completed.filter((id) => linked.includes(id)).length;
|
||||
doneItems += summary.completed;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -411,10 +410,9 @@ export default function ProjectDetailPage() {
|
||||
const productPlans = vPlans.filter((p) => p.type === 'product');
|
||||
if (productPlans.length > 0) {
|
||||
const totals = productPlans.reduce((acc, p) => {
|
||||
const linked = p.linkedRequirementIds || [];
|
||||
const completed = p.completedRequirementIds || [];
|
||||
acc.total += linked.length;
|
||||
acc.done += completed.filter((id) => linked.includes(id)).length;
|
||||
const summary = getRequirementCoverageSummary(p);
|
||||
acc.total += summary.total;
|
||||
acc.done += summary.completed;
|
||||
return acc;
|
||||
}, { total: 0, done: 0 });
|
||||
segments.push(totals.total > 0 ? (totals.done / totals.total) * 100 : 0);
|
||||
@@ -423,10 +421,9 @@ export default function ProjectDetailPage() {
|
||||
const uiPlans = vPlans.filter((p) => p.type === 'ui');
|
||||
if (uiPlans.length > 0) {
|
||||
const totals = uiPlans.reduce((acc, p) => {
|
||||
const linked = p.linkedRequirementIds || [];
|
||||
const completed = p.completedRequirementIds || [];
|
||||
acc.total += linked.length;
|
||||
acc.done += completed.filter((id) => linked.includes(id)).length;
|
||||
const summary = getRequirementCoverageSummary(p);
|
||||
acc.total += summary.total;
|
||||
acc.done += summary.completed;
|
||||
return acc;
|
||||
}, { total: 0, done: 0 });
|
||||
segments.push(totals.total > 0 ? (totals.done / totals.total) * 100 : 0);
|
||||
|
||||
@@ -32,6 +32,7 @@ import { getProjectAdoptedRequirementCandidates } from '@/lib/requirement-select
|
||||
import { calcBugSeverityRanking, calcPersonalEffortRanking, calcStageEffortMetrics, calcVersionOverviewEffortTotals } from '@/lib/version-overview';
|
||||
import { addVersionMembers, DEFAULT_VERSION_MEMBER_ROLE, filterVersionMemberCandidates } from '@/lib/version-members';
|
||||
import { addRecommendedVersionMembers, getDefaultRecommendedMemberNames, recommendVersionMembers, type MemberRecommendationGroup, type RecommendableRole } from '@/lib/member-recommendation';
|
||||
import { getRequirementCoverageSummary } from '@/lib/version-plan';
|
||||
|
||||
function formatOverviewDateTime(value?: string | null): string {
|
||||
if (!value) return '-';
|
||||
@@ -369,14 +370,13 @@ export default function VersionDetailPage() {
|
||||
doneItems += tasks.filter((t) => t.status === 'completed').length;
|
||||
}
|
||||
} else {
|
||||
const linked = p.linkedRequirementIds || [];
|
||||
const count = Math.max(linked.length, 1);
|
||||
const summary = getRequirementCoverageSummary(p);
|
||||
const count = Math.max(summary.total, 1);
|
||||
totalItems += count;
|
||||
if (p.status === 'completed') {
|
||||
doneItems += count;
|
||||
} else {
|
||||
const completed = p.completedRequirementIds || [];
|
||||
doneItems += completed.filter((id) => linked.includes(id)).length;
|
||||
doneItems += summary.completed;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
49
apps/web/components/ActivityLogPanel.tsx
Normal file
49
apps/web/components/ActivityLogPanel.tsx
Normal file
@@ -0,0 +1,49 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
import type { WorkActivitySourceType } from '@/lib/work-activity';
|
||||
import { getEntityActivityLogEntries, type EntityActivityLogEntry } from '@/lib/entity-activity-log';
|
||||
import { useWorkActivityStore } from '@/stores/useWorkActivityStore';
|
||||
|
||||
interface Props {
|
||||
sourceType: WorkActivitySourceType;
|
||||
sourceId: string;
|
||||
legacyEntries?: EntityActivityLogEntry[];
|
||||
title?: string;
|
||||
}
|
||||
|
||||
export function ActivityLogPanel({ sourceType, sourceId, legacyEntries = [], title = '操作日志' }: Props) {
|
||||
const { activities, fetchActivities } = useWorkActivityStore();
|
||||
|
||||
useEffect(() => {
|
||||
fetchActivities();
|
||||
}, [fetchActivities]);
|
||||
|
||||
const entries = useMemo(
|
||||
() => getEntityActivityLogEntries(activities, sourceType, sourceId, legacyEntries),
|
||||
[activities, sourceType, sourceId, legacyEntries],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-[var(--line)] bg-[var(--bg-card)] p-4">
|
||||
<div className="mb-3 text-[10px] uppercase tracking-wide text-[var(--ink-muted)]">{title}</div>
|
||||
{entries.length === 0 ? (
|
||||
<p className="text-[12px] text-[var(--ink-muted)]">暂无操作日志</p>
|
||||
) : (
|
||||
<div className="space-y-2.5">
|
||||
{entries.map((entry) => (
|
||||
<div key={entry.id} className="flex gap-2.5 text-[11px]">
|
||||
<span className="w-[110px] shrink-0 tabular-nums text-[var(--ink-muted)]">{formatDateTime(entry.occurredAt)}</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="font-medium text-[var(--ink)]">{entry.actorId || '系统'}</span>
|
||||
<span className="text-[var(--ink-soft)]"> {entry.label}</span>
|
||||
<div className="mt-0.5 truncate text-[var(--ink-muted)]">{entry.summary}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { X, Link2, ChevronRight, ArrowRightLeft } from 'lucide-react';
|
||||
import { BugStatusBadge } from './BugStatusBadge';
|
||||
import { ActivityLogPanel } from '@/components/ActivityLogPanel';
|
||||
import { useBugStore } from '@/stores/useBugStore';
|
||||
import { useTestCaseStore } from '@/stores/useTestCaseStore';
|
||||
import { useRequirementStore } from '@/stores/useRequirementStore';
|
||||
@@ -11,6 +12,7 @@ import { useAuthStore } from '@/stores/useAuthStore';
|
||||
import { BUG_ALLOWED_TRANSITIONS, BUG_STATUS_LABEL, BUG_SEVERITY_LABEL, BUG_SEVERITY_COLOR } from '@/lib/bug';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
import { isMemberReference, resolveMemberDisplayName } from '@/lib/member-system';
|
||||
import type { EntityActivityLogEntry } from '@/lib/entity-activity-log';
|
||||
import type { BugStatus } from '@/lib/bug';
|
||||
|
||||
const LOG_ACTION_LABEL: Record<string, string> = {
|
||||
@@ -53,6 +55,21 @@ export function BugDetailDrawer({ bugId, onClose, contextLabel }: Props) {
|
||||
const [transferTo, setTransferTo] = useState('');
|
||||
const [transferRemark, setTransferRemark] = useState('');
|
||||
const [lightboxSrc, setLightboxSrc] = useState<string | null>(null);
|
||||
const legacyLogEntries = useMemo<EntityActivityLogEntry[]>(() => {
|
||||
return (bug.logs || []).map((log) => {
|
||||
const from = log.fromValue ? resolveMemberDisplayName(log.fromValue, members) : '';
|
||||
const to = log.toValue ? resolveMemberDisplayName(log.toValue, members) : '';
|
||||
const change = from && to ? `${from} → ${to}` : '';
|
||||
const remark = log.remark ? `(${log.remark})` : '';
|
||||
return {
|
||||
id: `bug-log-${log.id}`,
|
||||
occurredAt: log.createdAt,
|
||||
actorId: resolveMemberDisplayName(log.operator, members),
|
||||
label: LOG_ACTION_LABEL[log.action] || log.action,
|
||||
summary: [change, remark].filter(Boolean).join(' ') || bug.title,
|
||||
};
|
||||
});
|
||||
}, [bug.logs, bug.title, members]);
|
||||
|
||||
const handleTransition = (to: BugStatus) => {
|
||||
if (to === 'fixed') { setShowResolutionInput(true); return; }
|
||||
@@ -201,27 +218,7 @@ export function BugDetailDrawer({ bugId, onClose, contextLabel }: Props) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 操作日志 */}
|
||||
{bug.logs && bug.logs.length > 0 && (
|
||||
<div className="rounded-xl border border-[var(--line)] bg-[var(--bg-card)] p-4">
|
||||
<div className="text-[10px] text-[var(--ink-muted)] uppercase tracking-wide mb-3">操作日志</div>
|
||||
<div className="space-y-2.5">
|
||||
{[...bug.logs].reverse().map((log) => (
|
||||
<div key={log.id} className="flex gap-2.5 text-[11px]">
|
||||
<span className="text-[var(--ink-muted)] tabular-nums shrink-0 w-[110px]">{formatDateTime(log.createdAt)}</span>
|
||||
<div className="flex-1">
|
||||
<span className="font-medium text-[var(--ink)]">{resolveMemberDisplayName(log.operator, members)}</span>
|
||||
<span className="text-[var(--ink-soft)]"> {LOG_ACTION_LABEL[log.action] || log.action}</span>
|
||||
{log.fromValue && log.toValue && (
|
||||
<span className="text-[var(--ink-muted)]"> {resolveMemberDisplayName(log.fromValue, members)} → {resolveMemberDisplayName(log.toValue, members)}</span>
|
||||
)}
|
||||
{log.remark && <span className="text-[var(--ink-muted)]"> ({log.remark})</span>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<ActivityLogPanel sourceType="bug" sourceId={bug.id} legacyEntries={legacyLogEntries} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useState, useMemo } from 'react';
|
||||
import { X, AlertTriangle, Link2, ChevronRight, Clock, User, Tag, Play, Trash2, ArrowRightLeft, CalendarRange } from 'lucide-react';
|
||||
import { StatusBadge } from './StatusBadge';
|
||||
import { CategoryChip } from './CategoryChip';
|
||||
import { ActivityLogPanel } from '@/components/ActivityLogPanel';
|
||||
import { useDevTaskStore } from '@/stores/useDevTaskStore';
|
||||
import { useWorkActivityStore } from '@/stores/useWorkActivityStore';
|
||||
import { useTaskCategoryStore } from '@/stores/useTaskCategoryStore';
|
||||
@@ -460,6 +461,8 @@ export function DevTaskDetailDrawer({ taskId, allTaskIds, onClose, contextLabel
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ActivityLogPanel sourceType="dev_task" sourceId={task.id} />
|
||||
|
||||
{predecessors.length > 0 && (
|
||||
<div className="rounded-xl border border-[var(--line)] bg-[var(--bg-card)] p-4">
|
||||
<div className="text-[10px] text-[var(--ink-muted)] uppercase tracking-wide mb-2">前置任务</div>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useState } from 'react';
|
||||
import { X, AlertTriangle, Link2, ChevronRight, Bug as BugIcon, Trash2, ArrowRightLeft } from 'lucide-react';
|
||||
import { TestCaseStatusBadge } from './TestCaseStatusBadge';
|
||||
import { BugStatusBadge } from '@/components/bug/BugStatusBadge';
|
||||
import { ActivityLogPanel } from '@/components/ActivityLogPanel';
|
||||
import { useTestCaseStore } from '@/stores/useTestCaseStore';
|
||||
import { useBugStore } from '@/stores/useBugStore';
|
||||
import { useRequirementStore } from '@/stores/useRequirementStore';
|
||||
@@ -314,6 +315,8 @@ export function TestCaseDetailDrawer({ testCaseId, onClose, onCreateBug, context
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ActivityLogPanel sourceType="test_case" sourceId={tc.id} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Sparkles, Loader2, AlertCircle, RotateCw } from 'lucide-react';
|
||||
import { appendPlanLog } from '@/lib/version-plan';
|
||||
import type { VersionPlan } from '@/lib/version-plan';
|
||||
import type { VersionWithContext } from '@/lib/derive';
|
||||
import { useVersionPlanStore } from '@/stores/useVersionPlanStore';
|
||||
@@ -102,6 +103,23 @@ export function AiDecomposeButton({ plan, version }: Props) {
|
||||
return '任务和用例';
|
||||
};
|
||||
|
||||
const appendAiLog = (
|
||||
target: AgentDecomposeTarget,
|
||||
status: 'started' | 'completed' | 'error',
|
||||
detail?: string,
|
||||
) => {
|
||||
const currentPlan = useVersionPlanStore.getState().plans.find((item) => item.id === plan.id) ?? plan;
|
||||
const statusText = status === 'started' ? '已触发' : status === 'completed' ? '已完成' : '失败';
|
||||
return appendPlanLog(currentPlan, {
|
||||
type: 'ai_decompose',
|
||||
actor: user?.name ?? plan.owner,
|
||||
title: `AI 拆解${targetText(target)}${statusText}`,
|
||||
detail,
|
||||
aiTarget: target,
|
||||
aiStatus: status,
|
||||
});
|
||||
};
|
||||
|
||||
const handleClick = async (target: AgentDecomposeTarget) => {
|
||||
if (loading) return;
|
||||
// 即便 persistStatus 是 in_progress,只要超过阈值就允许重新点
|
||||
@@ -117,6 +135,7 @@ export function AiDecomposeButton({ plan, version }: Props) {
|
||||
aiDecomposeAt: new Date().toISOString(),
|
||||
aiDecomposeTarget: target,
|
||||
aiDecomposeError: undefined,
|
||||
logs: appendAiLog(target, 'started'),
|
||||
});
|
||||
|
||||
const members = (version.members ?? []).map((m) => ({
|
||||
@@ -144,6 +163,7 @@ export function AiDecomposeButton({ plan, version }: Props) {
|
||||
aiDecomposeStatus: 'error',
|
||||
aiDecomposeTarget: target,
|
||||
aiDecomposeError: resp.error,
|
||||
logs: appendAiLog(target, 'error', resp.error),
|
||||
});
|
||||
} else {
|
||||
const targetFilteredResult = filterDecomposeResultByTarget(resp.result, target);
|
||||
@@ -166,6 +186,11 @@ export function AiDecomposeButton({ plan, version }: Props) {
|
||||
aiDecomposeStatus: 'completed',
|
||||
aiDecomposeTarget: target,
|
||||
aiDecomposeError: undefined,
|
||||
logs: appendAiLog(
|
||||
target,
|
||||
'completed',
|
||||
`生成开发任务 ${deduped.result.devTaskDrafts.length} 条,测试用例 ${deduped.result.testCaseDrafts.length} 条。已过滤重复开发任务 ${deduped.removedDevTaskCount} 条,重复测试用例 ${deduped.removedTestCaseCount} 条。`,
|
||||
),
|
||||
});
|
||||
}
|
||||
} catch (e: any) {
|
||||
@@ -174,6 +199,7 @@ export function AiDecomposeButton({ plan, version }: Props) {
|
||||
aiDecomposeStatus: 'error',
|
||||
aiDecomposeTarget: target,
|
||||
aiDecomposeError: msg,
|
||||
logs: appendAiLog(target, 'error', msg),
|
||||
});
|
||||
} finally {
|
||||
setActiveTarget(null);
|
||||
|
||||
@@ -5,9 +5,10 @@ import { X, Check, Link2, FileUp, ExternalLink, Play, ArrowRightLeft } from 'luc
|
||||
import { useVersionPlanStore } from '@/stores/useVersionPlanStore';
|
||||
import { useRequirementStore } from '@/stores/useRequirementStore';
|
||||
import { useMemberStore } from '@/stores/useMemberStore';
|
||||
import { useAuthStore } from '@/stores/useAuthStore';
|
||||
import {
|
||||
calcPlanProgress,
|
||||
calcLinkedReqProgress,
|
||||
getRequirementCoverageSummary,
|
||||
PRODUCT_PLAN_KIND_LABEL,
|
||||
PRODUCT_PLAN_REVIEW_FAILURE_OPTIONS,
|
||||
PRODUCT_PLAN_REVIEW_RESULT_LABEL,
|
||||
@@ -16,6 +17,7 @@ import { formatDateTime } from '@/lib/format';
|
||||
import type { PlanTask, ProductPlanKind, ProductPlanReviewFailureType, ProductPlanReviewResult, VersionPlan } from '@/lib/version-plan';
|
||||
import { canEditPlanRequirementCoverage, canTogglePlanChecklist, getPlanCompletionState } from '@/lib/version-plan-workflow';
|
||||
import type { PlanResultPayload } from '@/lib/version-plan-workflow';
|
||||
import { PlanLogTimeline, PlanRequirementCoveragePanel } from './PlanRequirementCoveragePanel';
|
||||
|
||||
interface Props {
|
||||
planId: string;
|
||||
@@ -49,6 +51,7 @@ export function PlanDetailDrawer({ planId, onClose, contextLabel }: Props) {
|
||||
const { plans, updatePlan, completePlan } = useVersionPlanStore();
|
||||
const { requirements } = useRequirementStore();
|
||||
const { members } = useMemberStore();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const [showTransfer, setShowTransfer] = useState(false);
|
||||
const [transferTo, setTransferTo] = useState('');
|
||||
const [resultType, setResultType] = useState<'link' | 'file'>('link');
|
||||
@@ -67,10 +70,11 @@ export function PlanDetailDrawer({ planId, onClose, contextLabel }: Props) {
|
||||
|
||||
const completionState = getPlanCompletionState(plan);
|
||||
const isResearch = plan.type === 'research';
|
||||
const progress = isResearch ? calcPlanProgress(plan.tasks) : calcLinkedReqProgress(plan.linkedRequirementIds, plan.completedRequirementIds);
|
||||
const progress = isResearch ? calcPlanProgress(plan.tasks) : getRequirementCoverageSummary(plan).percent;
|
||||
const linkedReqs = (plan.linkedRequirementIds || []).map((id) => requirements.find((r) => r.id === id)).filter(Boolean) as { id: string; code: string; title: string }[];
|
||||
const canToggle = canTogglePlanChecklist(plan);
|
||||
const canEditCoverage = canEditPlanRequirementCoverage(plan);
|
||||
const currentUserName = user?.name ?? plan.owner;
|
||||
const productPlanKind = plan.type === 'product' ? getProductPlanKind(plan) : undefined;
|
||||
const isProductDesignPlan = productPlanKind === 'design';
|
||||
const isProductReviewPlan = productPlanKind === 'review';
|
||||
@@ -82,13 +86,6 @@ export function PlanDetailDrawer({ planId, onClose, contextLabel }: Props) {
|
||||
updatePlan(plan.id, { tasks: updatedTasks });
|
||||
};
|
||||
|
||||
const handleToggleReq = (reqId: string) => {
|
||||
if (!canEditCoverage) return;
|
||||
const current = plan.completedRequirementIds || [];
|
||||
const next = current.includes(reqId) ? current.filter((id) => id !== reqId) : [...current, reqId];
|
||||
updatePlan(plan.id, { completedRequirementIds: next });
|
||||
};
|
||||
|
||||
const handleFile = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
@@ -235,32 +232,25 @@ export function PlanDetailDrawer({ planId, onClose, contextLabel }: Props) {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Product/UI: Linked Requirements */}
|
||||
{linkedReqs.length > 0 && (
|
||||
<div className="space-y-1.5">
|
||||
<div className="text-[11px] font-medium text-[var(--ink-muted)]">关联需求</div>
|
||||
{linkedReqs.map((req) => {
|
||||
const isDone = (plan.completedRequirementIds || []).includes(req.id);
|
||||
return (
|
||||
<div key={req.id} className="flex items-center gap-2 px-2 py-1.5 rounded-lg hover:bg-[var(--bg-subtle)]">
|
||||
<button
|
||||
disabled={!canEditCoverage}
|
||||
onClick={() => handleToggleReq(req.id)}
|
||||
className={`h-4 w-4 rounded border flex items-center justify-center shrink-0 transition-colors ${!canEditCoverage ? 'opacity-40 cursor-not-allowed' : ''} ${isDone ? 'bg-[var(--accent)] border-[var(--accent)]' : 'border-[var(--line)]'}`}
|
||||
>
|
||||
{isDone && <Check className="h-2.5 w-2.5 text-white" strokeWidth={3} />}
|
||||
</button>
|
||||
<span className="text-[11px] font-mono text-[var(--ink-muted)]">{req.code}</span>
|
||||
<span className={`flex-1 text-[12px] ${isDone ? 'line-through text-[var(--ink-muted)]' : 'text-[var(--ink)]'}`}>{req.title}</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div>
|
||||
<PlanRequirementCoveragePanel
|
||||
plan={plan}
|
||||
requirements={linkedReqs}
|
||||
canEdit={canEditCoverage}
|
||||
currentUserName={currentUserName}
|
||||
onUpdate={updatePlan}
|
||||
/>
|
||||
{plan.status === 'in_progress' && !completionState.canSubmitResult && (
|
||||
<p className="pt-1 text-[11px] text-[var(--ink-muted)]">还不能提交成果:{completionState.missingReasons.join('、')}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isResearch && (
|
||||
<PlanLogTimeline logs={plan.logs} className="border-l-0 border-t border-[var(--line)] pt-4 pl-0" />
|
||||
)}
|
||||
|
||||
{/* Result */}
|
||||
{plan.status === 'completed' && plan.resultUrl && (
|
||||
<div className="rounded-lg bg-[var(--bg-subtle)] p-3">
|
||||
|
||||
233
apps/web/components/version/PlanRequirementCoveragePanel.tsx
Normal file
233
apps/web/components/version/PlanRequirementCoveragePanel.tsx
Normal file
@@ -0,0 +1,233 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { Check, Clock3, Sparkles } from 'lucide-react';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
import type { Requirement } from '@/lib/requirement';
|
||||
import type { RequirementCoverageStatus, VersionPlan, VersionPlanLog } from '@/lib/version-plan';
|
||||
import {
|
||||
getRequirementCoverage,
|
||||
getRequirementCoverageStatus,
|
||||
getRequirementCoverageSummary,
|
||||
REQUIREMENT_COVERAGE_LABEL,
|
||||
updateRequirementCoverage,
|
||||
} from '@/lib/version-plan';
|
||||
|
||||
type RequirementOption = Pick<Requirement, 'id' | 'code' | 'title'> & { isHistorical?: boolean };
|
||||
|
||||
interface CoverageProps {
|
||||
plan: VersionPlan;
|
||||
requirements: RequirementOption[];
|
||||
canEdit: boolean;
|
||||
currentUserName: string;
|
||||
onUpdate: (id: string, data: Partial<VersionPlan>) => void;
|
||||
}
|
||||
|
||||
interface LogTimelineProps {
|
||||
logs?: VersionPlanLog[];
|
||||
className?: string;
|
||||
}
|
||||
|
||||
const COVERAGE_STATUS_OPTIONS: RequirementCoverageStatus[] = ['partial', 'completed', 'not_started'];
|
||||
|
||||
const COVERAGE_BADGE_STYLE: Record<RequirementCoverageStatus, string> = {
|
||||
not_started: 'border-zinc-200 bg-zinc-50 text-zinc-500',
|
||||
partial: 'border-amber-200 bg-amber-50 text-amber-700',
|
||||
completed: 'border-emerald-200 bg-emerald-50 text-emerald-700',
|
||||
};
|
||||
|
||||
function getLogIcon(log: VersionPlanLog) {
|
||||
if (log.type === 'ai_decompose') return <Sparkles className="h-3.5 w-3.5" />;
|
||||
if (log.type === 'requirement_progress') return <Check className="h-3.5 w-3.5" />;
|
||||
return <Clock3 className="h-3.5 w-3.5" />;
|
||||
}
|
||||
|
||||
function getLogTone(log: VersionPlanLog): string {
|
||||
if (log.aiStatus === 'error') return 'bg-red-50 text-red-700 ring-red-100';
|
||||
if (log.type === 'ai_decompose') return 'bg-purple-50 text-purple-700 ring-purple-100';
|
||||
if (log.coverageStatus === 'completed') return 'bg-emerald-50 text-emerald-700 ring-emerald-100';
|
||||
if (log.coverageStatus === 'partial') return 'bg-amber-50 text-amber-700 ring-amber-100';
|
||||
return 'bg-zinc-50 text-zinc-600 ring-zinc-100';
|
||||
}
|
||||
|
||||
export function PlanRequirementCoveragePanel({ plan, requirements, canEdit, currentUserName, onUpdate }: CoverageProps) {
|
||||
const [editingRequirementId, setEditingRequirementId] = useState<string | null>(null);
|
||||
const [draftStatus, setDraftStatus] = useState<RequirementCoverageStatus>('partial');
|
||||
const [completedContent, setCompletedContent] = useState('');
|
||||
const [remainingContent, setRemainingContent] = useState('');
|
||||
const summary = getRequirementCoverageSummary(plan);
|
||||
|
||||
if (requirements.length === 0) return null;
|
||||
|
||||
const openEditor = (req: RequirementOption) => {
|
||||
const coverage = getRequirementCoverage(plan, req.id);
|
||||
setEditingRequirementId(req.id);
|
||||
setDraftStatus(coverage?.status === 'completed' ? 'completed' : coverage?.status === 'not_started' ? 'not_started' : 'partial');
|
||||
setCompletedContent(coverage?.completedContent ?? '');
|
||||
setRemainingContent(coverage?.remainingContent ?? '');
|
||||
};
|
||||
|
||||
const closeEditor = () => {
|
||||
setEditingRequirementId(null);
|
||||
setCompletedContent('');
|
||||
setRemainingContent('');
|
||||
setDraftStatus('partial');
|
||||
};
|
||||
|
||||
const canSave = draftStatus === 'not_started'
|
||||
|| (draftStatus === 'completed' && completedContent.trim().length > 0)
|
||||
|| (draftStatus === 'partial' && completedContent.trim().length > 0 && remainingContent.trim().length > 0);
|
||||
|
||||
const saveCoverage = (req: RequirementOption) => {
|
||||
if (!canEdit || !canSave) return;
|
||||
const patch = updateRequirementCoverage(plan, {
|
||||
requirementId: req.id,
|
||||
status: draftStatus,
|
||||
completedContent: draftStatus === 'not_started' ? undefined : completedContent,
|
||||
remainingContent: draftStatus === 'partial' ? remainingContent : undefined,
|
||||
updatedBy: currentUserName,
|
||||
requirementCode: req.code,
|
||||
requirementTitle: req.title,
|
||||
});
|
||||
onUpdate(plan.id, patch);
|
||||
closeEditor();
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mt-3 space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<div className="text-[11px] font-semibold text-[var(--ink-muted)]">引用需求</div>
|
||||
<div className="mt-0.5 text-[11px] text-[var(--ink-soft)]">
|
||||
完全完成 {summary.completed} / {summary.total}
|
||||
{summary.partial > 0 && <span className="ml-2 text-amber-700">部分完成 {summary.partial}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<span className="shrink-0 text-[11px] font-medium tabular-nums text-[var(--ink-soft)]">{summary.percent}%</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="h-1.5 flex-1 overflow-hidden rounded-full bg-[var(--bg-subtle)]">
|
||||
<div className="h-full rounded-full bg-[var(--accent)] transition-all" style={{ width: `${summary.percent}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="max-h-56 space-y-1 overflow-y-auto rounded-lg bg-[var(--bg-subtle)] p-2 pr-1">
|
||||
{requirements.map((req) => {
|
||||
const status = getRequirementCoverageStatus(plan, req.id);
|
||||
const coverage = getRequirementCoverage(plan, req.id);
|
||||
const isEditing = editingRequirementId === req.id;
|
||||
return (
|
||||
<div key={req.id} className="rounded-md px-2 py-1.5 hover:bg-[var(--bg-card)]">
|
||||
<div className="flex min-w-0 items-start gap-2">
|
||||
<span className={`mt-0.5 inline-flex shrink-0 items-center rounded-md border px-1.5 py-0.5 text-[10px] font-medium ${COVERAGE_BADGE_STYLE[status]}`}>
|
||||
{REQUIREMENT_COVERAGE_LABEL[status]}
|
||||
</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<span className="shrink-0 font-mono text-[11px] text-[var(--ink-muted)]">{req.code}</span>
|
||||
<span className="min-w-0 truncate text-[12px] font-medium text-[var(--ink)]" title={req.title}>{req.title}</span>
|
||||
{req.isHistorical && <span className="shrink-0 rounded bg-orange-50 px-1.5 py-0.5 text-[10px] text-orange-600">历史</span>}
|
||||
</div>
|
||||
{(coverage?.completedContent || coverage?.remainingContent) && (
|
||||
<div className="mt-1 space-y-0.5 text-[11px] leading-4 text-[var(--ink-soft)]">
|
||||
{coverage.completedContent && <div className="line-clamp-2">已完成:{coverage.completedContent}</div>}
|
||||
{coverage.remainingContent && <div className="line-clamp-2 text-amber-700">剩余:{coverage.remainingContent}</div>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{canEdit && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => isEditing ? closeEditor() : openEditor(req)}
|
||||
className="shrink-0 rounded-md border border-[var(--line)] px-2 py-1 text-[11px] font-medium text-[var(--ink-soft)] hover:bg-[var(--bg-subtle)]"
|
||||
>
|
||||
{isEditing ? '收起' : '记录'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{isEditing && (
|
||||
<div className="mt-2 space-y-2 rounded-lg border border-[var(--line)] bg-[var(--bg-card)] p-2">
|
||||
<div className="grid grid-cols-3 gap-1.5">
|
||||
{COVERAGE_STATUS_OPTIONS.map((statusOption) => (
|
||||
<button
|
||||
key={statusOption}
|
||||
type="button"
|
||||
onClick={() => setDraftStatus(statusOption)}
|
||||
className={`h-7 rounded-md border text-[11px] font-medium transition-colors ${draftStatus === statusOption ? 'border-[var(--accent)] bg-[var(--accent-soft)] text-[var(--accent)]' : 'border-[var(--line)] text-[var(--ink-soft)] hover:bg-[var(--bg-subtle)]'}`}
|
||||
>
|
||||
{REQUIREMENT_COVERAGE_LABEL[statusOption]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{draftStatus !== 'not_started' && (
|
||||
<textarea
|
||||
value={completedContent}
|
||||
onChange={(e) => setCompletedContent(e.target.value)}
|
||||
rows={2}
|
||||
placeholder="本次已完成的内容"
|
||||
className="w-full resize-none rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-2 py-1.5 text-[12px] focus:border-[var(--accent)] focus:outline-none"
|
||||
/>
|
||||
)}
|
||||
{draftStatus === 'partial' && (
|
||||
<textarea
|
||||
value={remainingContent}
|
||||
onChange={(e) => setRemainingContent(e.target.value)}
|
||||
rows={2}
|
||||
placeholder="剩余未完成的内容"
|
||||
className="w-full resize-none rounded-lg border border-[var(--line)] bg-[var(--bg-card)] px-2 py-1.5 text-[12px] focus:border-[var(--accent)] focus:outline-none"
|
||||
/>
|
||||
)}
|
||||
<div className="flex justify-end gap-2">
|
||||
<button type="button" onClick={closeEditor} className="h-7 px-2 text-[11px] text-[var(--ink-muted)]">取消</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => saveCoverage(req)}
|
||||
disabled={!canSave}
|
||||
className="h-7 rounded-md bg-[var(--accent)] px-3 text-[11px] font-medium text-white hover:bg-[var(--accent-hover)] disabled:opacity-50"
|
||||
>
|
||||
保存记录
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PlanLogTimeline({ logs, className = '' }: LogTimelineProps) {
|
||||
const sortedLogs = [...(logs ?? [])].sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||||
const frameClass = className || 'border-l border-[var(--line)] pl-4';
|
||||
|
||||
return (
|
||||
<aside className={frameClass}>
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="text-[11px] font-semibold text-[var(--ink-muted)]">日志</div>
|
||||
<span className="text-[11px] tabular-nums text-[var(--ink-soft)]">{sortedLogs.length}</span>
|
||||
</div>
|
||||
{sortedLogs.length === 0 ? (
|
||||
<div className="mt-4 rounded-lg bg-[var(--bg-subtle)] px-3 py-4 text-center text-[11px] text-[var(--ink-muted)]">暂无日志</div>
|
||||
) : (
|
||||
<div className="mt-3 max-h-80 space-y-3 overflow-y-auto pr-1">
|
||||
{sortedLogs.map((log) => (
|
||||
<div key={log.id} className="relative pl-5">
|
||||
<span className={`absolute left-0 top-0 flex h-6 w-6 -translate-x-3 items-center justify-center rounded-full ring-4 ${getLogTone(log)}`}>
|
||||
{getLogIcon(log)}
|
||||
</span>
|
||||
<div className="space-y-1">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="min-w-0 text-[12px] font-medium leading-5 text-[var(--ink)]">{log.title}</div>
|
||||
<span className="shrink-0 text-[10px] text-[var(--ink-muted)]">{formatDateTime(log.createdAt)}</span>
|
||||
</div>
|
||||
<div className="text-[11px] text-[var(--ink-muted)]">{log.actor}</div>
|
||||
{log.detail && <div className="whitespace-pre-wrap rounded-md bg-[var(--bg-subtle)] px-2 py-1.5 text-[11px] leading-4 text-[var(--ink-soft)]">{log.detail}</div>}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
formatDuration,
|
||||
calcTotalDuration,
|
||||
calcPlanProgress,
|
||||
calcLinkedReqProgress,
|
||||
sortPlansNewestFirst,
|
||||
PRODUCT_PLAN_KIND_LABEL,
|
||||
PRODUCT_PLAN_REVIEW_FAILURE_OPTIONS,
|
||||
@@ -18,6 +17,7 @@ import { formatDateTime } from '@/lib/format';
|
||||
import { FieldError } from '@/components/FieldError';
|
||||
import { WorkDateTimePicker } from '@/components/WorkDateTimePicker';
|
||||
import { AiDecomposeButton } from './AiDecomposeButton';
|
||||
import { PlanLogTimeline, PlanRequirementCoveragePanel } from './PlanRequirementCoveragePanel';
|
||||
import type { VersionWithContext } from '@/lib/derive';
|
||||
import type { Requirement } from '@/lib/requirement';
|
||||
import { mergeSelectedRequirementOptions } from '@/lib/requirement-selector';
|
||||
@@ -119,6 +119,8 @@ export function PlanTab({ plans, versionId, version, versionDeadline, currentUse
|
||||
}
|
||||
return (
|
||||
<div key={plan.id} className="rounded-xl border border-[var(--line)] bg-[var(--bg-card)] p-4 shadow-[var(--shadow-sm)]">
|
||||
<div className={plan.type === 'research' ? '' : 'grid gap-4 xl:grid-cols-[minmax(0,1fr)_320px]'}>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-start justify-between gap-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
@@ -229,48 +231,14 @@ export function PlanTab({ plans, versionId, version, versionDeadline, currentUse
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{/* 关联需求 */}
|
||||
{plan.linkedRequirementIds && plan.linkedRequirementIds.length > 0 && requirementOptions.length > 0 && (
|
||||
<div className="mt-3 space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<div className="text-[11px] font-medium text-[var(--ink-muted)]">引用需求</div>
|
||||
<div className="mt-0.5 text-[11px] text-[var(--ink-soft)]">
|
||||
已覆盖 {(plan.completedRequirementIds || []).filter((id) => plan.linkedRequirementIds?.includes(id)).length} / {plan.linkedRequirementIds.length}
|
||||
</div>
|
||||
</div>
|
||||
<span className="shrink-0 text-[11px] font-medium tabular-nums text-[var(--ink-soft)]">{calcLinkedReqProgress(plan.linkedRequirementIds, plan.completedRequirementIds)}%</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex-1 h-1.5 rounded-full bg-[var(--bg-subtle)] overflow-hidden">
|
||||
<div className="h-full rounded-full bg-[var(--accent)] transition-all" style={{ width: `${calcLinkedReqProgress(plan.linkedRequirementIds, plan.completedRequirementIds)}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="max-h-44 space-y-1 overflow-y-auto rounded-lg bg-[var(--bg-subtle)] p-2 pr-1">
|
||||
{plan.linkedRequirementIds.map((rid) => {
|
||||
const req = requirementOptions.find((r) => r.id === rid);
|
||||
const isDone = (plan.completedRequirementIds || []).includes(rid);
|
||||
return req ? (
|
||||
<div key={rid} className="flex min-w-0 items-center gap-2 rounded-md px-2 py-1 hover:bg-[var(--bg-card)]">
|
||||
<button
|
||||
disabled={!canEditCoverage}
|
||||
onClick={() => {
|
||||
if (!canEditCoverage) return;
|
||||
const current = plan.completedRequirementIds || [];
|
||||
const next = isDone ? current.filter((id) => id !== rid) : [...current, rid];
|
||||
onUpdate(plan.id, { completedRequirementIds: next });
|
||||
}}
|
||||
className={`h-4 w-4 rounded border flex items-center justify-center shrink-0 transition-colors ${!canEditCoverage ? 'opacity-40 cursor-not-allowed' : ''} ${isDone ? 'bg-[var(--accent)] border-[var(--accent)]' : 'border-[var(--line)]'}`}
|
||||
>
|
||||
{isDone && <Check className="h-2.5 w-2.5 text-white" strokeWidth={3} />}
|
||||
</button>
|
||||
<span className="shrink-0 text-[11px] font-mono text-[var(--ink-muted)]">{req.code}</span>
|
||||
<span className={`min-w-0 flex-1 truncate text-[12px] ${isDone ? 'line-through text-[var(--ink-muted)]' : 'text-[var(--ink)]'}`} title={req.title}>{req.title}</span>
|
||||
</div>
|
||||
) : null;
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<PlanRequirementCoveragePanel
|
||||
plan={plan}
|
||||
requirements={plan.linkedRequirementIds.map((rid) => requirementOptions.find((r) => r.id === rid)).filter(Boolean) as Requirement[]}
|
||||
canEdit={canEditCoverage}
|
||||
currentUserName={currentUserName}
|
||||
onUpdate={onUpdate}
|
||||
/>
|
||||
)}
|
||||
{plan.status === 'in_progress' && !completionState.canSubmitResult && (
|
||||
<p className="mt-2 text-[11px] text-[var(--ink-muted)]">还不能提交成果:{completionState.missingReasons.join('、')}</p>
|
||||
@@ -314,6 +282,14 @@ export function PlanTab({ plans, versionId, version, versionDeadline, currentUse
|
||||
<button onClick={() => setCompletingPlan(plan)} className="text-[11px] font-medium text-green-700 hover:text-green-900 underline">{getSubmitActionLabel(plan)}</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{plan.type !== 'research' && (
|
||||
<PlanLogTimeline
|
||||
logs={plan.logs}
|
||||
className="border-t border-[var(--line)] pt-4 xl:border-l xl:border-t-0 xl:pt-0 xl:pl-4"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
48
apps/web/lib/entity-activity-log.test.ts
Normal file
48
apps/web/lib/entity-activity-log.test.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import type { WorkActivity } from './work-activity';
|
||||
import { getEntityActivityLogEntries } from './entity-activity-log';
|
||||
|
||||
function activity(patch: Partial<WorkActivity>): WorkActivity {
|
||||
return {
|
||||
id: 'act-1',
|
||||
actorId: '张三',
|
||||
date: '2026-06-29',
|
||||
occurredAt: '2026-06-29T01:00:00.000Z',
|
||||
sourceType: 'dev_task',
|
||||
sourceId: 'dev-1',
|
||||
action: 'dev_task_started',
|
||||
category: 'progress',
|
||||
title: '开发任务',
|
||||
summary: '开始开发:开发任务',
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
test('getEntityActivityLogEntries filters by source and sorts newest first', () => {
|
||||
const entries = getEntityActivityLogEntries([
|
||||
activity({ id: 'old', occurredAt: '2026-06-29T01:00:00.000Z' }),
|
||||
activity({ id: 'other-source', sourceType: 'test_case', sourceId: 'tc-1' }),
|
||||
activity({ id: 'new', occurredAt: '2026-06-29T03:00:00.000Z', action: 'dev_task_submitted' }),
|
||||
], 'dev_task', 'dev-1');
|
||||
|
||||
assert.deepEqual(entries.map((entry) => entry.id), ['new', 'old']);
|
||||
assert.equal(entries[0].label, '已提测');
|
||||
});
|
||||
|
||||
test('getEntityActivityLogEntries merges legacy logs with activity entries', () => {
|
||||
const entries = getEntityActivityLogEntries([
|
||||
activity({ id: 'activity-log', occurredAt: '2026-06-29T02:00:00.000Z' }),
|
||||
], 'dev_task', 'dev-1', [
|
||||
{
|
||||
id: 'legacy-log',
|
||||
actorId: '李四',
|
||||
occurredAt: '2026-06-29T04:00:00.000Z',
|
||||
label: '旧日志',
|
||||
summary: '历史操作记录',
|
||||
},
|
||||
]);
|
||||
|
||||
assert.deepEqual(entries.map((entry) => entry.id), ['legacy-log', 'activity-log']);
|
||||
});
|
||||
54
apps/web/lib/entity-activity-log.ts
Normal file
54
apps/web/lib/entity-activity-log.ts
Normal file
@@ -0,0 +1,54 @@
|
||||
import type { WorkActivity, WorkActivityAction, WorkActivitySourceType } from './work-activity';
|
||||
|
||||
export interface EntityActivityLogEntry {
|
||||
id: string;
|
||||
occurredAt: string;
|
||||
actorId: string;
|
||||
label: string;
|
||||
summary: string;
|
||||
}
|
||||
|
||||
export const WORK_ACTIVITY_ACTION_LABEL: Record<WorkActivityAction, string> = {
|
||||
version_plan_created: '新建计划',
|
||||
version_plan_started: '开始计划',
|
||||
version_plan_completed: '完成计划',
|
||||
dev_task_created: '新建开发任务',
|
||||
dev_task_started: '开始开发',
|
||||
dev_task_self_testing: '进入自测',
|
||||
dev_task_submitted: '已提测',
|
||||
dev_task_blocked: '标记阻塞',
|
||||
dev_task_unblocked: '解除阻塞',
|
||||
dev_task_transferred: '转交开发任务',
|
||||
test_case_created: '新建测试用例',
|
||||
test_case_started: '开始测试',
|
||||
test_case_passed: '测试通过',
|
||||
test_case_failed: '测试不通过',
|
||||
test_case_blocked: '测试阻塞',
|
||||
bug_created: '新建 Bug',
|
||||
bug_fixing: '开始修复',
|
||||
bug_fixed: '已修复',
|
||||
bug_closed: '已关闭',
|
||||
bug_blocked: 'Bug 阻塞',
|
||||
bug_transferred: '转交 Bug',
|
||||
progress_note_added: '补充进展',
|
||||
};
|
||||
|
||||
export function getEntityActivityLogEntries(
|
||||
activities: WorkActivity[],
|
||||
sourceType: WorkActivitySourceType,
|
||||
sourceId: string,
|
||||
legacyEntries: EntityActivityLogEntry[] = [],
|
||||
): EntityActivityLogEntry[] {
|
||||
const activityEntries = activities
|
||||
.filter((activity) => activity.sourceType === sourceType && activity.sourceId === sourceId)
|
||||
.map((activity) => ({
|
||||
id: activity.id,
|
||||
occurredAt: activity.occurredAt,
|
||||
actorId: activity.actorId,
|
||||
label: WORK_ACTIVITY_ACTION_LABEL[activity.action] || activity.action,
|
||||
summary: activity.summary,
|
||||
}));
|
||||
|
||||
return [...activityEntries, ...legacyEntries]
|
||||
.sort((a, b) => b.occurredAt.localeCompare(a.occurredAt));
|
||||
}
|
||||
@@ -38,6 +38,40 @@ test('requires product requirement coverage when linked requirements exist', ()
|
||||
assert.ok(state.missingReasons.includes('关联需求未全部覆盖'));
|
||||
});
|
||||
|
||||
test('does not treat partial requirement coverage as complete', () => {
|
||||
const state = getPlanCompletionState(plan({
|
||||
requirementCoverage: [{
|
||||
requirementId: 'r1',
|
||||
status: 'partial',
|
||||
completedContent: '完成列表主路径',
|
||||
remainingContent: '剩余筛选联动和空状态',
|
||||
updatedAt: '2026-06-29T09:00:00.000Z',
|
||||
updatedBy: 'PM',
|
||||
}],
|
||||
} as Partial<VersionPlan>));
|
||||
|
||||
assert.equal(state.requirementCompleted, 0);
|
||||
assert.equal(state.canSubmitResult, false);
|
||||
assert.ok(state.missingReasons.includes('关联需求未全部覆盖'));
|
||||
});
|
||||
|
||||
test('uses requirement coverage before legacy completed ids when both exist', () => {
|
||||
const state = getPlanCompletionState(plan({
|
||||
completedRequirementIds: ['r1'],
|
||||
requirementCoverage: [{
|
||||
requirementId: 'r1',
|
||||
status: 'partial',
|
||||
completedContent: '完成移动端',
|
||||
remainingContent: 'PC 端未完成',
|
||||
updatedAt: '2026-06-29T09:00:00.000Z',
|
||||
updatedBy: 'PM',
|
||||
}],
|
||||
} as Partial<VersionPlan>));
|
||||
|
||||
assert.equal(state.requirementCompleted, 0);
|
||||
assert.equal(state.canSubmitResult, false);
|
||||
});
|
||||
|
||||
test('allows product result submission after coverage is complete without task checklist', () => {
|
||||
const state = getPlanCompletionState(plan({
|
||||
completedRequirementIds: ['r1'],
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getRequirementCoverageSummary } from './version-plan';
|
||||
import type { ProductPlanKind, ProductPlanReviewFailureType, ProductPlanReviewResult, VersionPlan } from './version-plan';
|
||||
|
||||
export interface PlanResultPayload {
|
||||
@@ -67,10 +68,9 @@ export function getPlanCompletionState(plan: VersionPlan): PlanCompletionState {
|
||||
const checklistTotal = tasks.length;
|
||||
const checklistCompleted = tasks.filter((task) => task.status === 'completed').length;
|
||||
|
||||
const linked = plan.linkedRequirementIds ?? [];
|
||||
const completed = new Set(plan.completedRequirementIds ?? []);
|
||||
const requirementTotal = linked.length;
|
||||
const requirementCompleted = linked.filter((id) => completed.has(id)).length;
|
||||
const requirementSummary = getRequirementCoverageSummary(plan);
|
||||
const requirementTotal = requirementSummary.total;
|
||||
const requirementCompleted = requirementSummary.completed;
|
||||
|
||||
const missingReasons: string[] = [];
|
||||
if (requiresChecklist(plan) && checklistTotal === 0) missingReasons.push('缺少子任务');
|
||||
|
||||
@@ -35,3 +35,84 @@ test('sortPlansNewestFirst places newly created plans before older plans', () =>
|
||||
assert.deepEqual(sorted.map((item) => item.id), ['plan-300', 'plan-100', 'manual-old']);
|
||||
assert.deepEqual(plans.map((item) => item.id), ['plan-100', 'manual-old', 'plan-300']);
|
||||
});
|
||||
|
||||
test('derives requirement coverage from new records and legacy completed ids', () => {
|
||||
const getRequirementCoverageStatus = (versionPlan as any).getRequirementCoverageStatus as undefined | ((item: VersionPlan, requirementId: string) => string);
|
||||
const getRequirementCoverageSummary = (versionPlan as any).getRequirementCoverageSummary as undefined | ((item: VersionPlan) => {
|
||||
total: number;
|
||||
completed: number;
|
||||
partial: number;
|
||||
notStarted: number;
|
||||
percent: number;
|
||||
});
|
||||
assert.equal(typeof getRequirementCoverageStatus, 'function');
|
||||
assert.equal(typeof getRequirementCoverageSummary, 'function');
|
||||
|
||||
const item = plan({
|
||||
linkedRequirementIds: ['r1', 'r2', 'r3', 'r4'],
|
||||
completedRequirementIds: ['r2'],
|
||||
requirementCoverage: [
|
||||
{
|
||||
requirementId: 'r1',
|
||||
status: 'partial',
|
||||
completedContent: '完成主流程原型',
|
||||
remainingContent: '补充异常状态',
|
||||
updatedAt: '2026-06-29T09:00:00.000Z',
|
||||
updatedBy: 'PM',
|
||||
},
|
||||
{
|
||||
requirementId: 'r3',
|
||||
status: 'completed',
|
||||
completedContent: '已覆盖列表和详情',
|
||||
updatedAt: '2026-06-29T10:00:00.000Z',
|
||||
updatedBy: 'PM',
|
||||
},
|
||||
],
|
||||
} as Partial<VersionPlan>);
|
||||
|
||||
assert.equal(getRequirementCoverageStatus!(item, 'r1'), 'partial');
|
||||
assert.equal(getRequirementCoverageStatus!(item, 'r2'), 'completed');
|
||||
assert.equal(getRequirementCoverageStatus!(item, 'r4'), 'not_started');
|
||||
assert.deepEqual(getRequirementCoverageSummary!(item), {
|
||||
total: 4,
|
||||
completed: 2,
|
||||
partial: 1,
|
||||
notStarted: 1,
|
||||
percent: 50,
|
||||
});
|
||||
});
|
||||
|
||||
test('updates requirement coverage, syncs legacy completed ids, and creates a plan log', () => {
|
||||
const updateRequirementCoverage = (versionPlan as any).updateRequirementCoverage as undefined | ((item: VersionPlan, input: {
|
||||
requirementId: string;
|
||||
status: string;
|
||||
completedContent?: string;
|
||||
remainingContent?: string;
|
||||
updatedBy: string;
|
||||
updatedAt: string;
|
||||
requirementCode?: string;
|
||||
requirementTitle?: string;
|
||||
}) => any);
|
||||
assert.equal(typeof updateRequirementCoverage, 'function');
|
||||
|
||||
const next = updateRequirementCoverage!(plan({
|
||||
linkedRequirementIds: ['r1'],
|
||||
completedRequirementIds: ['r1'],
|
||||
}), {
|
||||
requirementId: 'r1',
|
||||
status: 'partial',
|
||||
completedContent: '完成移动端主流程',
|
||||
remainingContent: 'PC 端筛选规则未完成',
|
||||
updatedBy: 'PM',
|
||||
updatedAt: '2026-06-29T12:00:00.000Z',
|
||||
requirementCode: 'QY0001',
|
||||
requirementTitle: '需求池筛选',
|
||||
});
|
||||
|
||||
assert.deepEqual(next.completedRequirementIds, []);
|
||||
assert.equal(next.requirementCoverage?.[0]?.status, 'partial');
|
||||
assert.equal(next.logs?.length, 1);
|
||||
assert.equal(next.logs?.[0]?.type, 'requirement_progress');
|
||||
assert.equal(next.logs?.[0]?.actor, 'PM');
|
||||
assert.equal(next.logs?.[0]?.requirementCode, 'QY0001');
|
||||
});
|
||||
|
||||
@@ -3,6 +3,9 @@ import type { AgentDecomposeTarget } from '@ftb/shared';
|
||||
export type PlanTaskStatus = 'pending' | 'in_progress' | 'completed';
|
||||
export type ProductPlanKind = 'design' | 'review';
|
||||
export type ProductPlanReviewResult = 'passed' | 'failed';
|
||||
export type RequirementCoverageStatus = 'not_started' | 'partial' | 'completed';
|
||||
export type VersionPlanLogType = 'requirement_progress' | 'ai_decompose' | 'system';
|
||||
export type AiDecomposeLogStatus = 'started' | 'completed' | 'error';
|
||||
export type ProductPlanReviewFailureType =
|
||||
| 'requirement_mismatch'
|
||||
| 'information_architecture'
|
||||
@@ -44,6 +47,52 @@ export interface PlanTask {
|
||||
status: PlanTaskStatus;
|
||||
}
|
||||
|
||||
export interface VersionPlanRequirementCoverage {
|
||||
requirementId: string;
|
||||
status: RequirementCoverageStatus;
|
||||
completedContent?: string;
|
||||
remainingContent?: string;
|
||||
updatedAt: string;
|
||||
updatedBy: string;
|
||||
}
|
||||
|
||||
export interface VersionPlanLog {
|
||||
id: string;
|
||||
type: VersionPlanLogType;
|
||||
createdAt: string;
|
||||
actor: string;
|
||||
title: string;
|
||||
detail?: string;
|
||||
requirementId?: string;
|
||||
requirementCode?: string;
|
||||
requirementTitle?: string;
|
||||
coverageStatus?: RequirementCoverageStatus;
|
||||
aiTarget?: AgentDecomposeTarget;
|
||||
aiStatus?: AiDecomposeLogStatus;
|
||||
}
|
||||
|
||||
export interface RequirementCoverageUpdateInput {
|
||||
requirementId: string;
|
||||
status: RequirementCoverageStatus;
|
||||
completedContent?: string;
|
||||
remainingContent?: string;
|
||||
updatedAt?: string;
|
||||
updatedBy: string;
|
||||
requirementCode?: string;
|
||||
requirementTitle?: string;
|
||||
}
|
||||
|
||||
export type PlanLogDraft = Omit<VersionPlanLog, 'id' | 'createdAt'> & {
|
||||
id?: string;
|
||||
createdAt?: string;
|
||||
};
|
||||
|
||||
export const REQUIREMENT_COVERAGE_LABEL: Record<RequirementCoverageStatus, string> = {
|
||||
not_started: '未开始',
|
||||
partial: '部分完成',
|
||||
completed: '完全完成',
|
||||
};
|
||||
|
||||
export interface VersionPlan {
|
||||
id: string;
|
||||
versionId: string;
|
||||
@@ -56,6 +105,8 @@ export interface VersionPlan {
|
||||
tasks?: PlanTask[];
|
||||
completedRequirementIds?: string[];
|
||||
linkedRequirementIds?: string[];
|
||||
requirementCoverage?: VersionPlanRequirementCoverage[];
|
||||
logs?: VersionPlanLog[];
|
||||
productPlanKind?: ProductPlanKind;
|
||||
resultType?: 'link' | 'file';
|
||||
resultTitle?: string;
|
||||
@@ -81,6 +132,106 @@ export interface VersionPlan {
|
||||
|
||||
export type PlanType = VersionPlan['type'];
|
||||
|
||||
function makePlanLogId(createdAt: string): string {
|
||||
const time = new Date(createdAt).getTime();
|
||||
const suffix = Math.random().toString(36).slice(2, 8);
|
||||
return `plan-log-${Number.isFinite(time) ? time : Date.now()}-${suffix}`;
|
||||
}
|
||||
|
||||
export function getRequirementCoverage(plan: VersionPlan, requirementId: string): VersionPlanRequirementCoverage | undefined {
|
||||
const explicit = plan.requirementCoverage?.find((item) => item.requirementId === requirementId);
|
||||
if (explicit) return explicit;
|
||||
if ((plan.completedRequirementIds ?? []).includes(requirementId)) {
|
||||
return {
|
||||
requirementId,
|
||||
status: 'completed',
|
||||
updatedAt: plan.completedAt ?? plan.createdAt,
|
||||
updatedBy: plan.owner,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function getRequirementCoverageStatus(plan: VersionPlan, requirementId: string): RequirementCoverageStatus {
|
||||
return getRequirementCoverage(plan, requirementId)?.status ?? 'not_started';
|
||||
}
|
||||
|
||||
export function getRequirementCoverageSummary(plan: VersionPlan): {
|
||||
total: number;
|
||||
completed: number;
|
||||
partial: number;
|
||||
notStarted: number;
|
||||
percent: number;
|
||||
} {
|
||||
const linkedIds = plan.linkedRequirementIds ?? [];
|
||||
const total = linkedIds.length;
|
||||
const completed = linkedIds.filter((id) => getRequirementCoverageStatus(plan, id) === 'completed').length;
|
||||
const partial = linkedIds.filter((id) => getRequirementCoverageStatus(plan, id) === 'partial').length;
|
||||
const notStarted = Math.max(total - completed - partial, 0);
|
||||
return {
|
||||
total,
|
||||
completed,
|
||||
partial,
|
||||
notStarted,
|
||||
percent: total === 0 ? 0 : Math.round((completed / total) * 100),
|
||||
};
|
||||
}
|
||||
|
||||
export function appendPlanLog(plan: VersionPlan, draft: PlanLogDraft): VersionPlanLog[] {
|
||||
const createdAt = draft.createdAt ?? new Date().toISOString();
|
||||
const log: VersionPlanLog = {
|
||||
...draft,
|
||||
id: draft.id ?? makePlanLogId(createdAt),
|
||||
createdAt,
|
||||
};
|
||||
return [log, ...(plan.logs ?? [])];
|
||||
}
|
||||
|
||||
export function updateRequirementCoverage(
|
||||
plan: VersionPlan,
|
||||
input: RequirementCoverageUpdateInput,
|
||||
): Pick<VersionPlan, 'requirementCoverage' | 'completedRequirementIds' | 'logs'> {
|
||||
const updatedAt = input.updatedAt ?? new Date().toISOString();
|
||||
const nextCoverage: VersionPlanRequirementCoverage = {
|
||||
requirementId: input.requirementId,
|
||||
status: input.status,
|
||||
completedContent: input.completedContent?.trim() || undefined,
|
||||
remainingContent: input.remainingContent?.trim() || undefined,
|
||||
updatedAt,
|
||||
updatedBy: input.updatedBy,
|
||||
};
|
||||
const requirementCoverage = [
|
||||
nextCoverage,
|
||||
...(plan.requirementCoverage ?? []).filter((item) => item.requirementId !== input.requirementId),
|
||||
];
|
||||
|
||||
const completedSet = new Set(plan.completedRequirementIds ?? []);
|
||||
if (input.status === 'completed') completedSet.add(input.requirementId);
|
||||
else completedSet.delete(input.requirementId);
|
||||
|
||||
const detail = [
|
||||
nextCoverage.completedContent ? `已完成:${nextCoverage.completedContent}` : '',
|
||||
nextCoverage.remainingContent ? `剩余:${nextCoverage.remainingContent}` : '',
|
||||
].filter(Boolean).join('\n');
|
||||
const reqLabel = [input.requirementCode, input.requirementTitle].filter(Boolean).join(' ');
|
||||
|
||||
return {
|
||||
requirementCoverage,
|
||||
completedRequirementIds: Array.from(completedSet),
|
||||
logs: appendPlanLog(plan, {
|
||||
type: 'requirement_progress',
|
||||
createdAt: updatedAt,
|
||||
actor: input.updatedBy,
|
||||
title: `${reqLabel || '需求'}更新为${REQUIREMENT_COVERAGE_LABEL[input.status]}`,
|
||||
detail: detail || undefined,
|
||||
requirementId: input.requirementId,
|
||||
requirementCode: input.requirementCode,
|
||||
requirementTitle: input.requirementTitle,
|
||||
coverageStatus: input.status,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function getPlanCreatedAtTime(plan: VersionPlan): number {
|
||||
const time = new Date(plan.createdAt).getTime();
|
||||
return Number.isFinite(time) ? time : 0;
|
||||
|
||||
66
apps/web/lib/version-progress.test.ts
Normal file
66
apps/web/lib/version-progress.test.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { calcVersionProgress } from './version-progress';
|
||||
import type { Requirement } from './requirement';
|
||||
import type { VersionPlan } from './version-plan';
|
||||
|
||||
function requirement(id: string): Requirement {
|
||||
return {
|
||||
id,
|
||||
code: 'QY0001',
|
||||
title: '需求',
|
||||
description: '需求描述',
|
||||
productId: 'product-1',
|
||||
projectId: 'project-1',
|
||||
versionId: 'version-1',
|
||||
sourceType: 'internal',
|
||||
sourceTarget: '产品部',
|
||||
platforms: ['web'],
|
||||
typeId: 'type-1',
|
||||
status: 'planned',
|
||||
priority: 'P1',
|
||||
effort: 'M',
|
||||
creator: 'PM',
|
||||
createdAt: '2026-06-29',
|
||||
};
|
||||
}
|
||||
|
||||
function plan(patch: Partial<VersionPlan>): VersionPlan {
|
||||
return {
|
||||
id: 'plan-1',
|
||||
versionId: 'version-1',
|
||||
type: 'product',
|
||||
title: '产品方案',
|
||||
owner: 'PM',
|
||||
startTime: '2026-06-29T09:00',
|
||||
endTime: '2026-06-29T18:00',
|
||||
status: 'in_progress',
|
||||
linkedRequirementIds: ['r1'],
|
||||
completedRequirementIds: ['r1'],
|
||||
createdAt: '2026-06-29',
|
||||
addedBy: 'PM',
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
test('version progress uses explicit requirement coverage before legacy completed ids', () => {
|
||||
const progress = calcVersionProgress(
|
||||
'version-1',
|
||||
[plan({
|
||||
requirementCoverage: [{
|
||||
requirementId: 'r1',
|
||||
status: 'partial',
|
||||
completedContent: '完成主流程',
|
||||
remainingContent: '剩余异常状态',
|
||||
updatedAt: '2026-06-29T09:00:00.000Z',
|
||||
updatedBy: 'PM',
|
||||
}],
|
||||
} as Partial<VersionPlan>)],
|
||||
[requirement('r1')],
|
||||
[],
|
||||
[],
|
||||
);
|
||||
|
||||
assert.equal(progress, 0);
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getRequirementCoverageSummary } from './version-plan';
|
||||
import type { VersionPlan } from './version-plan';
|
||||
import type { Requirement } from './requirement';
|
||||
import type { DevTask } from './dev-task';
|
||||
@@ -38,10 +39,9 @@ export function calcVersionProgress(
|
||||
const productPlans = vPlans.filter((p) => p.type === 'product');
|
||||
if (productPlans.length > 0) {
|
||||
const totals = productPlans.reduce((acc, p) => {
|
||||
const linked = p.linkedRequirementIds || [];
|
||||
const completed = p.completedRequirementIds || [];
|
||||
acc.total += linked.length;
|
||||
acc.done += completed.filter((id) => linked.includes(id)).length;
|
||||
const summary = getRequirementCoverageSummary(p);
|
||||
acc.total += summary.total;
|
||||
acc.done += summary.completed;
|
||||
return acc;
|
||||
}, { total: 0, done: 0 });
|
||||
segments.push(totals.total > 0 ? (totals.done / totals.total) * 100 : 0);
|
||||
@@ -50,10 +50,9 @@ export function calcVersionProgress(
|
||||
const uiPlans = vPlans.filter((p) => p.type === 'ui');
|
||||
if (uiPlans.length > 0) {
|
||||
const totals = uiPlans.reduce((acc, p) => {
|
||||
const linked = p.linkedRequirementIds || [];
|
||||
const completed = p.completedRequirementIds || [];
|
||||
acc.total += linked.length;
|
||||
acc.done += completed.filter((id) => linked.includes(id)).length;
|
||||
const summary = getRequirementCoverageSummary(p);
|
||||
acc.total += summary.total;
|
||||
acc.done += summary.completed;
|
||||
return acc;
|
||||
}, { total: 0, done: 0 });
|
||||
segments.push(totals.total > 0 ? (totals.done / totals.total) * 100 : 0);
|
||||
|
||||
@@ -419,6 +419,18 @@
|
||||
|
||||
**理由**:领取代表成员承诺执行,计划时间代表承诺边界,二者应该在同一个动作里完成。列表层只表达“谁还没接手”,状态机层负责阻止未计划任务进入执行,页面不会被额外标签干扰。
|
||||
|
||||
## 35. 产品/UI 计划需求覆盖必须区分部分完成和完全完成
|
||||
|
||||
**问题**:产品方案和 UI 设计经常跨天推进,同一天可能只完成某条需求的一部分。旧的勾选式“引用需求已完成”只能表达完成/未完成,日报和后续分析无法知道本次完成了什么、还剩什么,也容易把部分完成误算成可提交成果。
|
||||
|
||||
**决策**:
|
||||
- VersionPlan 增加 `requirementCoverage[]`,每条引用需求记录 `not_started / partial / completed`、已完成内容、剩余内容、更新人和更新时间。
|
||||
- 旧的 `completedRequirementIds` 继续保留用于兼容历史数据,但当同一需求存在 `requirementCoverage` 时,以新覆盖状态为准。
|
||||
- 产品/UI 计划的成果提交门禁只认 `completed`,`partial` 只记录进度,不满足“关联需求全部覆盖”。
|
||||
- 计划增加 `logs[]`,记录需求进度更新和 AI 拆解触发/完成/失败,右侧日志时间线消费该数据。
|
||||
|
||||
**理由**:覆盖状态是产品/UI 计划自身的业务事实,不应该用简单 checkbox 表达。显式记录“已完成/剩余”能支撑日报、复盘和需求完成质量分析,同时保留旧字段可避免历史数据迁移成本。
|
||||
|
||||
## 36. 小宝预警规则优先,AI 只做解释
|
||||
|
||||
**问题**:如果直接让 AI 判断版本能否发版,模型可能忽略系统内的任务、Bug、测试、日报和权限事实,结论不可追溯;如果只按风险等级触发 AI,又会漏掉同等级内风险剧变,例如 P1 Bug 从 0 到 3、测试失败、发版日只剩 1 天。
|
||||
|
||||
@@ -223,6 +223,8 @@ AI 估时约束:
|
||||
- `version-plan-workflow.ts` 是调研/产品方案/UI 设计完成条件的唯一入口。
|
||||
- `requirement-selector.ts` 是版本内关联需求候选的唯一入口。
|
||||
- `TaskCategory.code` 是 AI 和系统任务类型的稳定映射锚点,`id` 只作为存储主键。
|
||||
- 产品方案和 UI 设计的引用需求不再用 checkbox 直接标记完成,必须通过 `requirementCoverage[]` 记录 `not_started / partial / completed`、本次已完成内容和剩余内容;只有 `completed` 计入成果提交门禁。
|
||||
- 产品/UI 计划右侧展示计划日志,需求进度更新和 AI 拆解触发/完成/失败都写入 `VersionPlan.logs[]`,页面只消费日志数据,不临时拼历史。
|
||||
## Work Activity Daily Report Flow (2026-06-26)
|
||||
|
||||
The daily report flow uses mixed evidence:
|
||||
|
||||
Reference in New Issue
Block a user