feat(版本详情): 完善流程日志与需求覆盖
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>
|
||||
|
||||
|
||||
@@ -27,20 +27,30 @@ function BugRowImpl({ bug, testCaseNo, onClick }: Props) {
|
||||
const members = useMemberStore((s) => s.members);
|
||||
const assigneeName = resolveMemberDisplayName(bug.assigneeId, members);
|
||||
return (
|
||||
<div onClick={onClick} className="flex items-center gap-3 px-4 py-2.5 border-b border-[var(--line)] hover:bg-[var(--bg-subtle)] cursor-pointer transition-colors last:border-b-0">
|
||||
<span className={`h-2 w-2 rounded-full shrink-0 ${PRIORITY_DOT[bug.priority] || 'bg-zinc-300'}`} />
|
||||
<span className="text-[11px] font-mono text-[var(--ink-muted)] w-16 shrink-0">{bug.bugNo}</span>
|
||||
<span className="text-[13px] text-[var(--ink)] flex-1 truncate">{bug.title}</span>
|
||||
<span className={`text-[10px] px-1.5 py-0.5 rounded shrink-0 ${BUG_SEVERITY_COLOR[bug.severity]}`}>{BUG_SEVERITY_LABEL[bug.severity]}</span>
|
||||
<BugStatusBadge status={bug.status} />
|
||||
<span className="text-[11px] text-[var(--ink-muted)] tabular-nums w-24 text-right shrink-0 whitespace-nowrap" title="计划修复时间">
|
||||
<div onClick={onClick} className="px-4 py-2 border-b border-[var(--line)] hover:bg-[var(--bg-subtle)] cursor-pointer transition-colors last:border-b-0">
|
||||
<div className="flex min-w-0 items-start gap-2">
|
||||
<span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${PRIORITY_DOT[bug.priority] || 'bg-zinc-300'}`} />
|
||||
<span className="mt-0.5 w-16 shrink-0 text-[11px] font-mono text-[var(--ink-muted)]">{bug.bugNo}</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex min-w-0 items-center gap-1.5">
|
||||
<span className="truncate text-[13px] font-medium leading-5 text-[var(--ink)]">{bug.title}</span>
|
||||
<span className="ml-auto inline-flex min-w-0 shrink-0 flex-wrap items-center justify-end gap-x-2.5 gap-y-1 text-[11px]">
|
||||
<span className="tabular-nums whitespace-nowrap text-[var(--ink-muted)]" title="计划修复时间">
|
||||
{bug.plannedFixAt ? formatDateTimeShort(bug.plannedFixAt) : '待排期'}
|
||||
</span>
|
||||
{actualHours > 0 && (
|
||||
<span className="text-[11px] text-[var(--ink-muted)] tabular-nums w-28 text-right shrink-0 whitespace-nowrap">{formatWorkHours(actualHours)}</span>
|
||||
<span className="tabular-nums whitespace-nowrap text-[var(--ink-muted)]">实际 {formatWorkHours(actualHours)}</span>
|
||||
)}
|
||||
{testCaseNo && <span className="text-[10px] font-mono text-[var(--ink-muted)] w-14 text-right shrink-0">{testCaseNo}</span>}
|
||||
<span className="text-[11px] text-[var(--ink-soft)] w-14 text-right truncate shrink-0">{assigneeName}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1 flex min-w-0 flex-wrap items-center justify-end gap-x-2.5 gap-y-1 text-[11px]">
|
||||
<span className={`shrink-0 rounded px-1.5 py-0.5 text-[10px] ${BUG_SEVERITY_COLOR[bug.severity]}`}>{BUG_SEVERITY_LABEL[bug.severity]}</span>
|
||||
<BugStatusBadge status={bug.status} />
|
||||
<span className="max-w-[120px] truncate whitespace-nowrap text-[var(--ink-soft)]">{assigneeName}</span>
|
||||
{testCaseNo && <span className="font-mono text-[10px] text-[var(--ink-muted)]">{testCaseNo}</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ import type { BugStatus } from '@/lib/bug';
|
||||
|
||||
export function BugStatusBadge({ status }: { status: BugStatus }) {
|
||||
return (
|
||||
<span className={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium ${BUG_STATUS_COLOR[status]}`}>
|
||||
<span className={`inline-flex h-5 shrink-0 items-center whitespace-nowrap rounded px-1.5 text-[10px] font-medium ${BUG_STATUS_COLOR[status]}`}>
|
||||
{BUG_STATUS_LABEL[status]}
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -1,13 +1,25 @@
|
||||
'use client';
|
||||
|
||||
import type { CSSProperties } from 'react';
|
||||
import type { TaskCategory } from '@/lib/task-category';
|
||||
|
||||
export function CategoryChip({ category }: { category?: TaskCategory }) {
|
||||
if (!category) return <span className="text-[11px] text-[var(--ink-muted)]">未分类</span>;
|
||||
export function CategoryChip({ category, widthEm }: { category?: TaskCategory; widthEm?: number }) {
|
||||
const widthStyle: CSSProperties = widthEm ? { width: `${widthEm}em` } : {};
|
||||
if (!category) {
|
||||
return (
|
||||
<span
|
||||
className="inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-medium"
|
||||
className="inline-flex h-5 shrink-0 items-center justify-center whitespace-nowrap rounded px-1.5 text-[10px] font-medium text-[var(--ink-muted)]"
|
||||
style={widthStyle}
|
||||
>
|
||||
未分类
|
||||
</span>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<span
|
||||
className="inline-flex h-5 shrink-0 items-center justify-center whitespace-nowrap rounded px-1.5 text-[10px] font-medium"
|
||||
style={{
|
||||
...widthStyle,
|
||||
backgroundColor: category.color ? `${category.color}15` : 'var(--bg-subtle)',
|
||||
color: category.color || 'var(--ink-soft)',
|
||||
}}
|
||||
|
||||
@@ -4,21 +4,26 @@ 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';
|
||||
import { useRequirementStore } from '@/stores/useRequirementStore';
|
||||
import { useMemberStore } from '@/stores/useMemberStore';
|
||||
import { useAuthStore } from '@/stores/useAuthStore';
|
||||
import { WorkDateTimePicker } from '@/components/WorkDateTimePicker';
|
||||
import {
|
||||
ALLOWED_TRANSITIONS,
|
||||
DEV_TASK_STATUS_LABEL,
|
||||
DEV_TASK_STATUS_COLOR,
|
||||
canStartDevTask,
|
||||
formatHours,
|
||||
getEstimateHours,
|
||||
getActualHours,
|
||||
needsDevTaskClaim,
|
||||
} from '@/lib/dev-task';
|
||||
import { needsDelayReason } from '@/lib/dev-task-transitions';
|
||||
import { formatShortTime } from '@/lib/work-hours';
|
||||
import { calcWorkHours, formatShortTime, isoToLocal, localToISO } from '@/lib/work-hours';
|
||||
import type { DevTaskStatus } from '@/lib/dev-task';
|
||||
|
||||
interface Props {
|
||||
@@ -28,16 +33,32 @@ interface Props {
|
||||
contextLabel?: string;
|
||||
}
|
||||
|
||||
function defaultPlanStartLocal(): string {
|
||||
const d = new Date();
|
||||
d.setHours(9, 0, 0, 0);
|
||||
return isoToLocal(d.toISOString());
|
||||
}
|
||||
|
||||
function defaultPlanEndLocal(): string {
|
||||
const d = new Date();
|
||||
d.setHours(18, 0, 0, 0);
|
||||
return isoToLocal(d.toISOString());
|
||||
}
|
||||
|
||||
export function DevTaskDetailDrawer({ taskId, allTaskIds, onClose, contextLabel }: Props) {
|
||||
const { tasks, changeStatus, setBlocked, deleteTask, updateTask } = useDevTaskStore();
|
||||
const addProgressNote = useWorkActivityStore((s) => s.addProgressNote);
|
||||
const { categories } = useTaskCategoryStore();
|
||||
const { requirements } = useRequirementStore();
|
||||
const { members } = useMemberStore();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const [showTransfer, setShowTransfer] = useState(false);
|
||||
const [transferTo, setTransferTo] = useState('');
|
||||
const [showDelayInput, setShowDelayInput] = useState(false);
|
||||
const [delayReason, setDelayReason] = useState('');
|
||||
const [showPlanInput, setShowPlanInput] = useState(false);
|
||||
const [planStartLocal, setPlanStartLocal] = useState('');
|
||||
const [planEndLocal, setPlanEndLocal] = useState('');
|
||||
const [progressNote, setProgressNote] = useState('');
|
||||
const [progressBlocker, setProgressBlocker] = useState('');
|
||||
const [progressHelperId, setProgressHelperId] = useState('');
|
||||
@@ -61,8 +82,42 @@ export function DevTaskDetailDrawer({ taskId, allTaskIds, onClose, contextLabel
|
||||
const actual = useMemo(() => getActualHours(task), [task]);
|
||||
const overrun = actual > estimate && estimate > 0;
|
||||
const requireDelay = task.status === 'todo' && needsDelayReason(task);
|
||||
const currentUserName = user?.name || '';
|
||||
const needsClaim = needsDevTaskClaim(task);
|
||||
const startReady = canStartDevTask(task);
|
||||
const visibleNextStatuses = nextStatuses.filter((status) => status !== 'in_progress' || startReady);
|
||||
const planStartISO = localToISO(planStartLocal);
|
||||
const planEndISO = localToISO(planEndLocal);
|
||||
const planStartBeforeEnd = Boolean(planStartISO && planEndISO && planStartISO < planEndISO);
|
||||
const planEstimateHours = planStartBeforeEnd ? calcWorkHours(planStartISO, planEndISO) : 0;
|
||||
|
||||
const openPlanInput = () => {
|
||||
setPlanStartLocal(task.expectedStartAt ? isoToLocal(task.expectedStartAt) : defaultPlanStartLocal());
|
||||
setPlanEndLocal(task.expectedEndAt ? isoToLocal(task.expectedEndAt) : defaultPlanEndLocal());
|
||||
setShowPlanInput(true);
|
||||
};
|
||||
|
||||
const handleSavePlan = () => {
|
||||
const assigneeId = task.assigneeId || currentUserName;
|
||||
if (!assigneeId) {
|
||||
alert('领取前需要先登录或选择负责人');
|
||||
return;
|
||||
}
|
||||
if (!planStartBeforeEnd || planEstimateHours <= 0 || !planStartISO || !planEndISO) return;
|
||||
updateTask(task.id, {
|
||||
assigneeId,
|
||||
expectedStartAt: planStartISO,
|
||||
expectedEndAt: planEndISO,
|
||||
estimateHours: planEstimateHours,
|
||||
});
|
||||
setShowPlanInput(false);
|
||||
};
|
||||
|
||||
const handleTransition = (to: DevTaskStatus) => {
|
||||
if (to === 'in_progress' && !startReady) {
|
||||
openPlanInput();
|
||||
return;
|
||||
}
|
||||
if (to === 'in_progress' && requireDelay && !showDelayInput) {
|
||||
setShowDelayInput(true);
|
||||
return;
|
||||
@@ -179,10 +234,10 @@ export function DevTaskDetailDrawer({ taskId, allTaskIds, onClose, contextLabel
|
||||
)}
|
||||
</div>
|
||||
|
||||
{nextStatuses.length > 0 && !showDelayInput && (
|
||||
{visibleNextStatuses.length > 0 && !showDelayInput && (
|
||||
<div className="flex items-center gap-2 pt-1 flex-wrap">
|
||||
<ChevronRight className="h-3.5 w-3.5 text-[var(--ink-muted)]" />
|
||||
{nextStatuses.map((s) => (
|
||||
{visibleNextStatuses.map((s) => (
|
||||
<button key={s} onClick={() => handleTransition(s)} className="h-8 px-4 rounded-lg text-[12px] font-medium bg-[var(--accent)] text-white hover:bg-[var(--accent-hover)] transition-colors">
|
||||
{DEV_TASK_STATUS_LABEL[s]}
|
||||
</button>
|
||||
@@ -190,6 +245,61 @@ export function DevTaskDetailDrawer({ taskId, allTaskIds, onClose, contextLabel
|
||||
</div>
|
||||
)}
|
||||
|
||||
{task.status === 'todo' && !startReady && !showPlanInput && (
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
<button
|
||||
onClick={openPlanInput}
|
||||
disabled={needsClaim && !currentUserName}
|
||||
className="h-8 px-4 rounded-lg text-[12px] font-medium bg-orange-500 text-white hover:bg-orange-600 disabled:opacity-50"
|
||||
>
|
||||
{needsClaim ? '领取并填写计划' : '填写计划'}
|
||||
</button>
|
||||
<span className="text-[11px] text-[var(--ink-muted)]">
|
||||
{needsClaim ? '领取时必须填写预计开始和预计截止' : '开始开发前需要补齐预计开始和预计截止'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showPlanInput && (
|
||||
<div className="rounded-lg border border-orange-200 bg-orange-50 p-3 space-y-3">
|
||||
<div className="text-[11px] font-medium text-orange-700">
|
||||
{needsClaim ? '领取并填写计划' : '填写计划'}
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div>
|
||||
<label className="mb-1 block text-[11px] text-orange-700">预计开始</label>
|
||||
<WorkDateTimePicker
|
||||
value={planStartLocal}
|
||||
onChange={setPlanStartLocal}
|
||||
placeholder="选择预计开始"
|
||||
defaultHour={9}
|
||||
className="bg-white"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-[11px] text-orange-700">预计截止</label>
|
||||
<WorkDateTimePicker
|
||||
value={planEndLocal}
|
||||
onChange={setPlanEndLocal}
|
||||
placeholder="选择预计截止"
|
||||
defaultHour={18}
|
||||
popoverAlign="right"
|
||||
className="bg-white"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-[11px] text-orange-700">
|
||||
执行预估:{planEstimateHours > 0 ? formatHours(planEstimateHours) : '请选择有效起止时间'}
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<button onClick={handleSavePlan} disabled={!planStartBeforeEnd || planEstimateHours <= 0} className="h-7 px-3 rounded text-[11px] font-medium bg-[var(--accent)] text-white disabled:opacity-50">保存</button>
|
||||
<button onClick={() => setShowPlanInput(false)} className="h-7 px-2 text-[11px] text-orange-700">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showDelayInput && (
|
||||
<div className="rounded-lg border border-orange-200 bg-orange-50 p-3 space-y-2">
|
||||
<div className="flex items-center gap-1.5 text-[11px] text-orange-700">
|
||||
@@ -332,7 +442,7 @@ export function DevTaskDetailDrawer({ taskId, allTaskIds, onClose, contextLabel
|
||||
<div className="flex items-center gap-2">
|
||||
<User className="h-3 w-3 text-[var(--ink-muted)]" />
|
||||
<span className="text-[var(--ink-muted)]">负责人</span>
|
||||
<span className="text-[var(--ink)] font-medium">{task.assigneeId}</span>
|
||||
<span className={`font-medium ${needsClaim ? 'text-orange-600' : 'text-[var(--ink)]'}`}>{needsClaim ? '待领取' : task.assigneeId}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-[var(--ink-muted)]">优先级</span>
|
||||
@@ -351,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>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { AlertTriangle } from 'lucide-react';
|
||||
import { StatusBadge } from './StatusBadge';
|
||||
import { CategoryChip } from './CategoryChip';
|
||||
import { getEstimateHours, getActualHours } from '@/lib/dev-task';
|
||||
import { getEstimateHours, getActualHours, needsDevTaskClaim } from '@/lib/dev-task';
|
||||
import { formatShortTime, formatWorkHours } from '@/lib/work-hours';
|
||||
import type { DevTask } from '@/lib/dev-task';
|
||||
import type { TaskCategory } from '@/lib/task-category';
|
||||
@@ -11,6 +11,7 @@ import type { TaskCategory } from '@/lib/task-category';
|
||||
interface Props {
|
||||
task: DevTask;
|
||||
category?: TaskCategory;
|
||||
categoryLabelWidthEm?: number;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
@@ -45,37 +46,64 @@ function hoursText(task: DevTask, estimate: number, actual: number): { text: str
|
||||
return { text: `${formatWorkHours(actual)} / ${formatWorkHours(estimate)}`, tone };
|
||||
}
|
||||
|
||||
export function DevTaskRow({ task, category, onClick }: Props) {
|
||||
export function DevTaskRow({ task, category, categoryLabelWidthEm, onClick }: Props) {
|
||||
const estimate = getEstimateHours(task);
|
||||
const actual = getActualHours(task);
|
||||
const range = timeRangeText(task);
|
||||
const hours = hoursText(task, estimate, actual);
|
||||
const needsClaim = needsDevTaskClaim(task);
|
||||
const labelWidthStyle = categoryLabelWidthEm ? { width: `${categoryLabelWidthEm}em` } : undefined;
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={onClick}
|
||||
className={`flex items-center gap-3 px-4 py-2.5 border-b border-[var(--line)] hover:bg-[var(--bg-subtle)] cursor-pointer transition-colors last:border-b-0 ${task.aiDraft ? 'border-l-2 border-l-purple-400 bg-purple-50/30' : ''}`}
|
||||
className={`px-4 py-2 border-b border-[var(--line)] hover:bg-[var(--bg-subtle)] cursor-pointer transition-colors last:border-b-0 ${task.aiDraft ? 'border-l-2 border-l-purple-400 bg-purple-50/30' : ''}`}
|
||||
>
|
||||
<span className={`h-2 w-2 rounded-full shrink-0 ${PRIORITY_DOT[task.priority] || 'bg-zinc-300'}`} title={task.priority} />
|
||||
<span className="text-[11px] font-mono text-[var(--ink-muted)] w-16 shrink-0">{task.taskNo}</span>
|
||||
<div className="flex-1 min-w-0 flex items-center gap-1.5">
|
||||
<span className="text-[13px] text-[var(--ink)] truncate">{task.title}</span>
|
||||
{task.aiDraft && (
|
||||
<span className="flex items-center gap-0.5 text-[10px] text-purple-600 bg-purple-100 px-1.5 py-0.5 rounded shrink-0" title="AI 拆解草案,编辑后会移除标记">
|
||||
AI 草案
|
||||
</span>
|
||||
<div className="flex min-w-0 items-start gap-2">
|
||||
<span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${PRIORITY_DOT[task.priority] || 'bg-zinc-300'}`} title={task.priority} />
|
||||
<span className="mt-0.5 w-16 shrink-0 text-[11px] font-mono text-[var(--ink-muted)]">{task.taskNo}</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex min-w-0 items-center gap-1.5">
|
||||
<span className="truncate text-[13px] font-medium leading-5 text-[var(--ink)]">{task.title}</span>
|
||||
<span className="ml-auto inline-flex min-w-0 shrink-0 flex-wrap items-center justify-end gap-x-2.5 gap-y-1 text-[11px]">
|
||||
{range.text && (
|
||||
<span className={`tabular-nums whitespace-nowrap ${range.tone}`} title={range.text}>{range.text}</span>
|
||||
)}
|
||||
<span className={`tabular-nums whitespace-nowrap ${hours.tone}`}>{hours.text}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1 flex min-w-0 flex-wrap items-center justify-end gap-x-2.5 gap-y-1 text-[11px]">
|
||||
{task.isBlocked && (
|
||||
<span className="flex items-center gap-0.5 text-[10px] text-red-500 bg-red-50 px-1.5 py-0.5 rounded shrink-0" title={task.blockReason}>
|
||||
<span className="inline-flex h-5 shrink-0 items-center gap-0.5 whitespace-nowrap rounded bg-red-50 px-1.5 text-[10px] font-medium text-red-500" title={task.blockReason}>
|
||||
<AlertTriangle className="h-2.5 w-2.5" />阻塞
|
||||
</span>
|
||||
)}
|
||||
{task.aiDraft && (
|
||||
<span
|
||||
className="inline-flex h-5 shrink-0 items-center justify-center whitespace-nowrap rounded bg-purple-100 px-1.5 text-[10px] font-medium text-purple-600"
|
||||
style={labelWidthStyle}
|
||||
title="AI 拆解草案,编辑后会移除标记"
|
||||
>
|
||||
AI 草案
|
||||
</span>
|
||||
)}
|
||||
{!needsClaim && (
|
||||
<span className="max-w-[140px] truncate whitespace-nowrap text-[var(--ink-soft)]">负责人:{task.assigneeId}</span>
|
||||
)}
|
||||
{needsClaim ? (
|
||||
<span
|
||||
className="inline-flex h-5 shrink-0 items-center justify-center whitespace-nowrap rounded bg-orange-50 px-1.5 text-[10px] font-medium text-orange-600"
|
||||
style={labelWidthStyle}
|
||||
>
|
||||
待领取
|
||||
</span>
|
||||
) : (
|
||||
<StatusBadge status={task.status} widthEm={categoryLabelWidthEm} />
|
||||
)}
|
||||
<CategoryChip category={category} widthEm={categoryLabelWidthEm} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<CategoryChip category={category} />
|
||||
<StatusBadge status={task.status} />
|
||||
<span className={`text-[11px] tabular-nums shrink-0 ${range.tone}`} title={range.text}>{range.text}</span>
|
||||
<span className={`text-[11px] tabular-nums w-40 text-right shrink-0 whitespace-nowrap ${hours.tone}`}>{hours.text}</span>
|
||||
<span className="text-[11px] text-[var(--ink-soft)] w-14 text-right truncate shrink-0">{task.assigneeId}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -111,6 +111,10 @@ export function DevTaskTab({ versionId, requirementIds, versionDeadline }: Props
|
||||
}, [paged]);
|
||||
|
||||
const categoryMap = useMemo(() => new Map(categories.map((c) => [c.id, c])), [categories]);
|
||||
const categoryLabelWidthEm = useMemo(
|
||||
() => Math.max(4, ...categories.map((category) => category.name.length)) + 1,
|
||||
[categories],
|
||||
);
|
||||
const requirementMap = useMemo(() => new Map(requirements.map((r) => [r.id, r])), [requirements]);
|
||||
const allTaskIds = useMemo(() => versionTasks.map((t) => t.id), [versionTasks]);
|
||||
|
||||
@@ -179,11 +183,16 @@ export function DevTaskTab({ versionId, requirementIds, versionDeadline }: Props
|
||||
const reqProgress = calcGroupProgress(reqTasks);
|
||||
return (
|
||||
<div key={reqId} className="rounded-lg border border-[var(--line)] bg-[var(--bg-card)] overflow-hidden">
|
||||
<div className="flex items-center gap-2 px-4 py-2 bg-[var(--bg-subtle)] border-b border-[var(--line)]">
|
||||
<div className="flex items-center bg-[var(--bg-subtle)] border-b border-[var(--line)]">
|
||||
<div className="pl-4 flex items-center">
|
||||
<input type="checkbox" checked={reqTasks.every((t) => selectedIds.has(t.id))} onChange={() => { const ids = reqTasks.map((t) => t.id); const allSelected = ids.every((id) => selectedIds.has(id)); const next = new Set(selectedIds); if (allSelected) ids.forEach((id) => next.delete(id)); else ids.forEach((id) => next.add(id)); setSelectedIds(next); }} className="h-3.5 w-3.5 rounded border-[var(--line)]" />
|
||||
<span className="text-[11px] font-mono text-[var(--ink-muted)]">{req?.code}</span>
|
||||
<span className="text-[12px] font-medium text-[var(--ink)] flex-1 truncate">{req?.title}</span>
|
||||
<span className="text-[11px] text-[var(--ink-muted)]">{reqProgress}%</span>
|
||||
</div>
|
||||
<div className="flex flex-1 min-w-0 items-center gap-2 px-4 py-2">
|
||||
<span className="h-2 w-2 shrink-0" />
|
||||
<span className="w-16 shrink-0 truncate text-[11px] font-mono text-[var(--ink-muted)]" title={req?.code}>{req?.code}</span>
|
||||
<span className="min-w-0 flex-1 truncate text-[12px] font-medium text-[var(--ink)]">{req?.title}</span>
|
||||
<span className="shrink-0 text-[11px] text-[var(--ink-muted)]">{reqProgress}%</span>
|
||||
</div>
|
||||
</div>
|
||||
{reqTasks.map((t) => (
|
||||
<div key={t.id} className="flex items-center">
|
||||
@@ -191,7 +200,7 @@ export function DevTaskTab({ versionId, requirementIds, versionDeadline }: Props
|
||||
<input type="checkbox" checked={selectedIds.has(t.id)} onChange={() => toggleSelect(t.id)} className="h-3.5 w-3.5 rounded border-[var(--line)]" onClick={(e) => e.stopPropagation()} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<DevTaskRow task={t} category={categoryMap.get(t.categoryId)} onClick={() => setSelectedTaskId(t.id)} />
|
||||
<DevTaskRow task={t} category={categoryMap.get(t.categoryId)} categoryLabelWidthEm={categoryLabelWidthEm} onClick={() => setSelectedTaskId(t.id)} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
@@ -3,9 +3,12 @@
|
||||
import { DEV_TASK_STATUS_LABEL, DEV_TASK_STATUS_COLOR } from '@/lib/dev-task';
|
||||
import type { DevTaskStatus } from '@/lib/dev-task';
|
||||
|
||||
export function StatusBadge({ status }: { status: DevTaskStatus }) {
|
||||
export function StatusBadge({ status, widthEm }: { status: DevTaskStatus; widthEm?: number }) {
|
||||
return (
|
||||
<span className={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium ${DEV_TASK_STATUS_COLOR[status]}`}>
|
||||
<span
|
||||
className={`inline-flex h-5 shrink-0 items-center justify-center whitespace-nowrap rounded px-1.5 text-[10px] font-medium ${DEV_TASK_STATUS_COLOR[status]}`}
|
||||
style={widthEm ? { width: `${widthEm}em` } : undefined}
|
||||
>
|
||||
{DEV_TASK_STATUS_LABEL[status]}
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -26,6 +26,12 @@ function defaultPlannedTestLocal(): string {
|
||||
return isoToLocal(d.toISOString());
|
||||
}
|
||||
|
||||
function defaultPlannedEndLocal(): string {
|
||||
const d = new Date();
|
||||
d.setHours(10, 0, 0, 0);
|
||||
return isoToLocal(d.toISOString());
|
||||
}
|
||||
|
||||
export function TestCaseCreateModal({ versionId, requirementIds, roundNo, onClose }: Props) {
|
||||
const { createTestCase } = useTestCaseStore();
|
||||
const { requirements } = useRequirementStore();
|
||||
@@ -49,6 +55,7 @@ export function TestCaseCreateModal({ versionId, requirementIds, roundNo, onClos
|
||||
);
|
||||
const [estimateHours, setEstimateHours] = useState(0.5);
|
||||
const [plannedTestLocal, setPlannedTestLocal] = useState(defaultPlannedTestLocal);
|
||||
const [plannedEndLocal, setPlannedEndLocal] = useState(defaultPlannedEndLocal);
|
||||
const [assigneeId, setAssigneeId] = useState(user?.name || '');
|
||||
const [description, setDescription] = useState('');
|
||||
const [prototypeNotes, setPrototypeNotes] = useState('');
|
||||
@@ -69,7 +76,9 @@ export function TestCaseCreateModal({ versionId, requirementIds, roundNo, onClos
|
||||
|
||||
const normalizedEstimateHours = clampTestCaseEstimateHours(selectedCategory?.code, estimateHours);
|
||||
const plannedTestAt = localToISO(plannedTestLocal);
|
||||
const canSubmit = title.trim() && categoryId && normalizedEstimateHours > 0 && Boolean(plannedTestAt);
|
||||
const plannedEndAt = localToISO(plannedEndLocal);
|
||||
const hasValidPlan = Boolean(plannedTestAt && plannedEndAt && plannedEndAt > plannedTestAt);
|
||||
const canSubmit = title.trim() && categoryId && normalizedEstimateHours > 0 && hasValidPlan;
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (!canSubmit) return;
|
||||
@@ -92,6 +101,7 @@ export function TestCaseCreateModal({ versionId, requirementIds, roundNo, onClos
|
||||
priority,
|
||||
estimateHours: normalizedEstimateHours,
|
||||
plannedTestAt,
|
||||
plannedEndAt,
|
||||
assigneeId: assigneeId || undefined,
|
||||
references: references.length > 0 ? references : undefined,
|
||||
createdBy: user?.name || '系统',
|
||||
@@ -154,15 +164,32 @@ export function TestCaseCreateModal({ versionId, requirementIds, roundNo, onClos
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="block text-[12px] text-[var(--ink-soft)] mb-1">计划测试时间 *</label>
|
||||
<label className="block text-[12px] text-[var(--ink-soft)] mb-1">计划开始 *</label>
|
||||
<WorkDateTimePicker
|
||||
value={plannedTestLocal}
|
||||
onChange={setPlannedTestLocal}
|
||||
placeholder="选择计划测试时间"
|
||||
placeholder="选择计划开始时间"
|
||||
defaultHour={9}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-[12px] text-[var(--ink-soft)] mb-1">计划结束 *</label>
|
||||
<WorkDateTimePicker
|
||||
value={plannedEndLocal}
|
||||
onChange={setPlannedEndLocal}
|
||||
placeholder="选择计划结束时间"
|
||||
defaultHour={10}
|
||||
popoverAlign="right"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{!hasValidPlan && plannedTestLocal && plannedEndLocal && (
|
||||
<div className="rounded-lg border border-amber-200 bg-amber-50 p-2 text-[11px] text-amber-700">
|
||||
计划开始必须早于计划结束
|
||||
</div>
|
||||
)}
|
||||
<div>
|
||||
<label className="block text-[12px] text-[var(--ink-soft)] mb-1">测试步骤 & 预期结果</label>
|
||||
<textarea rows={4} value={description} onChange={(e) => setDescription(e.target.value)} className="w-full rounded-lg border border-[var(--line)] bg-[var(--bg)] px-3 py-2 text-[13px] focus:border-[var(--accent)] focus:outline-none resize-none" placeholder="1. 操作步骤... 2. 预期结果..." />
|
||||
|
||||
@@ -4,14 +4,17 @@ 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';
|
||||
import { useMemberStore } from '@/stores/useMemberStore';
|
||||
import { useTaskCategoryStore } from '@/stores/useTaskCategoryStore';
|
||||
import { useAuthStore } from '@/stores/useAuthStore';
|
||||
import { WorkDateTimePicker } from '@/components/WorkDateTimePicker';
|
||||
import { CategoryChip } from '@/components/dev-task/CategoryChip';
|
||||
import { TC_ALLOWED_TRANSITIONS, TEST_CASE_STATUS_LABEL, getTestCaseActualHours } from '@/lib/test-case';
|
||||
import { formatWorkHours } from '@/lib/work-hours';
|
||||
import { TC_ALLOWED_TRANSITIONS, TEST_CASE_STATUS_LABEL, canStartTestCase, getTestCaseActualHours, needsTestCaseClaim } from '@/lib/test-case';
|
||||
import { calcWorkHours, formatWorkHours, isoToLocal, localToISO } from '@/lib/work-hours';
|
||||
import { formatDateTime } from '@/lib/format';
|
||||
import { BUG_SEVERITY_LABEL, BUG_SEVERITY_COLOR } from '@/lib/bug';
|
||||
import type { TestCaseStatus } from '@/lib/test-case';
|
||||
@@ -23,14 +26,30 @@ interface Props {
|
||||
contextLabel?: string;
|
||||
}
|
||||
|
||||
function defaultPlanStartLocal(): string {
|
||||
const d = new Date();
|
||||
d.setHours(9, 0, 0, 0);
|
||||
return isoToLocal(d.toISOString());
|
||||
}
|
||||
|
||||
function defaultPlanEndLocal(): string {
|
||||
const d = new Date();
|
||||
d.setHours(10, 0, 0, 0);
|
||||
return isoToLocal(d.toISOString());
|
||||
}
|
||||
|
||||
export function TestCaseDetailDrawer({ testCaseId, onClose, onCreateBug, contextLabel }: Props) {
|
||||
const { testCases, changeStatus, deleteTestCase, updateTestCase } = useTestCaseStore();
|
||||
const { bugs } = useBugStore();
|
||||
const { requirements } = useRequirementStore();
|
||||
const { members } = useMemberStore();
|
||||
const { categories } = useTaskCategoryStore();
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const [showTransfer, setShowTransfer] = useState(false);
|
||||
const [transferTo, setTransferTo] = useState('');
|
||||
const [showPlanInput, setShowPlanInput] = useState(false);
|
||||
const [planStartLocal, setPlanStartLocal] = useState('');
|
||||
const [planEndLocal, setPlanEndLocal] = useState('');
|
||||
|
||||
const tc = testCases.find((c) => c.id === testCaseId);
|
||||
if (!tc) return null;
|
||||
@@ -42,6 +61,39 @@ export function TestCaseDetailDrawer({ testCaseId, onClose, onCreateBug, context
|
||||
const executorEstimateHours = typeof tc.estimateHours === 'number' && tc.estimateHours > 0 ? tc.estimateHours : undefined;
|
||||
const aiEstimateHours = typeof tc.aiEstimateHours === 'number' && tc.aiEstimateHours > 0 ? tc.aiEstimateHours : undefined;
|
||||
const actualHours = getTestCaseActualHours(tc);
|
||||
const planDisplay = tc.plannedTestAt && tc.plannedEndAt
|
||||
? `${formatDateTime(tc.plannedTestAt)} → ${formatDateTime(tc.plannedEndAt)}`
|
||||
: tc.plannedTestAt ? formatDateTime(tc.plannedTestAt) : '-';
|
||||
const currentUserName = user?.name || '';
|
||||
const needsClaim = needsTestCaseClaim(tc);
|
||||
const startReady = canStartTestCase(tc);
|
||||
const visibleNextStatuses = nextStatuses.filter((status) => status !== 'running' || startReady);
|
||||
const planStartISO = localToISO(planStartLocal);
|
||||
const planEndISO = localToISO(planEndLocal);
|
||||
const planStartBeforeEnd = Boolean(planStartISO && planEndISO && planEndISO > planStartISO);
|
||||
const planEstimateHours = planStartBeforeEnd ? calcWorkHours(planStartISO, planEndISO) : 0;
|
||||
|
||||
const openPlanInput = () => {
|
||||
setPlanStartLocal(tc.plannedTestAt ? isoToLocal(tc.plannedTestAt) : defaultPlanStartLocal());
|
||||
setPlanEndLocal(tc.plannedEndAt ? isoToLocal(tc.plannedEndAt) : defaultPlanEndLocal());
|
||||
setShowPlanInput(true);
|
||||
};
|
||||
|
||||
const handleSavePlan = () => {
|
||||
const assigneeId = tc.assigneeId || currentUserName;
|
||||
if (!assigneeId) {
|
||||
alert('领取前需要先登录或选择负责人');
|
||||
return;
|
||||
}
|
||||
if (!planStartBeforeEnd || planEstimateHours <= 0 || !planStartISO || !planEndISO) return;
|
||||
updateTestCase(tc.id, {
|
||||
assigneeId,
|
||||
plannedTestAt: planStartISO,
|
||||
plannedEndAt: planEndISO,
|
||||
estimateHours: planEstimateHours,
|
||||
});
|
||||
setShowPlanInput(false);
|
||||
};
|
||||
|
||||
const [failReason, setFailReason] = useState('');
|
||||
const [blockReason, setBlockReason] = useState('');
|
||||
@@ -49,6 +101,10 @@ export function TestCaseDetailDrawer({ testCaseId, onClose, onCreateBug, context
|
||||
const [showBlockInput, setShowBlockInput] = useState(false);
|
||||
|
||||
const handleTransition = (to: TestCaseStatus) => {
|
||||
if (to === 'running' && !startReady) {
|
||||
openPlanInput();
|
||||
return;
|
||||
}
|
||||
if (to === 'failed') { setShowFailInput(true); return; }
|
||||
if (to === 'blocked') { setShowBlockInput(true); return; }
|
||||
changeStatus(tc.id, to);
|
||||
@@ -122,10 +178,10 @@ export function TestCaseDetailDrawer({ testCaseId, onClose, onCreateBug, context
|
||||
{tc.executedAt && <span className="text-[11px] text-[var(--ink-muted)]">执行于 {tc.executedAt}</span>}
|
||||
</div>
|
||||
|
||||
{nextStatuses.length > 0 && !showFailInput && !showBlockInput && (
|
||||
{visibleNextStatuses.length > 0 && !showFailInput && !showBlockInput && (
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
<ChevronRight className="h-3.5 w-3.5 text-[var(--ink-muted)]" />
|
||||
{nextStatuses.map((s) => (
|
||||
{visibleNextStatuses.map((s) => (
|
||||
<button key={s} onClick={() => handleTransition(s)} className={`h-8 px-4 rounded-lg text-[12px] font-medium transition-colors ${s === 'passed' ? 'bg-emerald-500 text-white hover:bg-emerald-600' : s === 'failed' ? 'bg-red-500 text-white hover:bg-red-600' : 'bg-[var(--accent)] text-white hover:bg-[var(--accent-hover)]'}`}>
|
||||
{TEST_CASE_STATUS_LABEL[s]}
|
||||
</button>
|
||||
@@ -133,6 +189,61 @@ export function TestCaseDetailDrawer({ testCaseId, onClose, onCreateBug, context
|
||||
</div>
|
||||
)}
|
||||
|
||||
{tc.status === 'pending' && !startReady && !showPlanInput && (
|
||||
<div className="flex items-center gap-2 pt-1">
|
||||
<button
|
||||
onClick={openPlanInput}
|
||||
disabled={needsClaim && !currentUserName}
|
||||
className="h-8 px-4 rounded-lg text-[12px] font-medium bg-orange-500 text-white hover:bg-orange-600 disabled:opacity-50"
|
||||
>
|
||||
{needsClaim ? '领取并填写计划' : '填写计划'}
|
||||
</button>
|
||||
<span className="text-[11px] text-[var(--ink-muted)]">
|
||||
{needsClaim ? '领取时必须填写计划开始和计划结束' : '开始测试前需要补齐计划开始和计划结束'}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showPlanInput && (
|
||||
<div className="rounded-lg border border-orange-200 bg-orange-50 p-3 space-y-3">
|
||||
<div className="text-[11px] font-medium text-orange-700">
|
||||
{needsClaim ? '领取并填写计划' : '填写计划'}
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div>
|
||||
<label className="mb-1 block text-[11px] text-orange-700">计划开始</label>
|
||||
<WorkDateTimePicker
|
||||
value={planStartLocal}
|
||||
onChange={setPlanStartLocal}
|
||||
placeholder="选择计划开始"
|
||||
defaultHour={9}
|
||||
className="bg-white"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="mb-1 block text-[11px] text-orange-700">计划结束</label>
|
||||
<WorkDateTimePicker
|
||||
value={planEndLocal}
|
||||
onChange={setPlanEndLocal}
|
||||
placeholder="选择计划结束"
|
||||
defaultHour={10}
|
||||
popoverAlign="right"
|
||||
className="bg-white"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="text-[11px] text-orange-700">
|
||||
执行预估:{planEstimateHours > 0 ? formatWorkHours(planEstimateHours) : '请选择有效起止时间'}
|
||||
</span>
|
||||
<div className="flex gap-2">
|
||||
<button onClick={handleSavePlan} disabled={!planStartBeforeEnd || planEstimateHours <= 0} className="h-7 px-3 rounded text-[11px] font-medium bg-[var(--accent)] text-white disabled:opacity-50">保存</button>
|
||||
<button onClick={() => setShowPlanInput(false)} className="h-7 px-2 text-[11px] text-orange-700">取消</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showFailInput && (
|
||||
<div className="flex gap-2 pt-1">
|
||||
<input value={failReason} onChange={(e) => setFailReason(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter') confirmFail(); }} placeholder="不通过原因(可选)" className="flex-1 h-8 rounded-lg border border-[var(--line)] px-3 text-[12px] focus:border-red-400 focus:outline-none" autoFocus />
|
||||
@@ -157,10 +268,10 @@ export function TestCaseDetailDrawer({ testCaseId, onClose, onCreateBug, context
|
||||
<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="grid grid-cols-2 gap-y-3 gap-x-4 text-[12px]">
|
||||
<div><span className="text-[var(--ink-muted)]">计划测试:</span><span className="text-[var(--ink)] font-medium">{tc.plannedTestAt ? formatDateTime(tc.plannedTestAt) : '待排期'}</span></div>
|
||||
<div><span className="text-[var(--ink-muted)]">计划测试:</span><span className="text-[var(--ink)] font-medium">{planDisplay}</span></div>
|
||||
<div><span className="text-[var(--ink-muted)]">优先级:</span><span className="text-[var(--ink)] font-medium">{tc.priority}</span></div>
|
||||
<div className="flex items-center gap-1.5"><span className="text-[var(--ink-muted)]">任务类型:</span><CategoryChip category={category} /></div>
|
||||
<div><span className="text-[var(--ink-muted)]">负责人:</span><span className="text-[var(--ink)] font-medium">{tc.assigneeId || '-'}</span></div>
|
||||
<div><span className="text-[var(--ink-muted)]">负责人:</span><span className={`font-medium ${needsClaim ? 'text-orange-600' : 'text-[var(--ink)]'}`}>{needsClaim ? '待领取' : tc.assigneeId}</span></div>
|
||||
<div><span className="text-[var(--ink-muted)]">AI 预估:</span><span className="text-[var(--ink)] font-medium">{aiEstimateHours ? formatWorkHours(aiEstimateHours) : '—'}</span></div>
|
||||
<div><span className="text-[var(--ink-muted)]">执行预估:</span><span className="text-[var(--ink)] font-medium">{executorEstimateHours ? formatWorkHours(executorEstimateHours) : '待负责人填写'}</span></div>
|
||||
<div><span className="text-[var(--ink-muted)]">创建人:</span><span className="text-[var(--ink)]">{tc.createdBy}</span></div>
|
||||
@@ -204,6 +315,8 @@ export function TestCaseDetailDrawer({ testCaseId, onClose, onCreateBug, context
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<ActivityLogPanel sourceType="test_case" sourceId={tc.id} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { memo } from 'react';
|
||||
import { TestCaseStatusBadge } from './TestCaseStatusBadge';
|
||||
import { getTestCaseActualHours, getTestCaseEstimateHours } from '@/lib/test-case';
|
||||
import { getTestCaseActualHours, getTestCaseEstimateHours, needsTestCaseClaim } from '@/lib/test-case';
|
||||
import { formatWorkHours } from '@/lib/work-hours';
|
||||
import { formatDateTimeShort } from '@/lib/format';
|
||||
import type { TestCase } from '@/lib/test-case';
|
||||
@@ -11,6 +11,7 @@ import type { TaskCategory } from '@/lib/task-category';
|
||||
interface Props {
|
||||
testCase: TestCase;
|
||||
category?: TaskCategory;
|
||||
categoryLabelWidthEm?: number;
|
||||
bugCount: number;
|
||||
onClick?: () => void;
|
||||
}
|
||||
@@ -22,19 +23,64 @@ const PRIORITY_DOT: Record<string, string> = {
|
||||
P3: 'bg-zinc-300',
|
||||
};
|
||||
|
||||
function TestCaseRowImpl({ testCase, category, bugCount, onClick }: Props) {
|
||||
function TestCaseRowImpl({ testCase, category, categoryLabelWidthEm, bugCount, onClick }: Props) {
|
||||
const estimateHours = getTestCaseEstimateHours(testCase);
|
||||
const actualHours = getTestCaseActualHours(testCase);
|
||||
const needsClaim = needsTestCaseClaim(testCase);
|
||||
const labelWidthStyle = categoryLabelWidthEm ? { width: `${categoryLabelWidthEm}em` } : undefined;
|
||||
const hasExecutorEstimate = typeof testCase.estimateHours === 'number' && testCase.estimateHours > 0;
|
||||
const hasAiEstimate = typeof testCase.aiEstimateHours === 'number' && testCase.aiEstimateHours > 0;
|
||||
const estimatePrefix = hasExecutorEstimate ? '执行预' : hasAiEstimate ? 'AI预' : '预';
|
||||
const planText = testCase.plannedTestAt && testCase.plannedEndAt
|
||||
? `${formatDateTimeShort(testCase.plannedTestAt)} → ${formatDateTimeShort(testCase.plannedEndAt)}`
|
||||
: testCase.plannedTestAt ? formatDateTimeShort(testCase.plannedTestAt) : '';
|
||||
return (
|
||||
<div onClick={onClick} className={`flex items-center gap-3 px-4 py-2.5 border-b border-[var(--line)] hover:bg-[var(--bg-subtle)] cursor-pointer transition-colors last:border-b-0 ${testCase.aiDraft ? 'border-l-2 border-l-purple-400 bg-purple-50/30' : ''}`}>
|
||||
<span className={`h-2 w-2 rounded-full shrink-0 ${PRIORITY_DOT[testCase.priority] || 'bg-zinc-300'}`} />
|
||||
<span className="text-[11px] font-mono text-[var(--ink-muted)] w-14 shrink-0">{testCase.caseNo}</span>
|
||||
<div onClick={onClick} className={`px-4 py-2 border-b border-[var(--line)] hover:bg-[var(--bg-subtle)] cursor-pointer transition-colors last:border-b-0 ${testCase.aiDraft ? 'border-l-2 border-l-purple-400 bg-purple-50/30' : ''}`}>
|
||||
<div className="flex min-w-0 items-start gap-2">
|
||||
<span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${PRIORITY_DOT[testCase.priority] || 'bg-zinc-300'}`} />
|
||||
<span className="mt-0.5 w-14 shrink-0 text-[11px] font-mono text-[var(--ink-muted)]">{testCase.caseNo}</span>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex min-w-0 items-center gap-1.5">
|
||||
<span className="truncate text-[13px] font-medium leading-5 text-[var(--ink)]">{testCase.title}</span>
|
||||
<span className="ml-auto inline-flex min-w-0 shrink-0 flex-wrap items-center justify-end gap-x-2.5 gap-y-1 text-[11px]">
|
||||
{planText && (
|
||||
<span className="tabular-nums whitespace-nowrap text-[var(--ink-muted)]" title="计划测试时间">{planText}</span>
|
||||
)}
|
||||
<span className="tabular-nums whitespace-nowrap text-[var(--ink-muted)]">
|
||||
{actualHours > 0 ? `${formatWorkHours(actualHours)} / ${formatWorkHours(estimateHours)}` : `${estimatePrefix} ${formatWorkHours(estimateHours)}`}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="mt-1 flex min-w-0 flex-wrap items-center justify-end gap-x-2.5 gap-y-1 text-[11px]">
|
||||
{bugCount > 0 && (
|
||||
<span className="inline-flex h-5 shrink-0 items-center whitespace-nowrap rounded bg-red-50 px-1.5 text-[10px] font-medium text-red-500">{bugCount} Bug</span>
|
||||
)}
|
||||
{testCase.aiDraft && (
|
||||
<span
|
||||
className="inline-flex h-5 w-24 shrink-0 items-center justify-center rounded px-1.5 text-[10px] font-medium whitespace-nowrap"
|
||||
className="inline-flex h-5 shrink-0 items-center justify-center whitespace-nowrap rounded bg-purple-100 px-1.5 text-[10px] font-medium text-purple-600"
|
||||
style={labelWidthStyle}
|
||||
title="AI 拆解草案,编辑后会移除标记"
|
||||
>
|
||||
AI 草案
|
||||
</span>
|
||||
)}
|
||||
{!needsClaim && (
|
||||
<span className="max-w-[140px] truncate whitespace-nowrap text-[var(--ink-soft)]">负责人:{testCase.assigneeId}</span>
|
||||
)}
|
||||
{needsClaim ? (
|
||||
<span
|
||||
className="inline-flex h-5 shrink-0 items-center justify-center whitespace-nowrap rounded bg-orange-50 px-1.5 text-[10px] font-medium text-orange-600"
|
||||
style={labelWidthStyle}
|
||||
>
|
||||
待领取
|
||||
</span>
|
||||
) : (
|
||||
<TestCaseStatusBadge status={testCase.status} widthEm={categoryLabelWidthEm} />
|
||||
)}
|
||||
<span
|
||||
className="inline-flex h-5 shrink-0 items-center justify-center rounded px-1.5 text-[10px] font-medium whitespace-nowrap"
|
||||
style={{
|
||||
...(categoryLabelWidthEm ? { width: `${categoryLabelWidthEm}em` } : {}),
|
||||
backgroundColor: category?.color ? `${category.color}15` : 'var(--bg-subtle)',
|
||||
color: category?.color || 'var(--ink-soft)',
|
||||
}}
|
||||
@@ -42,25 +88,9 @@ function TestCaseRowImpl({ testCase, category, bugCount, onClick }: Props) {
|
||||
>
|
||||
{category?.name || '未分类'}
|
||||
</span>
|
||||
<div className="flex-1 min-w-0 flex items-center gap-1.5">
|
||||
<span className="text-[13px] text-[var(--ink)] truncate">{testCase.title}</span>
|
||||
{testCase.aiDraft && (
|
||||
<span className="text-[10px] text-purple-600 bg-purple-100 px-1.5 py-0.5 rounded shrink-0" title="AI 拆解草案,编辑后会移除标记">
|
||||
AI 草案
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{bugCount > 0 && (
|
||||
<span className="text-[10px] text-red-500 bg-red-50 px-1.5 py-0.5 rounded shrink-0">{bugCount} Bug</span>
|
||||
)}
|
||||
<TestCaseStatusBadge status={testCase.status} />
|
||||
<span className="text-[11px] text-[var(--ink-muted)] tabular-nums w-24 text-right shrink-0 whitespace-nowrap" title="计划测试时间">
|
||||
{testCase.plannedTestAt ? formatDateTimeShort(testCase.plannedTestAt) : '待排期'}
|
||||
</span>
|
||||
<span className="text-[11px] text-[var(--ink-muted)] tabular-nums w-32 text-right shrink-0 whitespace-nowrap">
|
||||
{actualHours > 0 ? `${formatWorkHours(actualHours)} / ${formatWorkHours(estimateHours)}` : `${estimatePrefix} ${formatWorkHours(estimateHours)}`}
|
||||
</span>
|
||||
<span className="text-[11px] text-[var(--ink-soft)] w-14 text-right truncate shrink-0">{testCase.assigneeId || '-'}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,9 +3,12 @@
|
||||
import { TEST_CASE_STATUS_LABEL, TEST_CASE_STATUS_COLOR } from '@/lib/test-case';
|
||||
import type { TestCaseStatus } from '@/lib/test-case';
|
||||
|
||||
export function TestCaseStatusBadge({ status }: { status: TestCaseStatus }) {
|
||||
export function TestCaseStatusBadge({ status, widthEm }: { status: TestCaseStatus; widthEm?: number }) {
|
||||
return (
|
||||
<span className={`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium ${TEST_CASE_STATUS_COLOR[status]}`}>
|
||||
<span
|
||||
className={`inline-flex h-5 shrink-0 items-center justify-center whitespace-nowrap rounded px-1.5 text-[10px] font-medium ${TEST_CASE_STATUS_COLOR[status]}`}
|
||||
style={widthEm ? { width: `${widthEm}em` } : undefined}
|
||||
>
|
||||
{TEST_CASE_STATUS_LABEL[status]}
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -152,6 +152,10 @@ export function TestCaseTab({ versionId, requirementIds }: Props) {
|
||||
|
||||
const requirementMap = useMemo(() => new Map(requirements.map((r) => [r.id, r])), [requirements]);
|
||||
const categoryMap = useMemo(() => new Map(categories.map((c) => [c.id, c])), [categories]);
|
||||
const categoryLabelWidthEm = useMemo(
|
||||
() => Math.max(4, ...categories.map((category) => category.name.length)) + 1,
|
||||
[categories],
|
||||
);
|
||||
const bugCountByCase = useMemo(() => {
|
||||
const map = new Map<string, number>();
|
||||
for (const b of versionBugs) map.set(b.testCaseId, (map.get(b.testCaseId) ?? 0) + 1);
|
||||
@@ -230,21 +234,19 @@ export function TestCaseTab({ versionId, requirementIds }: Props) {
|
||||
<div className="pl-4 flex items-center">
|
||||
<input type="checkbox" checked={cases.every((c) => selectedIds.has(c.id))} onChange={() => { const ids = cases.map((c) => c.id); const allSel = ids.every((id) => selectedIds.has(id)); const next = new Set(selectedIds); if (allSel) ids.forEach((id) => next.delete(id)); else ids.forEach((id) => next.add(id)); setSelectedIds(next); }} className="h-3.5 w-3.5 rounded border-[var(--line)]" />
|
||||
</div>
|
||||
<div className="flex flex-1 min-w-0 items-center gap-3 px-4 py-2">
|
||||
<div className="flex flex-1 min-w-0 items-center gap-2 px-4 py-2">
|
||||
<span className="h-2 w-2 shrink-0" />
|
||||
<span className="w-14 min-w-0 shrink-0 truncate text-[11px] font-mono text-[var(--ink-muted)]" title={req?.code || '通用'}>{req?.code || '通用'}</span>
|
||||
{deliveryStatus ? (
|
||||
<span className={`inline-flex h-5 w-24 shrink-0 items-center justify-center rounded px-1.5 text-[10px] font-medium whitespace-nowrap ${
|
||||
<span className="text-[12px] font-medium text-[var(--ink)] flex-1 truncate">{req?.title || '未关联需求'}</span>
|
||||
{deliveryStatus && (
|
||||
<span className={`inline-flex h-5 w-14 shrink-0 items-center justify-center rounded px-1.5 text-[10px] font-medium whitespace-nowrap ${
|
||||
deliveryStatus === 'submitted'
|
||||
? 'bg-emerald-50 text-emerald-600 border border-emerald-100'
|
||||
: 'bg-orange-50 text-orange-600 border border-orange-100'
|
||||
}`}>
|
||||
{deliveryStatus === 'submitted' ? '已提测' : '待提测'}
|
||||
</span>
|
||||
) : (
|
||||
<span className="h-5 w-24 shrink-0" />
|
||||
)}
|
||||
<span className="text-[12px] font-medium text-[var(--ink)] flex-1 truncate">{req?.title || '未关联需求'}</span>
|
||||
<span className="text-[11px] text-[var(--ink-muted)]">{reqPassed}/{cases.length} 通过</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -254,7 +256,7 @@ export function TestCaseTab({ versionId, requirementIds }: Props) {
|
||||
<input type="checkbox" checked={selectedIds.has(c.id)} onChange={() => toggleSelect(c.id)} className="h-3.5 w-3.5 rounded border-[var(--line)]" onClick={(e) => e.stopPropagation()} />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<TestCaseRow testCase={c} category={categoryMap.get(c.categoryId)} bugCount={bugCountByCase.get(c.id) ?? 0} onClick={() => setSelectedCaseId(c.id)} />
|
||||
<TestCaseRow testCase={c} category={categoryMap.get(c.categoryId)} categoryLabelWidthEm={categoryLabelWidthEm} bugCount={bugCountByCase.get(c.id) ?? 0} onClick={() => setSelectedCaseId(c.id)} />
|
||||
</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>
|
||||
@@ -315,6 +283,14 @@ export function PlanTab({ plans, versionId, version, versionDeadline, currentUse
|
||||
</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>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import type { DevTask } from './dev-task';
|
||||
import { canStartDevTask, hasDevTaskPlan, needsDevTaskClaim, type DevTask } from './dev-task';
|
||||
import { applyDevTaskTransition, normalizeDevTaskOnCreate } from './dev-task-workflow';
|
||||
|
||||
function task(patch: Partial<DevTask> = {}): DevTask {
|
||||
@@ -47,6 +47,44 @@ test('todo to in_progress writes actualStartAt from manual click time', () => {
|
||||
assert.equal(result.patch?.actualStartAt, '2026-06-25T03:30:00.000Z');
|
||||
});
|
||||
|
||||
test('AI dev task without an assignee must be claimed with a plan before starting', () => {
|
||||
const draft = task({
|
||||
assigneeId: '',
|
||||
expectedStartAt: '',
|
||||
expectedEndAt: '',
|
||||
aiDraft: true,
|
||||
});
|
||||
|
||||
assert.equal(needsDevTaskClaim(draft), true);
|
||||
assert.equal(hasDevTaskPlan(draft), false);
|
||||
assert.equal(canStartDevTask(draft), false);
|
||||
|
||||
const result = applyDevTaskTransition(draft, 'in_progress', {
|
||||
now: new Date('2026-06-25T03:30:00.000Z'),
|
||||
});
|
||||
|
||||
assert.equal(result.ok, false);
|
||||
});
|
||||
|
||||
test('recommended assignee dev task still needs a plan before starting', () => {
|
||||
const draft = task({
|
||||
assigneeId: 'Alice',
|
||||
expectedStartAt: '',
|
||||
expectedEndAt: '',
|
||||
aiDraft: true,
|
||||
});
|
||||
|
||||
assert.equal(needsDevTaskClaim(draft), false);
|
||||
assert.equal(hasDevTaskPlan(draft), false);
|
||||
assert.equal(canStartDevTask(draft), false);
|
||||
|
||||
const result = applyDevTaskTransition(draft, 'in_progress', {
|
||||
now: new Date('2026-06-25T03:30:00.000Z'),
|
||||
});
|
||||
|
||||
assert.equal(result.ok, false);
|
||||
});
|
||||
|
||||
test('in_progress to testing does not write actualEndAt', () => {
|
||||
const result = applyDevTaskTransition(task({
|
||||
status: 'in_progress',
|
||||
@@ -71,6 +109,21 @@ test('testing to submitted writes actualEndAt', () => {
|
||||
assert.equal(result.patch?.actualEndAt, '2026-06-25T05:00:00.000Z');
|
||||
});
|
||||
|
||||
test('blocked task cannot be submitted to test until unblocked', () => {
|
||||
const result = applyDevTaskTransition(task({
|
||||
status: 'testing',
|
||||
actualStartAt: '2026-06-25T03:30:00.000Z',
|
||||
isBlocked: true,
|
||||
blockReason: '等待接口联调',
|
||||
}), 'submitted', {
|
||||
now: new Date('2026-06-25T05:00:00.000Z'),
|
||||
});
|
||||
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.patch, undefined);
|
||||
assert.match(result.message || '', /\u963b\u585e/);
|
||||
});
|
||||
|
||||
test('invalid transition is rejected', () => {
|
||||
const result = applyDevTaskTransition(task(), 'submitted', {
|
||||
now: new Date('2026-06-25T05:00:00.000Z'),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { DevTask, DevTaskStatus } from './dev-task';
|
||||
import { canTransition } from './dev-task';
|
||||
import { canStartDevTask, canTransition } from './dev-task';
|
||||
|
||||
export interface DevTaskWorkflowResult {
|
||||
ok: boolean;
|
||||
@@ -30,7 +30,15 @@ export function applyDevTaskTransition(
|
||||
return { ok: false, message: `不允许从「${task.status}」流转到「${to}」` };
|
||||
}
|
||||
|
||||
if (to === 'submitted' && task.isBlocked) {
|
||||
return { ok: false, message: '任务仍处于阻塞中,请先解除阻塞后再提测' };
|
||||
}
|
||||
|
||||
const nowIso = (options.now ?? new Date()).toISOString();
|
||||
if (to === 'in_progress' && !canStartDevTask(task)) {
|
||||
return { ok: false, message: '开始开发前需要先领取并填写预计开始和预计截止时间' };
|
||||
}
|
||||
|
||||
const patch: Partial<DevTask> = {
|
||||
status: to,
|
||||
aiDraft: false,
|
||||
|
||||
@@ -112,6 +112,21 @@ function roundEffortHours(hours: number): number {
|
||||
return Number(hours.toFixed(2));
|
||||
}
|
||||
|
||||
export function needsDevTaskClaim(task: Pick<DevTask, 'assigneeId'>): boolean {
|
||||
return !task.assigneeId?.trim();
|
||||
}
|
||||
|
||||
export function hasDevTaskPlan(task: Pick<DevTask, 'expectedStartAt' | 'expectedEndAt'>): boolean {
|
||||
if (!task.expectedStartAt || !task.expectedEndAt) return false;
|
||||
const start = new Date(task.expectedStartAt).getTime();
|
||||
const end = new Date(task.expectedEndAt).getTime();
|
||||
return Number.isFinite(start) && Number.isFinite(end) && end > start;
|
||||
}
|
||||
|
||||
export function canStartDevTask(task: Pick<DevTask, 'assigneeId' | 'expectedStartAt' | 'expectedEndAt'>): boolean {
|
||||
return !needsDevTaskClaim(task) && hasDevTaskPlan(task);
|
||||
}
|
||||
|
||||
export function getActualHours(task: DevTask, now: Date = new Date()): number {
|
||||
if (!task.actualStartAt) return 0;
|
||||
const end = task.actualEndAt ?? (task.status === 'submitted' ? task.updatedAt : now.toISOString());
|
||||
|
||||
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));
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import type { TestCase } from './test-case';
|
||||
import { canStartTestCase, hasTestCasePlan, needsTestCaseClaim } from './test-case';
|
||||
import { applyTestCaseTransition, normalizeTestCaseOnCreate } from './test-case-workflow';
|
||||
|
||||
function tc(patch: Partial<TestCase> = {}): TestCase {
|
||||
@@ -14,6 +15,9 @@ function tc(patch: Partial<TestCase> = {}): TestCase {
|
||||
categoryId: 'cat-test-functional',
|
||||
priority: 'P2',
|
||||
status: 'pending',
|
||||
assigneeId: 'QA',
|
||||
plannedTestAt: '2026-06-25T01:00:00.000Z',
|
||||
plannedEndAt: '2026-06-25T02:00:00.000Z',
|
||||
createdBy: 'QA',
|
||||
createdAt: '2026-06-25T00:00:00.000Z',
|
||||
updatedAt: '2026-06-25T00:00:00.000Z',
|
||||
@@ -48,6 +52,44 @@ test('pending to running writes startedAt', () => {
|
||||
assert.equal(result.patch?.startedAt, '2026-06-25T01:00:00.000Z');
|
||||
});
|
||||
|
||||
test('AI test case without an assignee must be claimed with a plan before running', () => {
|
||||
const draft = tc({
|
||||
assigneeId: undefined,
|
||||
plannedTestAt: undefined,
|
||||
plannedEndAt: undefined,
|
||||
aiDraft: true,
|
||||
});
|
||||
|
||||
assert.equal(needsTestCaseClaim(draft), true);
|
||||
assert.equal(hasTestCasePlan(draft), false);
|
||||
assert.equal(canStartTestCase(draft), false);
|
||||
|
||||
const result = applyTestCaseTransition(draft, 'running', {
|
||||
now: new Date('2026-06-25T01:00:00.000Z'),
|
||||
});
|
||||
|
||||
assert.equal(result.ok, false);
|
||||
});
|
||||
|
||||
test('recommended assignee test case still needs a plan before running', () => {
|
||||
const draft = tc({
|
||||
assigneeId: 'QA',
|
||||
plannedTestAt: undefined,
|
||||
plannedEndAt: undefined,
|
||||
aiDraft: true,
|
||||
});
|
||||
|
||||
assert.equal(needsTestCaseClaim(draft), false);
|
||||
assert.equal(hasTestCasePlan(draft), false);
|
||||
assert.equal(canStartTestCase(draft), false);
|
||||
|
||||
const result = applyTestCaseTransition(draft, 'running', {
|
||||
now: new Date('2026-06-25T01:00:00.000Z'),
|
||||
});
|
||||
|
||||
assert.equal(result.ok, false);
|
||||
});
|
||||
|
||||
test('running to passed writes completedAt', () => {
|
||||
const result = applyTestCaseTransition(tc({
|
||||
status: 'running',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { TestCase, TestCaseStatus } from './test-case';
|
||||
import { canTcTransition, getTestCaseRoundNo } from './test-case';
|
||||
import { canStartTestCase, canTcTransition, getTestCaseRoundNo } from './test-case';
|
||||
|
||||
export interface TestCaseWorkflowResult {
|
||||
ok: boolean;
|
||||
@@ -36,6 +36,10 @@ export function applyTestCaseTransition(
|
||||
}
|
||||
|
||||
const nowIso = (options.now ?? new Date()).toISOString();
|
||||
if (to === 'running' && !canStartTestCase(testCase)) {
|
||||
return { ok: false, message: '开始测试前需要先领取并填写计划开始和计划结束时间' };
|
||||
}
|
||||
|
||||
const patch: Partial<TestCase> = {
|
||||
status: to,
|
||||
aiDraft: false,
|
||||
|
||||
@@ -23,6 +23,7 @@ export interface TestCase {
|
||||
estimateHours?: number;
|
||||
aiEstimateHours?: number;
|
||||
plannedTestAt?: string;
|
||||
plannedEndAt?: string;
|
||||
startedAt?: string;
|
||||
completedAt?: string;
|
||||
executedAt?: string;
|
||||
@@ -98,6 +99,7 @@ export function normalizeTestCase(testCase: Partial<TestCase>, index = 0): TestC
|
||||
estimateHours: typeof testCase.estimateHours === 'number' && testCase.estimateHours > 0 ? testCase.estimateHours : undefined,
|
||||
aiEstimateHours: typeof testCase.aiEstimateHours === 'number' && testCase.aiEstimateHours > 0 ? testCase.aiEstimateHours : undefined,
|
||||
plannedTestAt: testCase.plannedTestAt,
|
||||
plannedEndAt: testCase.plannedEndAt,
|
||||
startedAt: testCase.startedAt,
|
||||
completedAt: testCase.completedAt,
|
||||
executedAt: testCase.executedAt,
|
||||
@@ -172,6 +174,7 @@ export function copyTestCaseToRound(source: TestCase, roundNo: number, createdBy
|
||||
estimateHours: source.estimateHours,
|
||||
aiEstimateHours: source.aiEstimateHours,
|
||||
plannedTestAt: source.plannedTestAt,
|
||||
plannedEndAt: source.plannedEndAt,
|
||||
assigneeId: source.assigneeId,
|
||||
startedAt: undefined,
|
||||
completedAt: undefined,
|
||||
@@ -224,6 +227,23 @@ export function getTestCaseEstimateHours(tc: TestCase): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
export function needsTestCaseClaim(testCase: Pick<TestCase, 'assigneeId'>): boolean {
|
||||
return !testCase.assigneeId?.trim();
|
||||
}
|
||||
|
||||
export function hasTestCasePlan(testCase: Pick<TestCase, 'plannedTestAt' | 'plannedEndAt'>): boolean {
|
||||
if (!testCase.plannedTestAt || !testCase.plannedEndAt) return false;
|
||||
const start = new Date(testCase.plannedTestAt).getTime();
|
||||
const end = new Date(testCase.plannedEndAt).getTime();
|
||||
return Number.isFinite(start) && Number.isFinite(end) && end > start;
|
||||
}
|
||||
|
||||
export function canStartTestCase(
|
||||
testCase: Pick<TestCase, 'assigneeId' | 'plannedTestAt' | 'plannedEndAt'>,
|
||||
): boolean {
|
||||
return !needsTestCaseClaim(testCase) && hasTestCasePlan(testCase);
|
||||
}
|
||||
|
||||
export function getTestCaseActualHours(tc: TestCase, now: Date = new Date()): number {
|
||||
if (!tc.startedAt) return 0;
|
||||
const isTerminal = tc.status === 'passed' || tc.status === 'failed' || tc.status === 'blocked';
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -96,8 +96,9 @@
|
||||
**决策**:
|
||||
- `status: todo|in_progress|testing|submitted`
|
||||
- `isBlocked: boolean` + `blockReason: string` + `blockedById: string`
|
||||
- DevTask 存在阻塞时不能转为 `submitted`,必须先解除阻塞再提测。
|
||||
|
||||
**理由**:阻塞和状态正交。工作台筛选 `isBlocked=true` 一键拉出所有阻塞项,跨状态。
|
||||
**理由**:阻塞和状态正交。工作台筛选 `isBlocked=true` 一键拉出所有阻塞项,跨状态;但 `submitted` 代表开发交付完成,仍必须满足“当前无阻塞”的完成条件。
|
||||
|
||||
## 11. 加班原因可选,且去掉"其他"
|
||||
|
||||
@@ -352,7 +353,7 @@
|
||||
- 新建统一的工作日日期时间选择组件,创建任务时复用同一套交互。
|
||||
- 内置国务院办公厅发布的 2026 年中国法定节假日和调休工作日;未知年份按周末/工作日兜底。
|
||||
- 选择节假日或周末时只提示,不阻止保存;选择调休工作日时按工作日提示。
|
||||
- TestCase 增加 `plannedTestAt`,Bug 增加 `plannedFixAt`,保存为 ISO 时间戳。
|
||||
- TestCase 增加 `plannedTestAt` / `plannedEndAt`,Bug 增加 `plannedFixAt`,保存为 ISO 时间戳。
|
||||
|
||||
**理由**:项目排期需要贴近中国工作日,但研发和线上 Bug 可能确实安排在非工作日处理,所以系统负责提醒,最终是否保存交给用户判断。
|
||||
|
||||
@@ -405,6 +406,31 @@
|
||||
|
||||
**理由**:负责人推荐能减少项目经理初次分配成本,但分配本身是团队执行承诺,必须由人确认。把推荐和写入分开,可以复用版本成员上下文,又避免模型幻觉姓名或越权自动派单。
|
||||
|
||||
## 34. AI 草案领取和计划必须绑定
|
||||
|
||||
**问题**:AI 生成的 DevTask / TestCase 如果没有负责人,团队需要先领取;如果把“待领取”和“待排期”拆成两个可见状态,会让版本详情列表出现更多标签,且无法体现“领取时就应该承诺计划”的业务动作。
|
||||
|
||||
**决策**:
|
||||
- 版本详情开发任务和测试用例不显示“待排期”标签。
|
||||
- 无负责人时显示“待领取”,领取入口必须同时填写计划起止时间。
|
||||
- 用户采纳 AI 推荐负责人后,草案已经有负责人,不再需要领取;但开始开发/测试前仍必须补齐计划起止时间。
|
||||
- DevTask 进入 `in_progress` 前必须具备 `assigneeId`、`expectedStartAt`、`expectedEndAt`。
|
||||
- TestCase 进入 `running` 前必须具备 `assigneeId`、`plannedTestAt`、`plannedEndAt`。
|
||||
|
||||
**理由**:领取代表成员承诺执行,计划时间代表承诺边界,二者应该在同一个动作里完成。列表层只表达“谁还没接手”,状态机层负责阻止未计划任务进入执行,页面不会被额外标签干扰。
|
||||
|
||||
## 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 天。
|
||||
|
||||
2394
docs/superpowers/plans/2026-06-29-xiaobao-warning.md
Normal file
2394
docs/superpowers/plans/2026-06-29-xiaobao-warning.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -35,6 +35,22 @@
|
||||
|
||||
开发任务从“待开发”切换到“开发中”时,只有当前时间已经超过 `expectedEndAt`(预计截止)才要求填写延后原因。超过预计开始时间但仍未超过预计截止时间,不视为延后。
|
||||
|
||||
## AI 草案领取与计划流程
|
||||
|
||||
开发任务和测试用例由 AI 生成后,版本详情里不再显示独立的“待排期”状态:
|
||||
|
||||
1. DevTask / TestCase 没有负责人时显示“待领取”。
|
||||
2. 点击“领取并填写计划”时同时写入当前用户为负责人,并填写计划起止时间。
|
||||
3. 已采纳推荐负责人的 AI 草案已经有负责人,不需要领取,但开始开发/测试前仍必须点击“填写计划”补齐计划起止时间。
|
||||
4. DevTask 开始开发前必须同时具备 `assigneeId`、`expectedStartAt`、`expectedEndAt`;TestCase 开始测试前必须同时具备 `assigneeId`、`plannedTestAt`、`plannedEndAt`。
|
||||
5. 计划起止时间自动按工作日历计算 `estimateHours`。AI 预估仍保留在 `aiEstimateHours`,不代表负责人已确认排期。
|
||||
|
||||
## 开发任务提测流程
|
||||
|
||||
1. DevTask 从“自测”转为“已提测”前,任务不能处于阻塞中。
|
||||
2. 如果 `isBlocked=true`,必须先解除阻塞并清空阻塞原因,再允许提测。
|
||||
3. “已提测”仍然是 DevTask 终态;后续测试通过或失败不回写 DevTask 状态。
|
||||
|
||||
## 测试轮次流程
|
||||
|
||||
测试用例支持按版本开启多轮测试:
|
||||
@@ -207,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:
|
||||
@@ -244,8 +262,8 @@ AI 解读不由人工按钮触发。`at_risk`、`likely_delayed`、`blocked` 自
|
||||
- 调研、产品方案、UI 设计、开发任务、测试用例、Bug 创建时使用统一工作日日期时间选择器。
|
||||
- 日期选择器接入中国节假日日历。当前内置 2026 年国务院办公厅放假调休安排;其他年份先按周末/工作日兜底。
|
||||
- 非工作日只提示,不阻止保存;调休工作日按工作日提示。
|
||||
- 测试用例计划测试时间字段为 `plannedTestAt`;Bug 计划修复时间字段为 `plannedFixAt`。
|
||||
- 测试轮次复制用例时保留计划测试时间、AI 预估和执行预估,清空实际执行记录。
|
||||
- 测试用例计划测试时间字段为 `plannedTestAt` / `plannedEndAt`;Bug 计划修复时间字段为 `plannedFixAt`。
|
||||
- 测试轮次复制用例时保留计划测试起止时间、AI 预估和执行预估,清空实际执行记录。
|
||||
|
||||
## 工时统计口径
|
||||
|
||||
|
||||
Reference in New Issue
Block a user